Coverage for portfolio/model_book.py: 100%
185 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"""The multi-asset model book as a definition, and the one function that turns it into a row (V6.6.9).
3The book is a blend of generations: a crypto trend sleeve and a model-driven book, each a `SleeveSpec` sized by `signal_to_weights`.
4Three callers need the same row and must not drift: the research engine (`evaluation/model_book_round.py`), the daily decision tool
5(`scripts/model_book_decide.py`) and `main.py` in its default-off in-Lean mode. Each calls `row_for_session`; they differ only in
6where the closes and the scores come from. Pure: no Lean, no file reads, no clock. pandas is imported lazily, so a Lean start that
7never runs the model book pays nothing (rule 11).
8"""
10from __future__ import annotations
12import math
13from collections.abc import Callable, Iterable, Mapping, Sequence
14from dataclasses import dataclass, field
15from typing import TYPE_CHECKING, Any
17from portfolio.generation_blend import blend_generation_rows
19if TYPE_CHECKING:
20 import pandas as pd
22 from portfolio.premia_signals import ResearchPanel, SleeveSpec, WeightSettings
24CLASSES = ("equity", "bond", "forex", "crypto")
25PHASES = 5
26HEAD_TABLES = ("ml_a1",)
27RANK_HEADS = ("rank_20d", "rank_5d")
30def phase_offsets(rebalance_every: int, phases: int = PHASES) -> list[int]:
31 """The start offsets a rebalance cycle is averaged over (the same list `evaluation.premia_research.phase_offsets` gives)."""
32 return sorted({int(i * rebalance_every / phases) for i in range(phases)})
35# --- the definition ------------------------------------------------------------------------------------------------------------
38@dataclass(frozen=True)
39class BookPart:
40 """One generation's share of the blended book and the spec that produces its rows."""
42 generation: str
43 share: float
44 kind: str # "sleeve" (a rule sleeve, default sizing) or "book" (the model book, the round's sizing)
45 spec: Mapping[str, Any]
46 phase_index: int = 0
49@dataclass(frozen=True)
50class BlendDefinition:
51 """The installed book: its parts, when its rows start counting rebalances, and the Lean run that pins it."""
53 parts: tuple[BookPart, ...]
54 history_start: str
55 pinned_run: str | None = None
56 shares: Mapping[str, float] = field(default_factory=dict)
57 settings: Mapping[str, Any] | None = None # the book part's WeightSettings fields; the sleeve parts keep the defaults
60def parse_definition(raw: Mapping[str, Any]) -> BlendDefinition:
61 """The blend shape (`{"kind": "blend", "parts": [...]}`) or the single-rule shape every earlier candidate file uses
62 (`{"survivors": [...], "method": ..., "phase_index": ...}`), which reads as one sleeve at share 1."""
63 if raw.get("kind") == "blend":
64 parts = tuple(
65 BookPart(str(part["generation"]), float(part["share"]), "book" if "book" in part else "sleeve", dict(part.get("book") or part["sleeve"]), int(part.get("phase_index", 0)))
66 for part in raw["parts"]
67 )
68 total = sum(part.share for part in parts)
69 if not parts or not math.isclose(total, 1.0, abs_tol=1e-9) or any(part.share <= 0.0 for part in parts):
70 raise ValueError(f"a blend's shares are positive and sum to 1, got {[part.share for part in parts]}")
71 else:
72 survivors = list(raw.get("survivors") or [])
73 if len(survivors) != 1 or raw.get("method") is not None:
74 raise ValueError("the single-rule shape holds exactly one survivor and no combination method")
75 parts = (BookPart("g0001", 1.0, "sleeve", {"survivor": survivors[0]}, int(raw.get("phase_index", 0))),)
76 return BlendDefinition(parts, str(raw["history_start"]), raw.get("pinned_run"), {part.generation: part.share for part in parts}, raw.get("settings"))
79def weight_settings(definition: BlendDefinition) -> tuple[WeightSettings, WeightSettings]:
80 """(the book part's settings, the sleeve parts' settings): the definition's own block for the book, the defaults every sleeve was frozen with."""
81 from portfolio.premia_signals import WeightSettings as Settings
83 return (Settings(**definition.settings) if definition.settings else Settings()), Settings()
86def spec_of(fields: Mapping[str, Any]) -> SleeveSpec:
87 """A `SleeveSpec` from its stored fields."""
88 from portfolio.premia_signals import SleeveSpec
90 if "survivor" in fields:
91 raise ValueError(f"{fields['survivor']!r} names a V6.5.0 rule by id; resolve it to a spec before building rows")
92 return SleeveSpec(
93 str(fields["id"]), str(fields.get("track", "BOOK")), str(fields.get("kind", "cross_sectional")), str(fields.get("family", "external_score")),
94 tuple(fields["universe"]), int(fields["rebalance_every"] if "rebalance_every" in fields else fields["every"]), dict(fields.get("params") or {}),
95 )
98# --- spec -> weights -----------------------------------------------------------------------------------------------------------
101def spec_weights(
102 spec: SleeveSpec, panel: ResearchPanel, signal: pd.DataFrame, *, settings: WeightSettings, listed: Callable[[str, str], bool] | None,
103 start: str, end: str, phase_offset: int,
104) -> dict[str, dict[str, float]]:
105 """The spec's weight rows over [start, end] from one phase offset: its optimizer, no-trade band or partial move, and the guards its
106 params name (a class loss guard, a stress scaler). A spec naming none is sized as every earlier round was."""
107 from portfolio.book_construction import partial_adjust_weights
108 from portfolio.book_optimizer import ClassLossGuard, no_trade_band, optimizer_for, stress_scaler
109 from portfolio.premia_signals import signal_to_weights, vix_ratio
111 adjust = None
112 if spec.params.get("band"):
113 band = float(spec.params["band"])
115 def adjust(previous, new):
116 return no_trade_band(previous, new, band=band)
117 elif spec.params.get("partial"):
118 fraction = float(spec.params["partial"])
120 def adjust(previous, new):
121 return partial_adjust_weights(previous, new, fraction)
122 guards = []
123 if spec.params.get("guard_classes"):
124 guards.append(ClassLossGuard(
125 panel.known.pct_change(fill_method=None), panel.asset_class, spec.params["guard_classes"],
126 lookback=int(spec.params.get("guard_lookback", 60)), max_loss=float(spec.params.get("guard_max_loss", 0.01)),
127 ))
128 if spec.params.get("vix_halve"):
129 guards.append(stress_scaler(vix_ratio(panel), float(spec.params["vix_halve"])))
131 def guard(date, row):
132 for step in guards:
133 row = step(date, row)
134 return row
136 return signal_to_weights(
137 signal, panel, kind=spec.kind, rebalance_every=spec.rebalance_every, phase_offset=phase_offset, settings=settings, start=start, end=end,
138 listed=listed, top_k=spec.params.get("top_k"), optimizer=optimizer_for(spec.params), adjust=adjust, guard=guard if guards else None,
139 )
142# --- signal tables -------------------------------------------------------------------------------------------------------------
145def within_class_z(table: pd.DataFrame, asset_class: Mapping[str, str]) -> pd.DataFrame:
146 """Each row's z-score inside its asset class; a class with under two names in a row, or no spread, has no view there."""
147 import numpy as np
148 import pandas as pd
150 out = pd.DataFrame(np.nan, index=table.index, columns=table.columns)
151 for name in sorted({asset_class.get(ticker) for ticker in table.columns}, key=str):
152 members = [ticker for ticker in table.columns if asset_class.get(ticker) == name]
153 block = table[members]
154 spread = block.std(axis=1, ddof=0).replace(0.0, np.nan)
155 z = block.sub(block.mean(axis=1), axis=0).div(spread, axis=0)
156 out[members] = z.where(block.notna().sum(axis=1) >= 2, np.nan)
157 return out
160def composite_signal(parts: Sequence[tuple[float, pd.DataFrame]], asset_class: Mapping[str, str]) -> pd.DataFrame:
161 """The weighted sum of the parts' within-class z-scores. A part with no view of a name is left out of that name's sum, which is
162 divided by the weights of the parts that had one; a name no part sees is NaN."""
163 total = None
164 weight = None
165 for share, table in parts:
166 z = within_class_z(table, asset_class)
167 value = z.fillna(0.0) * float(share)
168 seen = z.notna() * float(share)
169 total = value if total is None else total.add(value, fill_value=0.0)
170 weight = seen if weight is None else weight.add(seen, fill_value=0.0)
171 return total.div(weight.where(weight > 0.0))
174def trend_vote(known: pd.DataFrame, windows: Sequence[int] = (63, 126, 252)) -> pd.DataFrame:
175 """The mean sign of the return over each window, in [-1, 1]; NaN until the longest window exists."""
176 import numpy as np
178 votes = [np.sign(known / known.shift(window) - 1.0).where(known.shift(window).notna()) for window in windows]
179 return sum(votes) / float(len(votes))
182def momentum_12_1(known: pd.DataFrame) -> pd.DataFrame:
183 """The return from 252 to 21 sessions ago (the month just ended is skipped)."""
184 return known.shift(21) / known.shift(252) - 1.0
187def low_volatility_score(known: pd.DataFrame, window: int = 60) -> pd.DataFrame:
188 """Minus the trailing volatility of daily returns: the calmest name scores highest."""
189 return -known.pct_change(fill_method=None).rolling(window, min_periods=window).std()
192def signal_tables(panel: ResearchPanel, scores: Mapping[str, pd.DataFrame]) -> dict[str, pd.DataFrame]:
193 """The signal tables a trial or the installed book names, from the aligned score tables `scores` (`ml_a1`, `ml_a2`, `ml_a3`) and the
194 panel's known closes. All of them are as known at the session, so none needs a further shift."""
195 import numpy as np
196 import pandas as pd
198 known, classes = panel.known, panel.asset_class
199 columns = [ticker for ticker in known.columns if classes.get(ticker) in CLASSES]
200 base = scores["ml_a1"].reindex(index=known.index, columns=columns)
201 trend, momentum, calm = trend_vote(known[columns]), momentum_12_1(known[columns]), low_volatility_score(known[columns])
202 carry = panel.extras.get("fx_carry")
203 carry = carry.reindex(index=known.index, columns=columns) if carry is not None else pd.DataFrame(np.nan, index=known.index, columns=columns)
204 tables = {
205 "ml_a1": base,
206 "const": pd.DataFrame(1.0, index=known.index, columns=columns),
207 "mix_trend": composite_signal([(0.5, base), (0.5, trend)], classes),
208 "mix_mom": composite_signal([(0.5, base), (0.5, momentum)], classes),
209 "mix_lowvol": composite_signal([(0.5, base), (0.5, calm)], classes),
210 "mix_all4": composite_signal([(1.0, base), (1.0, momentum), (1.0, calm), (1.0, carry)], classes),
211 }
212 for name in ("ml_a2", "ml_a3"): # V6.6.10 (R-BOOK2): the other two tables as signals of their own, when they are given
213 if name in scores:
214 tables[name] = scores[name].reindex(index=known.index, columns=columns)
215 if "ml_a2" in scores and "ml_a3" in scores:
216 tables["mix_a23"] = composite_signal(
217 [(0.5, scores["ml_a2"].reindex(index=known.index, columns=columns)), (0.5, scores["ml_a3"].reindex(index=known.index, columns=columns))], classes,
218 )
219 return tables
222# --- rows ----------------------------------------------------------------------------------------------------------------------
225def forward_fill_rows(rows: Mapping[str, Mapping[str, float]], dates: Sequence[str]) -> dict[str, dict[str, float]]:
226 """Each date's row from the latest decision at or before it; a date before the first decision has no row."""
227 ordered = sorted(rows)
228 out: dict[str, dict[str, float]] = {}
229 position = -1
230 for date in dates:
231 while position + 1 < len(ordered) and ordered[position + 1] <= date:
232 position += 1
233 if position >= 0:
234 out[date] = dict(rows[ordered[position]])
235 return out
238def blend_rows(parts: Mapping[str, Mapping[str, Mapping[str, float]]], shares: Mapping[str, float]) -> dict[str, dict[str, float]]:
239 """On every decision date of any part, each part's latest row times its share (a part with no row yet is flat). Every part is carried
240 forward first, so a part that decides rarely is still held between its decisions."""
241 dates = sorted({date for rows in parts.values() for date in rows})
242 carried = {name: forward_fill_rows(rows, dates) for name, rows in parts.items()}
243 return {date: blend_generation_rows({name: carried[name].get(date, {}) for name in parts}, shares) for date in dates}
246def definition_rows(
247 definition: BlendDefinition, panel: ResearchPanel, tables: Mapping[str, pd.DataFrame], *, settings: WeightSettings, sleeve_settings: WeightSettings,
248 listed: Callable[[str, str], bool] | None, start: str, end: str, sleeve_signal: Callable[[SleeveSpec, ResearchPanel], pd.DataFrame],
249) -> dict[str, dict[str, dict[str, float]]]:
250 """{generation: {date: row}} over [start, end]. A "book" part reads its table from `tables` and is sized by `settings`; a "sleeve" part builds
251 its own signal from the panel (`sleeve_signal`) and is sized by `sleeve_settings` (the settings it was frozen with)."""
252 from portfolio.premia_signals import ResearchPanel as Panel
254 out: dict[str, dict[str, dict[str, float]]] = {}
255 extended = Panel(panel.known, panel.asset_class, panel.fred, {**panel.extras, **tables})
256 for part in definition.parts:
257 spec = spec_of(part.spec)
258 offsets = phase_offsets(spec.rebalance_every)
259 out[part.generation] = spec_weights(
260 spec, extended, sleeve_signal(spec, extended), settings=settings if part.kind == "book" else sleeve_settings, listed=listed,
261 start=start, end=end, phase_offset=offsets[part.phase_index % len(offsets)],
262 )
263 return out
266def row_for_session(
267 definition: BlendDefinition, panel: ResearchPanel, tables: Mapping[str, pd.DataFrame], session: str, *, settings: WeightSettings,
268 sleeve_settings: WeightSettings, listed: Callable[[str, str], bool] | None, sleeve_signal: Callable[[SleeveSpec, ResearchPanel], pd.DataFrame],
269) -> dict[str, float] | None:
270 """The blended row decided at `session`, or None when no part decides then (the book holds what it has). Rebalances are counted from
271 `definition.history_start`, so the row is the one the same definition gives over a longer window."""
272 if not decides_at(definition, panel.known.index, session):
273 return None
274 rows = definition_rows(
275 definition, panel, tables, settings=settings, sleeve_settings=sleeve_settings, listed=listed, start=definition.history_start, end=session,
276 sleeve_signal=sleeve_signal,
277 )
278 return blend_rows(rows, definition.shares).get(session)
281def decides_at(definition: BlendDefinition, sessions: Iterable[str], session: str) -> bool:
282 """Whether any part rebalances at `session`, counting sessions from `definition.history_start` the way `signal_to_weights` does. A cheap test
283 that lets the in-Lean book skip building rows on the days between decisions."""
284 count = sum(1 for date in sessions if definition.history_start <= str(date) <= session) - 1
285 for part in definition.parts:
286 every = int(part.spec["rebalance_every"] if "rebalance_every" in part.spec else part.spec["every"])
287 offsets = phase_offsets(every)
288 offset = offsets[part.phase_index % len(offsets)]
289 if count >= offset and (count - offset) % every == 0:
290 return True
291 return False
294def holding_for_session(
295 definition: BlendDefinition, panel: ResearchPanel, tables: Mapping[str, pd.DataFrame], session: str, *, settings: WeightSettings,
296 sleeve_settings: WeightSettings, listed: Callable[[str, str], bool] | None, sleeve_signal: Callable[[SleeveSpec, ResearchPanel], pd.DataFrame],
297) -> dict[str, float] | None:
298 """The row the book holds after `session`: its latest decision at or before it (None before the first). A daily decision tool writes this,
299 because a decision is the whole target, not a change to it."""
300 rows = definition_rows(
301 definition, panel, tables, settings=settings, sleeve_settings=sleeve_settings, listed=listed, start=definition.history_start, end=session,
302 sleeve_signal=sleeve_signal,
303 )
304 return forward_fill_rows(blend_rows(rows, definition.shares), [session]).get(session)
307# --- the in-Lean side ------------------------------------------------------------------------------------------------------------
310def session_scores(heads: Mapping[str, Mapping[str, float]], table: str = "ml_a1") -> dict[str, float]:
311 """One session's score per ticker as the walk-forward table defines it (`ml_a1`): the mean of the session's percentile ranks of the
312 sequence model's `rank_20d` and `rank_5d`, ranked among the tickers that have both. A ticker with a missing or non-finite head has no score."""
313 if table not in HEAD_TABLES:
314 raise ValueError(f"no in-Lean definition of the score table {table!r}; expected one of {HEAD_TABLES}")
315 usable = {ticker: [float(values[head]) for head in RANK_HEADS] for ticker, values in heads.items()
316 if all(head in values and math.isfinite(float(values[head])) for head in RANK_HEADS)}
317 if not usable:
318 return {}
319 ranks = [_percentile_ranks({ticker: pair[index] for ticker, pair in usable.items()}) for index in range(len(RANK_HEADS))]
320 return {ticker: sum(rank[ticker] for rank in ranks) / len(ranks) for ticker in usable}
323def _percentile_ranks(values: Mapping[str, float]) -> dict[str, float]:
324 """pandas' `rank(pct=True)` (average rank of ties over the count)."""
325 ordered = sorted(values.values())
326 count = len(ordered)
327 out = {}
328 for ticker, value in values.items():
329 below = sum(1 for other in ordered if other < value)
330 equal = sum(1 for other in ordered if other == value)
331 out[ticker] = (below + (equal + 1) / 2.0) / count
332 return out
335def permit_model_book_row(pins_ok: bool, row_finite: bool, model_age_ok: bool) -> bool:
336 """Whether the in-Lean model book may send a row to the order path: the model files are the pinned ones, every weight is finite, and the
337 models are inside their age limit. False holds the current book (the safe failure: nothing new, nothing closed)."""
338 return bool(pins_ok) and bool(row_finite) and bool(model_age_ok)
341def row_is_finite(row: Mapping[str, float]) -> bool:
342 """Every weight of a row is a finite number (an empty row is finite: the book is flat)."""
343 return all(isinstance(weight, (int, float)) and not isinstance(weight, bool) and math.isfinite(weight) for weight in row.values())
346def lean_panel(dates: Sequence[str], closes: Mapping[str, Iterable[float]], asset_class: Mapping[str, str]) -> ResearchPanel:
347 """A research panel from the closes the algorithm kept at each equity-session tick. Each tick's last known close is already the one a
348 backtest's `known_closes` would hold there (a crypto or forex bar is the one dated before the session), so nothing is shifted again."""
349 import pandas as pd
351 from portfolio.premia_signals import ResearchPanel as Panel
353 frame = pd.DataFrame({ticker: list(values) for ticker, values in closes.items()}, index=list(dates), dtype=float).ffill()
354 return Panel(frame, dict(asset_class), {}, {})
357def lean_session_row(
358 definition: BlendDefinition, *, dates: Sequence[str], closes: Mapping[str, Iterable[float]], asset_class: Mapping[str, str],
359 score_history: Mapping[str, Mapping[str, float]], settings: WeightSettings, sleeve_settings: WeightSettings,
360 sleeve_signal: Callable[[SleeveSpec, ResearchPanel], pd.DataFrame], listed: Callable[[str, str], bool] | None = None,
361) -> dict[str, float] | None:
362 """The row the in-Lean model book decides at the last of `dates`: the same `row_for_session` the research engine calls, over a panel of
363 the closes kept so far and a score table of the scores computed so far (`score_history`: session -> ticker -> score)."""
364 import pandas as pd
366 panel = lean_panel(dates, closes, asset_class)
367 table = pd.DataFrame.from_dict(dict(score_history), orient="index").reindex(index=panel.known.index, columns=panel.known.columns)
368 tables = signal_tables(panel, {"ml_a1": table})
369 return row_for_session(
370 definition, panel, tables, panel.known.index[-1], settings=settings, sleeve_settings=sleeve_settings, listed=listed, sleeve_signal=sleeve_signal,
371 )