Coverage for evaluation/fill_price_audit.py: 100%

128 statements  

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

1"""Fill price vs the bar's open, from a finished Lean run (V5.7.0, todo.md finding 6). 

2 

3The V5.6.0 round measured a median 5 bps / p99 53 bps gap between a fill and the dataset's open and could not say how 

4much was execution cost and how much was the dataset reading different prices than Lean trades. This separates them: 

5every fill is compared with (a) the dataset's open for that ticker-date and (b) the open in the Lean data zip itself, 

6and the two references are compared with each other. A zip-vs-dataset gap is a data-parity defect (AGENTS rule 12); a 

7fill-vs-zip gap on MARKET orders is slippage; on LIMIT orders it is the limit offset by design. 

8 

9Pure functions over parsed JSON/CSV rows plus one zip reader. stdlib only. 

10""" 

11 

12from __future__ import annotations 

13 

14import bisect 

15import csv 

16import io 

17import math 

18import zipfile 

19from collections import defaultdict 

20from datetime import datetime, timedelta, timezone 

21from pathlib import Path 

22 

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

24ORDER_TYPE_NAMES = {0: "market", 1: "limit"} 

25FILLED_STATUSES = {"filled", "partiallyfilled"} 

26# Equity fills land at the 09:30 New York open: 14:30 UTC (EST) or 13:30 UTC (EDT), so UTC-5 keeps them on that date. 

27EQUITY_DATE_SHIFT = timedelta(hours=5) 

28# Lean writes equity daily prices in deci-cents. 

29EQUITY_PRICE_SCALE = 1.0 / 10_000.0 

30 

31 

32def fills_from_run(run: dict) -> list[dict]: 

33 """One dict per filled order event: symbol, date, price, direction (+1 buy / -1 sell), asset class, order type.""" 

34 orders = run.get("result", {}).get("orders", {}) 

35 fills: list[dict] = [] 

36 for event in run.get("order_events", []): 

37 if str(event.get("status", "")).lower() not in FILLED_STATUSES: 

38 continue 

39 try: 

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

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

42 when = datetime.fromtimestamp(float(event["time"]), tz=timezone.utc) 

43 except (TypeError, ValueError, KeyError): 

44 continue 

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

46 continue 

47 order = orders.get(str(event.get("orderId")), {}) 

48 asset_class = SECURITY_TYPE_NAMES.get(int(order.get("securityType", 0) or 0), "other") 

49 local = when - EQUITY_DATE_SHIFT if asset_class == "equity" else when 

50 fills.append( 

51 { 

52 "symbol": str(event.get("symbolValue") or event.get("symbol", "")), 

53 "date": local.date().isoformat(), 

54 "price": price, 

55 "quantity": quantity, 

56 "direction": 1 if str(event.get("direction", "")).lower() == "buy" else -1, 

57 "asset_class": asset_class, 

58 "order_type": ORDER_TYPE_NAMES.get(int(order.get("type", 0) or 0), "other"), 

59 } 

60 ) 

61 return fills 

62 

63 

64def lean_daily_zip_path(data_root: Path, ticker: str, asset_class: str) -> Path | None: 

65 name = ticker.lower() 

66 if asset_class == "equity": 

67 return Path(data_root) / "equity" / "usa" / "daily" / f"{name}.zip" 

68 if asset_class == "crypto": 

69 return Path(data_root) / "crypto" / "coinbase" / "daily" / f"{name}_trade.zip" 

70 if asset_class == "forex": 

71 return Path(data_root) / "forex" / "oanda" / "daily" / f"{name}.zip" 

72 return None 

73 

74 

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

76 """{YYYY-MM-DD: open} from a Lean daily zip ("YYYYMMDD 00:00,open,high,low,close,..."). Missing file -> {}.""" 

77 path = Path(zip_path) 

78 if not path.exists(): 

79 return {} 

80 opens: dict[str, float] = {} 

81 with zipfile.ZipFile(path) as archive: 

82 for member in archive.namelist(): 

83 for row in csv.reader(io.StringIO(archive.read(member).decode("utf-8", errors="replace"))): 

84 if len(row) < 2 or len(row[0]) < 8: 

85 continue 

86 try: 

87 opens[f"{row[0][:4]}-{row[0][4:6]}-{row[0][6:8]}"] = float(row[1]) * price_scale 

88 except ValueError: 

89 continue 

90 return opens 

91 

92 

93def read_factor_file(path: Path) -> list[tuple[str, float, float]]: 

94 """Lean equity factor file rows `YYYYMMDD,price_factor,split_factor,reference_price` -> [(YYYY-MM-DD, price, split)], 

95 sorted by date. Missing file -> [].""" 

96 path = Path(path) 

97 if not path.exists(): 

98 return [] 

99 rows = [] 

100 for line in path.read_text(encoding="utf-8").splitlines(): 

101 parts = line.strip().split(",") 

102 if len(parts) < 3 or len(parts[0]) < 8: 

103 continue 

104 try: 

105 rows.append((f"{parts[0][:4]}-{parts[0][4:6]}-{parts[0][6:8]}", float(parts[1]), float(parts[2]))) 

106 except ValueError: 

107 continue 

108 return sorted(rows) 

109 

110 

111def apply_factor_rows(opens: dict[str, float], factors: list[tuple[str, float, float]]) -> dict[str, float]: 

112 """Lean's DataNormalizationMode.Adjusted (and train.apply_split_adjustments): each open times price_factor x 

113 split_factor of the first factor row dated on or AFTER it; dates after every row stay unadjusted.""" 

