Coverage for evaluation/backtest_api.py: 100%

133 statements  

« prev     ^ index     » next       coverage.py v7.17.3, created at 2026-11-22 12:55 +0000

1"""A general, cost-aware backtest of any weights on any prices (V6.6.5, #345): no Lean, no Docker, no model. 

2 

3Accounting is in units, as a broker books it. A decision row dated D sizes each order at D's close (`weight * NAV / close`); 

4with `fill="next_open"` the order fills at the next row's open, with `fill="close"` at D's close. Between decisions the 

5units are held and the weights drift. That is the convention `evaluation.target_weights_engine.simulate_target_weights` 

6uses for equities, and a test holds the two to the same returns. 

7 

8 result = backtest(weights, closes, opens=opens, cost_model=LinearCostModel(commission_bps=10)) 

9 print(result.report()) 

10 result.stats()["sharpe_ratio"] 

11""" 

12 

13from __future__ import annotations 

14 

15import math 

16from collections.abc import Mapping 

17from dataclasses import dataclass 

18from datetime import date 

19from typing import Literal 

20 

21import numpy as np 

22import pandas as pd 

23 

24from evaluation.lean_statistics import lean_statistics 

25from execution.cost_models import CostModel 

26 

27__all__ = ["BacktestResult", "backtest", "summary_statistics"] 

28 

29 

30def _max_drawdown(nav: pd.Series) -> float: 

31 if nav.empty: 

32 return 0.0 

33 peak = nav.cummax() 

34 return float((1.0 - nav / peak).max()) 

35 

36 

37def summary_statistics(returns: pd.Series, *, periods_per_year: int = 252, risk_free: float = 0.0, turnover: pd.Series | None = None, 

38 costs: pd.Series | None = None, nav: pd.Series | None = None) -> dict[str, float]: 

39 """CAGR, volatility, Sharpe, Sortino, PSR (Lean's formulas, at a constant annual `risk_free`), max drawdown, Calmar, 

40 annual turnover and annual cost drag in bps. Non-finite returns are dropped; an empty series gives zeros.""" 

41 clean = pd.to_numeric(returns, errors="coerce").replace([np.inf, -np.inf], np.nan).dropna() 

42 days = [pd.Timestamp(index).date() for index in clean.index] if len(clean) else [] 

43 lean = lean_statistics(clean.tolist(), days, trading_days_per_year=int(periods_per_year), rate_changes=[(date(1900, 1, 1), float(risk_free))]) 

44 curve = nav if nav is not None else (1.0 + clean).cumprod() 

45 years = len(clean) / float(periods_per_year) if len(clean) else 0.0 

46 growth = float((1.0 + clean).prod()) if len(clean) else 1.0 

47 cagr = growth ** (1.0 / years) - 1.0 if years > 0 and growth > 0 else 0.0 

48 max_dd = _max_drawdown(curve) 

49 turnover_annual = float(turnover.sum() / years) if turnover is not None and years > 0 else 0.0 

50 cost_drag = float(costs.sum() / years * 1e4) if costs is not None and years > 0 else 0.0 

51 out = { 

52 "total_return": growth - 1.0, 

53 "cagr": cagr, 

54 "annual_volatility": float(lean["annual_standard_deviation"]), 

55 "sharpe_ratio": float(lean["sharpe_ratio"]), 

56 "sortino_ratio": float(lean["sortino_ratio"]), 

57 "probabilistic_sharpe_ratio": float(lean["probabilistic_sharpe_ratio"]), 

58 "max_drawdown": max_dd, 

59 "calmar_ratio": cagr / max_dd if max_dd > 0 else 0.0, 

60 "turnover_annual": turnover_annual, 

61 "cost_drag_bps_annual": cost_drag, 

62 "observations": float(len(clean)), 

63 } 

64 return {key: (value if math.isfinite(value) else 0.0) for key, value in out.items()} 

65 

66 

67@dataclass(frozen=True) 

68class BacktestResult: 

69 """Daily series of one path. `returns` are net of costs, `gross_returns` before them; `costs` and `turnover` are 

70 fractions of the previous NAV; `weights` are the end-of-day holdings.""" 

71 

72 returns: pd.Series 

73 gross_returns: pd.Series 

74 nav: pd.Series 

