Coverage for scripts/v650_ml_scores.py: 100%

68 statements  

« prev     ^ index     » next       coverage.py v7.17.3, created at 2026-11-22 12:55 +0000

1"""Out-of-sample score tables of a walk-forward run (V6.5.0, tracks T1 and T2). 

2 

3Each window's model scores only that window's backtest split, from that window's own dataset and scaler, so no row is scored 

4by a model that saw its label. `--end` is the guard of the selection window: nothing later reaches the score file. 

5 

6 python scripts/v650_ml_scores.py --run-id walk-forward-<id> --end 2023-06-30 

7""" 

8 

9from __future__ import annotations 

10 

11import argparse 

12import json 

13import sys 

14from pathlib import Path 

15 

16import numpy as np 

17import pandas as pd 

18 

19ROOT = Path(__file__).resolve().parents[1] 

20sys.path.insert(0, str(ROOT)) 

21 

22OUT = ROOT / "ml" / "evaluation" / "v650" / "scores" 

23EXPORTS = {"multitask": ("multitask_model.json", "multitask_feature_schema.json"), 

24 "sequence": ("sequence_model.json", "sequence_feature_schema.json")} 

25HEADS = ("rank_20d", "rank_5d", "sector_neutral_rank_20d") 

26 

27 

28def window_heads(window_dir: Path, frame: pd.DataFrame, mask: np.ndarray, kind: str, sequence_window: int) -> dict[str, np.ndarray] | None: 

29 """Head values for the masked rows; None when this window's trainer wrote no artifacts.""" 

30 from evaluation.model_predictions import predict_heads 

31 

32 model_name, schema_name = EXPORTS[kind] 

33 if not (window_dir / model_name).exists(): 

34 return None 

35 export = json.loads((window_dir / model_name).read_text(encoding="utf-8")) 

36 schema = json.loads((window_dir / schema_name).read_text(encoding="utf-8")) 

37 return predict_heads( 

38 frame, export, schema["model_input_names"], list(HEADS), model_kind=kind, 

39 sequence_feature_schema=schema if kind == "sequence" else None, configured_window_size=sequence_window, 

40 row_mask=mask, batched=True, 

41 ) 

42 

43 

44def daily_rank(frame: pd.DataFrame, values: np.ndarray) -> pd.Series: 

45 return pd.Series(values, index=frame.index).groupby(frame["date"]).rank(pct=True) 

46 

47 

48def tables_for_window(window_dir: Path, *, end: str, sequence_window: int) -> dict[str, pd.DataFrame]: 

49 from retraining.slicing import read_csv_float32 

50 

51 # float32 in chunks (V6.6.10): a window's dataset is up to 2.2 GB of text; the models read float32 inputs either way 

52 frame = read_csv_float32(window_dir / "full_dataset.csv") 

53 frame["date"] = frame["date"].astype(str).str[:10] 

54 frame = frame.sort_values(["ticker", "date"]).reset_index(drop=True) 

55 mask = ((frame["split"] == "backtest") & (frame["date"] <= end)).to_numpy() 

56 if not mask.any(): 

57 return {} 

58 multitask = window_heads(window_dir, frame, mask, "multitask", sequence_window) 

59 sequence = window_heads(window_dir, frame, mask, "sequence", sequence_window) 

60 out: dict[str, pd.DataFrame] = {} 

61 

62 def add(name: str, values: pd.Series) -> None: 

63 out[name] = pd.DataFrame({"date": frame.loc[mask, "date"], "ticker": frame.loc[mask, "ticker"], "score": values[mask]}) 

64 

65 if sequence is not None: 

66 add("ml_a1", (daily_rank(frame, sequence["rank_20d"]) + daily_rank(frame, sequence["rank_5d"])) / 2.0) 

67 add("ml_a3", pd.Series(sequence["sector_neutral_rank_20d"], index=frame.index)) 

68 if multitask is not None: 

69 add("ml_a2", pd.Series(multitask["sector_neutral_rank_20d"], index=frame.index)) 

70 return out 

71 

72 

73def main() -> int: 

74 parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) 

75 parser.add_argument("--run-id", required=True) 

76 parser.add_argument("--end", required=True) 

77 parser.add_argument("--sequence-window", type=int, default=30) 

78 parser.add_argument("--out", default=None, help="where the score tables go (default ml/evaluation/v650/scores; a stack retrain writes into its own run folder)") 

79 args = parser.parse_args() 

80 out = Path(args.out) if args.out else OUT 

81 out = out if out.is_absolute() else ROOT / out 

82 run_dir = ROOT / "ml" / "versions" / args.run_id 

83 pieces: dict[str, list[pd.DataFrame]] = {} 

84 windows = sorted(run_dir.glob("window_*"), key=lambda path: int(path.name.split("_")[1])) 

85 for window_dir in windows: 

86 if not (window_dir / "full_dataset.csv").exists(): 

87 print(f"{window_dir.name}: no dataset", flush=True) 

88 continue 

89 for name, table in tables_for_window(window_dir, end=args.end, sequence_window=args.sequence_window).items(): 

90 pieces.setdefault(name, []).append(table) 

91 print(f"{window_dir.name} {name}: {len(table)} rows {table['date'].min()}..{table['date'].max()}", flush=True) 

92 out.mkdir(parents=True, exist_ok=True) 

93 for name, tables in pieces.items(): 

94 merged = pd.concat(tables, ignore_index=True).drop_duplicates(["date", "ticker"], keep="last").sort_values(["date", "ticker"]) 

95 merged.to_csv(out / f"{name}.csv", index=False, lineterminator="\n", float_format="%.6f") 

96 print(f"{name}: {len(merged)} rows to {merged['date'].max()}", flush=True) 

97 return 0 

98 

99 

100if __name__ == "__main__": 

101 raise SystemExit(main())