Coverage for risk/vol_target.py: 100%
29 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"""Volatility targeting (V6.6.5, #345): scale a book to an ex-ante annual volatility, never beyond a leverage cap.
3The trend sleeve's own per-coin targeting is `portfolio.trend_sleeve.annualised_vol`; this is the general, whole-book version.
4"""
6from __future__ import annotations
8import math
9from collections.abc import Mapping
11import numpy as np
12import pandas as pd
14__all__ = ["realized_vol", "volatility_target_weights"]
17def realized_vol(returns: pd.Series, *, window: int = 20, annualization: int = 252) -> pd.Series:
18 """Rolling sample standard deviation of `returns` times `sqrt(annualization)`; NaN until `window` finite values."""
19 clean = pd.to_numeric(returns, errors="coerce").replace([np.inf, -np.inf], np.nan)
20 return clean.rolling(int(window), min_periods=int(window)).std(ddof=1) * math.sqrt(float(annualization))
23def volatility_target_weights(weights: Mapping[str, float], cov: pd.DataFrame, *, target_annual_vol: float, max_leverage: float = 1.0,
24 annualization: int = 252) -> dict[str, float]:
25 """Scale `weights` so that `sqrt(w' cov w * annualization)` equals `target_annual_vol` (`cov` is of per-period returns),
26 then cap gross exposure at `max_leverage`. A name missing from `cov` is dropped; a non-finite or zero risk returns the
27 weights capped but unscaled. A target of zero is a flat book; a negative target or leverage raises ValueError
28 (V6.6.7, #376, formal/AetherFormal/VolTarget.lean: before, a zero target returned the weights unscaled and a negative
29 leverage was silently read as positive)."""
30 target = float(target_annual_vol)
31 if math.isfinite(target) and target < 0.0:
32 raise ValueError(f"target_annual_vol must be >= 0, got {target_annual_vol!r}")
33 if float(max_leverage) < 0.0:
34 raise ValueError(f"max_leverage must be >= 0, got {max_leverage!r}")
35 names = [name for name in weights if name in cov.index and name in cov.columns]
36 w = np.array([float(weights[name]) for name in names], dtype=float)
37 w = np.where(np.isfinite(w), w, 0.0)
38 cap = float(max_leverage)
39 if not names or not math.isfinite(cap) or target == 0.0:
40 return dict.fromkeys(names, 0.0)
41 matrix = cov.loc[names, names].to_numpy(float)
42 variance = float(w @ matrix @ w) * float(annualization) if np.all(np.isfinite(matrix)) else float("nan")
43 scale = target / math.sqrt(variance) if math.isfinite(variance) and variance > 0.0 and math.isfinite(target) and target > 0.0 else 1.0
44 scaled = w * scale
45 gross = float(np.abs(scaled).sum())
46 if gross > cap and gross > 0.0:
47 scaled = scaled * (cap / gross)
48 return {name: float(value) for name, value in zip(names, scaled, strict=False)}