Coverage for evaluation/backtest_statistics.py: 100%

432 statements  

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

1"""Backtest statistics of one finished Lean run (V6.3.0): the metric set of López de Prado, *Advances in Financial 

2Machine Learning*, ch. 14, computed from the run folder alone and rendered as the README's "Backtest Statistics". 

3 

4Two return streams are reported side by side: 

5 * **portfolio**: Lean's own equity curve; 

6 * **strategy**: the same curve without the T-bill cash sweep's P&L (`phase_v2.cash_sweep`), so idle-cash carry is not 

7 read as alpha. 

8Bet-level numbers (bets, hit ratio, holding period, long share) exclude the sweep ticker: buying T-bills is not a bet. 

9 

10The metric functions are pure (lists / arrays in, finite floats or None out); `compute_backtest_statistics` assembles 

11them from the parsers that already exist (`backtest_audit`, `lean_attribution`, `lean_statistics`, `fill_price_audit`). 

12A metric that cannot be computed is a row with `value None` and a `reason`, never a fabricated number. 

13""" 

14 

15from __future__ import annotations 

16 

17import bisect 

18import itertools 

19import json 

20import math 

21from collections import defaultdict 

22from datetime import date as date_type 

23from pathlib import Path 

24from statistics import NormalDist 

25from typing import TYPE_CHECKING, Any 

26 

27import numpy as np 

28 

29from json_safety import sanitize_json_finite 

30 

31if TYPE_CHECKING: 

32 from collections.abc import Iterable, Mapping, Sequence 

33 

34 from numpy.typing import ArrayLike 

35 

36DAYS_PER_YEAR = 365 

37EULER_GAMMA = 0.5772156649015329 

38_NORMAL = NormalDist() 

39 

40 

41# ---------------------------------------------------------------- pure metric functions 

42 

43 

44def _finite(value) -> float | None: 

45 try: 

46 value = float(value) 

47 except (TypeError, ValueError): 

48 return None 

49 return value if math.isfinite(value) else None 

50 

51 

52def hhi_concentration(values: ArrayLike) -> float | None: 

53 """AFML 14.6 `getHHI`: concentration of `values` (all one sign) normalised to [0, 1]; 0 = evenly spread, 1 = all in 

54 one observation. None for two or fewer observations.""" 

55 weights = np.abs(np.asarray([value for value in values if value is not None], dtype=float)) 

56 n = len(weights) 

57 if n <= 2 or weights.sum() <= 0.0: 

58 return None 

59 weights = weights / weights.sum() 

60 hhi = float((weights**2).sum()) 

61 return _finite((hhi - 1.0 / n) / (1.0 - 1.0 / n)) 

62 

63 

64def drawdown_episodes(dates: list[str], equity: list[float]) -> list[dict]: 

65 """AFML 14.7 `computeDD_TuW` on an equity curve: one episode per high-watermark that is followed by a loss, with its 

66 depth (fraction of the watermark), the watermark and recovery dates and the time under water in calendar days. The 

67 last episode is `open` when the curve never regained its watermark.""" 

68 episodes: list[dict] = [] 

69 if len(equity) < 2: 

70 return episodes 

71 hwm, hwm_date, trough = equity[0], dates[0], equity[0] 

72 for day, value in zip(dates[1:], equity[1:], strict=False): 

73 if value > hwm: 

74 if trough < hwm: 

75 episodes.append(_episode(hwm, hwm_date, trough, day, open_episode=False)) 

76 hwm, hwm_date, trough = value, day, value 

77 else: 

78 trough = min(trough, value) 

79 if trough < hwm: 

80 episodes.append(_episode(hwm, hwm_date, trough, dates[-1], open_episode=True)) 

81 return episodes 

82 

83 

84def _episode(hwm: float, start: str, trough: float, end: str, *, open_episode: bool) -> dict[str, Any]: 

85 return { 

86 "start": start, 

87 "end": end, 

88 "depth": (1.0 - trough / hwm) if hwm > 0.0 else 0.0, 

89 "days_under_water": (date_type.fromisoformat(end) - date_type.fromisoformat(start)).days, 

90 "open": open_episode, 

91 } 

92 

93 

94def percentile(values: ArrayLike, q: float) -> float | None: 

95 """The q-th percentile of the finite values; None when there are none.""" 

96 values = [value for value in values if value is not None and math.isfinite(value)] 

97 return _finite(np.percentile(values, q)) if values else None 

98 

99 

100def daily_returns(equity: list[float]) -> list[float]: 

101 """Period returns of an equity curve, skipping steps from a non-positive value.""" 

102 return [after / before - 1.0 for before, after in itertools.pairwise(equity) if before > 0.0] 

103 

104 

105def sharpe_ratio(returns: ArrayLike, periods_per_year: int = DAYS_PER_YEAR) -> float | None: 

106 """Annualised mean / sample std of per-period returns, no risk-free rate.""" 

107 values = np.asarray(returns, dtype=float) 

108 if len(values) < 2 or values.std(ddof=1) <= 0.0: 

109 return None 

110 return _finite(values.mean() / values.std(ddof=1) * math.sqrt(periods_per_year)) 

111 

112 

113def information_ratio(returns: ArrayLike, benchmark_returns: ArrayLike, periods_per_year: int = DAYS_PER_YEAR) -> float | None: 

114 """Annualised mean / std of the active return (strategy minus benchmark, same periods).""" 

115 active = np.asarray(returns, dtype=float) - np.asarray(benchmark_returns, dtype=float) 

116 if len(active) < 2 or active.std(ddof=1) <= 0.0: 

117 return None 

118 return _finite(active.mean() / active.std(ddof=1) * math.sqrt(periods_per_year)) 

119 

120 

121def _skew_kurtosis(values: np.ndarray) -> tuple[float, float]: 

122 """Sample skewness and (non-excess) kurtosis, population moments as in Bailey & López de Prado (2012).""" 

