Coverage for evaluation/lean_attribution.py: 100%

296 statements  

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

1"""Daily P&L of a finished Lean run, rebuilt per ticker and per component (V6.0.0, todo lead 2). 

2 

3The offline as-live simulator is only useful if it predicts what Lean does, and V5.8.0's BT1 showed a daily return 

4correlation of 0.02 between them. This module rebuilds the Lean side in the simulator's own terms so the two can be 

5compared day by day: 

6 

7 * every fill from `<id>-order-events.json` (signed quantity, price, fee, limit or market), 

8 * end-of-day positions and their mark-to-market P&L against the Lean data zips' daily closes (forex P&L converted from 

9 the quote currency to USD with the zips' own rates), 

10 * each ticker-day assigned to a component: the main book (members of the last FORMED book in the book-history log; 

11 live holds the book through a vetoed rebalance), the legacy signal (an equity/crypto position outside it), the bond 

12 and forex sleeves (by config asset class), crypto split into the core pairs and the capped graduates (a crypto 

13 position outside the book is `legacy_crypto`), 

14 * per rebalance date, what the live gates decided (engaged / vetoed and why) for the decision-agreement check. 

15 

16A daily fill's event time is the END of the bar it filled in (equity 16:00 New York = 20:00 UTC, crypto and forex the 

17next 00:00 UTC), so its bar date is the UTC date one second earlier. Pure functions plus thin zip/JSON readers. 

18""" 

19 

20from __future__ import annotations 

21 

22import bisect 

23import itertools 

24import zipfile 

25from collections import defaultdict 

26from dataclasses import dataclass 

27from datetime import datetime, timezone 

28from pathlib import Path 

29 

30LEAN_EQUITY_PRICE_SCALE = 1.0 / 10_000.0 

31COMPONENTS = ("main_book", "legacy", "legacy_crypto", "bond_sleeve", "forex_sleeve", "crypto_core", "crypto_graduate", "cash_sweep") 

32 

33 

34@dataclass(frozen=True) 

35class Fill: 

36 date: str 

37 ticker: str 

38 quantity: float 

39 price: float 

40 fee: float 

41 is_limit: bool 

42 

43 

44def fills_from_order_events(events: list[dict]) -> list[Fill]: 

45 """Filled (or partially filled) events in time order; quantity is signed (buy > 0).""" 

46 fills = [] 

47 for event in sorted(events, key=lambda item: (float(item.get("time", 0.0)), int(item.get("orderEventId", 0) or 0))): 

48 if str(event.get("status", "")).lower() not in {"filled", "partiallyfilled"}: 

49 continue 

50 quantity = float(event.get("fillQuantity") or 0.0) 

51 price = float(event.get("fillPrice") or 0.0) 

52 if quantity == 0.0 or price <= 0.0: 

53 continue 

54 bar_end = datetime.fromtimestamp(float(event["time"]) - 1.0, tz=timezone.utc) 

55 fills.append( 

56 Fill( 

57 date=bar_end.date().isoformat(), 

58 ticker=str(event.get("symbolValue") or event.get("symbol", "")).upper(), 

59 quantity=quantity, 

60 price=price, 

61 fee=abs(float(event.get("orderFeeAmount") or 0.0)), 

62 is_limit=event.get("limitPrice") not in (None, 0, 0.0), 

63 ) 

64 ) 

65 return fills 

66 

67 

68def read_daily_closes(zip_path: Path, price_scale: float = 1.0) -> dict[str, float]: 

69 """{YYYY-MM-DD: close} of a Lean daily zip (missing file -> {}).""" 

70 path = Path(zip_path) 

71 if not path.exists(): 

72 return {} 

73 closes: dict[str, float] = {} 

74 with zipfile.ZipFile(path) as archive: 

75 member = next((name for name in archive.namelist() if name.endswith(".csv")), None) 

76 if member is None: 

77 return {} 

78 for line in archive.read(member).decode("utf-8", errors="replace").splitlines(): 

79 fields = line.split(",") 

80 if len(fields) < 5 or len(fields[0]) < 8: 

81 continue 

82 try: 

