A portfolio is a collection of financial investments like stocks, bonds, commodities, cash, and cash equivalents, including closed-end funds and exchange-traded funds (ETFs), here in this topic I'm talking about stock portfolios.
Portfolio optimization is the process of selecting the best portfolio, out of the set of all portfolios being considered, according to some objective. The objective typically maximizes factors such as expected return and minimizes financial risk.
With the help of "daily returns", "annualized covariance matrix","portfolio variance","portfolio volatility" and "annual portfolio return" I'll do portfolio optimization on python. I'll take historical data of stocks with the help of "pandas DataReader" and then use statics formulas mentioned above to do the optimization and state what is the annual return and risk involved in the particular portfolio I've selected
I'm using Google Colab for the programming part.
#Importing Libraries
import pandas as pd
from pandas_datareader import data as web
import numpy as np
import matplotlib.pyplot as plt
from datetime import datetime
plt.style.use('fivethirtyeight')
#Get the stock data
assets = ['PNB.NS', 'YESBANK.NS', 'HDFC.NS', 'VOLTAS.NS']
#Assign weight/%of stock
weights = np.array([0.25, 0.25, 0.25, 0.25])
#get stock/portfolio start date
stockstartdate = '2015-01-01'
#get stock end date (today)
today = datetime.today().strftime('%Y-%m-%d')
today
#create a dataframe to store adjusted close price of the stocks
df = pd.DataFrame()
#store the adj close price in the dataframe
for stock in assets:
df[stock] = web.DataReader(stock, data_source='yahoo', start= stockstartdate, end = today)['Adj Close']
#visualize the data frame / stock / portfolio
title = 'Portfolio Adj Close Price History'
#get the stocks
my_stocks = df
#create and plot the graph
for c in my_stocks.columns.values:
plt.plot(my_stocks[c], label = c)
plt.title('Adj Close Price')
plt.xlabel('Date', fontsize = 18)
plt.ylabel('Adj Close Price', fontsize = 18)
plt.legend(my_stocks.columns.values, loc= 'upper left')
plt.show()
#calculating daily returns
returns = df.pct_change()
returns
#create and show the anualized covarience matrix
cov_matrix_annual = returns.cov() * 252
cov_matrix_annual
#calculate the protfolio variance
port_variance = np.dot(weights.T, np.dot(cov_matrix_annual, weights))
port_variance
#calculate the portfolio volitality aka standard deviation
port_volatility = np.sqrt(port_variance)
port_volatility
#calculate the annual portfolio return
portfolioSimpleAnnualReturn = np.sum(returns.mean()*weights)*252
portfolioSimpleAnnualReturn
#show the expected annual return, volatility (risk) and variance
percent_var = str(round(port_variance, 2)*100) + '%'
percent_vols = str(round(port_volatility,2)*100) + '%'
percent_ret = str(round(portfolioSimpleAnnualReturn,2)*100) + '%'
print('expected annual return: '+ percent_ret)
print('Annual volatility / risk: '+ percent_vols)
print('Annual variance: '+ percent_var)
Now you can try to optimize your own portfolio and see what is your expected annual return, volatility, and variance.
NOTE- The portfolio which I have optimized in this article is a fictional portfolio and I randomly created it that's why I have set the weights of the assets equal i.e "0.25" each so that it may complete 100% of the portfolio.
You can divide the weights according to your stocks in the portfolio.
Comments
Post a Comment