Coverage for evaluation/limit_fill_simulator.py: 100%

46 statements  

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

1"""V5.3.1 (development/Problems.md #34/#96) - an offline, counterfactual 

2answer to "how often would a real limit order actually fill" without a 

3live Lean run: for every (ticker, date) row in an existing dataset, this 

4computes a limit price the exact same way main.py's real order placement 

5does (execution.order_gate.resolve_limit_price(), the SAME pure function, 

6not a re-derived approximation), then scans that ticker's own next 

7`unfilled_timeout_bars` rows' high/low columns to determine whether a real 

8Lean fill engine plausibly would have crossed it. 

9 

10APPROXIMATION, NOT A REPLAY (read before trusting these numbers): this 

11simulates a signal firing on EVERY row, independent of whether main.py's 

12book/gates would have actually placed an order that day - it measures "if 

13an order were placed here, would it fill", not "how many of the real 

14orders in a given backtest filled" (development/Problems.md #34/#96's own 

15real order-events.json evidence is the ground truth for the latter 

16question; this module is deliberately a different, complementary 

17question). It also has no intrabar depth/tick data (only daily OHLC), so 

18it can only ever answer "did price trade through the limit", never 

19simulate a genuine partial fill - the same historical-bar-CSV ceiling 

20that makes PartiallyFilled unverifiable offline at all (see #34/#96's 

21verification notes).""" 

22 

23from __future__ import annotations 

24 

25import pandas as pd 

26 

27from execution.order_gate import resolve_limit_price 

28 

29 

30def simulate_limit_fills( 

31 dataset: pd.DataFrame, 

32 *, 

33 unfilled_timeout_bars: int, 

34 offset_multiplier: float = 1.0, 

35 ticker_column: str = "ticker", 

36 date_column: str = "date", 

37 security_type_column: str = "security_type", 

38) -> dict: 

39 """Per ticker (grouped, sorted by date_column): for every row with at 

40 least `unfilled_timeout_bars` rows of data remaining for that ticker 

41 (rows too close to the end of a ticker's history are EXCLUDED from the 

42 denominator entirely, not counted as a timeout - a thin-data edge 

43 effect, not a real timeout, matching calibrate_book_confidence_spread()'s 

44 own "excluded, not counted as 0" convention), simulates BOTH a buy and 

45 a sell limit order (the real book trades both long and short, so 

46 simulating only one side would under-cover the calibration question). 

47 

48 A buy fills the first bar (within the timeout window) whose `low` 

49 reaches at/below the buy limit price; a sell fills the first bar whose 

50 `high` reaches at/above the sell limit price - otherwise it's a 

51 timeout. `liquidity_spread_proxy` (already in ml/datasets/*.csv, the 

52 same column execution.order_gate.resolve_limit_price() expects as 

53 spread_fraction) supplies the spread input. 

54 

55 Returns {"overall": {...}, "by_asset_class": {security_type: {...}}, 

56 "by_side": {"buy": {...}, "sell": {...}}}, each a dict of 

57 {"num_signals", "fill_rate", "timeout_rate", "mean_bars_to_fill"}. 

58 An empty/all-thin dataset returns all-zero stats, never raises.""" 

59 records: list[dict] = [] 

60 

61 has_security_type = security_type_column in dataset.columns 

62 for _ticker, group in dataset.groupby(ticker_column, sort=False): 

63 group = group.sort_values(date_column).reset_index(drop=True) 

64 closes = group["close"].to_numpy() 

65 highs = group["high"].to_numpy() 

66 lows = group["low"].to_numpy() 

67 spreads = group["liquidity_spread_proxy"].to_numpy() 

68 security_types = group[security_type_column].to_numpy() if has_security_type else [None] * len(group) 

69 num_rows = len(group) 

70 

71 for i in range(num_rows): 

72 if i + unfilled_timeout_bars >= num_rows: 

73 continue # too close to the end of this ticker's data - excluded, not a timeout 

74 reference_price = float(closes[i]) 

75 raw_spread = spreads[i] 

76 spread_fraction = 0.0 if pd.isna(raw_spread) else float(raw_spread) 

77 security_type = security_types[i] 

78 

79 for is_buy in (True, False): 

80 limit_price = resolve_limit_price(reference_price, spread_fraction, is_buy, offset_multiplier) 

81 bars_to_fill = None 

82 for offset in range(1, unfilled_timeout_bars + 1): 

83 j = i + offset 

84 crossed = lows[j] <= limit_price if is_buy else highs[j] >= limit_price 

85 if crossed: 

86 bars_to_fill = offset 

87 break 

88 records.append( 

89 { 

90 "side": "buy" if is_buy else "sell", 

91 "security_type": security_type, 

92 "filled": bars_to_fill is not None, 

93 "bars_to_fill": bars_to_fill, 

94 } 

95 ) 

96 

97 return { 

98 "overall": _summarize_fill_records(records), 

99 "by_asset_class": { 

100 str(security_type): _summarize_fill_records(group_records) 

101 for security_type, group_records in _group_by(records, "security_type").items() 

102 }, 

103 "by_side": { 

104 side: _summarize_fill_records(group_records) for side, group_records in _group_by(records, "side").items() 

105 }, 

106 } 

107 

108 

109def sweep_limit_fill_offsets( 

110 dataset: pd.DataFrame, 

111 *, 

112 unfilled_timeout_bars: int, 

113 offset_multipliers: list[float], 

114 ticker_column: str = "ticker", 

115 date_column: str = "date", 

116 security_type_column: str = "security_type", 

117) -> dict: 

118 """Runs simulate_limit_fills() once per offset_multiplier - calibration 

119 insight into how a more/less passive limit placement trades off fill 

120 rate vs. price improvement. Returns {str(multiplier): result}.""" 

121 return { 

122 str(multiplier): simulate_limit_fills( 

123 dataset, 

124 unfilled_timeout_bars=unfilled_timeout_bars, 

125 offset_multiplier=multiplier, 

126 ticker_column=ticker_column, 

127 date_column=date_column, 

128 security_type_column=security_type_column, 

129 ) 

130 for multiplier in offset_multipliers 

131 } 

132 

133 

134def _group_by(records: list[dict], key: str) -> dict: 

135 groups: dict = {} 

136 for record in records: 

137 groups.setdefault(record[key], []).append(record) 

138 return groups 

139 

140 

141def _summarize_fill_records(records: list[dict]) -> dict: 

142 num_signals = len(records) 

143 if num_signals == 0: 

144 return {"num_signals": 0, "fill_rate": 0.0, "timeout_rate": 0.0, "mean_bars_to_fill": None} 

145 num_filled = sum(1 for record in records if record["filled"]) 

146 bars_to_fill_values = [record["bars_to_fill"] for record in records if record["bars_to_fill"] is not None] 

147 return { 

148 "num_signals": num_signals, 

149 "fill_rate": num_filled / num_signals, 

150 "timeout_rate": (num_signals - num_filled) / num_signals, 

151 "mean_bars_to_fill": (sum(bars_to_fill_values) / len(bars_to_fill_values)) if bars_to_fill_values else None, 

152 }