Coverage for evaluation/backtest_audit.py: 100%

264 statements  

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

1"""Order-level audit of a finished Lean backtest (V5.5.0, Problems.md #127/#128). 

2 

3Lean's own statistics say HOW MUCH a run made; they cannot say WHAT it traded. 

4The 2026-08-27 backtest (Sharpe -2.51 against an offline book at ~+1) was only 

5explained by reading its fills by hand: equity gross ~3% of NAV, 121 of 155 

6equity entries from the old probability signal rather than the book, forex 

7sized outside the book up to 60% short, duplicate limit orders that never 

8timed out, and a Sharpe that differed by ~1.1 purely because Lean subtracts a 

9risk-free rate. This module is that reading, made repeatable: every number 

10the trace used, computed from the run folder alone (no Lean, no Docker). 

11 

12Pure functions over parsed JSON/text plus one loader, so each metric is unit 

13tested on a synthetic run (tests/test_backtest_audit.py). stdlib only. 

14""" 

15 

16from __future__ import annotations 

17 

18import itertools 

19import json 

20import math 

21import re 

22from collections import Counter, defaultdict 

23from datetime import datetime, timedelta, timezone 

24from pathlib import Path 

25 

26from evaluation.rank_signal_calibration import segment_logged_records_by_run 

27 

28# Lean enums (QuantConnect.Orders / QuantConnect.SecurityType). 

29ORDER_STATUS_FILLED = 3 

30ORDER_STATUS_CANCELED = 5 

31ORDER_TYPE_LIMIT = 1 

32SECURITY_TYPE_NAMES = {1: "equity", 2: "option", 4: "forex", 5: "future", 7: "crypto"} 

33TRADE_DIRECTION_SHORT = 1 

34 

35HOLDING_BUCKETS = ((0, 1, "0-1d"), (2, 5, "2-5d"), (6, 10, "6-10d"), (11, 15, "11-15d"), (16, 20, "16-20d")) 

36 

37 

38def _parse_time(value) -> datetime | None: 

39 """Lean writes ISO-8601 strings in orders/trades and epoch seconds in 

40 charts/order events.""" 

41 if value is None: 

42 return None 

43 if isinstance(value, (int, float)): 

44 return datetime.fromtimestamp(float(value), tz=timezone.utc) 

45 try: 

46 return datetime.fromisoformat(str(value).replace("Z", "+00:00")) 

47 except ValueError: 

48 return None 

49 

50 

51def configured_run_window(result: dict) -> tuple[datetime | None, datetime | None]: 

52 """(start, end) the run was configured for (`algorithmConfiguration`). Lean keeps charting about two days past the end, 

53 so a window label read off the last chart point names a date the run never traded.""" 

54 configuration = result.get("algorithmConfiguration") or {} 

55 return _parse_time(configuration.get("startDate")), _parse_time(configuration.get("endDate")) 

56 

57 

58def _symbol_value(order: dict) -> str: 

59 symbol = order.get("symbol") 

60 if isinstance(symbol, dict): 

61 return str(symbol.get("value", "")) 

62 return str(symbol or "") 

63 

64 

65CASH_SWEEP_CLASS = "cash_sweep" 

66 

67 

68def class_by_ticker_from_config(config: dict) -> dict[str, str]: 

69 """Upper-case ticker -> the config's asset class. The T-bill sweep ticker (`phase_v2.cash_sweep.ticker`, BIL) is its 

70 own class: it is a Lean equity, but filing it under "equity" put ~0.8 of NAV into the equity long exposure and its 

71 carry into equity P&L, overstating the book's long tilt.""" 

72 mapping = { 

73 str(asset["ticker"]).upper(): str(asset.get("asset_class") or asset.get("security_type")) 

74 for asset in config.get("phase1", {}).get("universe", {}).get("assets", []) 

75 if asset.get("ticker") and (asset.get("asset_class") or asset.get("security_type")) 

76 } 

77 sweep_ticker = config.get("phase_v2", {}).get("cash_sweep", {}).get("ticker") 

78 if sweep_ticker: 

