Coverage for evaluation/walk_forward_linear.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"""A walk-forward linear model of the characteristics (V6.6.1): Fama-MacBeth slopes, ridge-shrunk and held to a sign fixed in advance.
3The neural and tree models read near-constant fundamentals in their early years (filings: 19 names in 2009, 292 in 2010, 466 in 2011), so they
4behaved like price models. A monthly cross-sectional slope has no such problem, and with so few effective degrees of freedom it can barely
5overfit. It starts as an equal-weight composite of the signs and leans on its own slopes only as labels arrive.
6"""
8from __future__ import annotations
10from collections.abc import Mapping
12import numpy as np
13import pandas as pd
15MIN_SLOPE_MONTHS = 12
16MIN_SLOPE_NAMES = 30
19def _rank_matrix(features: Mapping[str, pd.DataFrame], names: list[str], index, columns) -> np.ndarray:
20 """dates x tickers x features, each a cross-sectional rank centred at zero; a missing value reads as the middle."""
21 layers = [features[name].reindex(index=index, columns=columns).rank(axis=1, pct=True).sub(0.5).to_numpy(dtype=float) for name in names]
22 return np.stack(layers, axis=2)
25def monthly_slope(ranks: np.ndarray, label: np.ndarray, *, ridge: float) -> np.ndarray | None:
26 """One date's ridge slope of the label on the ranked features, on names with a label and at least one feature."""
27 keep = np.isfinite(label) & np.isfinite(ranks).any(axis=1)
28 if keep.sum() < MIN_SLOPE_NAMES:
29 return None
30 matrix = np.nan_to_num(ranks[keep], nan=0.0)
31 target = label[keep] - np.mean(label[keep])
32 return np.linalg.solve(matrix.T @ matrix + float(ridge) * np.eye(matrix.shape[1]), matrix.T @ target)
35def fama_macbeth_ridge(
36 features: Mapping[str, pd.DataFrame], label: pd.DataFrame, *, signs: Mapping[str, float], kappa: int = 36, ridge: float = 1.0, horizon: int = 21,
37 purge_sessions: int = 21, every: int = 21, start: str,
38) -> pd.DataFrame:
39 """Session x ticker scores from `start`. The score at D is the features at D times the mean of the last `kappa` monthly slopes whose label had
40 fully ended by D - `purge_sessions`. A mean slope whose sign disagrees with `signs` counts as zero, so noise can't flip a published premium, and
41 with every slope at zero the row is NaN. With fewer than `MIN_SLOPE_MONTHS` slopes it uses the signs as equal weights."""
42 names = sorted(signs)
43 missing = [name for name in names if name not in features]
44 if missing:
45 raise KeyError(f"features {missing} are not in this cell")
46 index, columns = list(label.index), list(label.columns)
47 ranks = _rank_matrix(features, names, index, columns)
48 prior = np.array([float(signs[name]) for name in names])
49 labels = label.to_numpy(dtype=float)
50 position = {date: row for row, date in enumerate(index)}
51 if start not in position:
52 later = [row for row, date in enumerate(index) if date >= start]
53 if not later:
54 return pd.DataFrame(np.nan, index=index, columns=columns, dtype=float)
55 first = later[0]
56 else:
57 first = position[start]
58 slope_rows = list(range(0, len(index), max(1, int(every))))
59 slopes: dict[int, np.ndarray] = {}
60 out = np.full(labels.shape, np.nan)
61 for row in range(first, len(index)):
62 usable = [slope_row for slope_row in slope_rows if slope_row + int(horizon) + int(purge_sessions) <= row]
63 for slope_row in usable[-int(kappa):]:
64 if slope_row not in slopes:
65 value = monthly_slope(ranks[slope_row], labels[slope_row], ridge=ridge)
66 slopes[slope_row] = np.full(len(names), np.nan) if value is None else value
67 recent = [slopes[slope_row] for slope_row in usable[-int(kappa):] if np.isfinite(slopes[slope_row]).all()]
68 if len(recent) < MIN_SLOPE_MONTHS:
69 weights = prior
70 else:
71 mean = np.mean(recent, axis=0)
72 weights = np.where(np.sign(mean) == np.sign(prior), mean, 0.0)
73 if not np.any(weights):
74 continue # every slope disagrees with its prior: no view today, not a bet against the evidence
75 present = np.isfinite(ranks[row]).any(axis=1)
76 scored = np.nan_to_num(ranks[row], nan=0.0) @ weights
77 out[row, present] = scored[present]
78 return pd.DataFrame(out, index=index, columns=columns)