83 closes[f"{fields[0][:4]}-{fields[0][4:6]}-{fields[0][6:8]}"] = float(fields[4]) * price_scale 

84 except ValueError: 

85 continue 

86 return closes 

87 

88 

89def closes_for_universe(config: dict, root: Path, tickers: set[str], *, data_dir: str = "data") -> dict[str, dict[str, float]]: 

90 """Daily closes of `tickers` (plus the forex rates needed to convert quote currencies) from their config zips, under 

91 the run's own data root. An asset's `data_path` always begins with `data/`.""" 

92 assets = {str(asset["ticker"]).upper(): asset for asset in config["phase1"]["universe"]["assets"]} 

93 sweep = (config.get("phase_v2", {}) or {}).get("cash_sweep") or {} 

94 if sweep.get("ticker") and sweep.get("data_path"): # V6.2.0: the T-bill sweep is outside the universe 

95 assets.setdefault(str(sweep["ticker"]).upper(), {"security_type": "equity", "data_path": sweep["data_path"]}) 

96 wanted = set(tickers) 

97 for ticker in tickers: 

98 if assets.get(ticker, {}).get("security_type") == "forex": 

99 wanted.update(name for name in assets if assets[name].get("security_type") == "forex") 

100 closes = {} 

101 for ticker in wanted: 

102 asset = assets.get(ticker) 

103 if asset is None: 

104 continue 

105 scale = LEAN_EQUITY_PRICE_SCALE if asset.get("security_type") == "equity" else 1.0 

106 closes[ticker] = read_daily_closes(Path(root) / data_dir / Path(*Path(asset["data_path"]).parts[1:]), scale) 

107 return closes 

108 

109 

110def _value_asof(series: dict[str, float], sorted_dates: list[str], date: str) -> float | None: 

111 position = bisect.bisect_right(sorted_dates, date) - 1 

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

113 

114 

115def quote_to_usd_rate(ticker: str, date: str, closes: dict[str, dict[str, float]], sorted_dates: dict[str, list[str]]) -> float: 

116 """USD per one unit of a forex pair's quote currency on `date` (1.0 for XXXUSD and every non-forex ticker).""" 

117 if len(ticker) != 6 or ticker.endswith("USD"): 

118 return 1.0 

119 quote = ticker[3:] 

120 direct, inverse = f"{quote}USD", f"USD{quote}" 

121 if direct in closes: 

122 value = _value_asof(closes[direct], sorted_dates[direct], date) 

123 return float(value) if value else 1.0 

124 if inverse in closes: 

125 value = _value_asof(closes[inverse], sorted_dates[inverse], date) 

126 return 1.0 / float(value) if value else 1.0 

127 return 1.0 

128 

129 

130def daily_ticker_pnl( 

131 fills: list[Fill], closes: dict[str, dict[str, float]], dates: list[str], forex_tickers: set[str] = frozenset() 

132) -> dict[str, dict[str, dict]]: 

133 """{date: {ticker: {"pnl": gross USD P&L, "fee": USD, "position": end-of-day quantity, "fills": n, "limit_fills": n, 

134 "notional": traded USD}}} over `dates` (sorted). A position carried into a date earns quantity x (close - previous 

135 close); a fill earns quantity x (close - fill price) on its own date. Prices missing on a date carry the last one.""" 

136 sorted_dates = {ticker: sorted(series) for ticker, series in closes.items()} 

137 fills_by_date: dict[str, list[Fill]] = defaultdict(list) 

138 for fill in fills: 

139 fills_by_date[fill.date].append(fill) 

140 positions: dict[str, float] = defaultdict(float) 

141 last_close: dict[str, float] = {} 

142 out: dict[str, dict[str, dict]] = {} 

143 wanted_dates = set(dates) 

144 calendar = sorted(wanted_dates | set(fills_by_date)) 

145 for date in calendar: 

146 day: dict[str, dict] = {} 

147 tickers = {ticker for ticker, quantity in positions.items() if quantity != 0.0} | {fill.ticker for fill in fills_by_date.get(date, [])} 

148 for ticker in tickers: 