79 mapping[str(sweep_ticker).upper()] = CASH_SWEEP_CLASS 

80 return mapping 

81 

82 

83def _asset_class(order: dict, class_by_ticker: dict[str, str] | None = None) -> str: 

84 """The config's asset class when `class_by_ticker` knows the ticker (bond ETFs are Lean equities, so the security 

85 type alone files them under "equity"), else Lean's security type.""" 

86 if class_by_ticker: 

87 configured = class_by_ticker.get(_symbol_value(order).upper()) 

88 if configured: 

89 return configured 

90 return SECURITY_TYPE_NAMES.get(int(order.get("securityType", 0) or 0), "other") 

91 

92 

93# ---------------------------------------------------------------- equity / Sharpe 

94 

95 

96def daily_equity_from_chart(result: dict) -> list[tuple[str, float]]: 

97 """(date, close equity) from the 'Strategy Equity' chart, last point per 

98 UTC day. The chart also carries intraday points, which would otherwise 

99 inflate the return count.""" 

100 series = ( 

101 result.get("charts", {}).get("Strategy Equity", {}).get("series", {}).get("Equity", {}).get("values", []) 

102 ) 

103 last_by_day: dict[str, float] = {} 

104 for point in sorted(series, key=lambda candidate: candidate[0]): 

105 timestamp = _parse_time(point[0]) 

106 close = point[-1] if isinstance(point, (list, tuple)) else None 

107 if timestamp is None or close is None: 

108 continue 

109 last_by_day[timestamp.date().isoformat()] = float(close) 

110 return sorted(last_by_day.items()) 

111 

112 

113def sharpe_from_equity( 

114 daily_equity: list[tuple[str, float]], risk_free_annual: float = 0.0, trading_days: int = 252 

115) -> float | None: 

116 """Annualized Sharpe of daily equity returns. `risk_free_annual` is 

117 subtracted per day, exactly as Lean does with its own rate - the 

118 offline simulators subtract nothing, so the same curve scores ~1.1 

119 points differently at 1.3% annual volatility. None when undefined.""" 

120 values = [equity for _, equity in daily_equity] 

121 returns = [b / a - 1.0 for a, b in itertools.pairwise(values) if a > 0.0] 

122 if len(returns) < 2: 

123 return None 

124 daily_rf = risk_free_annual / trading_days 

125 excess = [value - daily_rf for value in returns] 

126 mean = sum(excess) / len(excess) 

127 variance = sum((value - mean) ** 2 for value in excess) / (len(excess) - 1) 

128 if variance <= 0.0: 

129 return None 

130 return mean / math.sqrt(variance) * math.sqrt(trading_days) 

131 

132 

133def period_summary( 

134 result: dict, start: str, end: str, class_by_ticker: dict[str, str] | None = None, risk_free_annual: float = 0.02, 

135) -> dict: 

136 """One sub-period of a longer run (V5.8.0: BT2 spans the backtest split and the holdout, and the two are judged 

137 separately). Return and drawdown start from the last equity point before `start`; trades count by exit date; 

138 `start`/`end` are ISO dates, inclusive.""" 

139 equity = daily_equity_from_chart(result) 

140 before = [point for point in equity if point[0] < start] 

141 inside = [point for point in equity if start <= point[0] <= end] 

142 curve = before[-1:] + inside 

143 values = [value for _, value in curve] 

144 peak, max_drawdown = 0.0, 0.0 

145 for value in values: 

146 peak = max(peak, value) 

147 if peak > 0.0: 

148 max_drawdown = min(max_drawdown, value / peak - 1.0) 

149 orders = result.get("orders", {}) 

150 pnl: dict[str, float] = defaultdict(float) 

151 trades = 0 

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

153 exit_time = _parse_time(trade.get("exitTime")) 

154 if exit_time is None or not (start <= exit_time.date().isoformat() <= end): 

155 continue 

156 order_ids = trade.get("orderIds") or [] 

157 first_order = orders.get(str(order_ids[0])) if order_ids else None 

158 pnl[_asset_class(first_order, class_by_ticker) if first_order else "other"] += float(trade.get("profitLoss", 0.0) or 0.0) 

