Coverage for execution/cost_model.py: 100%

100 statements  

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

1"""Expected-net-edge cost model (V5.1 Phase 0/1, item 3 of the V5.1 

2roadmap - the actual root cause of the fee drag: $2,769 in fees on $3,159 

3gross profit). Answers the one question nothing in this codebase asked 

4before: does this trade's expected edge clear its expected cost? 

5 

6Deliberately its own module in the existing execution/ package (sibling to 

7order_gate.py, which already owns every other fill/slippage-cost function): 

8this is the ENTRY-DECISION side of cost-awareness (should we trade at all, 

9how much edge is left after cost), where order_gate.py is entirely the 

10FILL side (how the already-decided trade's price gets adjusted). Reuses 

11order_gate-adjacent liquidity data rather than recomputing it - see 

12estimate_round_trip_cost_bps()'s docstring. 

13""" 

14 

15from __future__ import annotations 

16 

17import math 

18from dataclasses import asdict, dataclass 

19from typing import Any 

20 

21 

22@dataclass(frozen=True) 

23class NetEdgeDecision: 

24 """The net-edge gate's verdict for one order: expected edge, expected cost, net edge and whether it trades.""" 

25 expected_edge_bps: float 

26 expected_cost_bps: float 

27 net_edge_bps: float 

28 passes: bool 

29 reason: str 

30 

31 def to_dict(self) -> dict[str, Any]: 

32 return asdict(self) 

33 

34 

35def fee_override_for_security_type(cost_config: dict[str, Any], security_type: str | None) -> dict[str, Any] | None: 

36 """`phase_v2.costs.fee_by_type[<security_type>]` when it carries a finite, non-negative `fee_bps`, else None 

37 (the global commission terms apply, exactly as before the key existed).""" 

38 if not security_type: 

39 return None 

40 override = (cost_config.get("fee_by_type") or {}).get(str(security_type)) 

41 if not isinstance(override, dict): 

42 return None 

43 try: 

44 fee_bps = float(override.get("fee_bps")) 

45 except (TypeError, ValueError): 

46 return None 

47 return override if math.isfinite(fee_bps) and fee_bps >= 0.0 else None 

48 

49 

50def expected_fill_fee_bps(is_limit_route: bool, fill_rate: float, maker_bps: float, taker_bps: float) -> float: 

51 """Expected exchange fee in bps of one fill (V6.0.0): a limit order pays the maker rate when it fills and the taker 

52 rate when it times out into a market order; a market order always pays the taker rate. `fill_rate` is clipped to 

53 [0, 1].""" 

54 if not is_limit_route: 

55 return float(taker_bps) 

56 rate = min(1.0, max(0.0, float(fill_rate))) 

57 return rate * float(maker_bps) + (1.0 - rate) * float(taker_bps) 

58 

59 

60def route_aware_per_side_fee_bps(route_config: dict[str, Any]) -> float: 

61 """Per-side fee of a round trip from `fee_by_type.<class>.route_aware` {maker_bps, taker_bps, entry_limit, exit_limit, 

62 fill_rate, exit_fill_rate (default fill_rate)}: the mean of the entry side and the exit side, each priced by its own 

63 route.""" 

64 maker, taker = float(route_config["maker_bps"]), float(route_config["taker_bps"]) 

65 rate = float(route_config.get("fill_rate", 1.0)) 

66 exit_rate = float(route_config.get("exit_fill_rate", rate)) 

67 entry = expected_fill_fee_bps(bool(route_config.get("entry_limit", True)), rate, maker, taker) 

68 exit_ = expected_fill_fee_bps(bool(route_config.get("exit_limit", False)), exit_rate, maker, taker) 

69 return (entry + exit_) / 2.0 

70 

71 

72def route_aware_fee_bps(override: dict[str, Any]) -> float | None: 

73 """The route-aware per-side fee of a `fee_by_type` entry, or None when it carries no enabled `route_aware` block.""" 

74 block = override.get("route_aware") 

75 if not isinstance(block, dict) or not block.get("enabled", False): 

76 return None 

77 try: 

78 value = route_aware_per_side_fee_bps(block) 

79 except (KeyError, TypeError, ValueError): 

80 return None 

