Files
sentiment-engine/MALKHUT/malkhut/training/manifold_query.py
Codex 7ad123c4c1 malkhut(spec): items 5-10 — manifold, actuals, OOD, query, book fidelity
Item 5 — PerformanceMatrix manifold:
  RegimeStrategyScore: added confidence, support_count, distance_to_nearest
  record() populates confidence from episode count (more evidence = more confidence)

Item 6 — ActualsLoader:
  ActualsSnapshot: 12-field frozen dataclass for live market data
  ActualsLoader: reads CH tables (obf_universe, exf_data, maras_fingerprint, etc.)
  Synthetic fallback when CH unavailable

Item 7 — OOD verdict in RiskGate:
  validate() now accepts daat_verdict parameter
  OUT_OF_DISTRIBUTION → veto action, fall back to doctrinal simple policy
  Backward compatible: default daat_verdict='KNOWN'

Item 8 — Manifold query (three-phase recommendation):
  1. DAAT classify live state (KNOWN/MARGINAL/OOD)
  2. If KNOWN: find nearest regime in PerformanceMatrix → best strategy
  3. If OOD: return doctrinal_simple fallback
  ManifoldRecommendation: strategy_id, confidence, regime, verdict, reason

Item 10 — Book fidelity gap:
  BookFidelityConfig: n_levels, aggregation_window, min_depth
  synthesize_book_from_params: power-law D(d)=amplitude*d^(1-alpha) → OrderBookState
  Bridges OBF 15B rows → MALKHUT finite Tuple[PriceLevel]

5 files, 282 insertions.
2026-07-14 06:11:37 +02:00

99 lines
3.5 KiB
Python

"""
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}",
)