159 trades += 1 

160 return { 

161 "start": start, 

162 "end": end, 

163 "num_days": len(inside), 

164 "net_return": (values[-1] / values[0] - 1.0) if len(values) >= 2 and values[0] > 0.0 else None, 

165 "max_drawdown": max_drawdown, 

166 "sharpe_no_risk_free": sharpe_from_equity(curve, 0.0), 

167 "sharpe_with_risk_free": sharpe_from_equity(curve, risk_free_annual), 

168 "closed_trades": trades, 

169 "realized_pnl_by_class": {asset_class: round(value, 2) for asset_class, value in sorted(pnl.items())}, 

170 } 

171 

172 

173def exposure_summary(result: dict) -> dict[str, dict[str, float]]: 

174 """Mean / max / peak of each series in Lean's 'Exposure' chart (long/short 

175 ratio per asset class, fraction of NAV). Short series are NEGATIVE, so 

176 `max` is 0.0 for them and says nothing about the cap; `peak` is the value 

177 of largest magnitude (the figure to compare with a short-exposure cap).""" 

178 summary: dict[str, dict[str, float]] = {} 

179 for name, series in result.get("charts", {}).get("Exposure", {}).get("series", {}).items(): 

180 values = [float(point[1]) for point in series.get("values", []) if point[1] is not None] 

181 if values: 

182 summary[name] = {"mean": sum(values) / len(values), "max": max(values), "peak": max(values, key=abs)} 

183 return summary 

184 

185 

186# ---------------------------------------------------------------- orders 

187 

188 

189def weekday_sessions_between(created: datetime, closed: datetime) -> int: 

190 """Weekday sessions elapsed after `created` up to and including `closed`'s date. main.py counts a limit order's age 

191 in equity-session bars (`bar_index` only advances on those), so a Friday order cancelled on Wednesday is 3 sessions 

192 old although it was open 5 calendar days. Holidays are not known here (the audit allows slack for them).""" 

193 day, last, sessions = created.date() + timedelta(days=1), closed.date(), 0 

194 while day <= last: 

195 sessions += day.weekday() < 5 

196 day += timedelta(days=1) 

197 return sessions 

198 

199 

200def find_overlapping_orders( 

201 orders: dict[str, dict], max_open_days: float = 5.0, max_open_sessions: int | None = None 

202) -> dict: 

203 """Same-symbol, same-direction orders whose open windows overlap, and 

204 orders that stayed open too long: longer than `max_open_sessions` weekday sessions when given (the unit 

205 `phase_v2.limit_orders.unfilled_timeout_bars` is counted in), else longer than `max_open_days` calendar days. 

206 

207 A window runs from createdTime to the fill (lastFillTime) or the cancel. 

208 Overlap on a LIMIT order is the V5.5.0 bug: a still-unfilled entry was 

209 re-submitted every bar without cancelling the previous ticket, so several 

210 could fill (AMZN: three orders, 689 shares, ~3x target).""" 

211 windows: dict[tuple[str, int], list[tuple[datetime, datetime, str, int]]] = defaultdict(list) 

212 open_too_long: list[dict] = [] 

213 for order_id, order in orders.items(): 

214 created = _parse_time(order.get("createdTime") or order.get("time")) 

215 closed = _parse_time(order.get("lastFillTime") or order.get("canceledTime")) 

216 if created is None or closed is None: 

217 continue 

218 symbol = _symbol_value(order) 

219 direction = int(order.get("direction", 0) or 0) 

220 order_type = int(order.get("type", 0) or 0) 

221 windows[(symbol, direction)].append((created, closed, str(order_id), order_type)) 

222 open_days = (closed - created).total_seconds() / 86400.0 

223 open_sessions = weekday_sessions_between(created, closed) 

224 too_long = open_sessions > max_open_sessions if max_open_sessions is not None else open_days > max_open_days 

225 if order_type == ORDER_TYPE_LIMIT and too_long: 

226 open_too_long.append( 

227 {"symbol": symbol, "order_id": str(order_id), "open_days": round(open_days, 2), "open_sessions": open_sessions} 

228 ) 

