Coverage for liquidity/market_liquidity.py: 100%
105 statements
« prev ^ index » next coverage.py v7.17.3, created at 2026-11-22 12:55 +0000
« prev ^ index » next coverage.py v7.17.3, created at 2026-11-22 12:55 +0000
1"""Per-asset market liquidity and execution impact assessment for Aether Quant V2.
3Estimates whether a target order is reasonable given the asset's observed
4daily dollar volume. All thresholds are configurable via config.json
5phase_v2.liquidity.
7Bid-ask spread cost (V2-23.1): estimated dynamically per asset per bar via
8estimate_high_low_spread() -- the Corwin & Schultz (2012) high-low spread
9estimator, computed from each asset's own recent daily high/low ranges (data
10already collected every bar, no bid/ask quote feed needed). TYPICAL_SPREAD_BY_TYPE
11remains as a static fallback for the first bar or two of a run, before enough
12high/low history has accumulated to estimate from.
13"""
15from __future__ import annotations
17import math
18from dataclasses import asdict, dataclass
19from typing import Any
21TRADING_DAYS_PER_YEAR = 252
23TYPICAL_SPREAD_BY_TYPE: dict[str, float] = {
24 "equity": 0.0005,
25 "crypto": 0.0020,
26}
28# V5.2.6 (development/Problems.md) - forex quote-bar data structurally never
29# carries a trade-volume figure (main.py::_midpoint_bar_from_quote_bar()
30# hardcodes volume=0.0), and core-tier crypto (BTCUSD/LTCUSD) was found to
31# report volume=0.0 on at least one real bar despite the same-date raw Lean
32# data file showing real, large trade volume - both cases were previously
33# indistinguishable from "genuinely zero liquidity" by build_liquidity_decision()
34# below, unconditionally blocking every forex/crypto order regardless of book
35# selection. Mirrors evaluation/rank_book_simulator.py::capacity_curve()'s own
36# existing precedent - "a true zero here means 'no real liquidity signal for
37# this asset,' not 'zero capacity'" - which was previously applied only
38# offline, never live. Used as a fallback DAILY DOLLAR VOLUME (not a bypass)
39# so participation-rate/round-trip-cost checks stay fully active downstream -
40# see build_liquidity_decision()'s zero_volume_fallback_ddv parameter.
41TYPICAL_DAILY_DOLLAR_VOLUME_BY_TYPE: dict[str, float] = {
42 "forex": 5_000_000_000.0,
43 "crypto": 1_000_000_000.0,
44}
46# Corwin & Schultz (2012) constant: 3 - 2*sqrt(2), from the paper's alpha formula.
47_CORWIN_SCHULTZ_CONSTANT = 3 - 2 * math.sqrt(2)
50def estimate_high_low_spread(highs: list[float], lows: list[float]) -> float | None:
51 """Corwin & Schultz (2012) high-low bid-ask spread estimator.
53 Estimates the fractional bid-ask spread (e.g. 0.001 = 10 bps) from nothing
54 but consecutive days' high/low ranges -- no bid/ask/fill data required.
55 Computes one estimate per consecutive 2-bar window and averages them.
56 Per-window estimates are clipped to 0.0 when negative, a known artifact
57 of the estimator in low-volatility/noisy conditions (standard practice,
58 not a bug).
60 Returns None if fewer than 2 valid (positive, high >= low) bars are
61 available -- callers should fall back to a static proxy in that case.
62 """
63 if len(highs) != len(lows) or len(highs) < 2:
64 return None
66 window_spreads: list[float] = []
67 for index in range(len(highs) - 1):
68 high_1, low_1 = float(highs[index]), float(lows[index])
69 high_2, low_2 = float(highs[index + 1]), float(lows[index + 1])
70 if high_1 <= 0 or low_1 <= 0 or high_2 <= 0 or low_2 <= 0:
71 continue
72 if high_1 < low_1 or high_2 < low_2:
73 continue
75 beta = math.log(high_1 / low_1) ** 2 + math.log(high_2 / low_2) ** 2
76 low_min = min(low_1, low_2)
77 high_max = max(high_1, high_2)
78 gamma = math.log(high_max / low_min) ** 2
80 alpha = (
81 (math.sqrt(2 * beta) - math.sqrt(beta)) / _CORWIN_SCHULTZ_CONSTANT
82 - math.sqrt(gamma / _CORWIN_SCHULTZ_CONSTANT)
83 )
84 spread = 2 * (math.exp(alpha) - 1) / (1 + math.exp(alpha))
85 window_spreads.append(max(0.0, spread))
87 if not window_spreads:
88 return None
90 return sum(window_spreads) / len(window_spreads)
93def cap_spread_proxy(spread_proxy: float | None, security_type: str, caps_by_type: dict[str, Any] | None) -> float | None:
94 """V5.5.0 (Problems.md #133) - clamp the spread used by the liquidity GATE
95 and cost estimate for one asset class. The Corwin-Schultz estimator reads
96 a daily high-low range as a bid-ask spread; for crypto and forex mid bars
97 that range is volatility, not spread (the 2026-10-07 run's last bar:
98 BTCUSD 1.31%, LTCUSD 1.25%, AUDUSD 0.35% against real spreads of a few
99 bps), so `max_round_trip_cost_fraction` (0.25%) blocked 126 of 179 forex
100 and all 24 crypto book selections. ONLY the gate/cost input is capped:
101 `liquidity_spread_proxy` as a MODEL FEATURE stays untouched (train/live
102 parity). No cap configured for the class (or a malformed one) -> the
103 value passes through unchanged; None passes through (callers then use
104 their static fallback)."""
105 if spread_proxy is None:
106 return None
107 cap = (caps_by_type or {}).get(security_type)
108 try:
109 cap_value = float(cap) if cap is not None else None
110 value = float(spread_proxy)
111 except (TypeError, ValueError):
112 return spread_proxy
113 if cap_value is None or not math.isfinite(cap_value) or cap_value < 0.0 or not math.isfinite(value):
114 return spread_proxy
115 return min(value, cap_value)
118@dataclass(frozen=True)
119class LiquidityDecision:
120 """The liquidity check of one order: dollar volume, order value, participation, estimated spread and impact, and the verdict."""
121 daily_dollar_volume: float
122 order_value: float
123 participation_rate: float
124 estimated_slippage: float
125 spread_proxy: float
126 estimated_round_trip_cost: float
127 liquidity_risk: str
128 recommended_action: str
129 adjusted_target_weight: float
130 reasons: list[str]
132 def to_dict(self) -> dict[str, Any]:
133 return asdict(self)
136def build_liquidity_decision(
137 close: float,
138 volume: float,
139 target_weight: float,
140 portfolio_value: float,
141 annualized_volatility: float,
142 security_type: str = "equity",
143 thin_participation_threshold: float = 0.002,
144 high_impact_participation_threshold: float = 0.01,
145 blocked_participation_threshold: float = 0.05,
146 min_daily_dollar_volume: float = 100_000.0,
147 high_impact_size_factor: float = 0.5,
148 slippage_factor: float = 0.1,
149 dynamic_spread: float | None = None,
150 max_round_trip_cost_fraction: float | None = None,
151 zero_volume_fallback_ddv: float | None = None,
152) -> LiquidityDecision:
153 """Size an order against the bar's dollar volume: participation, spread and impact estimates, and whether to trade, shrink or skip it."""
154 close = float(close)
155 volume = float(volume)
156 target_weight = float(target_weight)
157 portfolio_value = max(float(portfolio_value), 1.0)
158 annualized_volatility = max(float(annualized_volatility), 0.0)
159 reasons: list[str] = []
161 # V5.4.7 (development/Problems.md #123): a negative dynamic spread
162 # (miswired caller) would LOWER the round-trip cost below the pure
163 # impact estimate and could bypass the cost ceiling; a non-finite one
164 # poisons every comparison downstream (`nan < cap` is False). Both
165 # degrade to the per-type typical spread.
166 spread_proxy = (
167 float(dynamic_spread)
168 if dynamic_spread is not None
169 else TYPICAL_SPREAD_BY_TYPE.get(str(security_type), 0.001)
170 )
171 if not math.isfinite(spread_proxy) or spread_proxy < 0.0:
172 spread_proxy = TYPICAL_SPREAD_BY_TYPE.get(str(security_type), 0.001)
174 daily_dollar_volume = close * volume
175 # A non-finite close/volume (corrupt bar) must not poison the gating
176 # math either - treat it like the documented zero-volume path so the
177 # block gate (not NaN comparisons) decides.
178 if not math.isfinite(daily_dollar_volume):
179 daily_dollar_volume = 0.0
181 # No order to place — no liquidity concern.
182 if target_weight == 0.0:
183 return LiquidityDecision(
184 daily_dollar_volume=daily_dollar_volume,
185 order_value=0.0,
186 participation_rate=0.0,
187 estimated_slippage=0.0,
188 spread_proxy=spread_proxy,
189 estimated_round_trip_cost=spread_proxy,
190 liquidity_risk="normal",
191 recommended_action="allow",
192 adjusted_target_weight=0.0,
193 reasons=["no_order_target_weight_zero"],
194 )
196 # V5.2.6 (development/Problems.md) - a reported volume of EXACTLY 0.0
197 # can mean either "genuinely zero liquidity" (rare, real) or "this
198 # asset class's data feed structurally/empirically never reports
199 # volume" (forex always; core-tier crypto observed at least once) -
200 # the two were previously indistinguishable here, unconditionally
201 # blocking every forex/crypto order regardless of real-world
202 # liquidity or book selection. zero_volume_fallback_ddv=None (the
203 # default) is a strict no-op, byte-identical to pre-V5.2.6 behavior -
204 # this only ever activates for a caller (main.py) that explicitly
205 # resolves a fallback for this specific security_type. Substitutes
206 # ONLY the DOWNSTREAM gating math (participation_rate and everything
207 # derived from it) - the returned daily_dollar_volume field stays the
208 # REAL (possibly zero) value for honest dashboard/diagnostic display,
209 # and every check below still runs against the fallback figure, so a
210 # large order or a genuinely thin fallback-covered asset can still
211 # trip the participation-rate/round-trip-cost gates exactly as normal
212 # - this is a missing-data workaround, not a bypass.
213 effective_daily_dollar_volume = daily_dollar_volume
214 zero_volume_treated_as_missing = False
215 if volume == 0.0 and zero_volume_fallback_ddv is not None:
216 effective_daily_dollar_volume = float(zero_volume_fallback_ddv)
217 zero_volume_treated_as_missing = True
218 reasons.append(f"zero_volume_treated_as_missing_data_fallback_ddv_{effective_daily_dollar_volume:.0f}")
220 # Zero (and not covered by a fallback) or insufficient volume → blocked.
221 # V5.4.7 (#123): the effective-volume floor comparison also guards a
222 # misconfigured min_daily_dollar_volume <= 0 - with close*volume == 0
223 # AND a non-positive floor, both block conditions below previously
224 # evaluated False and the division at participation_rate divided by
225 # zero. A floor that can't bind is treated as "no floor", but zero
226 # effective volume still blocks.
227 if not zero_volume_treated_as_missing and volume == 0.0:
228 reasons.append("zero_volume")
229 return LiquidityDecision(
230 daily_dollar_volume=daily_dollar_volume,
231 order_value=portfolio_value * abs(target_weight),
232 participation_rate=1.0,
233 estimated_slippage=0.0,
234 spread_proxy=spread_proxy,
235 estimated_round_trip_cost=spread_proxy,
236 liquidity_risk="blocked",
237 recommended_action="block",
238 adjusted_target_weight=0.0,
239 reasons=reasons,
240 )
241 if min_daily_dollar_volume > 0.0 and effective_daily_dollar_volume < min_daily_dollar_volume:
242 reasons.append(f"daily_dollar_volume_below_floor_{min_daily_dollar_volume:.0f}")
243 return LiquidityDecision(
244 daily_dollar_volume=daily_dollar_volume,
245 order_value=portfolio_value * abs(target_weight),
246 participation_rate=1.0,
247 estimated_slippage=0.0,
248 spread_proxy=spread_proxy,
249 estimated_round_trip_cost=spread_proxy,
250 liquidity_risk="blocked",
251 recommended_action="block",
252 adjusted_target_weight=0.0,
253 reasons=reasons,
254 )
255 if effective_daily_dollar_volume <= 0.0:
256 # Last-resort guard: nothing left to divide by (misconfig class
257 # above) - block conservatively instead of ZeroDivisionError-ing
258 # the whole bar.
259 reasons.append(f"degenerate_daily_dollar_volume_floor_{min_daily_dollar_volume:.0f}")
260 return LiquidityDecision(
261 daily_dollar_volume=daily_dollar_volume,
262 order_value=portfolio_value * abs(target_weight),
263 participation_rate=1.0,
264 estimated_slippage=0.0,
265 spread_proxy=spread_proxy,
266 estimated_round_trip_cost=spread_proxy,
267 liquidity_risk="blocked",
268 recommended_action="block",
269 adjusted_target_weight=0.0,
270 reasons=reasons,
271 )
273 order_value = portfolio_value * abs(target_weight)
274 participation_rate = order_value / effective_daily_dollar_volume
276 daily_vol = annualized_volatility / math.sqrt(TRADING_DAYS_PER_YEAR)
277 estimated_slippage = participation_rate * daily_vol * slippage_factor
278 estimated_round_trip_cost = estimated_slippage + spread_proxy
280 # V5.1 Phase 1 (development/Problems.md, item 3) - a hard ceiling on
281 # estimated_round_trip_cost itself (spread + impact, as a fraction of
282 # order value), independent of the participation-rate tiers below - a
283 # low-participation order can still carry an expensive round-trip cost
284 # on a wide-spread/high-volatility name, which the participation-rate
285 # gates alone never catch. max_round_trip_cost_fraction=None (the
286 # default) is a strict no-op - this check simply never fires, byte-
287 # identical to it not existing. Checked BEFORE the participation tiers
288 # below so an expensive-but-thin order is blocked for the right
289 # reason (cost, not participation).
290 if max_round_trip_cost_fraction is not None and estimated_round_trip_cost > max_round_trip_cost_fraction:
291 reasons.append(f"round_trip_cost_{estimated_round_trip_cost:.5f}_exceeds_max_{max_round_trip_cost_fraction:.5f}")
292 return LiquidityDecision(
293 daily_dollar_volume=daily_dollar_volume,
294 order_value=order_value,
295 participation_rate=participation_rate,
296 estimated_slippage=estimated_slippage,
297 spread_proxy=spread_proxy,
298 estimated_round_trip_cost=estimated_round_trip_cost,
299 liquidity_risk="expensive",
300 recommended_action="block",
301 adjusted_target_weight=0.0,
302 reasons=reasons,
303 )
305 if participation_rate >= blocked_participation_threshold:
306 reasons.append(f"participation_rate_{participation_rate:.4f}_exceeds_blocked_threshold")
307 return LiquidityDecision(
308 daily_dollar_volume=daily_dollar_volume,
309 order_value=order_value,
310 participation_rate=participation_rate,
311 estimated_slippage=estimated_slippage,
312 spread_proxy=spread_proxy,
313 estimated_round_trip_cost=estimated_round_trip_cost,
314 liquidity_risk="blocked",
315 recommended_action="block",
316 adjusted_target_weight=0.0,
317 reasons=reasons,
318 )
320 if participation_rate >= high_impact_participation_threshold:
321 reasons.append(f"participation_rate_{participation_rate:.4f}_exceeds_high_impact_threshold")
322 adjusted = target_weight * high_impact_size_factor
323 return LiquidityDecision(
324 daily_dollar_volume=daily_dollar_volume,
325 order_value=order_value,
326 participation_rate=participation_rate,
327 estimated_slippage=estimated_slippage,
328 spread_proxy=spread_proxy,
329 estimated_round_trip_cost=estimated_round_trip_cost,
330 liquidity_risk="high_impact",
331 recommended_action="reduce_size",
332 adjusted_target_weight=adjusted,
333 reasons=reasons,
334 )
336 if participation_rate >= thin_participation_threshold:
337 reasons.append(f"participation_rate_{participation_rate:.4f}_exceeds_thin_threshold")
338 return LiquidityDecision(
339 daily_dollar_volume=daily_dollar_volume,
340 order_value=order_value,
341 participation_rate=participation_rate,
342 estimated_slippage=estimated_slippage,
343 spread_proxy=spread_proxy,
344 estimated_round_trip_cost=estimated_round_trip_cost,
345 liquidity_risk="thin",
346 recommended_action="simulate_instead",
347 adjusted_target_weight=target_weight,
348 reasons=reasons,
349 )
351 reasons.append("participation_rate_within_normal_bounds")
352 return LiquidityDecision(
353 daily_dollar_volume=daily_dollar_volume,
354 order_value=order_value,
355 participation_rate=participation_rate,
356 estimated_slippage=estimated_slippage,
357 spread_proxy=spread_proxy,
358 estimated_round_trip_cost=estimated_round_trip_cost,
359 liquidity_risk="normal",
360 recommended_action="allow",
361 adjusted_target_weight=target_weight,
362 reasons=reasons,
363 )