123 centred = values - values.mean() 

124 std = centred.std() 

125 if std <= 0.0: 

126 return 0.0, 3.0 

127 return float((centred**3).mean() / std**3), float((centred**4).mean() / std**4) 

128 

129 

130def probabilistic_sharpe_ratio(returns: ArrayLike, benchmark_sharpe_per_period: float = 0.0) -> float | None: 

131 """PSR (Bailey & López de Prado 2012): P(true Sharpe > benchmark) given the sample's length, skew and kurtosis. Both 

132 Sharpe ratios are per period (not annualised).""" 

133 values = np.asarray(returns, dtype=float) 

134 n = len(values) 

135 if n < 3 or values.std(ddof=1) <= 0.0: 

136 return None 

137 sharpe = values.mean() / values.std(ddof=1) 

138 skew, kurtosis = _skew_kurtosis(values) 

139 denominator = 1.0 - skew * sharpe + (kurtosis - 1.0) / 4.0 * sharpe**2 

140 if denominator <= 0.0: 

141 return None 

142 return _finite(_NORMAL.cdf((sharpe - benchmark_sharpe_per_period) * math.sqrt(n - 1) / math.sqrt(denominator))) 

143 

144 

145def expected_max_sharpe(num_trials: int, trial_sharpe_variance: float) -> float | None: 

146 """SR0 of the deflated Sharpe ratio: the expected maximum Sharpe of `num_trials` unskilled trials whose Sharpe ratios 

147 have variance `trial_sharpe_variance` (same units as the returned value).""" 

148 if num_trials < 2 or trial_sharpe_variance is None or trial_sharpe_variance <= 0.0: 

149 return None 

150 quantile_a = _NORMAL.inv_cdf(1.0 - 1.0 / num_trials) 

151 quantile_b = _NORMAL.inv_cdf(1.0 - 1.0 / (num_trials * math.e)) 

152 return _finite(math.sqrt(trial_sharpe_variance) * ((1.0 - EULER_GAMMA) * quantile_a + EULER_GAMMA * quantile_b)) 

153 

154 

155def deflated_sharpe_ratio(returns: ArrayLike, trial_annual_sharpes: list[float], periods_per_year: int = DAYS_PER_YEAR) -> dict[str, Any]: 

156 """DSR (Bailey & López de Prado 2014): PSR against SR0, the best Sharpe expected from the number of configurations 

157 tried. Trial Sharpes are annual; they are moved to this series' period (÷ sqrt(periods_per_year)) first.""" 

158 trials = [value for value in (_finite(item) for item in trial_annual_sharpes) if value is not None] 

159 if len(trials) < 2: 

160 return {"value": None, "num_trials": len(trials), "reason": "fewer than 2 registered trials"} 

161 variance_annual = float(np.var(trials, ddof=1)) 

162 sr0_annual = expected_max_sharpe(len(trials), variance_annual) 

163 if sr0_annual is None: 

164 return {"value": None, "num_trials": len(trials), "reason": "trial Sharpe ratios have no variance"} 

165 value = probabilistic_sharpe_ratio(returns, sr0_annual / math.sqrt(periods_per_year)) 

166 return { 

167 "value": value, "num_trials": len(trials), "trial_sharpe_variance_annual": variance_annual, 

168 "expected_max_sharpe_annual": sr0_annual, "reason": None if value is not None else "return series too short or flat", 

169 } 

170 

171 

172def classification_scores(y_true: ArrayLike, y_pred: ArrayLike, probabilities: ArrayLike | None=None) -> dict[str, Any]: 

173 """Accuracy, precision, recall, F1 of binary calls (1 = up / long), and the negative log-loss when probabilities of 

174 class 1 exist (higher is better; 0 is a perfect forecaster, -0.693 a coin flip).""" 

175 truth = np.asarray(y_true, dtype=int) 

176 predicted = np.asarray(y_pred, dtype=int) 

177 n = len(truth) 

178 if n == 0: 

179 return {"n": 0} 

180 tp = int(((predicted == 1) & (truth == 1)).sum()) 

181 fp = int(((predicted == 1) & (truth == 0)).sum()) 

182 fn = int(((predicted == 0) & (truth == 1)).sum()) 

183 precision = tp / (tp + fp) if tp + fp else None 

184 recall = tp / (tp + fn) if tp + fn else None 

185 f1 = 2 * precision * recall / (precision + recall) if precision and recall else (0.0 if precision == 0.0 or recall == 0.0 else None) 

186 scores = { 

187 "n": n, 

188 "accuracy": float((predicted == truth).mean()), 

189 "precision": precision, 

190 "recall": recall, 

191 "f1": f1, 

192 "positive_rate": float(predicted.mean()), 

193 "neg_log_loss": None, 

194 } 

195 if probabilities is not None: 

196 clipped = np.clip(np.asarray(probabilities, dtype=float), 1e-15, 1.0 - 1e-15) 

197 scores["neg_log_loss"] = _finite(np.mean(truth * np.log(clipped) + (1 - truth) * np.log(1.0 - clipped))) 

198 return scores 

199 

200 

201def bet_starts(positions_by_date: dict[str, dict[str, float]]) -> list[tuple[str, str, int]]: 

202 """(date, ticker, side) each time a position leaves zero or flips sign (AFML 14.2's definition of a bet).""" 

203 previous: dict[str, float] = {} 

204 starts = [] 

205 for day in sorted(positions_by_date): 

206 for ticker, quantity in sorted(positions_by_date[day].items()): 

207 before = previous.get(ticker, 0.0) 

208 if quantity != 0.0 and (before == 0.0 or (before > 0.0) != (quantity > 0.0)): 

209 starts.append((day, ticker, 1 if quantity > 0.0 else -1)) 

210 previous[ticker] = quantity 

211 return starts 

212 

213 

214def monthly_counts(days: list[str], first: str, last: str) -> list[int]: 

