Skip to content

Instantly share code, notes, and snippets.

@bjpcjp
Forked from bfan1256/metrics.py
Created Jan 15, 2022
Embed
What would you like to do?
5 Performance Metrics for Trading Algorithms and Investment Portfolios
from blankly import Alpaca, CoinbasePro # supports stocks, crypto, and forex
import numpy as np
from math import sqrt
def cagr(start_value: float, end_value: float, years: int):
return (end_value / start_value) ** (1.0 / years) - 1
def sharpe(account_values: np.array, risk_free_rate, annualize_coefficient):
diff = np.diff(account_values, 1) / account_values[1:] # this gets our pct_return in the array
# we'll get the mean and calculate everything
# we multiply the mean of returns by the annualized coefficient and divide by annualized std
annualized_std = diff.std() * sqrt(annualize_coefficient)
return (diff.mean() * annualize_coefficient - risk_free_rate) / annualized_std
def sortino(account_values: np.array, risk_free_rate, annualize_coefficient):
diff = np.diff(account_values, 1) / account_values[1:]
# we'll get the mean and calculate everything
# remember, we're only using the negative returns
neg_returns = diff[diff < 0]
annualized_std = neg_returns.std() * sqrt(annualize_coefficient)
return (diff.mean() * annualize_coefficient - risk_free_rate) / annualized_std
def value_at_risk(account_values, alpha: float):
initial_value = account_values[0]
returns = np.diff(account_values, 1) / account_values[1:]
returns_sorted = np.sort(returns) # sort our returns (should be estimated normal)
index = int(alpha * len(returns_sorted))
return initial_value * abs(returns_sorted[index])
def max_drawdown(account_values):
returns = account_values.diff(1) / account_values[1:]
cumulative = (returns + 1).cumprod()
peak = cumulative.expanding(min_periods=1).max()
dd = (cumulative / peak) - 1
return dd.min()
a = Alpaca() # initialize the Alpaca Exchange
def beta(returns, baseline='SPY', return_resolution='1m'):
market_base_returns = a.interface.history(baseline, len(returns), resolution=return_resolution) # get the last X month bars of the baseline asset
m = np.matrix([returns, market_base_returns])
return np.cov(m)[0][1] / np.std(market_base_returns)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment