Coverage for portfolio/neutrality.py: 100%
55 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"""Beta and factor neutrality for any book (V6.6.5, #345). Dollar and sector neutrality are `portfolio.book_neutrality`.
3`beta_neutralize` either projects the book onto the space with zero net beta or, given a hedge instrument, adds a hedge
4leg; `factor_neutralize` projects out any set of exposures by least squares. Names without a beta or exposure are left as
5they are and count as zero exposure, never as a guessed one.
6"""
8from __future__ import annotations
10import math
11from collections.abc import Mapping
13import numpy as np
14import pandas as pd
16__all__ = ["estimate_betas", "beta_neutralize", "factor_neutralize", "net_beta"]
19def estimate_betas(returns: pd.DataFrame, market: pd.Series, *, window: int = 120, min_obs: int = 60) -> pd.Series:
20 """Each column's OLS beta to `market` over the last `window` rows where both are finite; NaN with fewer than `min_obs`."""
21 aligned_market = pd.to_numeric(market, errors="coerce").reindex(returns.index)
22 out: dict[str, float] = {}
23 for column in returns.columns:
24 pair = pd.DataFrame({"r": pd.to_numeric(returns[column], errors="coerce"), "m": aligned_market}).replace([np.inf, -np.inf], np.nan).dropna()
25 pair = pair.iloc[-int(window):]
26 if len(pair) < int(min_obs):
27 out[str(column)] = float("nan")
28 continue
29 variance = float(pair["m"].var(ddof=1))
30 out[str(column)] = float(pair["r"].cov(pair["m"]) / variance) if variance > 0.0 else float("nan")
31 return pd.Series(out, dtype=float)
34def net_beta(weights: Mapping[str, float], betas: Mapping[str, float]) -> float:
35 """`sum(w_i * beta_i)` over names with a finite beta."""
36 total = 0.0
37 for name, weight in weights.items():
38 beta = betas.get(name)
39 if beta is not None and math.isfinite(float(beta)) and math.isfinite(float(weight)):
40 total += float(weight) * float(beta)
41 return total
44def beta_neutralize(weights: Mapping[str, float], betas: Mapping[str, float], *, hedge: str | None = None) -> dict[str, float]:
45 """A book with zero net beta. With `hedge` (an instrument whose beta is in `betas`), its weight absorbs the net beta;
46 without it, `w - (w.b / b.b) * b` over the names with a finite beta, the smallest change that does it."""
47 book = {name: float(weight) if math.isfinite(float(weight)) else 0.0 for name, weight in weights.items()}
48 exposure = net_beta(book, betas)
49 if hedge is not None:
50 hedge_beta = float(betas.get(hedge, float("nan")))
51 if not math.isfinite(hedge_beta) or hedge_beta == 0.0:
52 raise ValueError(f"hedge {hedge!r} needs a finite, non-zero beta")
53 rest = exposure - book.get(hedge, 0.0) * hedge_beta
54 book[hedge] = -rest / hedge_beta
55 return book
56 known = {name: float(betas[name]) for name in book if name in betas and math.isfinite(float(betas[name]))}
57 norm = sum(beta * beta for beta in known.values())
58 if norm <= 0.0:
59 return book
60 scale = exposure / norm
61 return {name: weight - scale * known.get(name, 0.0) for name, weight in book.items()}
64def factor_neutralize(weights: pd.Series, exposures: pd.DataFrame, *, ridge: float = 1e-8) -> pd.Series:
65 """`w - X (X'X + ridge*I)^-1 X'w` on the names `weights` and `exposures` (names x factors) share; other names unchanged.
66 Rows of `exposures` with a non-finite value are left out of the projection."""
67 out = pd.to_numeric(weights, errors="coerce").fillna(0.0).astype(float).copy()
68 frame = exposures.reindex(out.index).replace([np.inf, -np.inf], np.nan).dropna()
69 if frame.empty:
70 return out
71 x = frame.to_numpy(float)
72 w = out.loc[frame.index].to_numpy(float)
73 gram = x.T @ x + max(float(ridge), 0.0) * np.eye(x.shape[1])
74 try:
75 coefficients = np.linalg.solve(gram, x.T @ w)
76 except np.linalg.LinAlgError:
77 return out
78 out.loc[frame.index] = w - x @ coefficients
79 return out