75 weights: pd.DataFrame 

76 turnover: pd.Series 

77 costs: pd.Series 

78 periods_per_year: int = 252 

79 

80 def stats(self, *, risk_free: float = 0.0) -> dict[str, float]: 

81 """`summary_statistics` of the net returns.""" 

82 return summary_statistics(self.returns, periods_per_year=self.periods_per_year, risk_free=risk_free, turnover=self.turnover, 

83 costs=self.costs, nav=self.nav) 

84 

85 def to_frame(self) -> pd.DataFrame: 

86 """The daily series side by side.""" 

87 return pd.DataFrame({"nav": self.nav, "return": self.returns, "gross_return": self.gross_returns, "turnover": self.turnover, 

88 "cost": self.costs, "gross_exposure": self.weights.abs().sum(axis=1)}) 

89 

90 def report(self, *, title: str = "Backtest", risk_free: float = 0.0) -> str: 

91 """A plain-text summary table.""" 

92 stats = self.stats(risk_free=risk_free) 

93 start, end = (str(self.nav.index[0]), str(self.nav.index[-1])) if len(self.nav) else ("-", "-") 

94 rows = [ 

95 ("Window", f"{start} to {end}"), ("Total return", f"{stats['total_return']:.2%}"), ("CAGR", f"{stats['cagr']:.2%}"), 

96 ("Volatility", f"{stats['annual_volatility']:.2%}"), ("Sharpe", f"{stats['sharpe_ratio']:.2f}"), ("Sortino", f"{stats['sortino_ratio']:.2f}"), 

97 ("Max drawdown", f"{stats['max_drawdown']:.2%}"), ("Calmar", f"{stats['calmar_ratio']:.2f}"), ("Turnover / yr", f"{stats['turnover_annual']:.1f}x"), 

98 ("Cost drag / yr", f"{stats['cost_drag_bps_annual']:.0f} bps"), 

99 ] 

100 width = max(len(name) for name, _ in rows) 

101 return "\n".join([title, "-" * len(title)] + [f"{name.ljust(width)} {value}" for name, value in rows]) 

102 

103 

104def _decision_rows(weights: pd.DataFrame, rebalance_every: int) -> list[bool]: 

105 has_row = weights.notna().any(axis=1).to_numpy() 

106 step = max(int(rebalance_every), 1) 

107 out, seen = [], 0 

108 for flag in has_row: 

109 decide = False 

110 if flag: 

111 decide = seen % step == 0 

112 seen += 1 

113 out.append(bool(decide)) 

114 return out 

115 

116 

117def backtest( 

118 weights: pd.DataFrame, 

119 prices: pd.DataFrame, 

120 *, 

121 opens: pd.DataFrame | None = None, 

122 cost_model: CostModel | None = None, 

123 fill: Literal["next_open", "close"] = "next_open", 

124 initial_nav: float = 100_000.0, 

125 rebalance_every: int = 1, 

126 periods_per_year: int = 252, 

127 adv_usd: Mapping[str, float] | None = None, 

128 daily_vol: Mapping[str, float] | None = None, 

129 min_weight_change: float = 0.0, 

130) -> BacktestResult: 

131 """Run `weights` (dates x tickers, a row of all-NaN = no decision that day, NaN cell = 0) over `prices` (closes). 

132 

133 `rebalance_every=k` acts on every k-th decision row. With `fill="next_open"`, `opens` is required; a name without an open 

134 that day fills at the previous close. A name without a usable close is never sized (its units are left alone). 

135 `adv_usd` and `daily_vol` feed a cost model that needs them (square-root impact). `min_weight_change` is the live 

136 path's deadband (`portfolio.target_weights.rebalance_deltas`): a smaller change is not traded, but a zero target always 

137 closes the name.""" 

138 if fill not in ("next_open", "close"): 

139 raise ValueError("fill must be 'next_open' or 'close'") 

140 if fill == "next_open" and opens is None: 

141 raise ValueError("fill='next_open' needs opens") 

142 nav0 = float(initial_nav) 

143 if not math.isfinite(nav0) or nav0 <= 0.0: 

144 raise ValueError("initial_nav must be positive and finite") 

145 index = prices.index 

146 tickers = list(prices.columns) 

147 target = weights.reindex(index=index, columns=tickers) 

