Coverage for scripts/build_holdout_dataset.py: 100%

67 statements  

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

1"""Build the out-of-window holdout dataset (V5.7.0, todo.md finding 10) from `data_holdout/` and the ACTIVE scaler. 

2 

3Run after `scripts/build_holdout_data.py --apply`. The features come from the same builders as the training dataset 

4(`train.build_feature_dataset`) on the holdout root; scaling uses the active `ml/scaler_stats.json` (never refit), the 

5asset-quality flags and eligibility come from the active dataset manifest (so the tradable pool is the live one), and 

6the `backtest` window of the written file is the holdout window. `aq evaluate ... --dataset holdout` then scores any 

7model on it. Writes `ml/datasets/holdout_dataset.csv` (gitignored with the other datasets). 

8 

9 python scripts/build_holdout_dataset.py [--root data] [--start <holdout start>] [--end <holdout end>] 

10 [--config-path config.json] [--windows-config config.json] [--output ml/datasets/holdout_dataset.csv] 

11 

12V5.8.0: the data window was extended to 2026 inside `data/`, so the default root is `data` and the default window is 

13`phase1.windows.holdout`. `--config-path` selects the feature definition (the config the scored models were trained 

14with - e.g. the pre-V5.8.0 config for the shipped V5.6.0 models), `--windows-config` the train/validation windows of the 

15written splits (e.g. the V5.8.0 config); that pair builds the baseline dataset that scores the ACTIVE models on the new 

16splits (`ml/datasets/v580_active_dataset.csv`). 

17 

18V6.0.0: `--full-splits` writes ONE dataset with all four splits of `--windows-config` (train / validation / backtest 

19from the training windows, `holdout` for the rows from `phase1.windows.holdout.start` on), scaled with the active 

20scaler; `--write-split-files` also writes `train_dataset.csv`, `validation_dataset.csv` and `backtest_dataset.csv` next 

21to `--output` (the files the trainers read). That is how `ml/datasets/full_dataset.csv` is refreshed without refitting 

22the scaler the installed models were trained with (`train.py --dataset-only` would refit it). 

23 

24Heavy (same cost as a dataset build): run it on the Codespace, never on the dev PC. 

25""" 

26 

27from __future__ import annotations 

28 

29import argparse 

30import json 

31import sys 

32from pathlib import Path 

33 

34ROOT_DIR = Path(__file__).resolve().parents[1] 

35sys.path.insert(0, str(ROOT_DIR)) 

36 

37import train # noqa: E402 

38 

39SPLIT_FILE_NAMES = {"train": "train_dataset.csv", "validation": "validation_dataset.csv", "backtest": "backtest_dataset.csv"} 

40 

41 

42def label_holdout_rows(dataset, holdout_start: str): 

43 """Rows of the extended `backtest` window dated on or after `holdout_start` become split `holdout`.""" 

44 import pandas as pd 

45 

46 dates = pd.to_datetime(dataset["date"]) 

47 in_holdout = (dataset["split"] == "backtest") & (dates >= pd.Timestamp(holdout_start)) 

48 dataset.loc[in_holdout.to_numpy(), "split"] = "holdout" 

49 return dataset 

50 

51 

52def full_split_window(windows: dict) -> tuple[str, str]: 

53 """(start, end) of the dataset's extended backtest window: the backtest split through the end of the holdout.""" 

54 if "holdout" not in windows: 

55 raise ValueError("--full-splits needs phase1.windows.holdout") 

56 return windows["backtest"]["start"], windows["holdout"]["end"] 

57 

58 

59def main() -> int: 

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

61 parser.add_argument("--root", default="data") 

62 parser.add_argument("--start", default=None, help="default: phase1.windows.holdout.start of --windows-config") 

63 parser.add_argument("--end", default=None, help="default: phase1.windows.holdout.end of --windows-config") 

64 parser.add_argument("--config-path", default=str(ROOT_DIR / "config.json")) 

