How do I calculate the portfolio standard deviation for a portfolio with 20 stocks?

In the course, we learnt how to calculate the portfolio standard deviation for two stocks. How can I extend it to 20 stocks?

Import numpy as np

import numpy as np


Calculate the portfolio standard deviation

portfolio_volatility = np.sqrt(np.dot(portfolio_weights.T, np.dot(cov_mat_annual, portfolio_weights))



print(portfolio_volatility)

Hello Esuabom, 



It's cool to know you are progressing in your course. Here you could find a seudo code to do what you requested:



Imagine you have only 2 stocks. Let's code:



"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""

Import numpy

import numpy as np


Portfolio weights. Notice the shape of this array has only 1 dimension. Shape: (2,)

portfolio_weights = np.array([0.5,0.5])


Calculate the portfolio standard deviation

portfolio_volatility = np.sqrt(np.dot(portfolio_weights, np.dot(cov_mat_annual, portfolio_weights))



print(portfolio_volatility)

"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""

The above code works well since the portfolio weights has only one dimension



Now, in case you have a 2D portfolio_weghts you have to code like this:



"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""

Import numpy

import numpy as np


Portfolio weights. Notice the shape of this array is (1,2)

portfolio_weights = np.matrix([0.5,0.5])


Calculate the portfolio standard deviation

portfolio_volatility = np.sqrt(np.dot(portfolio_weights, np.dot(cov_mat_annual, portfolio_weights.T))



print(portfolio_volatility[0][0])

"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""



The portfolio_weights dimension is (1,2), the covariance is (2,2) and the transposed portfolio_weigths is (2,1). Remember that in order to multiple matrices you have to coincide the adjacent dimensions of the matrices.



For example to premultiply the covariance with portfolio_weights you saw that the corresponding dimensions for the portfolio_wights and covariance were: (1,2) times (2,2).



The same to postmultiply the covariance with the transposed portfolio_weights. You saw that the corresponding dimensions were: (2,2) times (2,1).



To understand better the numpy dimensions, please refer to this link



In case you have new doubts, please let us know,



Jose Carlos