149 series = closes.get(ticker, {}) 

150 close = series.get(date) 

151 if close is None: 

152 close = _value_asof(series, sorted_dates.get(ticker, []), date) if series else None 

153 rate = quote_to_usd_rate(ticker, date, closes, sorted_dates) if ticker in forex_tickers else 1.0 

154 entry = {"pnl": 0.0, "fee": 0.0, "position": 0.0, "fills": 0, "limit_fills": 0, "notional": 0.0} 

155 held = positions[ticker] 

156 if held != 0.0 and close is not None and ticker in last_close: 

157 entry["pnl"] += held * (close - last_close[ticker]) * rate 

158 for fill in fills_by_date.get(date, []): 

159 if fill.ticker != ticker: 

160 continue 

161 if close is not None: 

162 entry["pnl"] += fill.quantity * (close - fill.price) * rate 

163 entry["fee"] += fill.fee 

164 entry["fills"] += 1 

165 entry["limit_fills"] += int(fill.is_limit) 

166 entry["notional"] += abs(fill.quantity * fill.price) * rate 

167 positions[ticker] += fill.quantity 

168 if abs(positions[ticker]) < 1e-12: 

169 positions[ticker] = 0.0 

170 entry["position"] = positions[ticker] 

171 if close is not None: 

172 last_close[ticker] = close 

173 day[ticker] = entry 

174 if date in wanted_dates or day: 

175 out[date] = day 

176 return out 

177 

178 

179def formed_book_by_date(book_history: list[dict], dates: list[str]) -> dict[str, frozenset[str]]: 

180 """Members of the last FORMED (non-empty) book on or before each date; live holds it through a vetoed rebalance.""" 

181 records = sorted((record for record in book_history if record.get("allocations")), key=lambda record: record["date"]) 

182 record_dates = [record["date"] for record in records] 

183 out = {} 

184 for date in dates: 

185 position = bisect.bisect_right(record_dates, date) - 1 

186 out[date] = frozenset(records[position]["allocations"]) if position >= 0 else frozenset() 

187 return out 

188 

189 

190def component_of(ticker: str, asset_class: str, members: frozenset[str], core_crypto: set[str]) -> str: 

191 if asset_class == "cash_sweep": 

192 return "cash_sweep" 

193 if asset_class == "bond": 

194 return "bond_sleeve" 

195 if asset_class == "forex": 

196 return "forex_sleeve" 

197 if asset_class == "crypto": 

198 if ticker not in members: 

199 return "legacy_crypto" 

200 return "crypto_core" if ticker in core_crypto else "crypto_graduate" 

201 return "main_book" if ticker in members else "legacy" 

202 

203 

204def opener_members_by_date( 

205 ticker_pnl: dict[str, dict[str, dict]], members_by_date: dict[str, frozenset[str]] 

206) -> dict[str, frozenset[str]]: 

207 """Per date, the tickers the BOOK owns: members of the book in force that day plus held positions that were opened 

208 while their ticker was a member. A member that leaves the book stays the book's until the position is closed (live 

209 exits it by rotation / age / stop, not as a legacy trade); a position opened outside the book stays legacy until the 

210 book adopts the ticker. Opening = flat (or the opposite sign) at the previous day's end, non-zero at this day's end.""" 

211 owned: dict[str, frozenset[str]] = {} 

212 opened_as_member: dict[str, bool] = {} 

213 previous_position: dict[str, float] = {} 

214 for date in sorted(ticker_pnl): 

215 members = members_by_date.get(date, frozenset()) 

216 for ticker, entry in ticker_pnl[date].items(): 

217 before = previous_position.get(ticker, 0.0) 

218 after = float(entry.get("position", 0.0)) 

219 if after == 0.0: 

220 opened_as_member.pop(ticker, None) 

221 elif before == 0.0 or (before > 0.0) != (after > 0.0): 

222 opened_as_member[ticker] = ticker in members 

223 previous_position[ticker] = after 

224 owned[date] = members | frozenset(ticker for ticker, flag in opened_as_member.items() if flag) 

225 return owned 

226 

227 