65 parser.add_argument("--windows-config", default=str(ROOT_DIR / "config.json")) 

66 parser.add_argument("--output", default=str(ROOT_DIR / "ml" / "datasets" / "holdout_dataset.csv")) 

67 parser.add_argument("--full-splits", action="store_true", help="V6.0.0: train/validation/backtest/holdout in one file") 

68 parser.add_argument("--write-split-files", action="store_true", help="V6.0.0: also the per-split files the trainers read") 

69 # V6.6.10: a retrained candidate's rows past its own dataset are scaled with ITS scaler and pool, not the installed ones 

70 parser.add_argument("--scaler-stats", default=str(ROOT_DIR / "ml" / "scaler_stats.json"), help="the scaler to apply (default: the active one)") 

71 parser.add_argument("--manifest", default=str(ROOT_DIR / "ml" / "dataset_manifest.json"), help="the asset-quality flags to apply (default: the active ones)") 

72 args = parser.parse_args() 

73 

74 config = json.loads(Path(args.config_path).read_text(encoding="utf-8")) 

75 windows_source = json.loads(Path(args.windows_config).read_text(encoding="utf-8"))["phase1"]["windows"] 

76 config["phase1"]["windows"] = { 

77 **config["phase1"]["windows"], 

78 **{key: windows_source[key] for key in ("training", "validation", "backtest") if key in windows_source}, 

79 } 

80 holdout_window = windows_source.get("holdout") or {} 

81 if args.full_splits: 

82 args.start, args.end = full_split_window(windows_source) 

83 args.start = args.start or holdout_window.get("start") 

84 args.end = args.end or holdout_window.get("end") 

85 if not args.start or not args.end: 

86 parser.error("no --start/--end and no phase1.windows.holdout in --windows-config") 

87 scaler_stats = json.loads(Path(args.scaler_stats).read_text(encoding="utf-8")) 

88 manifest = json.loads(Path(args.manifest).read_text(encoding="utf-8")) 

89 

90 holdout_config, dropped = train.build_holdout_config(config, args.root, args.start, args.end) 

91 print(f"assets kept: {len(holdout_config['phase1']['universe']['assets'])}, dropped (no holdout zip): {dropped}") 

92 dataset, _metadata = train.build_feature_dataset(holdout_config) 

93 dataset = train.apply_asset_quality_flags(dataset, manifest["asset_quality"]) 

94 dataset = train.apply_scaler_stats(dataset, scaler_stats) 

95 dataset, _ = train.add_asset_context_features(dataset, [asset["ticker"] for asset in holdout_config["phase1"]["universe"]["assets"]]) 

96 dataset, _ = train.add_asset_class_context_features(dataset, train.asset_class_by_ticker_from_config(holdout_config)) 

97 

98 if args.full_splits: 

99 dataset = label_holdout_rows(dataset, holdout_window["start"]) 

100 print("rows per split:", dataset["split"].value_counts(dropna=False).to_dict()) 

101 holdout_rows = dataset[dataset["split"] == ("holdout" if args.full_splits else "backtest")] 

102 print( 

103 f"rows: {len(dataset)} total, {len(holdout_rows)} in the holdout window " 

104 f"({holdout_rows['date'].min()}..{holdout_rows['date'].max()}), {holdout_rows['ticker'].nunique()} tickers" 

105 ) 

106 Path(args.output).parent.mkdir(parents=True, exist_ok=True) 

107 dataset.to_csv(args.output, index=False) 

108 print(f"written {args.output}; dropped assets: {dropped}") 

109 if args.write_split_files: 

110 for split, name in SPLIT_FILE_NAMES.items(): 

111 target = Path(args.output).parent / name 

112 dataset[dataset["split"] == split].to_csv(target, index=False) 

113 print(f"written {target}") 

114 return 0 

115 

116 

117if __name__ == "__main__": 

118 raise SystemExit(main())