Skip to content

Instantly share code, notes, and snippets.

@evanaze
Created August 21, 2020 16:36
Show Gist options
  • Save evanaze/c59928ef9e419022b7e1c3c249d6daa5 to your computer and use it in GitHub Desktop.
Save evanaze/c59928ef9e419022b7e1c3c249d6daa5 to your computer and use it in GitHub Desktop.
Some methods for calculating financial metrics
# helper functions
def CAGR(DF):
"Calculates the Compound Annual Growth Rate"
df = DF.copy()
df['daily_ret'] = df['Adj Close'].pct_change()
df['cum_return'] = (1 + df['daily_ret']).cumprod()
return (df['cum_return'])**(252/len(df)) - 1
def volatility(DF):
"Calculates the daily Volatility over a year, given we trade 252x a year"
df = DF.copy()
df['daily_ret'] = df['Adj Close'].pct_change()
vol = df['daily_ret'].std()*np.sqrt(252)
return vol
def sharpe(DF, rf=None):
"Sharpe ratio. RF = risk free rate. If not specified then rf=zero"
df = DF.copy()
if not rf:
rf = np.array([0]*len(df))
sr = (CAGR(df) - rf)/volatility(df)
return sr
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment