Coverage for evaluation/forward_ledger.py: 100%
109 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"""A forward record that can't be backfilled (V6.6.0): each session's decision by a frozen rule, hash-chained, dated by GitHub.
3A backtest can always be rerun until it looks good. A row committed by a scheduled Action on the day it was computed can't: the commit
4time and the chain together show the decision came before the return it earned. `scripts/forward_ledger.py` appends a row a session;
5`aq evaluate --forward-ledger` verifies the chain and judges it.
7A candidate that needs a model or fresh fundamentals can't compute on a bare runner, and missing data can't be guessed: both log a
8`no_data` row with the reason, never a silent gap.
9"""
11from __future__ import annotations
13import datetime
14import hashlib
15import json
16import math
17from collections.abc import Mapping, Sequence
18from pathlib import Path
19from typing import Any
21import numpy as np
22import pandas as pd
24from audit.hash_chain import GENESIS_HASH, compute_entry_hash, verify_chain
25from evaluation.power_analysis import excluded_alpha_sharpe, minimum_detectable_alpha_sharpe
26from portfolio.premia_signals import ResearchPanel, SleeveSpec, WeightSettings, signal_to_weights, sleeve_signal
28EVENT_TYPE = "forward_session"
29JUDGE_AT_SESSIONS = (60, 252)
30STALE_WARNING_SESSIONS = 3
31COST_BPS_BY_CLASS = {"crypto": 90.0, "equity": 4.5}
32TRADING_DAYS = 252.0
35def definition_sha256(definition: Mapping[str, Any]) -> str:
36 """SHA-256 of a forward definition's canonical JSON (sorted keys, no spaces): the identity a ledger row is bound to."""
37 return hashlib.sha256(json.dumps(definition, sort_keys=True, separators=(",", ":")).encode("utf-8")).hexdigest()
40class NoSessionToRecord(RuntimeError):
41 """The run found no session it may write (an override that is not a session, or an empty calendar). A scheduled run must fail loudly on this: a silent exit is how a record loses a session."""
44def resolve_session(sessions: Sequence[str], now_date: str, override: str | None = None) -> str | None:
45 """The session a run records. An override must be a real session. Otherwise the newest session on or before today, so a schedule delayed past midnight UTC, or a
46 weekend dispatch, still records the session it was for. Never a future date, and never an older gap: only the newest session can be written."""
47 if override:
48 return override if override in sessions else None
49 earlier = [day for day in sessions if day <= now_date]
50 return max(earlier) if earlier else None
53def session_for_outage(now: datetime.datetime) -> str:
54 """With no calendar (the fetch failed), the last weekday whose US close has passed. Dating an outage row by the calendar day would let a run at 02:00 UTC use up that day's own session."""
55 day = (now - datetime.timedelta(hours=21)).date()
56 while day.weekday() >= 5:
57 day -= datetime.timedelta(days=1)
58 return day.isoformat()
61def is_rebalance(sessions: Sequence[str], date: str, *, anchor: str, every: int) -> bool:
62 """Whether `date` is a decision day, counting sessions from the frozen file's last decision so the phase carries on unchanged."""
63 if date <= anchor:
64 return False
65 after = [day for day in sessions if anchor < day <= date]
66 return bool(after) and after[-1] == date and len(after) % int(every) == 0
69def decide(definition: Mapping[str, Any], known: pd.DataFrame, date: str) -> dict[str, float]:
70 """The frozen rule's weights at `date`, through the research pipeline. `known` holds only what was public by that session's close."""
71 spec = SleeveSpec(
72 str(definition["id"]), "forward", str(definition["kind"]), str(definition["family"]), tuple(definition["universe"]),
73 int(definition["rebalance_every"]), dict(definition.get("params") or {}),
74 )
75 panel = ResearchPanel(known, dict(definition["asset_class"]), {}, {})
76 settings = WeightSettings(**(definition.get("settings") or {}))
77 rows = signal_to_weights(sleeve_signal(spec, panel), panel, kind=spec.kind, rebalance_every=1, settings=settings, start=date, end=date)
78 return {ticker: float(weight) for ticker, weight in rows.get(date, {}).items()}
81def session_return(held: Mapping[str, float], marks: pd.DataFrame, previous: str, date: str, *, cost_bps: float, traded: float = 0.0) -> float | None:
82 """What the weights held earned between two sessions' marks, less the cost of today's trade. None if a held name has no mark."""
83 total = 0.0
84 for ticker, weight in held.items():
85 if ticker not in marks.columns:
86 return None
87 before, after = marks.at[previous, ticker], marks.at[date, ticker]
88 if not (np.isfinite(before) and np.isfinite(after) and before > 0.0):
89 return None
90 total += float(weight) * (float(after) / float(before) - 1.0)
91 return total - float(traded) * float(cost_bps) / 1e4
94def turnover(before: Mapping[str, float], after: Mapping[str, float]) -> float:
95 """Sum of absolute weight changes between two books, the traded fraction of NAV."""
96 return sum(abs(float(after.get(ticker, 0.0)) - float(before.get(ticker, 0.0))) for ticker in set(before) | set(after))
99def read_ledger(path: Path) -> list[dict]:
100 """The ledger's rows (one JSON object per line), or [] when the file does not exist."""
101 path = Path(path)
102 if not path.exists():
103 return []
104 return [json.loads(line) for line in path.read_text(encoding="utf-8").splitlines() if line.strip()]
107def append_row(path: Path, *, session: str, candidate: str, payload: Mapping[str, Any], created_at: str) -> dict[str, Any]:
108 """Links a row to the chain and appends it. The row's own session is in the payload, so a rewrite of a date breaks the hash."""
109 rows = read_ledger(path)
110 previous = rows[-1]["hash"] if rows else GENESIS_HASH
111 body = {"session": session, "candidate": candidate, **payload}
112 row = {"prev_hash": previous, "event_type": EVENT_TYPE, "created_at": created_at, "payload": body}
113 row["hash"] = compute_entry_hash(previous, EVENT_TYPE, created_at, body)
114 path = Path(path)
115 path.parent.mkdir(parents=True, exist_ok=True)
116 with path.open("a", encoding="utf-8", newline="\n") as handle:
117 handle.write(json.dumps(row, sort_keys=True) + "\n")
118 return row
121def last_row_for(rows: Sequence[dict], candidate: str) -> dict[str, Any] | None:
122 """The newest ledger row of a candidate, or None."""
123 return next((row for row in reversed(rows) if row["payload"].get("candidate") == candidate), None)
126def has_session(rows: Sequence[dict], candidate: str, session: str) -> bool:
127 """Whether the ledger already holds a row for this candidate and session."""
128 return any(row["payload"].get("candidate") == candidate and row["payload"].get("session") == session for row in rows)
131def _sharpe(values: np.ndarray) -> float | None:
132 if len(values) < 2 or values.std(ddof=1) <= 0.0:
133 return None
134 return float(values.mean() / values.std(ddof=1) * math.sqrt(TRADING_DAYS))
137def judge_candidate(rows: Sequence[dict], candidate: str) -> dict[str, Any]:
138 """Sessions recorded, Sharpe, alpha t against the benchmarks each row carries, and what this many sessions can and can't show."""
139 from evaluation.alpha_proof import alpha_regression
141 mine = [row["payload"] for row in rows if row["payload"].get("candidate") == candidate]
142 usable = [row for row in mine if row.get("status") == "ok" and row.get("session_return") is not None]
143 returns = pd.Series({row["session"]: float(row["session_return"]) for row in usable}, dtype=float).sort_index()
144 report: dict = {
145 "candidate": candidate, "rows": len(mine), "sessions": int(len(returns)), "no_data_sessions": sum(1 for row in mine if row.get("status") != "ok"),
146 "first": str(returns.index.min()) if len(returns) else None, "last": str(returns.index.max()) if len(returns) else None,
147 "sharpe": _sharpe(returns.to_numpy()), "judgeable_at": list(JUDGE_AT_SESSIONS), "judgeable": len(returns) >= JUDGE_AT_SESSIONS[0],
148 "fully_judgeable": len(returns) >= JUDGE_AT_SESSIONS[1],
149 }
150 years = len(returns) / TRADING_DAYS
151 report["minimum_detectable_alpha_sharpe_at_t2"] = minimum_detectable_alpha_sharpe(years, 2.0) if years > 0 else None
152 if len(returns) >= 20:
153 benchmarks = pd.DataFrame({row["session"]: row.get("benchmarks") or {} for row in usable}).T.sort_index().astype(float)
154 if not benchmarks.empty:
155 alpha = alpha_regression(returns, benchmarks, annualization=TRADING_DAYS)
156 report["alpha"] = alpha
157 if alpha.get("t_hac") is not None:
158 report["excluded_alpha_sharpe"] = excluded_alpha_sharpe(float(alpha["t_hac"]), years)
159 return report
162def judge_ledger(rows: Sequence[dict], *, today_sessions: Sequence[str] = ()) -> dict[str, Any]:
163 """Chain check first: a broken chain makes every figure meaningless. `today_sessions` warns of a schedule that stopped."""
164 valid, broken_at = verify_chain(list(rows))
165 report: dict = {"chain_valid": valid, "first_broken_row": broken_at, "rows": len(rows)}
166 if not valid:
167 return report
168 report["candidates"] = {name: judge_candidate(rows, name) for name in sorted({row["payload"].get("candidate") for row in rows})}
169 if not rows:
170 report["warning"] = "record not started: no row has been written yet (RUNBOOK: dispatch the workflow once)"
171 if rows and today_sessions:
172 last = max(row["payload"]["session"] for row in rows)
173 behind = sum(1 for day in today_sessions if day > last)
174 report["sessions_behind"] = behind
175 if behind > STALE_WARNING_SESSIONS:
176 report["warning"] = f"the last row is {behind} sessions old: GitHub disables a schedule after 60 days of no repo activity (RUNBOOK)"
177 return report