"""Append-only PostgreSQL `trial_ledger` client and cluster N-hat DSR evaluator.""" from __future__ import annotations import hashlib import json import math import struct from dataclasses import dataclass from typing import Any, Literal, Mapping, Sequence import numpy as np import psycopg from .calculations import ( DSR_VALIDATION_GATE, DeflatedSharpeResult, EffectiveTrialsResult, deflated_sharpe_ratio, effective_independent_trials, trial_moments, ) from .vault import VaultHoldoutFenceError, parse_timestamp_ms TrialStage = Literal["signal_ic", "event_study", "screen", "engine_backtest"] UniverseMarket = Literal["US_EQ", "CA_EQ", "US_CA_EQ", "FX"] HorizonBucket = Literal["intraday", "swing_1_10d", "position_10d_plus"] def _normalize_json_value(value: Any) -> Any: if value is None or isinstance(value, (bool, str)): return value if isinstance(value, (int, float)): if isinstance(value, float): if not math.isfinite(value): raise ValueError(f"Non-finite number forbidden in expression hash: {value!r}") if value == 0.0: return 0 return value if isinstance(value, Mapping): out: dict[str, Any] = {} for k in sorted(value.keys()): v = value[k] if v is not None: out[str(k)] = _normalize_json_value(v) return out if isinstance(value, (list, tuple)): return [_normalize_json_value(v) for v in value] raise TypeError(f"Unsupported value type for canonical_expression_hash: {type(value)!r}") def canonical_expression_hash( *, expression: str, params: Mapping[str, Any], universe: str, sample_start: str, sample_end: str, horizon: str, ) -> str: """64-hex SHA-256 over canonical ASCII-sorted JSON matching `@stock-bot/research`.""" collapsed_expr = " ".join(expression.strip().split()) payload = _normalize_json_value( { "expression": collapsed_expr, "horizon": horizon, "params": params, "sampleEnd": sample_end, "sampleStart": sample_start, "universe": universe, } ) encoded = json.dumps(payload, separators=(",", ":"), sort_keys=True, ensure_ascii=False).encode("utf-8") return hashlib.sha256(encoded).hexdigest() @dataclass(frozen=True) class RecordedTrial: trial_id: int created_at: str expression_hash: str n_obs: int sharpe_unann: float skewness: float kurtosis: float @dataclass(frozen=True) class ClusterDsrSummary: trial_id: int cluster_size: int effective_trials: float mean_correlation: float | None pairs_used: int pairs_skipped: int sr0: float standard_error: float dsr: float passes_gate: bool class TrialLedgerClient: """Append-only writer and cluster DSR reader for PostgreSQL `trial_ledger`.""" def __init__(self, dsn: str) -> None: self._dsn = dsn def record_trial( self, *, principal_id: str, stage: TrialStage, universe_market: UniverseMarket, horizon_bucket: HorizonBucket, expression_hash: str, sample_start: str, sample_end: str, vault_cutoff_date: str, daily_series: Sequence[float], campaign_id: str | None = None, hypothesis_id: str | None = None, ) -> RecordedTrial: """Validates Vault fence + float32 precision and inserts into `trial_ledger`.""" start_ms = parse_timestamp_ms(sample_start, "start", "sample_start") end_ms = parse_timestamp_ms(sample_end, "end", "sample_end") cutoff_ms = parse_timestamp_ms(vault_cutoff_date, "start", "vault_cutoff_date") if end_ms < start_ms: raise ValueError(f"sample_end ({sample_end}) precedes sample_start ({sample_start}).") if start_ms >= cutoff_ms: raise VaultHoldoutFenceError(sample_start, start_ms, cutoff_ms) if end_ms >= cutoff_ms: raise VaultHoldoutFenceError(sample_end, end_ms, cutoff_ms) # Quantize to IEEE-754 REAL (float32) before moment calculation so stored values match moments f32_values: list[float] = [] for x in daily_series: fx = float(x) if not math.isfinite(fx): raise ValueError("daily_series contains non-finite value.") packed = struct.unpack(" ClusterDsrSummary: """Loads target trial and its `(universe_market, horizon_bucket)` cluster and computes DSR.""" with psycopg.connect(self._dsn) as conn: with conn.cursor() as cur: cur.execute( """ SELECT trial_id, universe_market, horizon_bucket, n_obs, sharpe_unann, skewness, kurtosis, daily_series FROM trial_ledger WHERE trial_id = %s """, (trial_id,), ) target = cur.fetchone() if target is None: raise LookupError(f"trial_id={trial_id} not found in trial_ledger.") _, universe_market, horizon_bucket, n_obs, sr, skew, kurt, _ = target cur.execute( """ SELECT trial_id, sharpe_unann, daily_series FROM trial_ledger WHERE universe_market = %s AND horizon_bucket = %s ORDER BY trial_id ASC """, (universe_market, horizon_bucket), ) cluster_rows = cur.fetchall() cluster_sharpes = [float(r[1]) for r in cluster_rows] aligned_items: list[tuple[int, dict[str, float]]] = [] for r_id, _, r_series in cluster_rows: tid = int(r_id) dates = (observation_dates_by_trial_id or {}).get(tid) if dates is not None and len(dates) == len(r_series): aligned_items.append((tid, {d: float(v) for d, v in zip(dates, r_series)})) else: aligned_items.append((tid, {})) eff: EffectiveTrialsResult = effective_independent_trials(aligned_items) dsr_res: DeflatedSharpeResult = deflated_sharpe_ratio( sharpe_unann=float(sr), n_obs=int(n_obs), skewness=float(skew), kurtosis=float(kurt), n_hat=eff.n_hat, cluster_sharpes=cluster_sharpes, ) return ClusterDsrSummary( trial_id=trial_id, cluster_size=eff.k, effective_trials=eff.n_hat, mean_correlation=eff.mean_correlation, pairs_used=eff.pairs_used, pairs_skipped=eff.pairs_skipped, sr0=dsr_res.sr0, standard_error=dsr_res.standard_error, dsr=dsr_res.dsr, passes_gate=dsr_res.dsr >= dsr_gate, )