Coverage for portfolio/signal_construction.py: 100%
52 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"""Signal tables built from other signal tables (V6.6.1): the recipes a research round names, and a cross-sectional residual.
3Each works on tables of session x ticker known at that session's close, row by row, so a row depends on nothing later. Nothing here is fitted
4across dates: a recipe's signs and parts are fixed in the round's rule file before any score.
5"""
7from __future__ import annotations
9from collections.abc import Mapping
10from typing import Any
12import numpy as np
13import pandas as pd
15from portfolio.wide_signals import rank_mean
17MIN_RESIDUAL_NAMES = 30
20def residualise_signal(table: pd.DataFrame, exposures: Mapping[str, pd.DataFrame], sectors: Mapping[str, str]) -> pd.DataFrame:
21 """Per date, what is left of the signal's rank after an OLS on the ranked exposures and sector dummies. A name missing an exposure gets
22 NaN; a date with too few names is all NaN, never an unadjusted signal."""
23 columns = list(table.columns)
24 sector_names = sorted({sectors.get(ticker) for ticker in columns if sectors.get(ticker) not in (None, "unknown")})
25 sector_of = np.array([sectors.get(ticker) for ticker in columns], dtype=object)
26 ranked = [frame.reindex(index=table.index, columns=columns).rank(axis=1, pct=True).to_numpy(dtype=float) for _, frame in sorted(exposures.items())]
27 signal = table.rank(axis=1, pct=True).to_numpy(dtype=float)
28 out = np.full(signal.shape, np.nan)
29 for row in range(signal.shape[0]):
30 keep = np.isfinite(signal[row])
31 for exposure in ranked:
32 keep &= np.isfinite(exposure[row])
33 keep &= np.array([name in sector_names for name in sector_of])
34 if keep.sum() < MIN_RESIDUAL_NAMES:
35 continue
36 design = [exposure[row, keep] - 0.5 for exposure in ranked]
37 design += [(sector_of[keep] == name).astype(float) for name in sector_names]
38 matrix = np.column_stack(design)
39 beta, *_ = np.linalg.lstsq(matrix, signal[row, keep], rcond=None)
40 out[row, keep] = signal[row, keep] - matrix @ beta
41 return pd.DataFrame(out, index=table.index, columns=table.columns)
44def build_table(recipe: Mapping[str, Any], tables: Mapping[str, pd.DataFrame], member: pd.DataFrame | None = None, *, sectors: Mapping[str, str] | None = None) -> pd.DataFrame:
45 """One trial's table from a recipe in its round file: {"op": "single" | "rank_mean" | "residualise", "parts": [names], "signs": {name: -1.0},
46 "minimum": n, "exposures": [names]}. A missing part is an error: a trial must not quietly become a different trial."""
47 op = str(recipe["op"])
48 parts = [str(name) for name in recipe["parts"]]
49 missing = [name for name in parts if name not in tables]
50 if missing:
51 raise KeyError(f"recipe needs {missing}, which the cell does not hold")
52 signs = recipe.get("signs") or {}
53 frames = [tables[name] * float(signs.get(name, 1.0)) for name in parts]
54 if op == "single":
55 if len(frames) != 1:
56 raise ValueError("a single recipe has one part")
57 table = frames[0]
58 elif op == "rank_mean":
59 table = rank_mean(frames, minimum=int(recipe.get("minimum", len(frames))))
60 elif op == "residualise":
61 names = [str(name) for name in recipe.get("exposures") or ()]
62 unknown = [name for name in names if name not in tables]
63 if unknown:
64 raise KeyError(f"recipe needs exposures {unknown}, which the cell does not hold")
65 base = frames[0] if len(frames) == 1 else rank_mean(frames, minimum=int(recipe.get("minimum", len(frames))))
66 table = residualise_signal(base, {name: tables[name] for name in names}, sectors or {})
67 else:
68 raise ValueError(f"unknown recipe op {op!r}")
69 if member is None:
70 return table
71 return table.where(member.reindex(index=table.index, columns=table.columns, fill_value=False))