215 """Bets per calendar month from `first` to `last`, months without a bet included as zeros.""" 

216 counts: dict[str, int] = defaultdict(int) 

217 for day in days: 

218 counts[day[:7]] += 1 

219 year, month = int(first[:4]), int(first[5:7]) 

220 out = [] 

221 while f"{year:04d}-{month:02d}" <= last[:7]: 

222 out.append(counts.get(f"{year:04d}-{month:02d}", 0)) 

223 month += 1 

224 if month > 12: 

225 year, month = year + 1, 1 

226 return out 

227 

228 

229def _duration_days(text: str | None) -> float | None: 

230 """Lean's 'd.hh:mm:ss' / 'hh:mm:ss' trade duration in days.""" 

231 if not text: 

232 return None 

233 head, _, rest = str(text).partition(":") 

234 days = "0" 

235 if "." in head: 

236 days, head = head.split(".", 1) 

237 try: 

238 hours, minutes, seconds = (float(part) for part in f"{head}:{rest}".split(":")) 

239 return float(days) + (hours + minutes / 60.0 + seconds / 3600.0) / 24.0 

240 except ValueError: 

241 return None 

242 

243 

244# ---------------------------------------------------------------- assembly 

245 

246 

247def _row(metric: str, portfolio=None, strategy=None, fmt: str = "num", reason: str | None = None) -> dict[str, Any]: 

248 return {"metric": metric, "portfolio": portfolio, "strategy": strategy, "format": fmt, "reason": reason} 

249 

250 

251def _asof(series: dict[str, float], sorted_dates: list[str], day: str) -> float | None: 

252 position = bisect.bisect_right(sorted_dates, day) - 1 

253 return series[sorted_dates[position]] if position >= 0 else None 

254 

255 

256def _daily_chart_series(result: dict[str, Any], chart: str, series: str) -> dict[str, float]: 

257 """Last point per UTC day of one chart series (the same rule as `backtest_audit.daily_equity_from_chart`).""" 

258 from evaluation.backtest_audit import _parse_time 

259 

260 points = result.get("charts", {}).get(chart, {}).get("series", {}).get(series, {}).get("values", []) 

261 out: dict[str, float] = {} 

262 for point in sorted(points, key=lambda item: item[0]): 

263 stamp = _parse_time(point[0]) 

264 value = _finite(point[-1]) 

265 if stamp is not None and value is not None: 

266 out[stamp.date().isoformat()] = value 

267 return out 

268 

269 

270def _interval_sums(daily: dict[str, float], equity_dates: list[str]) -> list[float]: 

271 """Each value of `daily` added to the first equity date on or after its own date, then listed per equity return 

272 (dates[1:]); values before the first equity date land on the first return.""" 

273 sums = [0.0] * len(equity_dates) 

274 for day, value in daily.items(): 

275 position = min(bisect.bisect_left(equity_dates, day), len(equity_dates) - 1) 

276 sums[max(position, 1)] += value 

277 return sums[1:] 

278 

279 

280def _numbers(stats: dict[str, Any], key: str) -> float | None: 

281 """A Lean statistics string ('16.848%', '$1210.90', '0.082') as a float in its own unit.""" 

282 raw = stats.get(key) 

283 if raw is None: 

284 return None 

285 text = str(raw).replace("$", "").replace(",", "").replace("%", "").strip() 

286 return _finite(text) 

287 

288 

289def compute_backtest_statistics( 

290 run: dict[str, Any], 

291 config: dict[str, Any], 

292 root: Path, 

293 *, 

294 run_name: str, 

295 book_history: list[dict] | None = None, 

296 trial_annual_sharpes: list[float] | None = None, 

297 offline_classification: dict[str, dict] | None = None, 

298 lean_basis: dict[str, Any] | None = None, 

299 attribution: dict[str, Any] | None = None, 

300) -> dict[str, Any]: 

301 """Every section of the README's "Backtest Statistics" for one loaded run (`backtest_audit.load_backtest_run`). 

302 `lean_basis` is `lean_statistics.statistics_table` output, `attribution` `lean_attribution.attribute_run` output; both 

303 optional. Pure apart from reading the Lean data zips under `root` for closes and opens.""" 

304 from evaluation.backtest_audit import CASH_SWEEP_CLASS, class_by_ticker_from_config, configured_run_window, daily_equity_from_chart 

305 from evaluation.fill_price_audit import fills_from_run, zip_opens_for_fills 

306 from evaluation.lean_attribution import closes_for_universe, daily_ticker_pnl, fills_from_order_events, quote_to_usd_rate 

307 

308 result = run["result"] 

309 stats = result.get("statistics", {}) or {} 

310 days_per_year = int((config.get("runtime", {}) or {}).get("trading_days_per_year", DAYS_PER_YEAR) or DAYS_PER_YEAR) 

311 class_by_ticker = class_by_ticker_from_config(config) 

312 sweep = {ticker for ticker, kind in class_by_ticker.items() if kind == CASH_SWEEP_CLASS} 

313 forex = {ticker for ticker, kind in class_by_ticker.items() if kind == "forex"} 

314 

315 equity_points = daily_equity_from_chart(result) 

316 dates = [day for day, _ in equity_points] 

317 nav = [value for _, value in equity_points] 

318 if len(nav) < 3: 

319 return {"run": run_name, "status": "no equity curve"} 

320 calendar_days = max((date_type.fromisoformat(dates[-1]) - date_type.fromisoformat(dates[0])).days, 1) 

321 years = calendar_days / 365.0 

322 

323 fills = fills_from_order_events(run.get("order_events", [])) 

324 closes = closes_for_universe(config, root, {fill.ticker for fill in fills}) 

325 sorted_closes = {ticker: sorted(series) for ticker, series in closes.items()} 

326 ticker_pnl = daily_ticker_pnl(fills, closes, dates, forex) 

327 

328 # ---- the two return streams 

329 portfolio_returns = daily_returns(nav) 