81 return value if math.isfinite(value) and value >= 0.0 else None 

82 

83 

84def commission_terms_for_security_type(cost_config: dict[str, Any], security_type: str | None) -> tuple[float, float]: 

85 """(commission_bps_per_side, min_commission_usd) for one security type: the per-class override when 

86 configured (crypto pays a percentage exchange fee with no dollar floor, unlike IB's per-share 

87 equity commission), else the global terms.""" 

88 override = fee_override_for_security_type(cost_config, security_type) 

89 if override is None: 

90 return float(cost_config.get("commission_bps_per_side", 0.0)), float(cost_config.get("min_commission_usd", 0.0)) 

91 route_aware = route_aware_fee_bps(override) 

92 fee_bps = route_aware if route_aware is not None else float(override["fee_bps"]) 

93 return fee_bps, float(override.get("min_usd", 0.0) or 0.0) 

94 

95 

96def commission_bps_by_ticker(cost_config: dict[str, Any], security_type_by_ticker: dict[str, str]) -> dict[str, float]: 

97 """Per-ticker per-side commission bps for every ticker whose security type has a fee override - the 

98 offline simulator's `commission_bps_by_ticker`, so it charges the same fee the live gate assumes. An override 

99 may carry `sim_fee_bps` when a dollar floor (`min_usd`) makes its true cost per fill larger than `fee_bps` at 

100 realistic order sizes (forex: IB's $2 minimum on ~$2.6k fills is ~7.6 bps) - the simulator has no per-order floor.""" 

101 return { 

102 ticker: _simulated_fee_bps(override) 

103 for ticker, security_type in security_type_by_ticker.items() 

104 if (override := fee_override_for_security_type(cost_config, security_type)) is not None 

105 } 

106 

107 

108def _simulated_fee_bps(override: dict[str, Any]) -> float: 

109 """`sim_fee_bps` when given, else the route-aware per-side fee (V6.0.0, `route_aware.enabled`), else `fee_bps`.""" 

110 if "sim_fee_bps" in override: 

111 return float(override["sim_fee_bps"]) 

112 route_aware = route_aware_fee_bps(override) 

113 return route_aware if route_aware is not None else float(override["fee_bps"]) 

114 

115 

116def min_commission_usd_by_ticker(cost_config: dict[str, Any], security_type_by_ticker: dict[str, str]) -> dict[str, float]: 

117 """Per-ticker broker dollar floor per order (IB's $1 equity / $2 forex minimum, none for crypto): the simulator's 

118 `min_commission_usd_by_ticker`, so a small order costs what live pays (V6.0.0).""" 

119 floors = {} 

120 for ticker, security_type in security_type_by_ticker.items(): 

121 _rate, floor = commission_terms_for_security_type(cost_config, security_type) 

122 if floor > 0.0: 

123 floors[ticker] = floor 

124 return floors 

125 

126 

127def estimate_round_trip_cost_bps( 

128 liquidity_payload: dict[str, Any], 

129 *, 

130 commission_bps_per_side: float, 

131 min_commission_usd: float, 

132 order_value: float, 

133 extra_slippage_bps: float, 

134) -> float: 

135 """Reads liquidity_payload["estimated_round_trip_cost"] - already 

136 computed by liquidity/market_liquidity.py::build_liquidity_decision() 

137 (a fraction, e.g. 0.001 = 10bps) - and NEVER recomputes slippage; one 

138 estimate per bar, consistently used everywhere (the same rule 

139 main.py:1768-1771's own comment states). Adds the commission leg, 

140 expressed as bps of order_value with a min_commission_usd dollar floor 

141 (a small order can be commission-dominated even at a low bps rate), 

142 plus any extra_slippage_bps buffer (a deliberately simple manual 

143 safety margin, config-gated, defaults to 0.0). 

144 

145 order_value <= 0 (no order, or a zero-target-weight decision) returns 

146 just the liquidity round-trip cost plus extra_slippage_bps - the 

147 commission-floor conversion to bps is undefined at zero order value, 

148 so it is skipped rather than divided-by-zero. 

149 

150 V5.4.5 (development/Problems.md #116): the commission leg now covers 

151 BOTH sides of the round trip. The original math charged exactly one 

152 side's commission (rate leg and min_commission_usd floor alike) against 

153 a function whose contract - and this parameter's own name - is per-SIDE 

154 cost for a ROUND-TRIP estimate, understating expected cost by up to 2x 

155 and letting trades through whose true net edge was below the gate.""" 

