Coverage for train_cross_sectional.py: 100%
244 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 new-architecture track of V6.5.0: rank models that see the whole cross-section of a date, walked forward by year.
3The installed MLP and TCN score each asset alone. A set transformer reads all of a date's assets at once, so an asset's
4score can depend on the others; a gradient-boosted ranker is the non-neural comparison. Both read within-class ranks of the
5scaled features (a rank is unchanged by a scaler fitted on later data, so a window needs no scaler of its own) and
6learn the 20-day sector-neutral rank centred per (date, class), so knowing an asset's group earns nothing (Problems.md #259).
8 python train_cross_sectional.py --dataset ml/datasets/full_dataset.csv --model set_transformer --variant a \\
9 --seeds 1,2,3 --out ml/evaluation/v650/scores/t5_st_a.csv --score-end 2023-06-30
11`--score-end` is the guard of the selection window: nothing later is written to the score file.
13V6.6.0 adds the wide universe. `--panel` reads `scripts/v660_build_panel.py`'s parquet of one side's names, so a rank or a label can't
14see the other side, and `--score-panel` scores another panel (the held-out side) with the same yearly models. `mlp_multitask` is the
15installed model's own network family, on its rank head.
16"""
18from __future__ import annotations
20import argparse
21import json
22import logging
23import math
24from pathlib import Path
26import numpy as np
27import pandas as pd
29from features.training_splits import FIRST_TEST_YEAR, PURGE_DAYS, TARGET, annual_windows, centred_label, rank_inputs
31LOGGER = logging.getLogger("train_cross_sectional")
32EARLY_STOP_GAP_SESSIONS = 22
33SET_TRANSFORMER_VARIANTS = {"a": {"d": 32, "layers": 2, "heads": 2, "dropout": 0.3}, "b": {"d": 64, "layers": 2, "heads": 4, "dropout": 0.4}}
34GBM_VARIANTS = {"a": {"max_depth": 3, "learning_rate": 0.03, "max_iter": 300}, "b": {"max_depth": 5, "learning_rate": 0.02, "max_iter": 400}}
37def load_frame(dataset: Path, config: dict, schema: dict) -> tuple[pd.DataFrame, list[str]]:
38 from features.cross_sectional_inputs import asset_class_by_ticker
40 features = list(schema["scaled_feature_names"])
41 usecols = ["date", "ticker", TARGET, *features]
42 frame = pd.read_csv(dataset, usecols=usecols, dtype=dict.fromkeys([TARGET, *features], "float32"))
43 frame["date"] = frame["date"].astype(str).str[:10]
44 classes = asset_class_by_ticker(config)
45 frame["_class"] = frame["ticker"].astype(str).map(lambda ticker: classes.get(ticker, "unknown"))
46 frame[features] = rank_inputs(frame, features)
47 frame["_label"] = centred_label(frame)
48 return frame.sort_values(["date", "ticker"]).reset_index(drop=True), features
51def fit_predict_gbm(train: pd.DataFrame, test: pd.DataFrame, features: list[str], variant: str, seed: int) -> np.ndarray:
52 from evaluation.research_probes import fit_hgb_rank, predict_scores
54 usable = train[train["_label"].notna()]
55 model = fit_hgb_rank(
56 usable[features].to_numpy(np.float32), usable["_label"].to_numpy(np.float64),
57 min_samples_leaf=200, l2_regularization=1.0, random_state=seed, **GBM_VARIANTS[variant],
58 )
59 return predict_scores(model, test[features].to_numpy(np.float64))
62# V6.6.1: the fundamentals era. Signs are the published ones (`portfolio/wide_signals.py`), fixed before any score.
63FUNDAMENTAL_SIGNS = {
64 "gp_assets": 1.0, "net_issuance": -1.0, "asset_growth": -1.0, "accruals": -1.0, "earnings_yield": 1.0, "book_to_market": 1.0, "leverage": -1.0, "cfo_assets": 1.0,
65 "resmom_252": 1.0, "overnight_ret_252": 1.0, "dist_52w_high": 1.0, "beta_252": -1.0,
66}
69def fit_predict_monotone_gbm(train: pd.DataFrame, test: pd.DataFrame, features: list[str], variant: str, seed: int) -> np.ndarray:
70 """A small tree model held to each feature's published sign, so it can't learn a premium backward from a few years of data."""
71 from sklearn.ensemble import HistGradientBoostingRegressor
73 usable = train[train["_label"].notna()]
74 model = HistGradientBoostingRegressor(
75 max_depth=3, learning_rate=0.05, max_iter=200, min_samples_leaf=500, l2_regularization=1.0, random_state=seed,
76 monotonic_cst=[int(np.sign(FUNDAMENTAL_SIGNS.get(name, 0.0))) for name in features],
77 )
78 model.fit(usable[features].to_numpy(np.float32), usable["_label"].to_numpy(np.float64))
79 return model.predict(test[features].to_numpy(np.float64))
82def _set_ranker(num_features: int, num_classes: int, spec: dict):
83 import torch
84 from torch import nn
86 class SetRanker(nn.Module):
87 """Self-attention over one date's assets. No positional encoding: the assets are a set, so the score of an asset
88 must not depend on the order they are listed in."""
90 def __init__(self):
91 super().__init__()
92 self.classes = nn.Embedding(num_classes, 4)
93 self.project = nn.Linear(num_features + 4, spec["d"])
94 layer = nn.TransformerEncoderLayer(
95 spec["d"], spec["heads"], dim_feedforward=2 * spec["d"], dropout=spec["dropout"], batch_first=True, activation="gelu"
96 )
97 self.encoder = nn.TransformerEncoder(layer, spec["layers"], enable_nested_tensor=False)
98 self.head = nn.Linear(spec["d"], 1)
100 def forward(self, inputs: torch.Tensor, class_ids: torch.Tensor) -> torch.Tensor:
101 hidden = self.project(torch.cat([inputs, self.classes(class_ids)], dim=-1))
102 return self.head(self.encoder(hidden)).squeeze(-1)
104 return SetRanker()
107def _date_batches(frame: pd.DataFrame, features: list[str], class_index: dict[str, int]) -> list[dict]:
108 import torch
110 batches = []
111 for date, group in frame.groupby("date", sort=True):
112 labels = group["_label"].to_numpy(np.float32)
113 batches.append({
114 "date": date,
115 "x": torch.from_numpy(group[features].to_numpy(np.float32)).unsqueeze(0),
116 "c": torch.tensor([class_index.get(name, 0) for name in group["_class"]], dtype=torch.long).unsqueeze(0),
117 "y": torch.from_numpy(np.nan_to_num(labels)),
118 "mask": torch.from_numpy(np.isfinite(labels)),
119 "index": group.index.to_numpy(),
120 })
121 return batches
124def _date_ic(scores: np.ndarray, labels: np.ndarray) -> float | None:
125 keep = np.isfinite(labels)
126 if keep.sum() < 10:
127 return None
128 ranked = pd.Series(scores[keep]).rank().to_numpy()
129 target = pd.Series(labels[keep]).rank().to_numpy()
130 if ranked.std() == 0.0 or target.std() == 0.0:
131 return None
132 return float(np.corrcoef(ranked, target)[0, 1])
135def fit_predict_set_transformer(
136 train: pd.DataFrame, test: pd.DataFrame, features: list[str], variant: str, seed: int,
137 *, max_epochs: int = 20, patience: int = 3, learning_rate: float = 1e-3, weight_decay: float = 0.04, accumulate: int = 8,
138) -> np.ndarray:
139 import torch
141 from train import soft_spearman_loss
143 torch.manual_seed(seed)
144 rng = np.random.default_rng(seed)
145 classes = sorted(set(train["_class"]) | set(test["_class"]))
146 class_index = {name: i for i, name in enumerate(classes)}
147 model = _set_ranker(len(features), len(classes), SET_TRANSFORMER_VARIANTS[variant])
148 optimizer = torch.optim.AdamW(model.parameters(), lr=learning_rate, weight_decay=weight_decay)
150 batches = _date_batches(train, features, class_index)
151 # the tail of the training span, kept out by the same purge, decides when to stop
152 split = max(1, int(len(batches) * 0.85))
153 fit_batches, stop_batches = batches[: max(1, split - EARLY_STOP_GAP_SESSIONS)], batches[split:]
154 best_ic, best_state, stale = -math.inf, None, 0
155 for epoch in range(max_epochs):
156 model.train()
157 optimizer.zero_grad()
158 for position, index in enumerate(rng.permutation(len(fit_batches))):
159 batch = fit_batches[int(index)]
160 scores = model(batch["x"], batch["c"]).squeeze(0)
161 groups = torch.zeros_like(scores, dtype=torch.long)
162 loss = soft_spearman_loss(scores, batch["y"], groups, batch["mask"], 0.1)
163 loss = loss + 0.1 * ((scores[batch["mask"]] - batch["y"][batch["mask"]]) ** 2).mean()
164 (loss / accumulate).backward()
165 if (position + 1) % accumulate == 0:
166 torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0)
167 optimizer.step()
168 optimizer.zero_grad()
169 model.eval()
170 with torch.no_grad():
171 ics = [_date_ic(model(b["x"], b["c"]).squeeze(0).numpy(), np.where(b["mask"].numpy(), b["y"].numpy(), np.nan)) for b in stop_batches]
172 finite = [value for value in ics if value is not None]
173 score = float(np.mean(finite)) if finite else -math.inf
174 LOGGER.info("epoch %d stopping-span IC %.4f", epoch, score)
175 if score > best_ic:
176 best_ic, stale = score, 0
177 best_state = {key: value.clone() for key, value in model.state_dict().items()}
178 else:
179 stale += 1
180 if stale >= patience:
181 break
182 if best_state is not None:
183 model.load_state_dict(best_state)
184 model.eval()
185 predictions = np.full(len(test), np.nan)
186 positions = {index: i for i, index in enumerate(test.index)}
187 with torch.no_grad():
188 for batch in _date_batches(test, features, class_index):
189 scores = model(batch["x"], batch["c"]).squeeze(0).numpy()
190 for index, value in zip(batch["index"], scores, strict=False):
191 predictions[positions[index]] = float(value)
192 return predictions
195MLP_VARIANTS = {"a": {"hidden_layers": [128, 64], "dropout": 0.15}, "b": {"hidden_layers": [64, 32], "dropout": 0.3}}
198def fit_predict_mlp_multitask(
199 train: pd.DataFrame, test: pd.DataFrame, features: list[str], variant: str, seed: int,
200 *, max_epochs: int = 20, patience: int = 3, learning_rate: float = 1e-3, weight_decay: float = 0.04,
201) -> np.ndarray:
202 """`AetherNetMultiTaskHorizons`, the installed family, fitted on its rank_20d head by date: the same soft Spearman plus MSE anchor
203 and the same early stop as the set transformer. It scores each asset alone."""
204 import torch
206 from train import AetherNetMultiTaskHorizons, soft_spearman_loss
208 torch.manual_seed(seed)
209 rng = np.random.default_rng(seed)
210 spec = MLP_VARIANTS[variant]
211 model = AetherNetMultiTaskHorizons(len(features), spec["hidden_layers"], spec["dropout"], "relu", "layernorm")
212 optimizer = torch.optim.AdamW(model.parameters(), lr=learning_rate, weight_decay=weight_decay)
213 classes = {name: i for i, name in enumerate(sorted(set(train["_class"]) | set(test["_class"])))}
214 batches = _date_batches(train, features, classes)
215 split = max(1, int(len(batches) * 0.85))
216 fit_batches, stop_batches = batches[: max(1, split - EARLY_STOP_GAP_SESSIONS)], batches[split:]
218 def rank_scores(inputs: torch.Tensor) -> torch.Tensor:
219 return model(inputs)["rank_20d"].reshape(-1)
221 best_ic, best_state, stale = -math.inf, None, 0
222 for _ in range(max_epochs):
223 model.train()
224 for index in rng.permutation(len(fit_batches)):
225 batch = fit_batches[int(index)]
226 optimizer.zero_grad()
227 scores = rank_scores(batch["x"].squeeze(0))
228 groups = torch.zeros_like(scores, dtype=torch.long)
229 loss = soft_spearman_loss(scores, batch["y"], groups, batch["mask"], 0.1)
230 loss = loss + 0.1 * ((scores[batch["mask"]] - batch["y"][batch["mask"]]) ** 2).mean()
231 loss.backward()
232 torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0)
233 optimizer.step()
234 model.eval()
235 with torch.no_grad():
236 ics = [_date_ic(rank_scores(b["x"].squeeze(0)).numpy(), np.where(b["mask"].numpy(), b["y"].numpy(), np.nan)) for b in stop_batches]
237 finite = [value for value in ics if value is not None]
238 score = float(np.mean(finite)) if finite else -math.inf
239 if score > best_ic:
240 best_ic, stale = score, 0
241 best_state = {key: value.clone() for key, value in model.state_dict().items()}
242 else:
243 stale += 1
244 if stale >= patience:
245 break
246 if best_state is not None:
247 model.load_state_dict(best_state)
248 model.eval()
249 with torch.no_grad():
250 return rank_scores(torch.from_numpy(test[features].to_numpy(np.float32))).numpy().astype(np.float64)
253FITTERS = {"gbm": fit_predict_gbm, "set_transformer": fit_predict_set_transformer, "mlp_multitask": fit_predict_mlp_multitask, "gbm_monotone": fit_predict_monotone_gbm}
256def load_panel_frame(panel: Path, *, feature_set: str, target: str, train_start: str | None = None) -> tuple[pd.DataFrame, list[str]]:
257 """One side's parquet. Ranks and labels are computed on what the file holds, so a file of one side's names can't leak the other. `train_start`
258 drops earlier rows, for a model that should only learn from years that hold its features (filings: 19 names in 2009, 466 in 2011)."""
259 from features.wide_panel import INFO_FEATURES, PRICE_FEATURES
261 wanted = {"price": list(PRICE_FEATURES), "fundamental": list(FUNDAMENTAL_SIGNS)}.get(feature_set, [*PRICE_FEATURES, *INFO_FEATURES])
262 frame = pd.read_parquet(panel)
263 if feature_set == "fundamental":
264 missing = [name for name in wanted if name not in frame.columns]
265 if missing:
266 raise ValueError(f"the panel has no {missing}: a missing feature must not silently change the model")
267 if train_start:
268 frame = frame[frame["date"].astype(str).str[:10] >= train_start]
269 features = [name for name in wanted if name in frame.columns]
270 frame = frame.rename(columns={"sector": "_class"})
271 frame["date"] = frame["date"].astype(str).str[:10]
272 frame[features] = rank_inputs(frame, features)
273 frame["_label"] = frame[target].astype("float32")
274 keep = ["date", "ticker", "_class", "_label", *features]
275 return frame[keep].sort_values(["date", "ticker"]).reset_index(drop=True), features
278def walk_forward_scores(
279 frame: pd.DataFrame, features: list[str], model: str, variant: str, seeds: list[int], *, score_end: str | None,
280 first_test_year: int = FIRST_TEST_YEAR, purge_days: int = PURGE_DAYS, score_frame: pd.DataFrame | None = None, max_epochs: int | None = None,
281 cache_dir: Path | None = None,
282) -> pd.DataFrame:
283 """date, ticker, score for every test year, averaged over the seeds. Test rows past `score_end` are never scored. With `score_frame`,
284 training still reads `frame` alone and each year's model scores `score_frame`'s rows. With `cache_dir` (V6.6.10), each year's scores
285 are saved as they are made and a year already saved is read back instead of trained: a stopped run continues at its next year."""
286 pieces = []
287 scored = frame if score_frame is None else score_frame
288 for window in annual_windows(sorted(scored["date"].unique()), first_test_year=first_test_year, purge_days=purge_days):
289 if score_end is not None and window["test_start"] > score_end:
290 break
291 last = window["test_end"] if score_end is None else min(window["test_end"], score_end)
292 train = frame[frame["date"] <= window["train_end"]]
293 test = scored[(scored["date"] >= window["test_start"]) & (scored["date"] <= last)]
294 if train.empty or test.empty:
295 continue
296 cached = Path(cache_dir) / f"{window['test_start']}_{last}.csv" if cache_dir is not None else None
297 if cached is not None and cached.exists():
298 LOGGER.info("window %s: scored before, read from %s", window["test_start"], cached)
299 pieces.append(pd.read_csv(cached, dtype={"date": str, "ticker": str}))
300 continue
301 LOGGER.info("window %s: %d train rows, %d test rows", window["test_start"], len(train), len(test))
302 extra = {"max_epochs": max_epochs} if max_epochs else {}
303 predictions = np.mean([FITTERS[model](train, test, features, variant, seed, **extra) for seed in seeds], axis=0)
304 piece = pd.DataFrame({"date": test["date"].to_numpy(), "ticker": test["ticker"].to_numpy(), "score": predictions})
305 if cached is not None:
306 cached.parent.mkdir(parents=True, exist_ok=True)
307 partial = cached.with_name(cached.name + ".partial")
308 piece.to_csv(partial, index=False, lineterminator="\n")
309 partial.replace(cached)
310 pieces.append(piece)
311 return pd.concat(pieces, ignore_index=True) if pieces else pd.DataFrame(columns=["date", "ticker", "score"])
314def main(argv: list[str] | None = None) -> int:
315 logging.basicConfig(level=logging.INFO, format="%(asctime)s %(message)s")
316 parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
317 parser.add_argument("--dataset", default="ml/datasets/full_dataset.csv")
318 parser.add_argument("--config", default="config.json")
319 parser.add_argument("--schema", default="ml/feature_schema.json")
320 parser.add_argument("--model", choices=sorted(FITTERS), required=True)
321 parser.add_argument("--variant", choices=["a", "b"], required=True)
322 parser.add_argument("--seeds", default="1,2,3")
323 parser.add_argument("--out", required=True)
324 parser.add_argument("--score-end", default=None)
325 parser.add_argument("--panel", default=None, help="a side's parquet from scripts/v660_build_panel.py, instead of --dataset")
326 parser.add_argument("--score-panel", default=None, help="score this panel's rows with the same yearly models")
327 parser.add_argument("--feature-set", choices=["price", "all", "fundamental"], default="all")
328 parser.add_argument("--train-start", default=None, help="drop panel rows before this date from training")
329 parser.add_argument("--target", default="target_wide_20d")
330 parser.add_argument("--first-test-year", type=int, default=FIRST_TEST_YEAR)
331 parser.add_argument("--purge-days", type=int, default=PURGE_DAYS)
332 parser.add_argument("--max-epochs", type=int, default=None, help="neural models only: the compute fallback rules.json fixes in advance")
333 parser.add_argument("--year-cache", default=None, help="save each test year's scores here and reuse them, so a stopped run continues at its next year")
334 args = parser.parse_args(argv)
335 cache = Path(args.year_cache) if args.year_cache else None
336 seeds = [int(seed) for seed in args.seeds.split(",")]
337 if args.panel:
338 frame, features = load_panel_frame(Path(args.panel), feature_set=args.feature_set, target=args.target, train_start=args.train_start)
339 score_frame = load_panel_frame(Path(args.score_panel), feature_set=args.feature_set, target=args.target)[0] if args.score_panel else None
340 scores = walk_forward_scores(
341 frame, features, args.model, args.variant, seeds, score_end=args.score_end, first_test_year=args.first_test_year, purge_days=args.purge_days,
342 score_frame=score_frame, max_epochs=args.max_epochs, cache_dir=cache,
343 )
344 else:
345 config = json.loads(Path(args.config).read_text(encoding="utf-8"))
346 schema = json.loads(Path(args.schema).read_text(encoding="utf-8"))
347 frame, features = load_frame(Path(args.dataset), config, schema)
348 scores = walk_forward_scores(frame, features, args.model, args.variant, seeds, score_end=args.score_end, cache_dir=cache)
349 out = Path(args.out)
350 out.parent.mkdir(parents=True, exist_ok=True)
351 scores.to_csv(out, index=False, lineterminator="\n", float_format="%.6f")
352 LOGGER.info("wrote %d scores, %s..%s, to %s", len(scores), scores["date"].min(), scores["date"].max(), out)
353 return 0
356if __name__ == "__main__":
357 raise SystemExit(main())