330 sweep_net_by_day = { 

331 day: sum(entry["pnl"] - entry["fee"] for ticker, entry in tickers.items() if ticker in sweep) 

332 for day, tickers in ticker_pnl.items() 

333 } 

334 sweep_per_return = _interval_sums(sweep_net_by_day, dates) 

335 strategy_pnl = [(after - before) - carry for before, after, carry in zip(nav, nav[1:], sweep_per_return, strict=False)] 

336 strategy_returns = [pnl / before for pnl, before in zip(strategy_pnl, nav, strict=False) if before > 0.0] 

337 strategy_curve = [nav[0]] 

338 for pnl in strategy_pnl: 

339 strategy_curve.append(strategy_curve[-1] + pnl) 

340 sweep_net_total = float(sum(sweep_per_return)) 

341 

342 # ---- positions, notionals, bets 

343 nav_by_date = dict(zip(dates, nav, strict=False)) 

344 positions_ex_sweep: dict[str, dict[str, float]] = {} 

345 gross_all, gross_ex, max_position = [], [], (0.0, None, None) 

346 notional_all = notional_ex = fees_all = fees_ex = 0.0 

347 for day in sorted(ticker_pnl): 

348 exposure_all = exposure_ex = 0.0 

349 held = {} 

350 for ticker, entry in ticker_pnl[day].items(): 

351 notional_all += entry["notional"] 

352 fees_all += entry["fee"] 

353 if ticker not in sweep: 

354 notional_ex += entry["notional"] 

355 fees_ex += entry["fee"] 

356 held[ticker] = entry["position"] 

357 close = _asof(closes.get(ticker, {}), sorted_closes.get(ticker, []), day) 

358 if close is None or entry["position"] == 0.0: 

359 continue 

360 rate = quote_to_usd_rate(ticker, day, closes, sorted_closes) if ticker in forex else 1.0 

361 value = abs(entry["position"] * close * rate) 

362 exposure_all += value 

363 if ticker not in sweep: 

364 exposure_ex += value 

365 if value > max_position[0]: 

366 max_position = (value, ticker, day) 

367 positions_ex_sweep[day] = held 

368 if day in nav_by_date and nav_by_date[day] > 0.0: 

369 gross_all.append(exposure_all / nav_by_date[day]) 

370 gross_ex.append(exposure_ex / nav_by_date[day]) 

371 bets = bet_starts(positions_ex_sweep) 

372 average_aum = float(np.mean(nav)) 

373 

374 # ---- closed trades (bets with an exit), sweep excluded 

375 trades = [] 

376 for trade in result.get("totalPerformance", {}).get("closedTrades", []) or []: 

377 symbols = trade.get("symbols") or [] 

378 ticker = str(symbols[0].get("value", "")).upper() if symbols else "" 

379 if ticker in sweep: 

380 continue 

381 entry_day = str(trade.get("entryTime", ""))[:10] 

382 rate = quote_to_usd_rate(ticker, entry_day, closes, sorted_closes) if ticker in forex else 1.0 

383 entry_notional = abs(float(trade.get("entryPrice", 0.0) or 0.0) * float(trade.get("quantity", 0.0) or 0.0)) * rate 

384 net = float(trade.get("profitLoss", 0.0) or 0.0) - float(trade.get("totalFees", 0.0) or 0.0) 

385 trades.append({ 

386 "ticker": ticker, "long": int(trade.get("direction", 0) or 0) == 0, "net": net, 

387 "return": net / entry_notional if entry_notional > 0.0 else None, 

388 "days": _duration_days(trade.get("duration")), "notional": entry_notional, 

389 }) 

390 hits = [trade for trade in trades if trade["net"] > 0.0] 

391 misses = [trade for trade in trades if trade["net"] <= 0.0] 

392 weighted_days = [(trade["days"], trade["notional"]) for trade in trades if trade["days"] is not None and trade["notional"] > 0.0] 

393 

394 # (portfolio, strategy, benchmark) return per equity date on which the benchmark has both ends 

395 benchmark = _daily_chart_series(result, "Benchmark", "Benchmark") 

396 benchmark_flat = len({benchmark[day] for day in dates if day in benchmark}) <= 1 

397 paired = [] 

398 for index in range(1, len(dates)): 

399 before, after = benchmark.get(dates[index - 1]), benchmark.get(dates[index]) 

400 if before and after and index - 1 < len(strategy_returns): 

401 paired.append((portfolio_returns[index - 1], strategy_returns[index - 1], after / before - 1.0)) 

402 paired_array = np.asarray(paired, dtype=float).reshape(-1, 3) 

403 

404 def _benchmark_correlation(column: int) -> float | None: 

405 if benchmark_flat or len(paired_array) < 3 or paired_array[:, column].std() <= 0 or paired_array[:, 2].std() <= 0: 

406 return None 

407 return _finite(np.corrcoef(paired_array[:, column], paired_array[:, 2])[0, 1]) 

408 

409 pnl_total = nav[-1] - nav[0] 

410 total_return = nav[-1] / nav[0] - 1.0 

411 strategy_total = strategy_curve[-1] / strategy_curve[0] - 1.0 

412 cagr = (1.0 + total_return) ** (365.0 / calendar_days) - 1.0 

413 strategy_cagr = (1.0 + strategy_total) ** (365.0 / calendar_days) - 1.0 if strategy_total > -1.0 else None 

414 long_net = sum(trade["net"] for trade in trades if trade["long"]) 

415 short_net = sum(trade["net"] for trade in trades if not trade["long"]) 

416 

417 configured_start, configured_end = configured_run_window(result) 