229 

230 overlapping_pairs: list[dict] = [] 

231 for (symbol, _direction), entries in windows.items(): 

232 entries.sort() 

233 for index, (_created, closed, order_id, order_type) in enumerate(entries): 

234 for other_created, _other_closed, other_id, other_type in entries[index + 1:]: 

235 if other_created >= closed: 

236 break 

237 overlapping_pairs.append( 

238 { 

239 "symbol": symbol, 

240 "orders": [order_id, other_id], 

241 "types": [order_type, other_type], 

242 } 

243 ) 

244 limit_pairs = [pair for pair in overlapping_pairs if ORDER_TYPE_LIMIT in pair["types"]] 

245 return { 

246 "num_overlapping_pairs": len(overlapping_pairs), 

247 "num_overlapping_limit_pairs": len(limit_pairs), 

248 "overlapping_limit_pairs": limit_pairs[:50], 

249 "num_limit_orders_open_too_long": len(open_too_long), 

250 "limit_orders_open_too_long": open_too_long[:50], 

251 "max_open_days_threshold": max_open_days, 

252 "max_open_sessions_threshold": max_open_sessions, 

253 } 

254 

255 

256def carried_book_members(book_history: list[dict], on_date: str) -> frozenset[str] | None: 

257 """The book live was carrying on `on_date`: the allocations of the latest 

258 record dated <= on_date (a vetoed rebalance logs an EMPTY allocations 

259 dict, which correctly means 'no book'). None when there is no record.""" 

260 chosen = None 

261 for record in book_history: 

262 if record.get("date", "") <= on_date: 

263 chosen = record 

264 else: 

265 break 

266 if chosen is None: 

267 return None 

268 return frozenset((chosen.get("allocations") or {}).keys()) 

269 

270 

271def classify_entries( 

272 closed_trades: list[dict], orders: dict[str, dict], book_history: list[dict], 

273 class_by_ticker: dict[str, str] | None = None, 

274) -> dict: 

275 """Per asset class: how many position openings were book members, how 

276 many were non-members (the old probability signal), and how many have no 

277 book record to compare against. `closed_trades` is Lean's 

278 totalPerformance.closedTrades; the entry's decision date is the 

279 createdTime of the trade's first order.""" 

280 counts: dict[str, Counter] = defaultdict(Counter) 

281 for asset_class, bucket, _trade in _bucketed_trades(closed_trades, orders, book_history, class_by_ticker): 

282 counts[asset_class][bucket] += 1 

283 return {asset_class: dict(counter) for asset_class, counter in sorted(counts.items())} 

284 

285 

286def _bucketed_trades( 

287 closed_trades: list[dict], orders: dict[str, dict], book_history: list[dict], 

288 class_by_ticker: dict[str, str] | None = None, 

289): 

290 """(asset_class, bucket, trade) per closed trade; bucket is book_member, non_member or no_book_record.""" 

291 history = sorted(book_history, key=lambda record: record.get("date", "")) 

292 for trade in closed_trades: 

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

294 symbol = str(symbols[0].get("value", "")) if symbols else "" 

295 order_ids = trade.get("orderIds") or [] 

296 first_order = orders.get(str(order_ids[0])) if order_ids else None 

297 asset_class = _asset_class(first_order, class_by_ticker) if first_order else "other" 

298 created = _parse_time((first_order or {}).get("createdTime")) or _parse_time(trade.get("entryTime")) 

299 members = carried_book_members(history, created.date().isoformat()) if created else None 

300 if members is None: 

301 bucket = "no_book_record" 

302 elif symbol in members: 

303 bucket = "book_member" 

304 else: 

305 bucket = "non_member" 

306 yield asset_class, bucket, trade 

307 

308 

309def pnl_by_entry_bucket( 

310 closed_trades: list[dict], orders: dict[str, dict], book_history: list[dict], 

311 class_by_ticker: dict[str, str] | None = None, 

312) -> dict: 

