Introduction to Portfolio Risk Management in Python
Dakota Wixom
Quantitative Analyst | QuantCourse.com
Assuming StockReturns
is a pandas
DataFrame of stock returns, you can calculate the correlation matrix as follows:
correlation_matrix = StockReturns.corr()
print(correlation_matrix)
Portfolio standard deviation for a two asset portfolio:
$$ \sigma_p = \sqrt{ w_1^2 \sigma_1^2 + w_2^2 \sigma_2^2 + 2 w_1 w_2 \rho_{1, 2} \sigma_1 \sigma_2 }$$
To calculate the co-variance matrix ($ \Sigma $) of returns X:
Assuming StockReturns
is a pandas
DataFrame of stock returns, you can calculate the covariance matrix as follows:
cov_mat = StockReturns.cov()
cov_mat
To annualize the covariance matrix:
cov_mat_annual = cov_mat * 252
The formula for portfolio volatility is:
$$ \sigma_{Portfolio} = \sqrt{ w_T \cdot \Sigma \cdot w } $$
Examples of matrix transpose operations:
The dot product operation of two vectors a and b:
To calculate portfolio volatility assume a weights array and a covariance matrix:
import numpy as np
port_vol = np.sqrt(np.dot(weights.T, np.dot(cov_mat, weights)))
port_vol
0.035
Introduction to Portfolio Risk Management in Python