418 general = [ 

419 _row("Time range", f"{(configured_start.date().isoformat() if configured_start else dates[0])} to " 

420 f"{(configured_end.date().isoformat() if configured_end else dates[-1])}", None, "text"), 

421 _row("Years", years, None, "num2"), 

422 _row("Average AUM", average_aum, None, "usd"), 

423 _row("Capacity (Lean estimate)", _numbers(stats, "Estimated Strategy Capacity"), None, "usd", 

424 reason=f"lowest-capacity asset {stats.get('Lowest Capacity Asset', 'n/a')}"), 

425 _row("Leverage, mean (gross exposure / NAV)", _finite(np.mean(gross_all)) if gross_all else None, 

426 _finite(np.mean(gross_ex)) if gross_ex else None, "x"), 

427 _row("Leverage, max", _finite(max(gross_all)) if gross_all else None, _finite(max(gross_ex)) if gross_ex else None, "x"), 

428 _row("Maximum dollar position", None, max_position[0] or None, "usd", 

429 reason=f"{max_position[1]} on {max_position[2]}" if max_position[1] else "no position"), 

430 _row("Ratio of longs (share of bets)", None, (sum(1 for bet in bets if bet[2] > 0) / len(bets)) if bets else None, "pct"), 

431 _row("Longs : shorts (bets)", None, f"{sum(1 for bet in bets if bet[2] > 0)} : {sum(1 for bet in bets if bet[2] < 0)}", "text"), 

432 _row("Frequency of bets (per year)", None, len(bets) / years if bets else None, "num1"), 

433 _row("Average holding period (days, notional-weighted)", None, 

434 (sum(days * weight for days, weight in weighted_days) / sum(weight for _, weight in weighted_days)) if weighted_days else None, "num1"), 

435 _row("Annualized turnover (traded notional / AUM)", notional_all / average_aum / years, notional_ex / average_aum / years, "x"), 

436 _row("Correlation to underlying (SPY, daily)", _benchmark_correlation(0), _benchmark_correlation(1), 

437 "num3", reason="flat benchmark feed" if benchmark_flat else None), 

438 _row("Start equity", _numbers(stats, "Start Equity"), None, "usd"), 

439 _row("End equity", _numbers(stats, "End Equity"), None, "usd"), 

440 _row("Total orders", _numbers(stats, "Total Orders"), None, "int"), 

441 _row("Lean portfolio turnover (daily mean)", _numbers(stats, "Portfolio Turnover"), None, "pct_raw"), 

442 ] 

443 

444 performance = [ 

445 _row("PnL", pnl_total, pnl_total - sweep_net_total, "usd_signed"), 

446 _row("PnL from the T-bill sweep (carry)", sweep_net_total, None, "usd_signed"), 

447 _row("PnL from long positions (closed bets, net of fees)", None, long_net, "usd_signed"), 

448 _row("PnL from short positions (closed bets, net of fees)", None, short_net, "usd_signed"), 

449 _row("Annualized rate of return", cagr, strategy_cagr, "pct_signed"), 

450 _row("Hit ratio (closed bets net of fees)", None, len(hits) / len(trades) if trades else None, "pct"), 

451 _row("Average return from hits", None, _finite(np.mean([t["return"] for t in hits if t["return"] is not None])) if hits else None, "pct_signed"), 

452 _row("Average return from misses", None, _finite(np.mean([t["return"] for t in misses if t["return"] is not None])) if misses else None, "pct_signed"), 

453 _row("Time-weighted return (no external flows: the chained return)", float(np.prod([1.0 + r for r in portfolio_returns]) - 1.0), 

454 strategy_total, "pct_signed"), 

455 _row("Net profit (Lean)", _numbers(stats, "Net Profit"), None, "pct_raw"), 

456 _row("Win rate / loss rate (Lean, all trades)", f"{stats.get('Win Rate', 'n/a')} / {stats.get('Loss Rate', 'n/a')}", None, "text"), 

457 _row("Average win / average loss (Lean)", f"{stats.get('Average Win', 'n/a')} / {stats.get('Average Loss', 'n/a')}", None, "text"), 

458 _row("Profit-loss ratio (Lean)", _numbers(stats, "Profit-Loss Ratio"), None, "num2"), 

459 _row("Expectancy (Lean)", _numbers(stats, "Expectancy"), None, "num3"), 

460 _row("Unrealized at the end (Lean)", _numbers(result.get("runtimeStatistics", {}) or {}, "Unrealized"), None, "usd_signed"), 

461 ] 

462 

463 episodes = drawdown_episodes(dates, nav) 

464 strategy_episodes = drawdown_episodes(dates, strategy_curve) 

465 trade_stats = result.get("totalPerformance", {}).get("tradeStatistics", {}) or {} 

466 runs = [ 

467 _row("HHI of positive returns", hhi_concentration([r for r in portfolio_returns if r > 0.0]), 

468 hhi_concentration([r for r in strategy_returns if r > 0.0]), "num3"), 

469 _row("HHI of negative returns", hhi_concentration([r for r in portfolio_returns if r < 0.0]), 

470 hhi_concentration([r for r in strategy_returns if r < 0.0]), "num3"), 

471 _row("HHI of time between bets (bets per month)", None, hhi_concentration(monthly_counts([bet[0] for bet in bets], dates[0], dates[-1])) if bets else None, "num3"), 

472 _row("95-percentile drawdown", percentile([e["depth"] for e in episodes], 95), percentile([e["depth"] for e in strategy_episodes], 95), "pct"), 

473 _row("95-percentile time under water (days)", percentile([e["days_under_water"] for e in episodes], 95), 

474 percentile([e["days_under_water"] for e in strategy_episodes], 95), "num1"), 

475 _row("Maximum drawdown", max((e["depth"] for e in episodes), default=0.0), max((e["depth"] for e in strategy_episodes), default=0.0), "pct"), 

476 _row("Longest time under water (days)", max((e["days_under_water"] for e in episodes), default=0), 

477 max((e["days_under_water"] for e in strategy_episodes), default=0), "int"), 

478 _row("Drawdown episodes", len(episodes), len(strategy_episodes), "int"), 

479 _row("Drawdown (Lean)", _numbers(stats, "Drawdown"), None, "pct_raw"), 

480 _row("Drawdown recovery (Lean, days)", _numbers(stats, "Drawdown Recovery"), None, "int"), 

481 _row("Maximum drawdown duration (Lean)", trade_stats.get("maximumDrawdownDuration"), None, "text"), 

482 ] 