313 """Realized P&L and fees per asset class and entry bucket - the evidence for keeping or disabling the legacy 

314 (non-book) sleeve. `net_pnl` = Lean's profitLoss minus the trade's totalFees.""" 

315 totals: dict[str, dict[str, dict[str, float]]] = defaultdict(lambda: defaultdict(lambda: defaultdict(float))) 

316 for asset_class, bucket, trade in _bucketed_trades(closed_trades, orders, book_history, class_by_ticker): 

317 cell = totals[asset_class][bucket] 

318 cell["trades"] += 1 

319 cell["realized_pnl"] += float(trade.get("profitLoss", 0.0) or 0.0) 

320 cell["fees"] += float(trade.get("totalFees", 0.0) or 0.0) 

321 return { 

322 asset_class: { 

323 bucket: { 

324 "trades": int(cell["trades"]), 

325 "realized_pnl": round(cell["realized_pnl"], 2), 

326 "fees": round(cell["fees"], 2), 

327 "net_pnl": round(cell["realized_pnl"] - cell["fees"], 2), 

328 } 

329 for bucket, cell in sorted(buckets.items()) 

330 } 

331 for asset_class, buckets in sorted(totals.items()) 

332 } 

333 

334 

335def holding_period_histogram(closed_trades: list[dict]) -> dict[str, int]: 

336 """Calendar days between entry and exit. A cluster at 14-15 days is the 

337 signature of exits blocked by `trade_cooldown_bars`.""" 

338 histogram: Counter = Counter() 

339 for trade in closed_trades: 

340 entry, exit_time = _parse_time(trade.get("entryTime")), _parse_time(trade.get("exitTime")) 

341 if entry is None or exit_time is None: 

342 continue 

343 days = (exit_time - entry).total_seconds() / 86400.0 

344 label = "21d+" 

345 for low, high, name in HOLDING_BUCKETS: 

346 if low <= days < high + 1: 

347 label = name 

348 break 

349 histogram[label] += 1 

350 return dict(histogram) 

351 

352 

353def pnl_and_fees_by_asset_class( 

354 closed_trades: list[dict], orders: dict[str, dict], order_events: list[dict], 

355 class_by_ticker: dict[str, str] | None = None, 

356) -> dict: 

357 """Realized P&L and fees per asset class, and fees in bps of traded 

358 notional per fill. Per-share fees on a mis-adjusted ~$4 price inflate 

359 this (16-49 bps per side in the 08-27 run), which is how the double 

360 split adjustment (Problems.md #128) shows up.""" 

361 class_by_symbol = {_symbol_value(order): _asset_class(order, class_by_ticker) for order in orders.values()} 

362 pnl: dict[str, float] = defaultdict(float) 

363 for trade in closed_trades: 

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

365 symbol = str(symbols[0].get("value", "")) if symbols else "" 

366 pnl[class_by_symbol.get(symbol, "other")] += float(trade.get("profitLoss", 0.0) or 0.0) 

367 

368 fees: dict[str, float] = defaultdict(float) 

369 notional: dict[str, float] = defaultdict(float) 

370 for event in order_events: 

371 if event.get("status") != "filled": 

372 continue 

373 asset_class = class_by_symbol.get(str(event.get("symbolValue", "")), "other") 

374 fees[asset_class] += float(event.get("orderFeeAmount", 0.0) or 0.0) 

375 notional[asset_class] += abs(float(event.get("fillPrice", 0.0) or 0.0) * float(event.get("fillQuantity", 0.0) or 0.0)) 

376 return { 

377 asset_class: { 

378 "realized_pnl": round(pnl.get(asset_class, 0.0), 2), 

379 "fees": round(fees.get(asset_class, 0.0), 2), 

380 "fee_bps_per_fill": ( 

381 round(fees[asset_class] / notional[asset_class] * 1e4, 2) if notional.get(asset_class) else None 

382 ), 

383 } 

384 for asset_class in sorted(set(pnl) | set(fees)) 

385 } 

386 

387 

388# ---------------------------------------------------------------- book history / logs 

389 

390 

391def summarize_book_history(book_history: list[dict], start_date: str | None, end_date: str | None) -> dict: 

