import numpy as np
import pandas as pd
import pyatl
rng = np.random.default_rng(1)
days = pd.bdate_range("2024-01-02", periods=500)
close = np.round(20_000 * np.exp(np.cumsum(rng.normal(0.0002, 0.012, len(days)))), -1)
frame = pd.DataFrame(
{"open": close, "high": close, "low": close, "close": close, "volume": 1e6}, index=days
)
class Momentum:
def __init__(self):
self.closes = []
def on_bar(self, ctx, bar):
self.closes.append(bar.close)
if len(self.closes) > 20:
ctx.target(bar.symbol, 200 if bar.close > self.closes[-21] else 0)
result = pyatl.backtest(
Momentum(), {"005930": frame}, commission=0.00015, sell_tax=0.002
)Measures of your own
BacktestResult reports the library’s figures, and carries the fills and the equity curve as NumPy columns, so any other measure is computed from them.
The library’s figures, recomputed
result.equity["period_return"] is the series the library’s Sharpe and Sortino are computed from: each period’s return, computed exactly from decimal equity and rounded to eight places, NaN on the first point and wherever the library has no return (after a bar whose equity could not be valued, or after equity at or below zero). For a run like this one, a measure computed from it matches the library’s; one computed from the floating-point equity levels agrees to about four significant digits. If equity was at or below zero before the last point, the library reports no Sharpe or Sortino at all, while the remaining returns would still give a number: check np.isnan(result.sharpe) before comparing.
equity = result.equity["equity"]
returns = result.equity["period_return"]
valid = returns[~np.isnan(returns)]
from_levels = equity[1:] / equity[:-1] - 1
peak = np.maximum.accumulate(equity)
print(f"total return library {result.total_return:.10f} numpy {equity[-1] / equity[0] - 1:.10f}")
print(f"max drawdown library {result.max_drawdown:.10f} numpy {((peak - equity) / peak).max():.10f}")
print(f"sharpe library {result.sharpe:.10f} from period_return {valid.mean() / valid.std(ddof=1):.10f}")
print(f" from the levels instead {from_levels.mean() / from_levels.std(ddof=1):.10f}")total return library -0.0019134200 numpy -0.0019134200
max drawdown library 0.0092213438 numpy 0.0092213438
sharpe library -0.0153188045 from period_return -0.0153188045
from the levels instead -0.0153198587
Check result.unvalued_bars == 0 first: a bar whose equity could not be valued has no point in the curve, and a return computed between two exported points would span it.
Measures the library does not report
years = (result.equity["time"][-1] - result.equity["time"][0]) / (365.25 * 86400e9)
cagr = (equity[-1] / equity[0]) ** (1 / years) - 1
var_95 = -np.quantile(valid, 0.05)
fills = pd.DataFrame(result.fills)
trades = fills.groupby("side")["quantity"].sum()
print(f"CAGR {cagr:.2%}, one-day VaR(95%) {var_95:.2%}")
print(f"shares bought {trades.get('buy', 0):.0f}")CAGR -0.10%, one-day VaR(95%) 0.04%
shares bought 6200
Costs per fill are columns too: commission, tax (KRW) and slippage (the price per share given up, already in price).