Skip to content

ENH: Add *annualized* return/volatility/Sharpe/Sortino stats #156

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 4 commits into from
Oct 28, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
38 changes: 32 additions & 6 deletions backtesting/backtesting.py
Original file line number Diff line number Diff line change
Expand Up @@ -1339,7 +1339,7 @@ def _compute_stats(self, broker: _Broker, strategy: Strategy) -> pd.Series:

equity = pd.Series(broker._equity).bfill().fillna(broker._cash).values
dd = 1 - equity / np.maximum.accumulate(equity)
dd_dur, dd_peaks = self._compute_drawdown_duration_peaks(pd.Series(dd, index=data.index))
dd_dur, dd_peaks = self._compute_drawdown_duration_peaks(pd.Series(dd, index=index))

equity_df = pd.DataFrame({
'Equity': equity,
Expand Down Expand Up @@ -1386,25 +1386,51 @@ def _round_timedelta(value, _period=_data_period(index)):
s.loc['Return [%]'] = (equity[-1] - equity[0]) / equity[0] * 100
c = data.Close.values
s.loc['Buy & Hold Return [%]'] = (c[-1] - c[0]) / c[0] * 100 # long-only return
s.loc['Max. Drawdown [%]'] = max_dd = -np.nan_to_num(dd.max()) * 100

def geometric_mean(x):
return np.exp(np.log(1 + x).sum() / (len(x) or np.nan)) - 1

day_returns = gmean_day_return = annual_trading_days = np.array(np.nan)
if index.is_all_dates:
day_returns = equity_df['Equity'].resample('D').last().dropna().pct_change()
gmean_day_return = geometric_mean(day_returns)
annual_trading_days = (
365 if index.dayofweek.to_series().between(5, 6).mean() > 2/7 * .6 else
252)

# Annualized return and risk metrics are computed based on the (mostly correct)
# assumption that the returns are compounded. See: https://dx.doi.org/10.2139/ssrn.3054517
# Our annualized return matches `empyrical.annual_return(day_returns)` whereas
# our risk doesn't; they use the simpler approach below.
annualized_return = (1 + gmean_day_return)**annual_trading_days - 1
s.loc['Return (Ann.) [%]'] = annualized_return * 100
s.loc['Volatility (Ann.) [%]'] = np.sqrt((day_returns.var(ddof=1) + (1 + gmean_day_return)**2)**annual_trading_days - (1 + gmean_day_return)**(2*annual_trading_days)) * 100 # noqa: E501
# s.loc['Return (Ann.) [%]'] = gmean_day_return * annual_trading_days * 100
# s.loc['Risk (Ann.) [%]'] = day_returns.std(ddof=1) * np.sqrt(annual_trading_days) * 100

# Our Sharpe mismatches `empyrical.sharpe_ratio()` because they use arithmetic mean return
# and simple standard deviation
s.loc['Sharpe Ratio'] = np.clip(s.loc['Return (Ann.) [%]'] / (s.loc['Volatility (Ann.) [%]'] or np.nan), 0, np.inf) # noqa: E501
# Our Sortino mismatches `empyrical.sortino_ratio()` because they use arithmetic mean return
s.loc['Sortino Ratio'] = np.clip(annualized_return / (np.sqrt(np.mean(day_returns.clip(-np.inf, 0)**2)) * np.sqrt(annual_trading_days)), 0, np.inf) # noqa: E501
max_dd = -np.nan_to_num(dd.max())
s.loc['Calmar Ratio'] = np.clip(annualized_return / (-max_dd or np.nan), 0, np.inf)
s.loc['Max. Drawdown [%]'] = max_dd * 100
s.loc['Avg. Drawdown [%]'] = -dd_peaks.mean() * 100
s.loc['Max. Drawdown Duration'] = _round_timedelta(dd_dur.max())
s.loc['Avg. Drawdown Duration'] = _round_timedelta(dd_dur.mean())
s.loc['# Trades'] = n_trades = len(trades)
s.loc['Win Rate [%]'] = win_rate = np.nan if not n_trades else (pl > 0).sum() / n_trades * 100 # noqa: E501
s.loc['Best Trade [%]'] = returns.max() * 100
s.loc['Worst Trade [%]'] = returns.min() * 100
mean_return = np.exp(np.log(1 + returns).sum() / (len(returns) or np.nan)) - 1
mean_return = geometric_mean(returns)
s.loc['Avg. Trade [%]'] = mean_return * 100
s.loc['Max. Trade Duration'] = _round_timedelta(durations.max())
s.loc['Avg. Trade Duration'] = _round_timedelta(durations.mean())
s.loc['Profit Factor'] = returns[returns > 0].sum() / (abs(returns[returns < 0].sum()) or np.nan) # noqa: E501
s.loc['Expectancy [%]'] = ((returns[returns > 0].mean() * win_rate -
returns[returns < 0].mean() * (100 - win_rate)))
s.loc['SQN'] = np.sqrt(n_trades) * pl.mean() / (pl.std() or np.nan)
s.loc['Sharpe Ratio'] = mean_return / (returns.std() or np.nan)
s.loc['Sortino Ratio'] = mean_return / (returns[returns < 0].std() or np.nan)
s.loc['Calmar Ratio'] = mean_return / ((-max_dd / 100) or np.nan)

s.loc['_strategy'] = strategy
s.loc['_equity_curve'] = equity_df
Expand Down
8 changes: 5 additions & 3 deletions backtesting/test/_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -261,7 +261,7 @@ def test_compute_stats(self):
'Avg. Trade [%]': 2.3537113951143773,
'Best Trade [%]': 53.59595229490424,
'Buy & Hold Return [%]': 703.4582419772772,
'Calmar Ratio': 0.049055964204885415,
'Calmar Ratio': 0.4445179349739874,
'Duration': pd.Timedelta('3116 days 00:00:00'),
'End': pd.Timestamp('2013-03-01 00:00:00'),
'Equity Final [$]': 51959.94999999997,
Expand All @@ -272,10 +272,12 @@ def test_compute_stats(self):
'Max. Drawdown [%]': -47.98012705007589,
'Max. Trade Duration': pd.Timedelta('183 days 00:00:00'),
'Profit Factor': 2.0880175388920286,
'Return (Ann.) [%]': 21.32802699608929,
'Return [%]': 419.59949999999964,
'Volatility (Ann.) [%]': 36.53825234483751,
'SQN': 0.916892986080858,
'Sharpe Ratio': 0.17914126763602636,
'Sortino Ratio': 0.5588698138148217,
'Sharpe Ratio': 0.5837177650097084,
'Sortino Ratio': 1.0923863161583591,
'Start': pd.Timestamp('2004-08-19 00:00:00'),
'Win Rate [%]': 46.15384615384615,
'Worst Trade [%]': -18.39887353835481,
Expand Down