Created
September 16, 2020 11:29
-
-
Save yuyasugano/d1ba87ea242e50db99fe1c6f2e93beba to your computer and use it in GitHub Desktop.
Pandas volatility calculation for portfolio
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# use pivot to reshape DataFrame with only Adj Close | |
df = multiData.copy() | |
closePrice = df[['Close']] | |
closePrice = closePrice.reset_index() | |
closePriceTable = closePrice.pivot(index='Date', columns='Ticker', values='Close') | |
closePriceTable.tail() | |
# compute volatility using Pandas rolling and std methods, the trading days is set to 252 days | |
TRADING_DAYS = 252 | |
returns_portfolio = np.log(closePriceTable/closePriceTable.shift(1)) | |
returns_portfolio.fillna(0, inplace=True) | |
volatility_portfolio = returns_portfolio.rolling(window=TRADING_DAYS).std()*np.sqrt(TRADING_DAYS) | |
volatility_portfolio.tail() | |
fig = plt.figure(figsize=(15, 7)) | |
ax2 = fig.add_subplot(1, 1, 1) | |
volatility_portfolio.plot(ax=ax2) | |
ax2.set_xlabel('Date') | |
ax2.set_ylabel('Volatility') | |
ax2.set_title('Portfolio annualized volatility') | |
plt.show() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment