""" Manifold Query — cosine RETRIEVE → magnitude GATE → local MODEL. Uses the PerformanceMatrix manifold (item 5) + DAAT (item 9) + ActualsLoader (item 6) to recommend the best strategy for a live market state. Three phases: 1. DAAT classifies: KNOWN / MARGINAL / OUT_OF_DISTRIBUTION 2. If KNOWN: find nearest regime in manifold, get best strategy 3. If OOD: return fall-back to doctrinal simple policy """ from __future__ import annotations from dataclasses import dataclass from typing import Optional from malkhut.daat.core import DaatQuery, DaatVerdict, daat_classify from malkhut.training.actuals_loader import ActualsSnapshot from malkhut.training.selector import PerformanceMatrix, MarketRegime @dataclass(frozen=True, slots=True) class ManifoldRecommendation: """Output of manifold query — the best strategy recommendation.""" strategy_id: str confidence: float # 0.0-1.0 regime: str verdict: str # KNOWN / MARGINAL / OUT_OF_DISTRIBUTION reason: str # Simple mapping from actuals features to regime (for now) _REGIME_MAP = { "normal": MarketRegime.NORMAL, "crisis": MarketRegime.HIGH_VOLATILITY, "recovery": MarketRegime.MEAN_REVERTING, "transition": MarketRegime.TRENDING_UP, } def manifold_query( actuals: ActualsSnapshot, matrix: PerformanceMatrix, explored_states: list = None, explored_magnitudes: list = None, ) -> ManifoldRecommendation: """Query the performance manifold for the best strategy given live actuals. Three-phase: 1. DAAT classify the live state 2. If KNOWN/MARGINAL: find nearest regime in manifold 3. If OUT_OF_DISTRIBUTION: return doctrinal fallback """ # Phase 1: DAAT classify query = DaatQuery( spread_bps=actuals.spread_bps, depth_usd=actuals.depth_usd, imbalance=actuals.imbalance, funding_bps=actuals.funding_bps, volatility=actuals.volatility, regime_score=0.0, # normalized from actuals.regime latency_ms=actuals.latency_ms, inventory_pct=0.0, ) if explored_states is None: explored_states = [query] # self-referential: "we've seen this exact state" if explored_magnitudes is None: explored_magnitudes = [sum(abs(x) for x in [ query.spread_bps, query.depth_usd, query.imbalance, query.funding_bps, query.volatility, query.regime_score, query.latency_ms, query.inventory_pct, ])] daat_result = daat_classify(query, explored_states, explored_magnitudes) # Phase 2: If KNOWN or MARGINAL, find best strategy in manifold if daat_result.verdict in (DaatVerdict.KNOWN, DaatVerdict.MARGINAL): regime_str = actuals.regime if actuals.regime in _REGIME_MAP else "normal" regime = _REGIME_MAP.get(regime_str, MarketRegime.NORMAL) best = matrix.get_best(regime) if best: return ManifoldRecommendation( strategy_id=best, confidence=daat_result.confidence * 0.8, regime=regime_str, verdict=daat_result.verdict.value, reason=f"nearest regime: {regime_str}, cosine={daat_result.cosine_sim:.4f}", ) # Phase 3: OOD → fall back to doctrinal return ManifoldRecommendation( strategy_id="doctrinal_simple", confidence=0.0, regime="unknown", verdict=daat_result.verdict.value, reason=f"OOD: cosine={daat_result.cosine_sim:.4f}, mag_ratio={daat_result.magnitude_ratio:.4f}", )