228def component_daily_pnl( 

229 ticker_pnl: dict[str, dict[str, dict]], class_by_ticker: dict[str, str], members_by_date: dict[str, frozenset[str]], 

230 core_crypto: set[str], *, by_opener: bool = True, 

231) -> dict[str, dict[str, dict]]: 

232 """{date: {component: {"pnl", "fee", "fills", "limit_fills", "notional"}}}. By default a position belongs to the 

233 component that opened it (opener_members_by_date); `by_opener=False` assigns it by the book in force each day, so a 

234 former member still held counts as legacy (the V6.0.0 view).""" 

235 if by_opener: 

236 members_by_date = opener_members_by_date(ticker_pnl, members_by_date) 

237 out: dict[str, dict[str, dict]] = {} 

238 for date, day in ticker_pnl.items(): 

239 members = members_by_date.get(date, frozenset()) 

240 components: dict[str, dict] = {} 

241 for ticker, entry in day.items(): 

242 name = component_of(ticker, class_by_ticker.get(ticker, "equity"), members, core_crypto) 

243 bucket = components.setdefault(name, {"pnl": 0.0, "fee": 0.0, "fills": 0, "limit_fills": 0, "notional": 0.0}) 

244 for key in bucket: 

245 bucket[key] += entry[key] 

246 out[date] = components 

247 return out 

248 

249 

250def rebalance_decisions(book_history: list[dict], start: str | None = None, end: str | None = None) -> dict[str, dict]: 

251 """{date: {"engaged": bool, "reason": veto reason or None, "members": n}} for each live rebalance record in the window 

252 (warm-up records whose universe was not ready are dropped: they carry `thin_universe_or_zero_top_n`).""" 

253 out = {} 

254 for record in sorted(book_history, key=lambda item: item.get("date", "")): 

255 date = record.get("date", "") 

256 if (start and date < start) or (end and date > end): 

257 continue 

258 reason = record.get("gate_veto_reason") 

259 out[date] = {"engaged": bool(record.get("allocations")), "reason": reason, "members": len(record.get("allocations") or {})} 

260 return out 

261 

262 

263def fee_bps_by_route(ticker_pnl: dict[str, dict[str, dict]], class_by_ticker: dict[str, str], fills: list[Fill], 

264 closes_rate=None) -> dict[str, dict]: 

265 """Per asset class and route (limit / market): fills, fees and fee per traded notional in bps.""" 

266 totals: dict[str, dict] = defaultdict(lambda: {"fills": 0, "fee": 0.0, "notional": 0.0}) 

267 for fill in fills: 

268 key = f"{class_by_ticker.get(fill.ticker, 'equity')}/{'limit' if fill.is_limit else 'market'}" 

269 bucket = totals[key] 

270 bucket["fills"] += 1 

271 bucket["fee"] += fill.fee 

272 rate = closes_rate(fill) if closes_rate else 1.0 

273 bucket["notional"] += abs(fill.quantity * fill.price) * rate 

274 return { 

275 key: dict(value, fee_bps=(value["fee"] / value["notional"] * 1e4) if value["notional"] else None) 

276 for key, value in sorted(totals.items()) 

277 } 

278 

279 

280def reconcile_with_equity_curve(component_pnl: dict[str, dict[str, dict]], daily_equity: list[tuple[str, float]]) -> dict: 

281 """Rebuilt net P&L against Lean's own equity curve: total difference and the correlation of daily changes.""" 

282 import numpy as np 

283 

284 rebuilt = {date: sum(entry["pnl"] - entry["fee"] for entry in day.values()) for date, day in component_pnl.items()} 

285 lean = {date: equity - previous for (_, previous), (date, equity) in itertools.pairwise(daily_equity)} 

286 common = sorted(set(rebuilt) & set(lean)) 

287 total_rebuilt = sum(rebuilt.values()) 

288 total_lean = daily_equity[-1][1] - daily_equity[0][1] if len(daily_equity) > 1 else 0.0 

289 correlation = None 

290 if len(common) > 2: 

291 a = np.array([rebuilt[date] for date in common]) 

292 b = np.array([lean[date] for date in common]) 

