Skip to content

Instantly share code, notes, and snippets.

@yuyasugano
Created September 16, 2020 11:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yuyasugano/d1ba87ea242e50db99fe1c6f2e93beba to your computer and use it in GitHub Desktop.
Save yuyasugano/d1ba87ea242e50db99fe1c6f2e93beba to your computer and use it in GitHub Desktop.
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