148 decide = _decision_rows(target, rebalance_every) 

149 target_values = target.fillna(0.0).to_numpy(float) 

150 closes = prices.astype(float).ffill().to_numpy(float) 

151 open_values = opens.reindex(index=index, columns=tickers).astype(float).to_numpy(float) if opens is not None else closes 

152 

153 units = np.zeros(len(tickers)) 

154 cash = nav0 

155 pending: np.ndarray | None = None 

156 nav_out = np.zeros(len(index)) 

157 gross_out = np.zeros(len(index)) 

158 turnover_out = np.zeros(len(index)) 

159 cost_out = np.zeros(len(index)) 

160 held_weights = np.zeros((len(index), len(tickers))) 

161 previous_nav = nav0 

162 

163 def value(row: int) -> float: 

164 marks = np.where(np.isfinite(closes[row]), closes[row], 0.0) 

165 return float(cash + units @ marks) 

166 

167 def trade(delta: np.ndarray, price: np.ndarray) -> tuple[float, float]: 

168 nonlocal cash 

169 traded_value = 0.0 

170 fee_total = 0.0 

171 for column in np.nonzero(delta)[0]: 

172 notional = abs(float(delta[column] * price[column])) 

173 fee = 0.0 

174 if cost_model is not None and notional > 0.0: 

175 ticker = tickers[column] 

176 bps = cost_model.cost_bps(notional, adv_usd=(adv_usd or {}).get(ticker), daily_vol=(daily_vol or {}).get(ticker)) 

177 fee = notional * (bps if math.isfinite(bps) and bps > 0.0 else 0.0) / 1e4 

178 cash -= float(delta[column] * price[column]) + fee 

179 units[column] += delta[column] 

180 traded_value += notional 

181 fee_total += fee 

182 return traded_value, fee_total 

183 

184 for row in range(len(index)): 

185 traded = fees = 0.0 

186 if pending is not None: 

187 price = np.where(np.isfinite(open_values[row]) & (open_values[row] > 0.0), open_values[row], closes[row - 1] if row > 0 else closes[row]) 

188 delta = np.where(np.isfinite(price) & (price > 0.0), pending - units, 0.0) 

189 traded, fees = trade(delta, price) 

190 pending = None 

191 nav_now = value(row) 

192 if decide[row] and nav_now > 0.0: 

193 price = closes[row] 

194 usable = np.isfinite(price) & (price > 0.0) 

195 safe_price = np.where(usable, price, 1.0) 

196 wanted = np.where(usable, target_values[row] * nav_now / safe_price, units) 

197 if min_weight_change > 0.0: 

198 current = units * safe_price / nav_now 

199 small = usable & (target_values[row] != 0.0) & (np.abs(target_values[row] - current) < float(min_weight_change)) 

200 wanted = np.where(small, units, wanted) 

201 if fill == "close": 

202 more_traded, more_fees = trade(np.where(usable, wanted - units, 0.0), price) 

203 traded, fees = traded + more_traded, fees + more_fees 

204 nav_now = value(row) 

205 else: 

206 pending = wanted 

207 nav_out[row] = nav_now 

208 marks = np.where(np.isfinite(closes[row]), closes[row], 0.0) 

209 held_weights[row] = units * marks / nav_now if nav_now > 0.0 else 0.0 

210 turnover_out[row] = traded / previous_nav if previous_nav > 0.0 else 0.0 

211 cost_out[row] = fees / previous_nav if previous_nav > 0.0 else 0.0 

212 gross_out[row] = (nav_now + fees) / previous_nav - 1.0 if previous_nav > 0.0 else 0.0 

213 previous_nav = nav_now 

214 

215 nav_series = pd.Series(nav_out, index=index, name="nav") 

216 returns = nav_series / pd.Series(np.r_[nav0, nav_out[:-1]], index=index) - 1.0 

217 return BacktestResult( 

218 returns=returns.rename("return"), gross_returns=pd.Series(gross_out, index=index, name="gross_return"), nav=nav_series, 

219 weights=pd.DataFrame(held_weights, index=index, columns=tickers), turnover=pd.Series(turnover_out, index=index, name="turnover"), 

220 costs=pd.Series(cost_out, index=index, name="cost"), periods_per_year=int(periods_per_year), 

221 ) 

222