483 

484 run_fills = fills_from_run(run) 

485 zip_opens = zip_opens_for_fills(run_fills, Path(root) / "data") 

486 slippage_all = slippage_ex = covered_all = covered_ex = 0.0 

487 missing = 0 

488 for fill in run_fills: 

489 reference = zip_opens.get((fill["symbol"], fill["date"])) 

490 ticker = fill["symbol"].upper() 

491 rate = quote_to_usd_rate(ticker, fill["date"], closes, sorted_closes) if ticker in forex else 1.0 

492 notional = abs(fill["price"] * fill.get("quantity", 0.0)) * rate 

493 if reference is None or reference <= 0.0 or notional <= 0.0: 

494 missing += 1 

495 continue 

496 cost = fill["direction"] * (fill["price"] - reference) / reference * notional 

497 slippage_all += cost 

498 covered_all += notional 

499 if ticker not in sweep: 

500 slippage_ex += cost 

501 covered_ex += notional 

502 strategy_net = pnl_total - sweep_net_total 

503 shortfall = [ 

504 _row("Traded notional", notional_all, notional_ex, "usd"), 

505 _row("Broker fees", fees_all, fees_ex, "usd"), 

506 _row("Broker fees per turnover (bps of traded notional)", fees_all / notional_all * 1e4 if notional_all else None, 

507 fees_ex / notional_ex * 1e4 if notional_ex else None, "bps"), 

508 _row("Average slippage per turnover (bps vs the bar's open)", slippage_all / covered_all * 1e4 if covered_all else None, 

509 slippage_ex / covered_ex * 1e4 if covered_ex else None, "bps", 

510 reason=f"{missing} fills without a reference open" if missing else None), 

511 _row("Dollar performance per turnover (bps)", pnl_total / notional_all * 1e4 if notional_all else None, 

512 strategy_net / notional_ex * 1e4 if notional_ex else None, "bps"), 

513 _row("Return on execution costs (net PnL / (fees + slippage))", 

514 pnl_total / (fees_all + slippage_all) if fees_all + slippage_all > 0.0 else None, 

515 strategy_net / (fees_ex + slippage_ex) if fees_ex + slippage_ex > 0.0 else None, "x"), 

516 _row("Total fees (Lean)", _numbers(stats, "Total Fees"), None, "usd"), 

517 ] 

518 

519 strategy_dsr = deflated_sharpe_ratio(strategy_returns, trial_annual_sharpes or [], days_per_year) 

520 portfolio_dsr = deflated_sharpe_ratio(portfolio_returns, trial_annual_sharpes or [], days_per_year) 

521 has_benchmark = len(paired_array) > 2 and not benchmark_flat 

522 efficiency = [ 

523 _row("Annualized Sharpe ratio (Lean: risk-free rate subtracted)", _numbers(stats, "Sharpe Ratio"), None, "num3"), 

524 _row("Annualized Sharpe ratio (no risk-free rate)", sharpe_ratio(portfolio_returns, days_per_year), sharpe_ratio(strategy_returns, days_per_year), "num3"), 

525 _row("Information ratio vs SPY", 

526 information_ratio(paired_array[:, 0], paired_array[:, 2], days_per_year) if has_benchmark else None, 

527 information_ratio(paired_array[:, 1], paired_array[:, 2], days_per_year) if has_benchmark else None, 

528 "num3", reason="flat benchmark feed" if benchmark_flat else None), 

529 _row("Information ratio (Lean)", _numbers(stats, "Information Ratio"), None, "num3"), 

530 _row("Probabilistic Sharpe ratio (P[true Sharpe > 0])", probabilistic_sharpe_ratio(portfolio_returns), probabilistic_sharpe_ratio(strategy_returns), "pct"), 

531 _row("Probabilistic Sharpe ratio (Lean, vs its benchmark)", _numbers(stats, "Probabilistic Sharpe Ratio"), None, "pct_raw"), 

532 _row("Deflated Sharpe ratio", portfolio_dsr["value"], strategy_dsr["value"], "pct", 

533 reason=(f"{strategy_dsr['num_trials']} registered trials, expected best Sharpe {strategy_dsr['expected_max_sharpe_annual']:.2f}" 

534 if strategy_dsr.get("expected_max_sharpe_annual") is not None else strategy_dsr.get("reason"))), 

535 _row("Sortino ratio (Lean)", _numbers(stats, "Sortino Ratio"), None, "num3"), 

536 _row("Alpha / beta (Lean)", f"{stats.get('Alpha', 'n/a')} / {stats.get('Beta', 'n/a')}", None, "text"), 

537 _row("Annual standard deviation (Lean)", _numbers(stats, "Annual Standard Deviation"), None, "num3"), 

538 _row("Annual variance (Lean)", _numbers(stats, "Annual Variance"), None, "num4"), 

539 _row("Tracking error (Lean)", _numbers(stats, "Tracking Error"), None, "num3"), 

540 _row("Treynor ratio (Lean)", _numbers(stats, "Treynor Ratio"), None, "num3"), 

541 ] 

542 for label, row in ((lean_basis or {}).get("replica") or {}).items(): 

543 efficiency.append(_row(f"Sharpe, Lean formula ({label})", _finite(row.get("sharpe_ratio")), None, "num3")) 

544 

545 classification = _classification_section(book_history, closes, sorted_closes, offline_classification) 

546 attribution_section = _attribution_section(ticker_pnl, dates, nav, class_by_ticker, years, average_aum, days_per_year, attribution) 

547 