156 round_trip_fraction = float(liquidity_payload.get("estimated_round_trip_cost", 0.0) or 0.0) 

157 round_trip_bps = round_trip_fraction * 10_000.0 

158 

159 commission_bps_effective = 0.0 

160 if order_value > 0.0: 

161 commission_from_rate_usd = order_value * commission_bps_per_side / 10_000.0 

162 # Each side's commission = max(rate leg, dollar floor); a round trip 

163 # pays it twice (entry + exit), same notional both ways. 

164 per_side_commission_usd = max(commission_from_rate_usd, min_commission_usd) 

165 round_trip_commission_usd = 2.0 * per_side_commission_usd 

166 commission_bps_effective = round_trip_commission_usd / order_value * 10_000.0 

167 

168 return round_trip_bps + commission_bps_effective + extra_slippage_bps 

169 

170 

171def expected_edge_bps( 

172 predicted_rank: float | None, 

173 *, 

174 edge_bps_per_rank_unit: float, 

175 holding_bars: int, 

176 horizon_days: int, 

177 trade_direction: int = 1, 

178) -> float: 

179 """Linear-in-rank-deviation expected edge estimate, measured IN THE 

180 DIRECTION OF THE TRADE. rank_deviation = (rank - 0.5) * 2 is positive 

181 for a top-ranked asset (expected to rise) and negative for a 

182 bottom-ranked one (expected to fall) - `trade_direction` (+1 long, -1 

183 short) says which side the caller actually intends to trade, so the 

184 result is the edge realized if that trade is entered, not merely the 

185 raw long-side edge. 

186 

187 A rank of 0.5 (median - no view) always has zero expected edge. A rank 

188 of 1.0/0.0 has the full edge_bps_per_rank_unit magnitude, on whichever 

189 side the rank itself favors (long the top, short the bottom) - the 

190 book case, where trade_direction is derived from the same rank that 

191 picked the side, so the product is always the FULL magnitude, 

192 never negative. A mismatched trade (e.g. going long a bottom-ranked 

193 asset) correctly comes out negative and gets vetoed downstream. 

194 

195 Scaled down by min(1, holding_bars/horizon_days) - the rank head's own 

196 forward horizon (horizon_days, e.g. 20 for rank_20d) is how long the 

197 FULL predicted move is expected to take; holding for fewer bars than 

198 that only captures a fraction of it. 

199 

200 predicted_rank=None (model unavailable this bar) -> 0.0, the safe 

201 no-edge default, matching every other "missing prediction never 

202 changes trading behavior" contract in this codebase. 

203 

204 GUARDRAIL (Problems.md - net-edge gate blocked 100% of shorts): before 

205 this parameter existed, the gate measured only the raw long-side edge 

206 and applied it unconditionally to buy/sell/short decisions alike, so 

207 every short entry (negative rank_deviation) was vetoed on every bar. 

208 trade_direction must always be threaded through from the caller's own 

209 signed intent (e.g. sign of the pre-cost target_weight) - never left 

210 at the default 1 for a short trade.""" 

211 if predicted_rank is None: 

212 return 0.0 

213 rank_deviation = (float(predicted_rank) - 0.5) * 2.0 

214 # V5.4.5: horizon_days <= 0 is a misconfiguration - previously the 

215 # else-branch handed back the FULL edge fraction (1.0), maximizing 

216 # exactly the trade the broken config should have neutralized. A 

217 # horizon that can't be interpreted conservatively yields NO edge. 

218 if horizon_days <= 0: 

219 return 0.0 

220 horizon_fraction = min(1.0, float(holding_bars) / float(horizon_days)) 

221 direction_sign = 1.0 if trade_direction >= 0 else -1.0 

222 edge = edge_bps_per_rank_unit * rank_deviation * horizon_fraction * direction_sign 

223 return edge if math.isfinite(edge) else 0.0 

224 

225 

