The volatility of a portfolio of stocks
This code uses Python to calculate the expected annualized return and volatility of a portfolio of stocks. Here is a breakdown of what each line of the code does:
#list of stocks in portfolio #NOTE THAT THESE MUST BE ENTERED IN ALPHABETICAL ORDER FOR THE RESULTS TO BE CORRECT!!!stocks = ['AAPL','AMZN','MSFT','YHOO']This line defines the list of stocks in the portfolio. It is important to note that the stocks must be entered in alphabetical order for the code to work correctly.
#download daily price data for each of the stocks in the portfoliodata = web.DataReader(stocks,data_source='yahoo',start='01/01/2010')['Adj Close']data.sort_index(inplace=True)These lines use the pandas_datareader library to download the daily closing price data for each stock in the portfolio from Yahoo Finance. The data is then sorted in ascending order by date.
#convert daily stock prices into daily returnsreturns = data.pct_change()This line calculates the daily returns of the portfolio by taking the percentage change in price from one day to the next.
#calculate mean daily return and covariance of daily returnsmean_daily_returns = returns.mean()cov_matrix = returns.cov()These lines calculate the mean daily return and covariance of daily returns for the portfolio.
#set array holding portfolio weights of each stockweights = np.asarray([0.5,0.2,0.2,0.1])This line sets the array of portfolio weights for each stock. In this case, the portfolio is composed of 50% AAPL, 20% AMZN and MSFT, and 10% YHOO.
#calculate annualised portfolio returnportfolio_return = round(np.sum(mean_daily_returns * weights) * 252,2)This line calculates the expected annualized return of the portfolio by multiplying the sum of the mean daily returns of each stock weighted by their respective portfolio weights by 252 (the number of trading days in a year). The result is rounded to two decimal places.
#calculate annualised portfolio volatilityportfolio_std_dev = round(np.sqrt(np.dot(weights.T,np.dot(cov_matrix, weights))) * np.sqrt(252),2)This line calculates the expected annualized volatility of the portfolio by taking the square root of the dot product of the portfolio weights, covariance matrix, and transposing the portfolio weights, then multiplying by the square root of 252. The result is rounded to two decimal places.
print('Portfolio expected annualised return is {} and volatility is {}').format(portfolio_return,portfolio_std_dev)This line prints out the expected annualized return and volatility of the portfolio in a formatted string. The values of portfolio_return and portfolio_std_dev are inserted into the string using the format() method.
No comments:
Post a Comment