Skip to content

Instantly share code, notes, and snippets.

@yuyasugano
Created September 16, 2020 11:58
Show Gist options
  • Save yuyasugano/90ef720bc1b7ce8a37b5a4acd21211be to your computer and use it in GitHub Desktop.
Save yuyasugano/90ef720bc1b7ce8a37b5a4acd21211be to your computer and use it in GitHub Desktop.
Pandas sharpe ratio calculation for portfolio
# compute sharpe ratio 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)
sharpe_ratio_portfolio = returns_portfolio.mean()/volatility_portfolio
sharpe_ratio_portfolio.tail()
fig = plt.figure(figsize=(15, 7))
ax4 = fig.add_subplot(1, 1, 1)
sharpe_ratio_portfolio[sharpe_ratio_portfolio.columns[sharpe_ratio_portfolio.columns != 'JWN']].plot(ax=ax4)
ax4.set_xlabel('Date')
ax4.set_ylabel('Sharpe ratio')
ax4.set_title('Sharpe ratio with the annualized volatility for portfolio')
plt.show()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment