Python for Finance: Part II: 2 Measuring Investment Risk
variance
S2 = (Σ (X-X–)2) / (N-1)
X–=15%
X=14%
X=16%
X=13%
X=17%
(14%-15%)2 = 0.01%
(16%-15%)2 = 0.01%
(13%-15%)2 = 0.04%
(17%-15%)2 = 0.04%
Σ=0.1%
S2=0.1% / (4-1)
S2=0.033%
S2=0.00033
standard deviation
S = √S2
√S2 = √0.00033 = 1.8%
Implementation
1 2 3 4 5 6 7 |
// variance sec_returns[['DIS', 'AMZN']].mean() sec_returns[['DIS', 'AMZN']].mean() * 250 // deviation sec_returns[['DIS', 'AMZN']].std() sec_returns[['DIS', 'AMZN']].std()*250**0.5 |
Calculating the covariance between securities
The correlation coefficient measures the relationship between two variables.
Pxy = ((x-x–) * (y-y–)) / (σxσy)
x: house size
y: house price
Implementation
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
AMZN_var = sec_returns['AMZN'].var() AMZN_var DIS_var = sec_returns['DIS'].var() DIS_var AMZN_var_a = sec_returns['AMZN'].var()*250 AMZN_var_a DIS_var_a = sec_returns['DIS'].var()*250 DIS_var_a cov_matrix = sec_returns.cov() cov_matrix // Useless. You don't need to multiply by 250 for calculating correlation. cov_matrix_a = sec_returns.cov()*250 cov_matrix_a corr_matrix = sec_returns.corr() corr_matrix |
Considering the risk of multiple securities in a portfolio
(a+b)2 = a2 + 2ab + b2
Portfolio variance (2 stocks):
(w1σ1 + w2σ2)2 = w12σ12 + 2w1σ1w2σ2p12 + w22σ22
Implementation
1 2 3 4 5 6 7 8 9 10 11 12 |
// Equal weighing scheme: weights = np.array([0.5,0.5]) // Portfolio Variance: pfolio_var = np.dot(weights.T, np.dot(sec_returns.cov()*250,weights)) pfolio_var // Portfolio Volatility: pfolio_vol = (np.dot(weights.T, np.dot(sec_returns.cov()*250,weights))) ** 0.5 pfolio_vol print (str(round(pfolio_vol,5)*100)+' %') |
Portfolio Variance
1. Variance of securities
2. Correlation (and Covariance)
3. Two types of investment risks
1) Un-diversifiable risk (Systematic risk): cannot be eliminated.
– Recession of the economy
– Low consumer spending
– Wars
– Forces of nature
2) Diversifiable risk (Idiosyncratic risk, company specific risk)
– Automotive
– Construction
– Energy
– Technology
Calculating Diversifiable and Non-Diversifiable Risk of a Portfolio
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
weights = np.array([0.5,0.5]) weights[0] weights[1] // Diversifiable Risk: AMZN_var_a = sec_returns['AMZN'].var()*250 AMZN_var_a DIS_var_a = sec_returns['DIS'].var()*250 DIS_var_a dr = pfolio_var - (weights[0]**2*AMZN_var_a) - (weights[1]**2*DIS_var_a) dr print(str(round(dr*100, 3))+' %') // Non-Diversifieable Risk: n_dr_1 = pfolio_var - dr n_dr_1 n_dr_2 = (weights[0]**2*AMZN_var_a)+(weights[1]**2*DIS_var_a) n_dr_2 n_dr_1 == n_dr_2 |