293 if a.std() > 0 and b.std() > 0: 

294 correlation = float(np.corrcoef(a, b)[0, 1]) 

295 return {"rebuilt_net_usd": total_rebuilt, "lean_net_usd": total_lean, "difference_usd": total_rebuilt - total_lean, 

296 "daily_change_correlation": correlation, "days_compared": len(common)} 

297 

298 

299def equity_at(result: dict, moment: datetime) -> float | None: 

300 """Lean's portfolio value at the last chart point at or before `moment` (UTC).""" 

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

302 stamp = moment.timestamp() 

303 best = None 

304 for point in points: 

305 if float(point[0]) <= stamp and (best is None or float(point[0]) >= float(best[0])): 

306 best = point 

307 return float(best[-1]) if best is not None else None 

308 

309 

310def lean_period_net(result: dict, start: str, end: str) -> float | None: 

311 """Lean's net P&L over the bars dated start..end: the 00:00 UTC chart points bracket every class's bars (equity closes 

312 at 20:00 UTC, a crypto/forex bar ends at 00:00 UTC), so a period edge never splits a bar.""" 

313 from datetime import timedelta 

314 

315 opening = equity_at(result, datetime.fromisoformat(start).replace(tzinfo=timezone.utc)) 

316 closing = equity_at(result, datetime.fromisoformat(end).replace(tzinfo=timezone.utc) + timedelta(days=1)) 

317 if opening is None or closing is None: 

318 return None 

319 return closing - opening 

320 

321 

322def attribute_run( 

323 run: dict, book_history: list[dict], config: dict, root: Path, *, period: tuple[str, str] | None = None, 

324 core_crypto: set[str] | None = None, 

325) -> dict: 

326 """The whole attribution for one loaded run (`evaluation.backtest_audit.load_backtest_run`).""" 

327 from evaluation.backtest_audit import daily_equity_from_chart 

328 

329 class_by_ticker = { 

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

331 for asset in config["phase1"]["universe"]["assets"] 

332 } 

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

334 if sweep_ticker: 

335 class_by_ticker.setdefault(str(sweep_ticker).upper(), "cash_sweep") 

336 if core_crypto is None: 

337 caps = (config.get("phase_v2", {}).get("class_weight_caps", {}) or {}).get("crypto", {}) or {} 

338 core_crypto = {str(ticker).upper() for ticker in caps.get("exempt", [])} 

339 fills = fills_from_order_events(run["order_events"]) 

340 daily_equity = daily_equity_from_chart(run["result"]) 

341 dates = [date for date, _ in daily_equity] # the whole run: a period is cut AFTER the marks are rebuilt 

342 tickers = {fill.ticker for fill in fills} 

343 closes = closes_for_universe(config, root, tickers) 

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

345 ticker_pnl = full_ticker_pnl = daily_ticker_pnl(fills, closes, dates, forex) 

346 if period: 

347 ticker_pnl = {date: day for date, day in ticker_pnl.items() if period[0] <= date <= period[1]} 

348 before = [(date, value) for date, value in daily_equity if date < period[0]][-1:] # the period's opening value 

349 daily_equity = before + [(date, value) for date, value in daily_equity if period[0] <= date <= period[1]] 

350 members = formed_book_by_date(book_history, sorted(full_ticker_pnl)) 

351 # Ownership needs every position's opening day, so it is derived over the whole run and then cut to the period. 

352 components = component_daily_pnl(full_ticker_pnl, class_by_ticker, members, core_crypto) 

353 by_membership = component_daily_pnl(full_ticker_pnl, class_by_ticker, members, core_crypto, by_opener=False) 

354 components = {date: day for date, day in components.items() if date in ticker_pnl} 

355 by_membership = {date: day for date, day in by_membership.items() if date in ticker_pnl} 

356 totals = _component_totals(components) 

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

358 in_period = [fill for fill in fills if not period or period[0] <= fill.date <= period[1]] 

359 routes = fee_bps_by_route( 

360 ticker_pnl, class_by_ticker, in_period, 

361 closes_rate=lambda fill: quote_to_usd_rate(fill.ticker, fill.date, closes, sorted_closes) if fill.ticker in forex else 1.0, 

362 ) 

