Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Pandas volatility calculation for portfolio
# 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