548 return sanitize_json_finite({ 

549 "run": run_name, 

550 "status": "OK", 

551 "window": {"start": dates[0], "end": dates[-1], "days": calendar_days}, 

552 "sections": { 

553 "general": general, "performance": performance, "runs": runs, "shortfall": shortfall, 

554 "efficiency": efficiency, "classification": classification, "attribution": attribution_section, 

555 }, 

556 }) 

557 

558 

559def _forward_return(series: dict[str, float], sorted_dates: list[str], day: str, horizon: int) -> float | None: 

560 position = bisect.bisect_right(sorted_dates, day) - 1 

561 if position < 0 or position + horizon >= len(sorted_dates): 

562 return None 

563 start, end = series[sorted_dates[position]], series[sorted_dates[position + horizon]] 

564 return end / start - 1.0 if start > 0.0 else None 

565 

566 

567LEAN_PROBABILITY_SOURCE = "direction_prob_multitask" 

568 

569 

570def lean_book_calls(book_history: Iterable[Mapping[str, Any]] | None, closes: Mapping[str, Mapping[str, float]], sorted_closes: Mapping[str, Sequence[str]], horizon: int = 20, source: str = LEAN_PROBABILITY_SOURCE) -> dict[str, Any]: 

571 """The Lean run's book calls as aligned lists: side (1 = long) vs the sign of the ticker's own `horizon`-bar forward 

572 move, plus the logged probability of "up" (`source` in the record's `member_probabilities`, V6.4.0) where there is one. 

573 `dates` / `tickers` identify each call so an offline score can be matched to it.""" 

574 calls = {"truth": [], "predicted": [], "probability": [], "dates": [], "tickers": []} 

575 for record in book_history or []: 

576 member_probabilities = record.get("member_probabilities") or {} 

577 for ticker, allocation in (record.get("allocations") or {}).items(): 

578 role = str((allocation or {}).get("role", "")).lower() 

579 name = str(ticker).upper() 

580 series = closes.get(name) 

581 if role not in ("long", "short") or not series: 

582 continue 

583 forward = _forward_return(series, sorted_closes[name], record.get("date", ""), horizon) 

584 if forward is None or forward == 0.0: 

585 continue 

586 probability = (member_probabilities.get(ticker) or {}).get(source) 

587 calls["truth"].append(1 if forward > 0.0 else 0) 

588 calls["predicted"].append(1 if role == "long" else 0) 

589 calls["probability"].append(float(probability) if isinstance(probability, (int, float)) and math.isfinite(probability) else None) 

590 calls["dates"].append(record.get("date", "")) 

591 calls["tickers"].append(name) 

592 return calls 

593 

594 

595def _classification_section(book_history, closes, sorted_closes, offline: dict[str, dict] | None, horizon: int = 20) -> list[dict]: 

596 """One row per source: the Lean run's book calls (side vs the sign of the ticker's own 20-bar forward return, with 

597 a log-loss when the run logged the head's probability) and the offline direction_20d heads (written by 

598 `aq evaluate --classification`).""" 

599 rows = [] 

600 calls = lean_book_calls(book_history, closes, sorted_closes, horizon) 

601 truth = calls["truth"] 

602 lean_scores = classification_scores(truth, calls["predicted"]) if truth else {"n": 0} 

603 with_probability = [index for index, value in enumerate(calls["probability"]) if value is not None] 

604 reason = "no book history for this run" 

605 if truth and len(with_probability) == len(truth): 

606 lean_scores = classification_scores(truth, calls["predicted"], calls["probability"]) 

607 reason = None 

608 elif truth: 

609 reason = "no probability is logged per book call" if not with_probability else ( 

610 f"probability logged for {len(with_probability)} of {len(truth)} calls") 

611 label = "Lean book calls (side vs 20-bar forward move" + ( 

612 f"; log-loss of the logged {LEAN_PROBABILITY_SOURCE})" if reason is None else ")") 

613 rows.append({"source": label, **lean_scores, "reason": reason}) 

614 for model, scores in sorted((offline or {}).items()): 

615 rows.append({"source": f"Offline {model} direction_20d (backtest split, threshold {scores.get('threshold', 0.5)})", 

616 **{key: scores.get(key) for key in ("n", "accuracy", "precision", "recall", "f1", "positive_rate", "neg_log_loss")}, 

617 "reason": None}) 

618 return rows 

619 

620 

621def _attribution_section(ticker_pnl, dates, nav, class_by_ticker, years, average_aum, days_per_year, attribution) -> dict[str, Any]: 

622 """Risk and return per asset class (the sweep is its own class), plus Lean-attribution components when given.""" 

623 daily_by_class: dict[str, dict[str, float]] = defaultdict(lambda: defaultdict(float)) 

624 fees_by_class: dict[str, float] = defaultdict(float) 

625 for day, tickers in ticker_pnl.items(): 

626 for ticker, entry in tickers.items(): 

627 asset_class = class_by_ticker.get(ticker, "equity") 

628 daily_by_class[asset_class][day] += entry["pnl"] - entry["fee"] 

629 fees_by_class[asset_class] += entry["fee"] 

630 per_class = {name: np.asarray(_interval_sums(days, dates)) for name, days in daily_by_class.items()} 

631 nav_before = np.asarray(nav[:-1], dtype=float) 

632 total = sum(per_class.values()) if per_class else np.zeros(len(nav) - 1) 

633 total_variance = float(np.var(total / nav_before, ddof=1)) if len(nav_before) > 1 else 0.0 

634 rows = [] 

635 for name in sorted(per_class): 

636 pnl = per_class[name] 

637 returns = pnl / nav_before 

638 cumulative = np.cumsum(pnl) 

639 peak = np.maximum.accumulate(np.concatenate([[0.0], cumulative]))[1:] 

640 std = float(returns.std(ddof=1)) if len(returns) > 1 else 0.0 