363 return { 

364 "period": list(period) if period else None, 

365 "components": totals, 

366 "components_by_membership": _component_totals(by_membership), 

367 "attribution": "opener", 

368 "fees_by_route": routes, 

369 "reconciliation": _reconciliation(components, daily_equity, run["result"], period), 

370 "rebalances": rebalance_decisions(book_history, *(period or (None, None))), 

371 "daily_components": {date: {name: round(entry["pnl"] - entry["fee"], 6) for name, entry in day.items()} 

372 for date, day in sorted(components.items())}, 

373 "daily_equity": daily_equity, 

374 } 

375 

376 

377def _component_totals(components: dict[str, dict[str, dict]]) -> dict[str, dict]: 

378 totals = {name: {"pnl": 0.0, "fee": 0.0, "fills": 0, "limit_fills": 0, "notional": 0.0} for name in COMPONENTS} 

379 for day in components.values(): 

380 for name, entry in day.items(): 

381 for key in totals[name]: 

382 totals[name][key] += entry[key] 

383 for entry in totals.values(): 

384 entry["net"] = entry["pnl"] - entry["fee"] 

385 return totals 

386 

387 

388def _reconciliation(components: dict, daily_equity: list, result: dict, period: tuple[str, str] | None) -> dict: 

389 report = reconcile_with_equity_curve(components, daily_equity) 

390 if period: 

391 lean_net = lean_period_net(result, period[0], period[1]) 

392 if lean_net is not None: 

393 report["lean_net_usd"] = lean_net 

394 report["difference_usd"] = report["rebuilt_net_usd"] - lean_net 

395 return report 

396 

397 

398def run_config_path(run_dir: Path, root: Path) -> Path | None: 

399 """The config a Lean run ran with: a snapshot in the run folder (`code/config.json`, when Lean copied it) or the frozen 

400 copy `ml/evaluation/run_configs/<run folder name>.json` (V6.1.0: Lean's `code/` folder holds no config.json, so each run's 

401 config is kept next to the evaluation artifacts). None when neither exists (callers fall back to the current config).""" 

402 for candidate in (run_dir / "code" / "config.json", root / "ml" / "evaluation" / "run_configs" / f"{run_dir.name}.json"): 

403 if candidate.exists(): 

404 return candidate 

405 return None 

406 

407 

408def _engine_log_start_utc(log_path: Path) -> datetime | None: 

409 """The first line's timestamp of a Lean engine log (`2026-10-16T16:27:41.28Z TRACE:: ...`), naive UTC; None if absent.""" 

410 try: 

411 with open(log_path, encoding="utf-8", errors="replace") as handle: 

412 first = handle.readline() 

413 return datetime.strptime(first[:19], "%Y-%m-%dT%H:%M:%S") 

414 except (OSError, ValueError): 

415 return None 

416 

417 

418def find_book_history_for_run(run_dir: Path, book_history_dir: Path) -> Path | None: 

419 """The per-run book-history file (`<UTC start>.jsonl`) that started closest to the run's start: the engine log's 

420 first UTC timestamp when the run has one (V6.2.0: the folder name is LOCAL time, and two runs three hours apart on 

421 a UTC+2 host matched each other's file), else the folder's own `YYYY-MM-DD_HH-MM-SS`.""" 

422 started = _engine_log_start_utc(Path(run_dir) / "log.txt") 

423 if started is None: 

424 try: 

425 started = datetime.strptime(Path(run_dir).name[:19], "%Y-%m-%d_%H-%M-%S") 

426 except ValueError: 

427 return None 

428 best, best_gap = None, None 

429 for path in Path(book_history_dir).glob("*.jsonl"): 

430 try: 

431 stamp = datetime.strptime(path.stem, "%Y%m%dT%H%M%SZ") 

432 except ValueError: 

433 continue 

434 gap = abs((stamp - started).total_seconds()) 

435 if best_gap is None or gap < best_gap: 

436 best, best_gap = path, gap 

437 return best if best_gap is not None and best_gap <= 12 * 3600 else None