Coverage for evaluation/pipeline.py: 100%
131 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"""One command from data to a verdict (V6.6.10): `aq pipeline run` for any project, `aq init`'s template or no project at all.
3A pipeline is a short TOML file. Its stages run in order and each records its result in `<runs>/<run id>/state.json`, so a run
4stopped by a reboot continues where it was:
6 data the closes: the bundled sample, or a wide CSV (a date column, one column per ticker)
7 signal your `score(closes)` from the signal file: a dates x tickers table, higher = expected to do better
8 train optional: a small model trained on the same closes (the example-model recipe, `--memory-profile low`), scored too
9 evaluate each signal's alpha report: IC by horizon, half-life, the long-short spread after costs, breadth
10 gate the thresholds the file wrote before the run: IC and its t at the gate horizon
11 report report.json and report.md in the run folder
13 [pipeline]
14 name = "my-signal"
15 data = "sample" # or "data/closes.csv"
16 signal = "my_signal.py"
17 train = false # true: also train and score a small model
19 [gate]
20 horizon = 20
21 min_ic = 0.02
22 min_t = 2.0
23"""
25from __future__ import annotations
27import datetime
28import importlib.util
29import json
30import sys
31from collections.abc import Callable, Mapping, Sequence
32from pathlib import Path
33from typing import Any
35import pandas as pd
37STAGES = ("data", "signal", "train", "evaluate", "gate", "report")
38DEFAULTS: dict[str, Any] = {
39 "pipeline": {"name": "pipeline", "data": "sample", "signal": "my_signal.py", "train": False, "cost_bps": 10.0},
40 "gate": {"horizon": 20, "min_ic": 0.02, "min_t": 2.0},
41}
42SMOKE_SIGNAL = "momentum_20"
45def load_pipeline(path: Path | None) -> dict[str, Any]:
46 """The pipeline file merged over the defaults; no file is the defaults (the bundled sample and 20-session momentum)."""
47 spec = {section: dict(values) for section, values in DEFAULTS.items()}
48 if path is None:
49 spec["pipeline"]["signal"] = SMOKE_SIGNAL
50 return spec
51 if sys.version_info < (3, 11):
52 raise ValueError("a pipeline file needs Python 3.11 or newer (tomllib); without a file, the defaults run on 3.10")
53 import tomllib # novermin (guarded above: the library itself runs on 3.10)
55 loaded = tomllib.loads(Path(path).read_text(encoding="utf-8"))
56 for section, values in loaded.items():
57 spec.setdefault(section, {}).update(values)
58 spec["root"] = str(Path(path).resolve().parent)
59 return spec
62def load_closes(source: str, *, root: Path) -> pd.DataFrame:
63 """`sample` is the library's bundled sample; anything else a wide CSV, relative to the pipeline file."""
64 if source == "sample":
65 from aether_quant.samples import load_sample_prices
67 return load_sample_prices()
68 closes = pd.read_csv(root / source, index_col=0)
69 closes.index = closes.index.astype(str)
70 return closes.astype(float)
73def momentum_20(closes: pd.DataFrame) -> pd.DataFrame:
74 """The smoke run's signal: the return over the last 20 sessions."""
75 return closes.pct_change(20, fill_method=None)
78def load_signal(reference: str, *, root: Path) -> Callable[[pd.DataFrame], pd.DataFrame]:
79 """The `score` function of a signal file (relative to the pipeline file), or the built-in smoke signal."""
80 if reference == SMOKE_SIGNAL:
81 return momentum_20
82 path = root / reference
83 spec = importlib.util.spec_from_file_location(f"aq_pipeline_signal_{path.stem}", path)
84 if spec is None or spec.loader is None:
85 raise FileNotFoundError(f"no signal file at {path}")
86 module = importlib.util.module_from_spec(spec)
87 spec.loader.exec_module(module)
88 if not callable(getattr(module, "score", None)):
89 raise AttributeError(f"{path.name} defines no score(closes)")
90 return module.score
93def gate_verdict(report: Mapping[str, Any], gate: Mapping[str, Any]) -> dict[str, Any]:
94 """Pass iff the IC at the gate horizon and its Newey-West t both reach the thresholds the file set before the run."""
95 horizon = int(gate["horizon"])
96 row = report.get("term_structure", {}).get(horizon) or report.get("term_structure", {}).get(str(horizon)) or {}
97 ic, t_stat = row.get("mean_ic"), row.get("t_hac")
98 passed = ic is not None and t_stat is not None and ic >= float(gate["min_ic"]) and t_stat >= float(gate["min_t"])
99 return {"passed": bool(passed), "horizon": horizon, "mean_ic": ic, "t_hac": t_stat, "min_ic": float(gate["min_ic"]), "min_t": float(gate["min_t"])}
102def run_stages(stages: Sequence[str], actions: Mapping[str, Callable[[], Any]], *, state_path: Path, emit: Callable[[str], None] = print) -> dict:
103 """Each stage once: a finished stage is skipped on a rerun, a failed one reruns. The state is written after every stage."""
104 state = json.loads(state_path.read_text(encoding="utf-8")) if state_path.exists() else {"done": {}}
105 for stage in stages:
106 if stage in state["done"]:
107 emit(f"{stage}: done before, skipped")
108 continue
109 emit(f"{stage}: running")
110 result = actions[stage]()
111 state["done"][stage] = {"at": datetime.datetime.now(datetime.timezone.utc).isoformat(timespec="seconds"), "result": result}
112 state_path.parent.mkdir(parents=True, exist_ok=True)
113 state_path.write_text(json.dumps(state, indent=1, default=str), encoding="utf-8")
114 return state
117def _wide(long: pd.DataFrame) -> pd.DataFrame:
118 return long.pivot(index="date", columns="ticker", values="score").sort_index()
121def pipeline_actions(spec: Mapping[str, Any], *, run_dir: Path, train_model: Callable[..., pd.DataFrame] | None = None) -> dict[str, Callable[[], Any]]:
122 """The stage functions of one run. `train_model(closes, work)` returns long model scores; the default trains the example multitask
123 network (torch, `--memory-profile low`) and is only imported when the file asks for it."""
124 from evaluation.alpha_behaviour import alpha_report
126 root = Path(spec.get("root", "."))
127 settings, gate = spec["pipeline"], spec["gate"]
128 paths = {"closes": run_dir / "closes.csv", "signal": run_dir / "signal.csv", "model": run_dir / "model_scores.csv", "evaluate": run_dir / "evaluate.json"}
130 def data() -> dict:
131 closes = load_closes(str(settings["data"]), root=root)
132 run_dir.mkdir(parents=True, exist_ok=True)
133 closes.to_csv(paths["closes"], index_label="date")
134 return {"sessions": int(len(closes)), "tickers": int(closes.shape[1]), "first": str(closes.index[0]), "last": str(closes.index[-1])}
136 def closes() -> pd.DataFrame:
137 frame = pd.read_csv(paths["closes"], index_col=0)
138 frame.index = frame.index.astype(str)
139 return frame
141 def signal() -> dict:
142 table = load_signal(str(settings["signal"]), root=root)(closes())
143 long = table.stack(future_stack=True).rename("score").reset_index()
144 long.columns = ["date", "ticker", "score"]
145 long.dropna().to_csv(paths["signal"], index=False)
146 return {"rows": int(long["score"].notna().sum())}
148 def train() -> dict:
149 if not settings.get("train"):
150 return {"skipped": "train = false"}
151 trainer = train_model or train_example_model
152 scores = trainer(closes(), run_dir / "model")
153 scores.to_csv(paths["model"], index=False)
154 return {"rows": int(len(scores))}
156 def evaluate() -> dict:
157 prices = closes()
158 groups = dict.fromkeys(prices.columns, "all")
159 reports = {}
160 for name, path in (("signal", paths["signal"]), ("model", paths["model"])):
161 if path.exists():
162 report = alpha_report(_wide(pd.read_csv(path, dtype={"date": str})).reindex(index=prices.index), prices, groups=groups,
163 factors={"momentum_20": momentum_20(prices)}, horizon=int(gate["horizon"]), cost_bps=float(settings.get("cost_bps", 10.0)))
164 reports[name] = report
165 paths["evaluate"].write_text(json.dumps(reports, indent=1, default=str), encoding="utf-8")
166 return {name: report["term_structure"][int(gate["horizon"])] for name, report in reports.items()}
168 def gate_stage() -> dict:
169 reports = json.loads(paths["evaluate"].read_text(encoding="utf-8"))
170 return {name: gate_verdict(report, gate) for name, report in reports.items()}
172 def report() -> str:
173 state = json.loads((run_dir / "state.json").read_text(encoding="utf-8"))
174 verdicts = state["done"]["gate"]["result"]
175 summary = {"name": settings["name"], "data": state["done"]["data"]["result"], "gate": verdicts}
176 (run_dir / "report.json").write_text(json.dumps(summary, indent=1, default=str), encoding="utf-8")
177 lines = [f"# {settings['name']}", "", f"Data: {summary['data']}", ""]
178 lines += [f"- **{name}**: {'PASS' if v['passed'] else 'FAIL'} - IC {v['mean_ic']} (t {v['t_hac']}) at {v['horizon']} sessions; needs IC >= {v['min_ic']}, t >= {v['min_t']}"
179 for name, v in verdicts.items()]
180 (run_dir / "report.md").write_text("\n".join(lines) + "\n", encoding="utf-8")
181 return str(run_dir / "report.md")
183 return {"data": data, "signal": signal, "train": train, "evaluate": evaluate, "gate": gate_stage, "report": report}
186def train_example_model(closes: pd.DataFrame, work: Path) -> pd.DataFrame:
187 """The example multitask network trained on these closes (the example-model recipe), scored on them."""
188 from retraining import model_catalog as catalog
190 root = Path(__file__).resolve().parents[1]
191 if not (root / "scripts" / "build_example_models.py").exists():
192 raise FileNotFoundError("`train = true` trains with the project's trainers: run it from a source checkout (pip install -e \".[train]\")")
193 spec = importlib.util.spec_from_file_location("aq_build_example_models", root / "scripts" / "build_example_models.py")
194 builder = importlib.util.module_from_spec(spec)
195 spec.loader.exec_module(builder)
196 work.mkdir(parents=True, exist_ok=True)
197 frame = catalog.example_dataset(closes)
198 frame.to_csv(work / "dataset.csv", index=False)
199 (work / "schema.json").write_text(json.dumps({"model_input_names": list(catalog.FEATURES)}), encoding="utf-8")
200 (work / "config.json").write_text(json.dumps(builder.training_config(json.loads((root / "config.json").read_text(encoding="utf-8")))), encoding="utf-8")
201 version = builder.train("multitask", work=work, config_path=work / "config.json", dataset=work / "dataset.csv", schema=work / "schema.json")
202 return catalog.score(catalog.load(version), closes)