641 rows.append({ 

642 "class": name, 

643 "net_pnl": float(pnl.sum()), 

644 "annual_return_on_aum": float(pnl.sum()) / average_aum / years, 

645 "annual_volatility": std * math.sqrt(days_per_year), 

646 "sharpe": _finite(returns.mean() / std * math.sqrt(days_per_year)) if std > 0.0 else None, 

647 "max_drawdown_on_aum": float((peak - cumulative).max()) / average_aum if len(cumulative) else 0.0, 

648 "risk_share": _finite(np.cov(returns, total / nav_before, ddof=1)[0, 1] / total_variance) if total_variance > 0.0 else None, 

649 "fees": fees_by_class[name], 

650 }) 

651 lean_net = nav[-1] - nav[0] 

652 components = [] 

653 for name, entry in sorted(((attribution or {}).get("components") or {}).items()): 

654 if entry.get("fills") or entry.get("pnl"): 

655 components.append({"component": name, "net_pnl": entry.get("net"), "fees": entry.get("fee"), "fills": entry.get("fills")}) 

656 return { 

657 "classes": rows, 

658 "unattributed_pnl": lean_net - float(sum(row["net_pnl"] for row in rows)), 

659 "components": components, 

660 } 

661 

662 

663# ---------------------------------------------------------------- I/O wrapper 

664 

665 

666def load_trial_sharpes(registry_path: Path) -> list[float]: 

667 """Annual Sharpe ratios of every registered research trial (`scripts/build_trial_registry.py`).""" 

668 try: 

669 payload = json.loads(Path(registry_path).read_text(encoding="utf-8")) 

670 except (OSError, ValueError): 

671 return [] 

672 return [trial["median_sharpe"] for trial in payload.get("trials", []) if _finite(trial.get("median_sharpe")) is not None] 

673 

674 

675def _benchmark_section(run: dict[str, Any], config: dict[str, Any], root: Path) -> list[dict]: 

676 """The run's portfolio and strategy against SPY, 60/40, Bitcoin and its own coins, on one calendar (`evaluation/lean_benchmarks.py`).""" 

677 import pandas as pd 

678 

679 from evaluation.alpha_proof import benchmark_daily_returns, strategy_daily_returns, to_sessions 

680 from evaluation.backtest_audit import class_by_ticker_from_config, daily_equity_from_chart 

681 from evaluation.lean_attribution import fills_from_order_events 

682 from evaluation.lean_benchmarks import benchmark_rows 

683 

684 points = daily_equity_from_chart(run["result"]) 

685 if len(points) < 3: 

686 return [] 

687 classes = class_by_ticker_from_config(config) 

688 crypto = sorted({fill.ticker for fill in fills_from_order_events(run.get("order_events", [])) if classes.get(fill.ticker) == "crypto"}) 

689 start, end = points[0][0], points[-1][0] 

690 benchmarks = benchmark_daily_returns(root, config, ("SPY", "AGG", "BTCUSD", *[coin for coin in crypto if coin != "BTCUSD"]), start=start, end=end) 

691 if benchmarks.empty: 

692 return [] 

693 nav = pd.Series(dict(points), dtype=float).sort_index() 

694 portfolio = to_sessions(nav.pct_change(fill_method=None).dropna(), benchmarks.index) 

695 strategy = to_sessions(strategy_daily_returns(run, config, root), benchmarks.index) 

696 return sanitize_json_finite(benchmark_rows(portfolio, strategy, benchmarks, crypto)) 

697 

698 

699def compute_for_run_dir(run_dir: Path, config: dict[str, Any], root: Path) -> dict[str, Any]: 

700 """`aq evaluate --backtest-stats`: load the run folder and its companions, then compute every section.""" 

701 from evaluation.backtest_audit import load_backtest_run 

702 from evaluation.lean_attribution import attribute_run, find_book_history_for_run, run_config_path 

703 from evaluation.lean_statistics import statistics_table 

704 

705 run_dir = Path(run_dir) 

706 root = Path(root) 

707 run = load_backtest_run(run_dir) 

708 snapshot = run_config_path(run_dir, root) 

709 run_config = json.loads(snapshot.read_text(encoding="utf-8")) if snapshot else config 

710 history_path = find_book_history_for_run(run_dir, root / "visualization" / "book_history") 

711 history = [] 

712 if history_path is not None: 

713 history = [json.loads(line) for line in history_path.read_text(encoding="utf-8").splitlines() if line.strip()] 

714 evaluation_dir = root / "ml" / "evaluation" 

715 offline = {} 

716 for model in ("multitask", "sequence"): 

717 path = evaluation_dir / f"classification_scores_{model}.json" 

718 if path.exists(): 

719 try: 

720 offline[model] = json.loads(path.read_text(encoding="utf-8")) 

721 except ValueError: 

722 pass 

723 lean_basis = None 

724 result_path = next((path for path in run_dir.glob("*.json") if path.stem.isdigit()), None) 

725 rate_files = {"shipped rate file, 365 days": root / "data" / "alternative" / "interest-rate" / "usa" / "interest-rate.csv"} 

726 if result_path is not None and all(path.exists() for path in rate_files.values()): 

727 try: 

728 table = statistics_table(result_path, {"shipped rate file": rate_files["shipped rate file, 365 days"]}, (365,)) 

729 lean_basis = table 

730 except (OSError, ValueError, KeyError, ZeroDivisionError): 

731 lean_basis = None 

732 attribution = attribute_run(run, history, run_config, root) if history else None 

733 stats = compute_backtest_statistics( 

734 run, run_config, root, run_name=run_dir.name, book_history=history, 

735 trial_annual_sharpes=load_trial_sharpes(evaluation_dir / "trial_registry.json"), 

736 offline_classification=offline, lean_basis=lean_basis, attribution=attribution, 

737 ) 

738 stats["sections"]["benchmarks"] = _benchmark_section(run, run_config, root) 

739 stats["book_history"] = str(history_path) if history_path else None 

740 stats["config"] = str(snapshot) if snapshot else "config.json" 

741 return stats