392 """Gate vetoes and the fate of book members over the run's date window 

393 (book_history.jsonl accumulates across runs, so it must be windowed).""" 

394 records = [ 

395 record 

396 for record in book_history 

397 if (start_date is None or record.get("date", "") >= start_date) 

398 and (end_date is None or record.get("date", "") <= end_date) 

399 ] 

400 veto_reasons = Counter(record.get("gate_veto_reason") or "none" for record in records if not record.get("allocations")) 

401 decisions: Counter = Counter() 

402 decision_reasons: Counter = Counter() 

403 for record in records: 

404 for decision in (record.get("book_member_decisions") or {}).values(): 

405 decisions[str(decision.get("action", "unknown"))] += 1 

406 for reason in decision.get("reasons", []) or []: 

407 decision_reasons[str(reason).split("=")[0]] += 1 

408 return { 

409 "num_rebalance_records": len(records), 

410 "num_engaged": sum(1 for record in records if record.get("allocations")), 

411 "veto_reasons": dict(veto_reasons), 

412 "member_decision_actions": dict(decisions), 

413 "member_decision_top_reasons": dict(decision_reasons.most_common(10)), 

414 } 

415 

416 

417def member_book_runs(config: dict) -> bool: 

418 """Whether a run with this config builds the member book and its rolling-IC gate. A target-weights run (from a file or 

419 the model book) returns before them in `main.py`'s on_data, so book_history.jsonl holds none of its records, and its 

420 latest segment belongs to an older run (#410).""" 

421 target_weights = (config.get("phase_v2") or {}).get("target_weights") or {} 

422 return not bool(target_weights.get("enabled", False)) 

423 

424 

425BOOK_NOT_APPLICABLE = { 

426 "applicable": False, 

427 "reason": "target-weights run: main.py trades the weights and never builds the member book or its rolling-IC gate", 

428} 

429 

430 

431def teardown_status(engine_log_text: str) -> dict: 

432 """Did Lean's embedded interpreter shut down cleanly? Read from the ENGINE 

433 log (`<run>/log.txt`), never the algorithm log - #104 was wrongly marked 

434 clean from `<id>-log.txt`, which never records the teardown.""" 

435 return { 

436 "shutdown_ended": bool(re.search(r"PythonInitializer\.Shutdown\(\): ended", engine_log_text)), 

437 "timed_out": "Operation timed out" in engine_log_text, 

438 "failed_to_shutdown_python": "Failed to shutdown python" in engine_log_text, 

439 } 

440 

441 

442# ---------------------------------------------------------------- orchestration 

443 

444 

445def load_backtest_run(run_dir: Path) -> dict: 

446 """Reads a Lean run folder. Missing optional files degrade to empty.""" 

447 run_dir = Path(run_dir) 

448 candidates = [ 

449 path 

450 for path in run_dir.glob("*.json") 

451 if re.fullmatch(r"\d+", path.stem) 

452 ] 

453 if not candidates: 

454 raise FileNotFoundError(f"no Lean result JSON (<id>.json) in {run_dir}") 

455 result_path = candidates[0] 

456 events_path = run_dir / f"{result_path.stem}-order-events.json" 

457 engine_log = run_dir / "log.txt" 

458 return { 

459 "result": json.loads(result_path.read_text(encoding="utf-8")), 

460 "order_events": json.loads(events_path.read_text(encoding="utf-8")) if events_path.exists() else [], 

461 "engine_log": engine_log.read_text(encoding="utf-8", errors="replace") if engine_log.exists() else "", 

462 "run_id": result_path.stem, 

463 } 

464 

465 

466def load_book_history(path: Path) -> list[dict]: 

467 """The cumulative `book_history.jsonl` plus, when `phase_v2.diagnostics.book_history.per_run_files` is on, the 

468 per-run files next to it (`book_history/<run_id>.jsonl`, oldest first). `path` may also be that directory.""" 

469 path = Path(path) 

470 files: list[Path] = [] 

471 if path.is_file(): 

472 files.append(path) 

473 per_run_dir = path if path.is_dir() else path.with_suffix("") 

