for 2 stocks we are using this coding.
portfolio_returns = aannual_returns['hdfcbank'] + bannual_returns['M&M']
porfolio_std_dev = math.sqrt((a**2)(annual_std_dev['hdfcbank']2) + (b2)(annual_std_dev['M&M']**2)
+ 2ab*cov_hdfcbank_MM[0, 1])
what's the coding for Portfolio return and Portfolio_std_dev for multiple stocks.
Hi Perumal,
Calculating portfolio returns and portfolio standard deviation for two stocks can be done using the linear equations as you have coded.
For multiple stock portfolio writing a linear equation would be difficult. This can be done using Matrix Multiplication.
The formulas for the same are given below.
Where,
1. Wi is the weight allocated to ith stock.
2. Xi is the expected returns of ith stock.
3. σij is the covariance between ith and jth stock. If i=j then it is the variance of the stock.
To do the same in Python, you can use the similar code as follows.
Assuming you have a dataframe of 'n' stock prices with the name stock_prices.
The below code generates random weights for 'n' stocks. If you an array of weights, you can use that.
weights = np.random.random(n)
weights /= np.sum(weights)
Calculate annualised returns
annual_returns = ((((stock_prices.iloc[-1]-stock_prices.iloc[0]) / stock_prices.iloc[0])+1)**(252/len(stock_prices)) - 1)
Calculate daily returns
daily_returns = stock_prices.pct_change()
Calculate covariance matrix
covariance_matrix = daily_returns.cov(bias=True)*252
Calculate portfolio returns. Use 'dot' method of numpy library to perform matrix multiplication.
portfolio_returns = np.sum(np.dot(annual_returns, weights))
Calculate portfolio standard deviation. In this '.T' method is used to transpose the matrix.
portfolio_std_dev = np.sqrt(np.dot(weights.T, np.dot(covariance_matrix, weights))) * np.sqrt(252)
Hope this helps!