Coverage for analyzer/market_analyzer.py: 100%
97 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"""Central market analyzer for Aether Quant V2: combines expert, regime,
2topology, liquidity and risk-engine outputs into one explainable per-asset
3action."""
5from __future__ import annotations
7import math
8from dataclasses import asdict, dataclass, field
9from typing import Any
11ACTIONS = ("observe", "simulate", "trade", "reduce_risk", "retrain_candidate")
14@dataclass(frozen=True)
15class MarketAnalysisDecision:
16 """The market analyzer's verdict for one symbol and bar: the action, the signal and the target weight, with the reasons behind them."""
17 action: str
18 signal: str
19 target_weight: float
20 confidence: float
21 probability_up: float
22 trading_eligible: bool
23 topology_considered: bool
24 liquidity_considered: bool
25 reasons: list[str]
26 signal_quality_score: float = 0.0
27 signal_quality_breakdown: dict = field(default_factory=dict)
28 predicted_return_magnitude: float | None = None
29 predicted_volatility: float | None = None
30 # V5.1 Phase 1 (development/Problems.md, item 3 - the actual root cause
31 # of the fee drag) - execution/cost_model.py::NetEdgeDecision.to_dict(),
32 # or None when the cost gate is disabled/uncalibrated/no rank
33 # prediction this bar. Defaulted so every existing positional
34 # construction and to_dict() consumer is unaffected.
35 net_edge: dict | None = None
37 def to_dict(self) -> dict[str, Any]:
38 return asdict(self)
41def _clamp01(value: float) -> float:
42 # V5.4.7 (development/Problems.md #121): min(1.0, nan) evaluates False
43 # and returns 1.0, so a NaN confidence component became a PERFECT
44 # quality score and sailed through the trade gate. Non-finite now
45 # degrades to 0.0 (no confidence), matching moe/gating.py's clamp.
46 if not math.isfinite(value):
47 return 0.0
48 return max(0.0, min(1.0, value))
51def compute_signal_quality_score(
52 confidence: float,
53 regime_confidence: float,
54 topology: dict[str, Any],
55 liquidity: dict[str, Any],
56) -> tuple[float, dict]:
57 """Bounded [0,1] composite of raw model confidence, regime confidence,
58 topology peer-support and liquidity friction. Always computed and
59 exposed (signal_quality_score/signal_quality_breakdown) for dashboard
60 visibility; only influences routing in build_market_analysis_decision()
61 when use_composite_signal_score=True - see analyzer/README.md. Small
62 hand-tuned weights, mirroring moe/gating.py's
63 _quality_multiplier/_performance_score style - not a trained model."""
64 confidence_component = _clamp01(float(confidence))
65 regime_component = _clamp01(float(regime_confidence))
67 correlation_strength = _clamp01(float(topology.get("correlation_strength", 0.0) or 0.0))
68 topology_penalty = {"isolated": 0.3, "elevated": 0.6}.get(str(topology.get("topology_risk", "unknown")), 1.0)
69 topology_component = correlation_strength * topology_penalty if topology else regime_component
71 participation_rate = _clamp01(float(liquidity.get("participation_rate", 0.0) or 0.0))
72 liquidity_component = _clamp01(1.0 - participation_rate) if liquidity else 1.0
74 weights = {"confidence": 0.45, "regime": 0.20, "topology": 0.20, "liquidity": 0.15}
75 score = (
76 weights["confidence"] * confidence_component
77 + weights["regime"] * regime_component
78 + weights["topology"] * topology_component
79 + weights["liquidity"] * liquidity_component
80 )
81 breakdown = {
82 "confidence_component": confidence_component,
83 "regime_component": regime_component,
84 "topology_component": topology_component,
85 "liquidity_component": liquidity_component,
86 "weights": dict(weights),
87 }
88 return _clamp01(score), breakdown
91def compute_trade_metric(
92 confidence: float,
93 regime_confidence: float,
94 topology: dict[str, Any],
95 liquidity: dict[str, Any],
96 use_composite_signal_score: bool,
97) -> float:
98 """V5.2.6 (development/Problems.md) - extracted verbatim from
99 build_market_analysis_decision()'s own inline trade_metric computation
100 so a calibration tool (evaluation/confidence_threshold_calibration.py)
101 can compute the IDENTICAL statistic against historical data without
102 re-deriving the formula and risking it silently drifting apart from
103 what the live gate actually checks. Pure extraction - zero behavior
104 change, build_market_analysis_decision() now calls this instead of
105 repeating the expression inline."""
106 signal_quality_score, _ = compute_signal_quality_score(confidence, regime_confidence, topology, liquidity)
107 return signal_quality_score if use_composite_signal_score else float(confidence)
110def build_market_analysis_decision(
111 signal_name: str,
112 confidence: float,
113 probability_up: float,
114 target_weight: float,
115 regime: dict[str, Any],
116 gating: dict[str, Any],
117 trading_eligible: bool,
118 trade_lock_active: bool,
119 trade_lock_reason: str | None = None,
120 topology: dict[str, Any] | None = None,
121 liquidity: dict[str, Any] | None = None,
122 min_confidence_to_trade: float = 0.12,
123 retrain_min_regime_confidence: float = 0.20,
124 low_regime_confidence_threshold: float = 0.35,
125 use_composite_signal_score: bool = False,
126 predicted_return_magnitude: float | None = None,
127 predicted_volatility: float | None = None,
128 is_currently_invested: bool = False,
129 net_edge: dict[str, Any] | None = None,
130 # V5.2.6 (development/Problems.md) - is_book_selected/
131 # min_confidence_to_trade_book_selected let a book-selected symbol
132 # (already ranked into the top/bottom-N by a DIFFERENT metric,
133 # predicted_rank_20d, before this function ever runs) clear Priority
134 # 7 via its own, separately-calibrated confidence floor instead of
135 # being vetoed by a threshold measuring the same rank-derived
136 # confidence value against itself. min_confidence_to_trade_book_selected=None
137 # (the default) is a strict no-op - every symbol, book-selected or
138 # not, uses min_confidence_to_trade exactly as before this existed.
139 # risk_off_override_min_severity narrows Priority 2 the same way -
140 # None (the default) reproduces today's unconditional override
141 # exactly; see that priority's own comment for why a bare 0.0 default
142 # would NOT be a safe no-op.
143 is_book_selected: bool = False,
144 min_confidence_to_trade_book_selected: float | None = None,
145 risk_off_override_min_severity: float | None = None,
146 # V5.6.0 - phase_v2.topology.elevated_veto_applies_to_book_members. True (default) is the long-standing
147 # behaviour: Priority 3 overrides every directional signal. False exempts a book-selected symbol, which the
148 # model already ranked with this volatility as an input feature (92 equity selections were cancelled this
149 # way in the 2020 sell-off run).
150 topology_veto_applies_to_book_members: bool = True,
151) -> MarketAnalysisDecision:
152 # signal_name == "short" (Phase 3 of the 5/10 -> 9/10 roadmap,
153 # portfolio/book_construction.py) is treated identically to "buy"/"sell"
154 # by every safety-tier check below (`in {"buy", "sell", "short"}`) - a
155 # book-selected short position passes through the exact same
156 # deterministic trade-lock/risk-off/topology/liquidity categorization
157 # as any other directional signal, never bypassing it. See
158 # analyzer/README.md for why this categorization stays deterministic.
159 """Combine a symbol's signal, confidence, regime, topology and liquidity into one `MarketAnalysisDecision` (trade, hold or veto, and the weight)."""
160 reasons: list[str] = []
162 # Priority 0 (evaluated before even trade-lock): closing an EXISTING
163 # position is risk-REDUCING by construction, so none of the protective
164 # vetoes below (trade-lock, risk-off regime, elevated topology) may
165 # block it - only ever suppress a new/added exposure. Before this fix
166 # they applied identically to "sell", so a risk-off regime or an
167 # elevated-topology reading during exactly the periods you'd most want
168 # to cut a position instead trapped it open (development/Problems.md:
169 # confirmed to be why the COVID-2020 drawdown window closed zero
170 # positions in the first real backtest). "sell" is the one signal that
171 # universally means "close whatever is open" (main.py::_apply_signal()
172 # liquidates on it regardless of long/short), so this only ever reduces
173 # risk, never increases it - a "short"/"buy" signal still goes through
174 # every tier below unchanged, and a "sell" with nothing currently open
175 # falls through too (there's nothing to protect by fast-pathing it).
176 if signal_name == "sell" and is_currently_invested:
177 reasons.append("exit_signal_for_open_position_bypasses_risk_vetoes")
178 bypass_quality_score, bypass_quality_breakdown = compute_signal_quality_score(
179 confidence, float((regime or {}).get("confidence", 0.0) or 0.0), topology or {}, liquidity or {}
180 )
181 return MarketAnalysisDecision(
182 action="trade",
183 signal=signal_name,
184 target_weight=target_weight,
185 confidence=confidence,
186 probability_up=probability_up,
187 trading_eligible=trading_eligible,
188 topology_considered=bool(topology),
189 liquidity_considered=bool(liquidity),
190 reasons=reasons,
191 signal_quality_score=bypass_quality_score,
192 signal_quality_breakdown=bypass_quality_breakdown,
193 predicted_return_magnitude=predicted_return_magnitude,
194 predicted_volatility=predicted_volatility,
195 )
196 decision_source = str(gating.get("decision_source", "unknown"))
197 regime_confidence = float(regime.get("confidence", 0.0) or 0.0)
198 risk_regime = str(regime.get("risk_regime", "risk_neutral"))
199 # V5.2.6 (development/Problems.md) - the continuous severity score
200 # behind risk_regime's own categorical classification (regime/
201 # market_regime.py::classify_risk_regime()) - Priority 2 below uses
202 # this to narrow its override to genuinely severe risk_off readings
203 # only, when configured to do so.
204 risk_score = float(regime.get("risk_score", 0.0) or 0.0)
205 topology = topology or {}
206 topology_considered = bool(topology)
207 topology_risk = str(topology.get("topology_risk", "unknown")) if topology_considered else "unknown"
208 liquidity = liquidity or {}
209 liquidity_considered = bool(liquidity)
210 liquidity_action = str(liquidity.get("recommended_action", "allow")) if liquidity_considered else "allow"
211 if topology_considered:
212 # V5.5.0 (Problems.md #128): the topology node payload carries
213 # "topology_risk", never "state" - every book decision logged
214 # topology_state=unknown. Fall back to it so the reason is real.
215 reasons.append(f"topology_state={topology.get('state') or topology_risk}")
216 else:
217 reasons.append("topology_absent_v2_11_pending")
219 # Always computed and exposed for dashboard visibility, regardless of
220 # use_composite_signal_score - see compute_signal_quality_score()'s
221 # docstring and analyzer/README.md. trade_metric is what priorities 7/8
222 # actually gate on below: the composite score when the flag is on,
223 # otherwise raw confidence - byte-identical to pre-flag behavior when
224 # use_composite_signal_score=False (the default).
225 signal_quality_score, signal_quality_breakdown = compute_signal_quality_score(
226 confidence, regime_confidence, topology, liquidity
227 )
228 # Deliberately NOT calling compute_trade_metric() here even though it
229 # computes the identical value - that would recompute
230 # compute_signal_quality_score() a second time per symbol per bar in
231 # this hot loop. compute_trade_metric() exists for callers (the
232 # calibration tool) that don't already have signal_quality_score in
233 # hand; this call site does, so it reuses it directly. Both paths are
234 # provably the same formula - see compute_trade_metric()'s own
235 # docstring.
236 trade_metric = signal_quality_score if use_composite_signal_score else float(confidence)
238 # Priority 1: reduce_risk - portfolio-level risk lock always wins.
239 if trade_lock_active:
240 reasons.append(trade_lock_reason or "risk_lock_active")
241 return MarketAnalysisDecision(
242 action="reduce_risk",
243 signal="hold",
244 target_weight=0.0,
245 confidence=confidence,
246 probability_up=probability_up,
247 trading_eligible=trading_eligible,
248 topology_considered=topology_considered,
249 liquidity_considered=liquidity_considered,
250 reasons=reasons,
251 signal_quality_score=signal_quality_score,
252 signal_quality_breakdown=signal_quality_breakdown,
253 predicted_return_magnitude=predicted_return_magnitude,
254 predicted_volatility=predicted_volatility,
255 )
257 # Priority 2: reduce_risk - asset-level risk regime override even
258 # without a portfolio-wide lock (e.g. risk_off + would-be trade).
259 #
260 # V5.2.6 (development/Problems.md) - narrowed to fire only when
261 # risk_score is at least risk_off_override_min_severity severe, when
262 # configured. Why a None-sentinel and not a plain 0.0 default: traced
263 # classify_risk_regime()'s three independent risk_off paths and found
264 # the drawdown-triggered path (normalized_drawdown >= threshold and
265 # volatility_regime != "low_volatility") can coincide with a
266 # risk_score as high as +0.10 (bullish trend + normal volatility +
267 # drawdown breach) - i.e. risk_off can be true even when the
268 # continuous severity score is mildly POSITIVE. A bare
269 # "risk_score <= 0.0" default would therefore NOT reproduce today's
270 # unconditional-override behavior for that case; only a None-sentinel
271 # (bypassing the severity check entirely when unconfigured) is a
272 # provably safe no-op. The model's own regime_risk_on/off/neutral and
273 # regime_signal_risk_score_scaled are active training features, so a
274 # milder risk_off reading falling through here lets the model's own
275 # already-learned regime sizing stand instead of being additionally,
276 # externally overridden by a rule the offline Sharpe number being
277 # chased was never subject to.
278 if (
279 risk_regime == "risk_off"
280 and (risk_off_override_min_severity is None or risk_score <= -risk_off_override_min_severity)
281 and signal_name in {"buy", "sell", "short"}
282 ):
283 reasons.append("risk_off_regime_overrides_directional_signal")
284 return MarketAnalysisDecision(
285 action="reduce_risk",
286 signal="hold",
287 target_weight=0.0,
288 confidence=confidence,
289 probability_up=probability_up,
290 trading_eligible=trading_eligible,
291 topology_considered=topology_considered,
292 liquidity_considered=liquidity_considered,
293 reasons=reasons,
294 signal_quality_score=signal_quality_score,
295 signal_quality_breakdown=signal_quality_breakdown,
296 predicted_return_magnitude=predicted_return_magnitude,
297 predicted_volatility=predicted_volatility,
298 )
300 # Priority 3: reduce_risk - elevated cross-sectional volatility pressure
301 # from the deterministic topology layer overrides a directional signal.
302 # V2-17.5 added a probabilistic topology overlay (topology.learned_topology)
303 # feeding the retrain-trigger/retraining pipeline, but deliberately left
304 # this rule reading only the deterministic topology_risk - see
305 # analyzer/README.md's "Deliberately deterministic".
306 if (
307 topology_risk == "elevated"
308 and signal_name in {"buy", "sell", "short"}
309 and (topology_veto_applies_to_book_members or not is_book_selected)
310 ):
311 reasons.append("topology_elevated_volatility_pressure_overrides_directional_signal")
312 return MarketAnalysisDecision(
313 action="reduce_risk",
314 signal="hold",
315 target_weight=0.0,
316 confidence=confidence,
317 probability_up=probability_up,
318 trading_eligible=trading_eligible,
319 topology_considered=topology_considered,
320 liquidity_considered=liquidity_considered,
321 reasons=reasons,
322 signal_quality_score=signal_quality_score,
323 signal_quality_breakdown=signal_quality_breakdown,
324 predicted_return_magnitude=predicted_return_magnitude,
325 predicted_volatility=predicted_volatility,
326 )
328 # Priority 4: retrain_candidate - zero experts contributing AND the
329 # regime read is itself low-confidence. Stateless per-bar heuristic,
330 # separate from the real trailing-window retrain-trigger system V2-16/17
331 # built in performance/triggers.py + retraining/ - this rule was never
332 # wired to it and still isn't; see analyzer/README.md.
333 if decision_source == "baseline_fallback" and regime_confidence < retrain_min_regime_confidence:
334 reasons.append("baseline_fallback_with_low_regime_confidence")
335 return MarketAnalysisDecision(
336 action="retrain_candidate",
337 signal="hold",
338 target_weight=0.0,
339 confidence=confidence,
340 probability_up=probability_up,
341 trading_eligible=trading_eligible,
342 topology_considered=topology_considered,
343 liquidity_considered=liquidity_considered,
344 reasons=reasons,
345 signal_quality_score=signal_quality_score,
346 signal_quality_breakdown=signal_quality_breakdown,
347 predicted_return_magnitude=predicted_return_magnitude,
348 predicted_volatility=predicted_volatility,
349 )
351 # Priority 5: simulate - liquidity blocked (zero volume or DDV below
352 # the floor). An unexecutable order must not reach the order book.
353 # See V2-18 for future data-driven calibration of these thresholds.
354 if liquidity_action == "block" and signal_name in {"buy", "sell", "short"}:
355 reasons.append("liquidity_blocked_insufficient_volume_simulate_instead")
356 return MarketAnalysisDecision(
357 action="simulate",
358 signal=signal_name,
359 target_weight=0.0,
360 confidence=confidence,
361 probability_up=probability_up,
362 trading_eligible=trading_eligible,
363 topology_considered=topology_considered,
364 liquidity_considered=liquidity_considered,
365 reasons=reasons,
366 signal_quality_score=signal_quality_score,
367 signal_quality_breakdown=signal_quality_breakdown,
368 predicted_return_magnitude=predicted_return_magnitude,
369 predicted_volatility=predicted_volatility,
370 )
372 # Priority 6: simulate - thin market; participation rate would be
373 # uncomfortably large relative to daily volume.
374 if liquidity_action == "simulate_instead" and signal_name in {"buy", "sell", "short"}:
375 reasons.append("liquidity_thin_market_simulate_instead")
376 return MarketAnalysisDecision(
377 action="simulate",
378 signal=signal_name,
379 target_weight=0.0,
380 confidence=confidence,
381 probability_up=probability_up,
382 trading_eligible=trading_eligible,
383 topology_considered=topology_considered,
384 liquidity_considered=liquidity_considered,
385 reasons=reasons,
386 signal_quality_score=signal_quality_score,
387 signal_quality_breakdown=signal_quality_breakdown,
388 predicted_return_magnitude=predicted_return_magnitude,
389 predicted_volatility=predicted_volatility,
390 )
392 # Priority 6.5 (V5.1 Phase 1, development/Problems.md, item 3 - the
393 # actual root cause of the fee drag: $2,769 in fees on $3,159 gross
394 # profit in the last representative backtest): the trade is
395 # directionally right often enough to show a rank-IC, but not by
396 # enough to pay the spread + impact + commission. `not
397 # is_currently_invested` matters - an EXIT must never be blocked by a
398 # cost gate, the same reasoning Priority 0's is_currently_invested
399 # bypass above already uses (closing risk-reducing-by-construction
400 # positions is not something a cost estimate should be able to trap
401 # open).
402 #
403 # Gates on net_edge["passes"] - the SAME field
404 # execution/cost_model.py::build_net_edge_decision() already computed
405 # (passes=True, reason="net_edge_gate_disabled" whenever the gate is
406 # disabled/uncalibrated/no rank prediction this bar) - deliberately
407 # NOT re-deriving "net_edge_bps < some threshold" here. Problems.md
408 # #76: an earlier version of this tier re-compared net_edge_bps
409 # against min_net_edge_bps directly; a "disabled" NetEdgeDecision's
410 # net_edge_bps defaults to 0.0 (not None), so once a preset set a real
411 # positive min_net_edge_bps threshold, 0.0 < threshold was true on
412 # EVERY bar for EVERY symbol - a supposedly no-op cost gate blocked
413 # 100% of entries (Lean Backtest 1: 0 orders end to end). Trusting the
414 # single "passes" verdict computed once, in one place, is what
415 # actually satisfies the "disabled config is a strict no-op" contract.
416 if (
417 net_edge is not None
418 and signal_name in {"buy", "sell", "short"}
419 and not is_currently_invested
420 and not net_edge.get("passes", True)
421 ):
422 reasons.append("expected_net_edge_below_cost_simulate_instead")
423 return MarketAnalysisDecision(
424 action="simulate",
425 signal=signal_name,
426 target_weight=0.0,
427 confidence=confidence,
428 probability_up=probability_up,
429 trading_eligible=trading_eligible,
430 topology_considered=topology_considered,
431 liquidity_considered=liquidity_considered,
432 reasons=reasons,
433 signal_quality_score=signal_quality_score,
434 signal_quality_breakdown=signal_quality_breakdown,
435 predicted_return_magnitude=predicted_return_magnitude,
436 predicted_volatility=predicted_volatility,
437 net_edge=net_edge,
438 )
440 # Priority 7: trade - only for trading-eligible assets with an actionable
441 # directional signal, sufficient confidence, no topology isolation, and
442 # no liquidity block (redundant guard — tiers 5/6 already caught those).
443 # Gates on trade_metric, not raw confidence directly - see trade_metric's
444 # definition above (identical to confidence unless
445 # use_composite_signal_score=True).
446 #
447 # V5.2.6 (development/Problems.md) - a book-selected symbol's
448 # `confidence` (main.py) is DERIVED from predicted_rank_20d, the same
449 # score that already selected it into the book's top/bottom-N before
450 # this function ever runs - reusing min_confidence_to_trade verbatim
451 # compares that symbol against itself via two different names for the
452 # same information. min_confidence_to_trade_book_selected lets book
453 # members clear a separately-calibrated floor instead; None (the
454 # default) reproduces today's single-threshold behavior exactly for
455 # every symbol, book-selected or not.
456 effective_min_confidence_to_trade = (
457 min_confidence_to_trade_book_selected
458 if is_book_selected and min_confidence_to_trade_book_selected is not None
459 else min_confidence_to_trade
460 )
461 if (
462 trading_eligible
463 and signal_name in {"buy", "sell", "short"}
464 and trade_metric >= effective_min_confidence_to_trade
465 and topology_risk != "isolated"
466 and liquidity_action not in {"block", "simulate_instead"}
467 ):
468 reasons.append(
469 "trading_eligible_book_selected_directional_signal_above_confidence_threshold"
470 if is_book_selected else
471 "trading_eligible_directional_signal_above_confidence_threshold"
472 )
473 return MarketAnalysisDecision(
474 action="trade",
475 signal=signal_name,
476 target_weight=target_weight,
477 confidence=confidence,
478 probability_up=probability_up,
479 trading_eligible=trading_eligible,
480 topology_considered=topology_considered,
481 liquidity_considered=liquidity_considered,
482 reasons=reasons,
483 signal_quality_score=signal_quality_score,
484 signal_quality_breakdown=signal_quality_breakdown,
485 predicted_return_magnitude=predicted_return_magnitude,
486 predicted_volatility=predicted_volatility,
487 # Visibility only - Priority 6.5 above already vetoed any trade
488 # whose net_edge failed the gate, so a trade reaching here
489 # either passed it or the gate was disabled/uncalibrated
490 # (net_edge=None) this bar.
491 net_edge=net_edge,
492 )
494 # Priority 8: simulate vs observe.
495 if signal_name in {"buy", "sell", "short"} and regime_confidence >= low_regime_confidence_threshold:
496 if topology_risk == "isolated":
497 reasons.append("topology_isolated_asset_lacks_peer_confirmation_simulate_instead")
498 elif trading_eligible:
499 reasons.append(
500 "book_selected_confidence_below_book_trade_threshold_simulate_instead"
501 if is_book_selected else
502 "confidence_below_trade_threshold_simulate_instead"
503 )
504 else:
505 reasons.append("observation_only_asset_directional_signal_simulate_instead")
506 return MarketAnalysisDecision(
507 action="simulate",
508 signal=signal_name,
509 target_weight=0.0,
510 confidence=confidence,
511 probability_up=probability_up,
512 trading_eligible=trading_eligible,
513 topology_considered=topology_considered,
514 liquidity_considered=liquidity_considered,
515 reasons=reasons,
516 signal_quality_score=signal_quality_score,
517 signal_quality_breakdown=signal_quality_breakdown,
518 predicted_return_magnitude=predicted_return_magnitude,
519 predicted_volatility=predicted_volatility,
520 )
522 reasons.append("no_actionable_edge")
523 return MarketAnalysisDecision(
524 action="observe",
525 signal="hold",
526 target_weight=0.0,
527 confidence=confidence,
528 probability_up=probability_up,
529 trading_eligible=trading_eligible,
530 topology_considered=topology_considered,
531 liquidity_considered=liquidity_considered,
532 reasons=reasons,
533 signal_quality_score=signal_quality_score,
534 signal_quality_breakdown=signal_quality_breakdown,
535 )