Coverage for evaluation/gate_replica_audit.py: 100%

81 statements  

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

1"""Which of the simulator's live-gate replicas trade differently from the engine? (V6.4.4, rule R-CAL5, Problems #249 lead) 

2 

3R-CAL4 found the live-gate rung (resize threshold, entry cooldown, trailing stop) lowers the simulator's daily correlation 

4with Lean on every run. This module classifies the trades both sides made, so the mechanism that differs most is named: 

5 

6 * Lean: every fill of a main-book ticker, aggregated per (date, ticker), against the position before it -> entry, exit, 

7 flip or resize (the order events carry no reason tag); 

8 * offline: the day-over-day change of the simulator's `weights_log` (its weights only move when it trades). 

9 

10`trade_profile` counts each kind on and off live's rebalance dates and the sessions between consecutive trades of a ticker 

11(the cooldown's footprint); `compare_profiles` puts both sides next to each other with each kind's share of the total 

12absolute count gap. Pure; no I/O. 

13""" 

14 

15from __future__ import annotations 

16 

17import statistics 

18from collections.abc import Iterable, Mapping, Sequence 

19 

20KINDS = ("entry", "exit", "flip", "resize") 

21 

22 

23def _kind(before: float, after: float, tolerance: float) -> str | None: 

24 if abs(after - before) <= tolerance: 

25 return None 

26 if abs(before) <= tolerance: 

27 return "entry" 

28 if abs(after) <= tolerance: 

29 return "exit" 

30 if (before > 0) != (after > 0): 

31 return "flip" 

32 return "resize" 

33 

34 

35def lean_trades(fills: Iterable, tickers: set[str] | None = None, *, tolerance: float = 1e-9) -> list[dict]: 

36 """[{date, ticker, kind}] from signed fills (`evaluation.lean_attribution.Fill`), one per (date, ticker).""" 

37 position: dict[str, float] = {} 

38 by_day: dict[tuple[str, str], float] = {} 

39 order: list[tuple[str, str]] = [] 

40 for fill in fills: 

41 ticker = str(fill.ticker).upper() 

42 if tickers is not None and ticker not in tickers: 

43 continue 

44 key = (str(fill.date)[:10], ticker) 

45 if key not in by_day: 

46 by_day[key] = 0.0 

47 order.append(key) 

48 by_day[key] += float(fill.quantity) 

49 out = [] 

50 for date, ticker in sorted(order): 

51 before = position.get(ticker, 0.0) 

52 after = before + by_day[(date, ticker)] 

53 position[ticker] = after 

54 kind = _kind(before, after, tolerance) 

55 if kind: 

56 out.append({"date": date, "ticker": ticker, "kind": kind}) 

57 return out 

58 

59 

60def offline_trades(dates: Sequence[str], weights_log: Sequence[Mapping[str, float]], *, tolerance: float = 1e-9) -> list[dict]: 

61 """[{date, ticker, kind}] from the simulator's post-rebalance weights per date.""" 

62 out, previous = [], {} 

63 for date, weights in zip(dates, weights_log, strict=False): 

64 weights = weights or {} 

65 for ticker in sorted(set(previous) | set(weights)): 

66 kind = _kind(float(previous.get(ticker, 0.0)), float(weights.get(ticker, 0.0)), tolerance) 

67 if kind: 

68 out.append({"date": str(date)[:10], "ticker": str(ticker).upper(), "kind": kind}) 

69 previous = dict(weights) 

70 return out 

71 

72 

73def trade_profile(trades: Sequence[Mapping], rebalance_dates: Iterable[str], session_dates: Sequence[str], *, 

74 lag_sessions: int = 0) -> dict: 

75 """Counts per kind on / off the rebalance dates and the median sessions between a ticker's consecutive trades. 

76 `lag_sessions` counts a trade up to that many sessions after a rebalance date as on it (Lean fills a close decision at 

77 the next open, so its fills are dated one session later than the simulator's decision).""" 

78 ordered = sorted(str(date)[:10] for date in session_dates) 

79 position = {date: index for index, date in enumerate(ordered)} 

80 rebalance = set() 

81 for date in rebalance_dates: 

82 index = position.get(str(date)[:10]) 

83 if index is None: 

84 rebalance.add(str(date)[:10]) 

85 continue 

86 rebalance.update(ordered[index:index + lag_sessions + 1]) 

87 counts = dict.fromkeys(KINDS, 0) 

88 off = dict.fromkeys(KINDS, 0) 

89 last_index: dict[str, int] = {} 

90 gaps: list[int] = [] 

91 for trade in sorted(trades, key=lambda item: (item["date"], item["ticker"])): 

92 counts[trade["kind"]] += 1 

93 if trade["date"] not in rebalance: 

94 off[trade["kind"]] += 1 

95 index = position.get(trade["date"]) 

96 if index is not None: 

97 if trade["ticker"] in last_index: 

98 gaps.append(index - last_index[trade["ticker"]]) 

99 last_index[trade["ticker"]] = index 

100 return {"counts": counts, "off_rebalance": off, "total": sum(counts.values()), 

101 "median_sessions_between_trades": statistics.median(gaps) if gaps else None, 

102 "share_within_5_sessions": (sum(1 for gap in gaps if gap <= 5) / len(gaps)) if gaps else None} 

103 

104 

105def compare_profiles(lean: Mapping, offline: Mapping) -> dict: 

106 """Side by side per kind (all / off-rebalance), each kind's share of the summed absolute count gap, ranked.""" 

107 rows, total_gap = {}, 0.0 

108 for kind in KINDS: 

109 for scope in ("counts", "off_rebalance"): 

110 gap = abs(int(offline[scope][kind]) - int(lean[scope][kind])) 

111 rows[f"{scope}.{kind}"] = {"lean": int(lean[scope][kind]), "offline": int(offline[scope][kind]), "abs_gap": gap} 

112 total_gap += gap 

113 for row in rows.values(): 

114 row["gap_share"] = row["abs_gap"] / total_gap if total_gap else 0.0 

115 ranked = sorted(rows, key=lambda name: rows[name]["abs_gap"], reverse=True) 

116 return {"rows": rows, "ranked": ranked, 

117 "median_sessions_between_trades": {"lean": lean.get("median_sessions_between_trades"), 

118 "offline": offline.get("median_sessions_between_trades")}, 

119 "share_within_5_sessions": {"lean": lean.get("share_within_5_sessions"), "offline": offline.get("share_within_5_sessions")}}