114 if not factors: 

115 return dict(opens) 

116 dates = [row[0] for row in factors] 

117 adjusted = {} 

118 for date, value in opens.items(): 

119 position = bisect.bisect_left(dates, date) 

120 factor = factors[position][1] * factors[position][2] if position < len(factors) else 1.0 

121 adjusted[date] = value * factor 

122 return adjusted 

123 

124 

125def _quantile(sorted_values: list[float], q: float) -> float: 

126 if not sorted_values: 

127 return math.nan 

128 position = q * (len(sorted_values) - 1) 

129 low, high = int(math.floor(position)), int(math.ceil(position)) 

130 return sorted_values[low] + (sorted_values[high] - sorted_values[low]) * (position - low) 

131 

132 

133def _distribution(values: list[float]) -> dict: 

134 ordered = sorted(values) 

135 absolute = sorted(abs(value) for value in values) 

136 if not ordered: 

137 return {"n": 0} 

138 return { 

139 "n": len(ordered), 

140 "median_signed_bps": round(_quantile(ordered, 0.5), 3), 

141 "mean_signed_bps": round(sum(ordered) / len(ordered), 3), 

142 "median_abs_bps": round(_quantile(absolute, 0.5), 3), 

143 "p90_abs_bps": round(_quantile(absolute, 0.9), 3), 

144 "p99_abs_bps": round(_quantile(absolute, 0.99), 3), 

145 "max_abs_bps": round(absolute[-1], 3), 

146 } 

147 

148 

149def fill_vs_reference(fills: list[dict], references: dict[tuple[str, str], float]) -> dict: 

150 """Per (asset class, order type): distribution of the signed cost in bps against `references[(symbol, date)]`. 

151 Positive = the fill was worse than the reference (paid more on a buy, received less on a sell).""" 

152 grouped: dict[str, list[float]] = defaultdict(list) 

153 missing = 0 

154 for fill in fills: 

155 reference = references.get((fill["symbol"], fill["date"])) 

156 if reference is None or reference <= 0.0: 

157 missing += 1 

158 continue 

159 cost_bps = fill["direction"] * (fill["price"] - reference) / reference * 1e4 

160 grouped[f"{fill['asset_class']}/{fill['order_type']}"].append(cost_bps) 

161 grouped[f"{fill['asset_class']}/all"].append(cost_bps) 

162 return {"groups": {key: _distribution(values) for key, values in sorted(grouped.items())}, "fills_without_reference": missing} 

163 

164 

165def reference_gap( 

166 dataset_opens: dict[tuple[str, str], float], zip_opens: dict[tuple[str, str], float] 

167) -> dict: 

168 """Dataset open vs Lean-zip open over the ticker-dates both have: a non-zero gap means the dataset reads different 

169 prices than Lean trades (adjustment source), independent of any execution cost.""" 

170 gaps = [ 

171 (dataset_opens[key] - zip_opens[key]) / zip_opens[key] * 1e4 

172 for key in dataset_opens.keys() & zip_opens.keys() 

173 if zip_opens[key] > 0.0 

174 ] 

175 return _distribution(gaps) 

176 

177 

178def zip_opens_for_fills(fills: list[dict], data_root: Path) -> dict[tuple[str, str], float]: 

179 """{(symbol, date): open} from the Lean data zips of every traded symbol; equity opens adjusted like the engine.""" 

180 zip_opens: dict[tuple[str, str], float] = {} 

181 for symbol, asset_class in sorted({(fill["symbol"], fill["asset_class"]) for fill in fills}): 

182 path = lean_daily_zip_path(data_root, symbol, asset_class) 

183 if path is None: 

184 continue 

185 scale = EQUITY_PRICE_SCALE if asset_class == "equity" else 1.0 

186 opens = read_zip_daily_opens(path, scale) 

187 if asset_class == "equity": 

188 # the engine trades Adjusted prices: apply the factor file the same way the dataset builder does 

189 opens = apply_factor_rows(opens, read_factor_file(Path(data_root) / "equity" / "usa" / "factor_files" / f"{symbol.lower()}.csv")) 

190 for date, value in opens.items(): 

191 zip_opens[(symbol, date)] = value 

192 return zip_opens 

193 

194 

195def audit_fills( 

196 run: dict, 

197 dataset_opens: dict[tuple[str, str], float], 

198 data_root: Path, 

199) -> dict: 

200 """The whole audit: fills against the dataset open and against the Lean zip open, plus the dataset-vs-zip gap on the 

201 traded ticker-dates.""" 

202 fills = fills_from_run(run) 

203 zip_opens = zip_opens_for_fills(fills, data_root) 

204 traded_keys = {(fill["symbol"], fill["date"]) for fill in fills} 

205 traded_dataset = {key: value for key, value in dataset_opens.items() if key in traded_keys} 

206 traded_zip = {key: value for key, value in zip_opens.items() if key in traded_keys} 

207 return { 

208 "num_fills": len(fills), 

209 "fill_vs_dataset_open": fill_vs_reference(fills, dataset_opens), 

210 "fill_vs_zip_open": fill_vs_reference(fills, zip_opens), 

211 "dataset_open_vs_zip_open_on_traded_dates": reference_gap(traded_dataset, traded_zip), 

212 "notes": [ 

213 "cost > 0 means worse than the reference open; limit fills differ from the open by the limit offset by design.", 

214 "equity fills are dated by the New York session (UTC-5); crypto/forex by their UTC date.", 

215 ], 

216 }