474 if per_run_dir.is_dir(): 

475 files.extend(sorted(per_run_dir.glob("*.jsonl"))) 

476 records = [] 

477 for file in files: 

478 for line in file.read_text(encoding="utf-8").splitlines(): 

479 line = line.strip() 

480 if not line: 

481 continue 

482 try: 

483 records.append(json.loads(line)) 

484 except ValueError: 

485 continue 

486 # File order is run order (appended per run, per-run files sorted by their start stamp); 

487 # callers segment it with segment_logged_records_by_run(). 

488 return records 

489 

490 

491def select_run_book_history(book_history: list[dict], run_index: int = -1) -> list[dict]: 

492 """book_history.jsonl accumulates EVERY backtest's records, so one date 

493 recurs across many runs (160 of 174 dates did, one in 8 runs - #99). 

494 Returns one run's records, date-sorted; run_index=-1 is the latest.""" 

495 segments = segment_logged_records_by_run(book_history) 

496 if not segments: 

497 return [] 

498 try: 

499 segment = segments[run_index] 

500 except IndexError: 

501 return [] 

502 return sorted(segment, key=lambda record: record.get("date", "")) 

503 

504 

505def audit_backtest_run( 

506 run: dict, 

507 book_history: list[dict], 

508 *, 

509 risk_free_annual: float = 0.02, 

510 max_open_days: float = 5.0, 

511 book_run_index: int = -1, 

512 max_open_sessions: int | None = None, 

513 class_by_ticker: dict[str, str] | None = None, 

514 periods: list[tuple[str, str]] | None = None, 

515 member_book: bool = True, 

516) -> dict: 

517 """The full audit. `run` is load_backtest_run()'s dict; `book_history` 

518 is the raw (multi-run) log, of which `book_run_index` selects one run. `class_by_ticker` (upper-case ticker -> 

519 config asset class) splits bonds out of "equity" and crypto/forex by config. `member_book=False` (member_book_runs() 

520 of the run's config) ignores the book history, which then belongs to another run.""" 

521 book_history = select_run_book_history(book_history, book_run_index) if member_book else [] 

522 result = run["result"] 

523 orders = result.get("orders", {}) 

524 closed_trades = result.get("totalPerformance", {}).get("closedTrades", []) 

525 equity = daily_equity_from_chart(result) 

526 start_date = equity[0][0] if equity else None 

527 end_date = equity[-1][0] if equity else None 

528 audit = { 

529 "run_id": run.get("run_id"), 

530 "window": {"start": start_date, "end": end_date, "num_days": len(equity)}, 

531 "lean_statistics": { 

532 key: result.get("statistics", {}).get(key) 

533 for key in ("Sharpe Ratio", "Net Profit", "Drawdown", "Total Orders", "Total Fees") 

534 }, 

535 "sharpe": { 

536 "no_risk_free": sharpe_from_equity(equity, 0.0), 

537 "with_risk_free": sharpe_from_equity(equity, risk_free_annual), 

538 "risk_free_annual_assumed": risk_free_annual, 

539 }, 

540 "exposure": exposure_summary(result), 

541 "entries_by_asset_class": classify_entries(closed_trades, orders, book_history, class_by_ticker), 

542 "pnl_by_entry_bucket": pnl_by_entry_bucket(closed_trades, orders, book_history, class_by_ticker), 

543 "orders": find_overlapping_orders(orders, max_open_days=max_open_days, max_open_sessions=max_open_sessions), 

544 "holding_period_days": holding_period_histogram(closed_trades), 

545 "pnl_and_fees": pnl_and_fees_by_asset_class(closed_trades, orders, run.get("order_events", []), class_by_ticker), 

546 "book": summarize_book_history(book_history, start_date, end_date) if member_book else dict(BOOK_NOT_APPLICABLE), 

547 "teardown": teardown_status(run.get("engine_log", "")), 

548 } 

549 if periods: 

550 audit["periods"] = [ 

551 period_summary(result, period_start, period_end, class_by_ticker, risk_free_annual) 

552 for period_start, period_end in periods 

553 ] 

554 return audit