Coverage for portfolio/book_optimizer.py: 100%
167 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 book optimizer (V6.6.9): how one session's scores become raw weights.
3The model book's old sizing was a formula per name (`min(max_w, 0.10 + 0.15 * confidence)`), blind to volatility and
4correlation. Each function here takes one session's scores and the trailing daily returns of the same names, and returns
5raw, unscaled weights; `portfolio.premia_signals.scale_and_cap` then applies the one volatility target and the caps, so
6every optimizer is judged at the same risk.
8Conventions: `scores` is a Series by ticker (NaN = no view), `returns` a (sessions x tickers) frame of daily returns
9on the session calendar, newest last, `asset_class` maps a ticker to its class. A name without usable risk history gets
10no weight; nothing here returns a NaN or raises on thin data.
12numpy and pandas only at import (HRP imports scipy lazily).
13"""
15from __future__ import annotations
17import math
18from collections.abc import Callable, Mapping, Sequence
19from functools import partial
21import numpy as np
22import pandas as pd
24MIN_CLASS_NAMES = 4
25VOL_WINDOW = 60
26LONG_WINDOW = 126
27EMPTY = pd.Series(dtype=float)
30def _volatility(returns: pd.DataFrame, window: int) -> pd.Series:
31 """Daily volatility over the last `window` sessions; only names where it is finite and positive."""
32 volatility = returns.iloc[-int(window):].std()
33 return volatility[np.isfinite(volatility) & (volatility > 0.0)]
36def _by_class(values: pd.Series, asset_class: Mapping[str, str]) -> list[pd.Series]:
37 """The series split by class; a ticker of no known class belongs to none."""
38 return [members for _, members in values.groupby(asset_class.get)] if len(values) else []
41def _to_unit_gross(weights: pd.Series) -> pd.Series:
42 gross = float(weights.abs().sum())
43 return weights / gross if gross > 0.0 and math.isfinite(gross) else weights.iloc[0:0]
46def centred_ranks(scores: pd.Series, asset_class: Mapping[str, str], min_names: int = MIN_CLASS_NAMES) -> pd.Series:
47 """Per class, the percentile rank centred on zero. Ranks stay centred within a class, so knowing a name's class earns
48 nothing (#259), and a class's gross follows its breadth. A class with fewer than `min_names` live names is left out.
49 The same numbers as `premia_signals._raw_weights` for the pooled kind."""
50 pieces = [
51 members.rank(pct=True) - (len(members) + 1) / (2.0 * len(members))
52 for members in _by_class(scores.dropna(), asset_class) if len(members) >= min_names
53 ]
54 return pd.concat(pieces) if pieces else EMPTY.copy()
57def pooled(scores: pd.Series, returns: pd.DataFrame, asset_class: Mapping[str, str]) -> pd.Series:
58 """Centred ranks as weights: the control every other optimizer is compared with."""
59 return centred_ranks(scores, asset_class)
62def inverse_vol_ranks(scores: pd.Series, returns: pd.DataFrame, asset_class: Mapping[str, str], vol_window: int = VOL_WINDOW) -> pd.Series:
63 """Centred rank over volatility, each class then scaled to the same gross: a calm name and a wild one carry the same
64 risk per unit of conviction, and no class dominates by being volatile."""
65 ranks = centred_ranks(scores, asset_class)
66 volatility = _volatility(returns.reindex(columns=ranks.index), vol_window)
67 raw = (ranks.reindex(volatility.index) / volatility).dropna()
68 pieces = [_to_unit_gross(members) for members in _by_class(raw, asset_class)]
69 pieces = [piece for piece in pieces if len(piece)]
70 return pd.concat(pieces) if pieces else EMPTY.copy()
73def _sub_book_volatility(weights: pd.Series, returns: pd.DataFrame, window: int) -> float:
74 covariance = returns.iloc[-int(window):].reindex(columns=weights.index).cov().fillna(0.0).to_numpy()
75 vector = weights.to_numpy(dtype=float)
76 variance = float(vector @ covariance @ vector)
77 return math.sqrt(variance) if math.isfinite(variance) and variance > 0.0 else 0.0
80def _equal_class_risk(sub_books: Sequence[pd.Series], returns: pd.DataFrame, window: int) -> pd.Series:
81 """Each class's sub-book scaled by one over its own ex-ante volatility; a class whose risk can't be measured is dropped."""
82 pieces = []
83 for sub_book in sub_books:
84 risk = _sub_book_volatility(sub_book, returns, window) if len(sub_book) else 0.0
85 if risk > 0.0:
86 pieces.append(sub_book / risk)
87 return _to_unit_gross(pd.concat(pieces)) if pieces else EMPTY.copy()
90def class_risk_parity(scores: pd.Series, returns: pd.DataFrame, asset_class: Mapping[str, str], vol_window: int = VOL_WINDOW) -> pd.Series:
91 """Centred ranks within a class, then every class at the same ex-ante risk: the book's risk is shared by the classes,
92 not by the names."""
93 ranks = centred_ranks(scores, asset_class)
94 known = ranks.reindex(_volatility(returns.reindex(columns=ranks.index), vol_window).index).dropna()
95 return _equal_class_risk([_to_unit_gross(members) for members in _by_class(known, asset_class)], returns, vol_window)
98def hrp_book(
99 scores: pd.Series, returns: pd.DataFrame, asset_class: Mapping[str, str], window: int = LONG_WINDOW, fraction: float = 1.0 / 3.0,
100 min_names: int = MIN_CLASS_NAMES,
101) -> pd.Series:
102 """Per class, the best and worst `fraction` by score, sized by hierarchical risk parity (single linkage, as López de
103 Prado has it) on the last `window` sessions; the classes are then set to equal risk."""
104 from portfolio.hrp_allocation import build_hrp_allocation
106 sub_books = []
107 measurable = _volatility(returns.reindex(columns=scores.index), window).index
108 for members in _by_class(scores.dropna().reindex(measurable).dropna(), asset_class):
109 if len(members) < min_names:
110 continue
111 ordered = members.sort_values(kind="mergesort")
112 count = max(1, int(len(ordered) * fraction))
113 longs, shorts = list(ordered.index[-count:]), list(ordered.index[:count])
114 history = {ticker: returns[ticker].dropna().iloc[-int(window):].tolist() for ticker in (*longs, *shorts) if ticker in returns.columns}
115 sub_books.append(pd.Series(build_hrp_allocation(history, selected_tickers_long=longs, selected_tickers_short=shorts, linkage_method="single"), dtype=float))
116 return _equal_class_risk(sub_books, returns, VOL_WINDOW)
119def shrunk_covariance(returns: pd.DataFrame, shrinkage: float) -> pd.DataFrame:
120 """The sample covariance shrunk toward a constant-correlation target (same variances, the mean correlation everywhere
121 else): `(1 - shrinkage) * S + shrinkage * F`. With many names and few sessions the sample matrix is too noisy to invert."""
122 sample = returns.cov()
123 deviation = np.sqrt(np.diag(sample.to_numpy()))
124 outer = np.outer(deviation, deviation)
125 count = len(deviation)
126 with np.errstate(divide="ignore", invalid="ignore"):
127 correlation = np.where(outer > 0.0, sample.to_numpy() / outer, 0.0)
128 mean_correlation = float((correlation.sum() - count) / (count * (count - 1))) if count > 1 else 0.0
129 target = mean_correlation * outer
130 np.fill_diagonal(target, deviation**2)
131 shrinkage = min(1.0, max(0.0, float(shrinkage)))
132 return pd.DataFrame((1.0 - shrinkage) * sample.to_numpy() + shrinkage * target, index=sample.index, columns=sample.columns)
135def shrunk_mean_variance(
136 scores: pd.Series, returns: pd.DataFrame, asset_class: Mapping[str, str], window: int = LONG_WINDOW, shrinkage: float = 0.5,
137) -> pd.Series:
138 """Mean-variance with the centred rank as the forecast (`mu_i = rank_i * sigma_i`, a constant information coefficient)
139 and a shrunk covariance: `w = pinv(Sigma) mu`. Only names with a full window of returns take part."""
140 ranks = centred_ranks(scores, asset_class)
141 history = returns.iloc[-int(window):].reindex(columns=ranks.index).dropna(axis=1, how="any")
142 volatility = _volatility(history, len(history)) if len(history) > 1 else EMPTY
143 if len(volatility) < 2:
144 return EMPTY.copy()
145 history = history[volatility.index]
146 forecast = (ranks.reindex(volatility.index) * volatility).to_numpy(dtype=float)
147 weights = np.linalg.pinv(shrunk_covariance(history, shrinkage).to_numpy()) @ forecast
148 if not np.isfinite(weights).all():
149 return EMPTY.copy()
150 return _to_unit_gross(pd.Series(weights, index=volatility.index))
153def risk_parity_core(returns: pd.DataFrame, asset_class: Mapping[str, str], vol_window: int = VOL_WINDOW) -> pd.Series:
154 """Long-only and model-free: one over volatility within a class, every class at the same risk. What a multi-asset
155 book earns from holding the classes, before any view."""
156 inverse = 1.0 / _volatility(returns, vol_window)
157 return _equal_class_risk([_to_unit_gross(members) for members in _by_class(inverse, asset_class)], returns, vol_window)
160def tilted_core(
161 scores: pd.Series, returns: pd.DataFrame, asset_class: Mapping[str, str], kappa: float = 1.0, vol_window: int = VOL_WINDOW,
162 z_cap: float = 2.0,
163) -> pd.Series:
164 """The risk-parity core tilted by the view: `core_i * max(0, 1 + kappa * z_i)`, `z_i` the score's z-score within its
165 class, capped. Long-only by construction; a name with no view, or in a class too small to rank, keeps its core weight."""
166 core = risk_parity_core(returns, asset_class, vol_window)
167 tilt = pd.Series(1.0, index=core.index)
168 for members in _by_class(scores.reindex(core.index).dropna(), asset_class):
169 spread = float(members.std(ddof=0)) if len(members) >= MIN_CLASS_NAMES else 0.0
170 if spread > 0.0 and math.isfinite(spread):
171 z_score = ((members - members.mean()) / spread).clip(-z_cap, z_cap)
172 tilt[members.index] = (1.0 + float(kappa) * z_score).clip(lower=0.0)
173 tilted = core * tilt
174 return _to_unit_gross(tilted[tilted > 0.0])
177def no_trade_band(current: Mapping[str, float], target: Mapping[str, float], band: float = 0.25) -> dict[str, float]:
178 """Keep a held weight while the new target is within `band` of it, relative to the larger of the two: small changes
179 cost more to trade than they are worth. A name the target drops always goes; applying it twice changes nothing."""
180 band = max(0.0, float(band))
181 out: dict[str, float] = {}
182 for ticker, wanted in target.items():
183 wanted = float(wanted)
184 held = float(current.get(ticker, 0.0))
185 keep = held != 0.0 and abs(wanted - held) <= band * max(abs(wanted), abs(held))
186 value = held if keep else wanted
187 if value != 0.0:
188 out[ticker] = value
189 return out
192def class_gross(row: Mapping[str, float], asset_class: Mapping[str, str]) -> dict[str, float]:
193 """Gross weight per class of one row."""
194 out: dict[str, float] = {}
195 for ticker, weight in row.items():
196 name = str(asset_class.get(ticker))
197 out[name] = out.get(name, 0.0) + abs(float(weight))
198 return out
201def drop_classes(row: Mapping[str, float], asset_class: Mapping[str, str], classes: Sequence[str]) -> dict[str, float]:
202 """The row without the names of `classes` (a suspended class holds nothing)."""
203 blocked = set(classes)
204 return {ticker: float(weight) for ticker, weight in row.items() if asset_class.get(ticker) not in blocked}
207def paper_loss_guard(increments: Sequence[float], *, lookback: int, max_loss: float) -> bool:
208 """Whether a class may be held: its own unguarded sub-book, on paper, has `lookback` sessions of record and its
209 trailing drawdown over them is within `max_loss` (a fraction of the book). It reads only the paper record, never what
210 was really held, so it needs no memory: a class comes back when its paper loss has healed, and one with too little
211 record stays out."""
212 from portfolio.sleeve_guard import trailing_drawdown
214 lookback = int(lookback)
215 if lookback <= 0 or len(increments) < lookback:
216 return False
217 return trailing_drawdown(increments, lookback) <= float(max_loss)
220class ClassLossGuard:
221 """A stateful `guard(date, row)` for `signal_to_weights`: a guarded class is held only while its own unguarded sub-book,
222 on paper, has not lost more than `max_loss` of the book over the last `lookback` sessions (`paper_loss_guard`). The
223 sub-book's daily increment is the previous row's class weights times the session's returns, so the guard reads nothing
224 from the date it decides. A class with fewer than `lookback` sessions of record stays out."""
226 def __init__(self, daily: pd.DataFrame, asset_class: Mapping[str, str], classes: Sequence[str], *, lookback: int = 60, max_loss: float = 0.01) -> None:
227 self._daily = daily
228 self._classes = tuple(classes)
229 self._asset_class = asset_class
230 self._lookback = int(lookback)
231 self._max_loss = float(max_loss)
232 self._increments: dict[str, list[float]] = {name: [] for name in self._classes}
233 self._previous_date: str | None = None
234 self._previous_row: dict[str, float] = {}
236 def _record(self, date: str) -> None:
237 if self._previous_date is None:
238 return
239 sessions = self._daily.loc[(self._daily.index > self._previous_date) & (self._daily.index <= date)]
240 for name in self._classes:
241 held = [ticker for ticker, weight in self._previous_row.items() if self._asset_class.get(ticker) == name and weight != 0.0]
242 if not held:
243 self._increments[name].extend([0.0] * len(sessions))
244 continue
245 moves = sessions.reindex(columns=held).fillna(0.0).mul(pd.Series({ticker: self._previous_row[ticker] for ticker in held}), axis=1)
246 self._increments[name].extend(moves.sum(axis=1).tolist())
248 def __call__(self, date: str, row: dict[str, float]) -> dict[str, float]:
249 self._record(date)
250 self._previous_date, self._previous_row = date, dict(row)
251 blocked = [name for name in self._classes if not paper_loss_guard(self._increments[name], lookback=self._lookback, max_loss=self._max_loss)]
252 return drop_classes(row, self._asset_class, blocked) if blocked else dict(row)
255def stress_scaler(ratio: pd.Series, threshold: float, factor: float = 0.5) -> Callable[[str, dict[str, float]], dict[str, float]]:
256 """A `guard(date, row)` that multiplies the whole row by `factor` on a session whose `ratio` (VIX over VIX3M, as known
257 then) is above `threshold`. A missing ratio leaves the row alone."""
258 values = ratio.astype(float)
260 def guard(date: str, row: dict[str, float]) -> dict[str, float]:
261 level = values.get(date)
262 scaled = level is not None and bool(pd.notna(level)) and float(level) > float(threshold)
263 return {ticker: weight * float(factor) for ticker, weight in row.items()} if scaled else dict(row)
265 return guard
268def _core_only(scores: pd.Series, returns: pd.DataFrame, asset_class: Mapping[str, str], **params: float) -> pd.Series:
269 return risk_parity_core(returns, asset_class, **params)
272OPTIMIZERS: dict[str, Callable[..., pd.Series]] = {
273 "pooled": pooled,
274 "inverse_vol": inverse_vol_ranks,
275 "class_risk_parity": class_risk_parity,
276 "hrp": hrp_book,
277 "mean_variance": shrunk_mean_variance,
278 "tilted_core": tilted_core,
279 "core": _core_only,
280}
281OPTIMIZER_PARAMS: dict[str, tuple[str, ...]] = {
282 "pooled": (), "inverse_vol": ("vol_window",), "class_risk_parity": ("vol_window",), "hrp": ("window", "fraction"),
283 "mean_variance": ("window", "shrinkage"), "tilted_core": ("kappa", "vol_window", "z_cap"), "core": ("vol_window",),
284}
287def optimizer_for(params: Mapping[str, object] | None) -> Callable[[pd.Series, pd.DataFrame, Mapping[str, str]], pd.Series] | None:
288 """The optimizer a definition names under `"optimizer"`, with the parameters it carries; None when it names none (the
289 path then sizes as before). The set is closed: an unknown name is an error, never an import."""
290 name = (params or {}).get("optimizer")
291 if name is None:
292 return None
293 if name not in OPTIMIZERS:
294 raise ValueError(f"unknown optimizer {name!r}; expected one of {sorted(OPTIMIZERS)}")
295 settings = {key: params[key] for key in OPTIMIZER_PARAMS[str(name)] if key in params}
296 return partial(OPTIMIZERS[str(name)], **settings) if settings else OPTIMIZERS[str(name)]