226def build_net_edge_decision( 

227 predicted_rank: float | None, 

228 liquidity_payload: dict[str, Any], 

229 order_value: float, 

230 cost_config: dict[str, Any], 

231 *, 

232 trade_direction: int = 1, 

233 security_type: str | None = None, 

234) -> NetEdgeDecision: 

235 """The one call site analyzer/market_analyzer.py's Priority 6.5 tier 

236 and risk/position_sizing.py::cost_sizing_multiplier() both consume. 

237 

238 `trade_direction` (+1 long, -1 short) must be the sign of the trade 

239 actually being evaluated - see expected_edge_bps()'s docstring for why 

240 this parameter exists at all. Defaults to 1 (long) only so callers 

241 that genuinely never trade short (or existing tests exercising the 

242 long side) do not need to pass it; every live call site must supply 

243 the real signed direction. 

244 

245 FAIL-OPEN, always: returns passes=True, reason="net_edge_gate_disabled" 

246 whenever cost_config["enabled"] is false, edge_bps_per_rank_unit is 

247 0.0 (uncalibrated - see `aq evaluate --calibrate-edge`), or 

248 predicted_rank is None. An uncalibrated or disabled cost model must 

249 never block a trade - the exact same "missing/degraded signal never 

250 changes trading behavior" contract every other optional overlay in 

251 this codebase (topology_sizing_multiplier(), rank_sizing_multiplier()) 

252 already follows.""" 

253 enabled = bool(cost_config.get("enabled", False)) 

254 edge_bps_per_rank_unit = float(cost_config.get("edge_bps_per_rank_unit", 0.0)) 

255 

256 if not enabled or edge_bps_per_rank_unit == 0.0 or predicted_rank is None: 

257 return NetEdgeDecision( 

258 expected_edge_bps=0.0, 

259 expected_cost_bps=0.0, 

260 net_edge_bps=0.0, 

261 passes=True, 

262 reason="net_edge_gate_disabled", 

263 ) 

264 

265 expected_edge = expected_edge_bps( 

266 predicted_rank, 

267 edge_bps_per_rank_unit=edge_bps_per_rank_unit, 

268 holding_bars=int(cost_config.get("holding_bars", 10)), 

269 horizon_days=int(cost_config.get("horizon_days", 20)), 

270 trade_direction=trade_direction, 

271 ) 

272 commission_bps_per_side, min_commission_usd = commission_terms_for_security_type(cost_config, security_type) 

273 expected_cost = estimate_round_trip_cost_bps( 

274 liquidity_payload, 

275 commission_bps_per_side=commission_bps_per_side, 

276 min_commission_usd=min_commission_usd, 

277 order_value=order_value, 

278 extra_slippage_bps=float(cost_config.get("extra_slippage_bps", 0.0)), 

279 ) 

280 # V5.4.5 (development/Problems.md #117): a NaN cost/edge previously 

281 # flowed straight into the comparison - `nan >= threshold` is False, so 

282 # the gate still failed closed but with the misleading generic 

283 # "net_edge_below_min_threshold" reason (indistinguishable from an 

284 # ordinary signal veto). NaN is now caught explicitly: fail CLOSED with 

285 # a reason that names the real cause. Reported magnitudes stay finite 

286 # (1e12 sentinel) so JSON state exports remain valid. 

287 if not math.isfinite(expected_cost): 

288 return NetEdgeDecision( 

289 expected_edge_bps=expected_edge, 

290 expected_cost_bps=1e12, 

291 net_edge_bps=-1e12, 

292 passes=False, 

293 reason="non_finite_cost_estimate", 

294 ) 

295 net_edge = expected_edge - expected_cost 

296 min_net_edge_bps = float(cost_config.get("min_net_edge_bps", 0.0)) 

297 passes = math.isfinite(net_edge) and net_edge >= min_net_edge_bps 

298 

299 return NetEdgeDecision( 

300 expected_edge_bps=expected_edge, 

301 expected_cost_bps=expected_cost, 

302 net_edge_bps=net_edge if math.isfinite(net_edge) else -1e12, 

303 passes=passes, 

304 reason=( 

305 "net_edge_clears_cost" if passes 

306 else "non_finite_expected_edge" if not math.isfinite(expected_edge) 

307 else "net_edge_below_min_threshold" 

308 ), 

309 )