diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index c8a8e59..0b6d3e6 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -11,10 +11,11 @@ permissions: jobs: test: - runs-on: ubuntu-latest + runs-on: ${{ matrix.os }} strategy: matrix: - python-version: ["3.10", "3.11"] + os: [ubuntu-latest, windows-latest] + python-version: ["3.10", "3.11", "3.12"] steps: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 diff --git a/README.md b/README.md index d491d88..84c92fc 100644 --- a/README.md +++ b/README.md @@ -29,6 +29,27 @@ python -m ruff check src tests `configs/position_only.yaml` 只做仓位择时,股票预算全部留在市场袖套。 +已有研究配置可以先做原生只读预检: + +```powershell +python -m quant_timing preflight --config configs/combined.yaml +``` + +预检与`run`共用来源解析、读取与静态业务校验,检查主市场/风格列、所需信号、现金或期货列、 +外部仓位和宏观输入,以及是否存在带后续收益日期的滚动窗口。输出JSON包含原配置、配置摘要、 +实际读取文件的SHA-256与修改时间、观察区间和结构性折数。预检不生成信号、权重、模拟账本、 +泄漏审计或可发布仓位,也不写文件;动态覆盖、有效计分与最新仓位发布仍在完整研究中判断。 + +来源可显式声明`source.evidence_kind`为`synthetic`、`retrospective`或`user_provided`;缺省为 +`unspecified`,不根据旧`source.mode`或文件名猜测。来源声明不是市场认证。 +相对路径保持原有配置目录/其父目录的解析顺序,预检和执行都固定到实际找到的同一文件。 +`run`重新读取并核对输入,在读取或研究期间变化时拒绝发布;输出目录不得包含来源文件。 +新的`run_context.json`随整套产物原子发布,记录本次输入身份,不改动既有标准CSV口径。 + +结构性预检通过不保证最新仓位能发布。历史不足或最新仍处于预热时,运行保留阻断原因与标准 +研究产物,不导出`position_scale.json`;宏观策略要求`hold_previous`时同样不发布新仓位。 +全样本曲线仍只作描述,滚动测试折与因果审计单独判断,不据此声称正超额收益。 + ## 输出 | 文件 | 用途 | diff --git a/src/quant_timing/cli.py b/src/quant_timing/cli.py index caea9c7..cf10b12 100644 --- a/src/quant_timing/cli.py +++ b/src/quant_timing/cli.py @@ -1,26 +1,25 @@ from __future__ import annotations import argparse +import json +import sys from pathlib import Path +import yaml + from quant_timing.comparison import run_horse_race from quant_timing.config import load_yaml, resolve_config from quant_timing.export import exit_code, write_run -from quant_timing.io import ( - load_macro_history, - load_prices, - load_scale_history, - load_signal_panel, - read_macro_context, - read_position_scale, - resolve_path, -) +from quant_timing.inputs import load_market +from quant_timing.preflight import prepare_inputs from quant_timing.study import run_study def main(argv: list[str] | None = None) -> int: parser = argparse.ArgumentParser(description="指数仓位择时与风格择时研究") sub = parser.add_subparsers(dest="command", required=True) + preflight = sub.add_parser("preflight", help="只读检查配置、来源与滚动窗口,不运行研究") + preflight.add_argument("--config", required=True, help="已有YAML研究配置") run = sub.add_parser("run", help="跑一条可复现的择时研究") run.add_argument("--config", required=True, help="YAML 配置") run.add_argument("--out", required=True, help="输出目录") @@ -30,28 +29,51 @@ def main(argv: list[str] | None = None) -> int: args = parser.parse_args(argv) if args.command == "compare": return compare_command(Path(args.config), Path(args.out)) - return run_command(Path(args.config), Path(args.out)) + try: + if args.command == "preflight": + payload = prepare_inputs(Path(args.config)).preflight() + print(json.dumps(payload, ensure_ascii=False, allow_nan=False)) + return 0 + return run_command(Path(args.config), Path(args.out)) + except (ValueError, OSError, yaml.YAMLError) as exc: + print(f"Timing input or research error: {exc}", file=sys.stderr) + return 2 def run_command(config_path: Path, out_dir: Path) -> int: - raw = load_yaml(config_path) - resolved = resolve_config(raw) - prices, extras = _load_market(raw, resolved, config_path) - result = run_study(prices, raw, **extras) - decision = write_run(result, prices, out_dir) + prepared = prepare_inputs(config_path) + destination = out_dir.resolve() + if any( + path == destination or destination in path.parents for path in prepared.sources.values() + ): + raise ValueError("output directory contains research source files") + result = run_study(prepared.prices, prepared.raw, **prepared.extras) + prepared.verify() + decision = write_run( + result, + prepared.prices, + out_dir, + input_context={ + "evidence_kind": prepared.evidence_kind, + "input_checks": prepared.describe(), + }, + ) code = exit_code(result.summary, decision) scale = decision["position_scale"] print( f"wrote {out_dir} status={result.summary['status']} action={decision['action']} " f"scale={scale} folds={result.summary['scored_folds']} exit={code}" ) + if code: + reason = decision["signals"].get("block_reason", result.summary["status"]) + print(f"Timing research publication blocked: {reason}", file=sys.stderr) return code def compare_command(config_path: Path, out_dir: Path) -> int: raw = load_yaml(config_path) resolved = resolve_config({**raw, "position": _first_model(raw)}) - prices, extras = _load_market(raw, resolved, config_path) + prices, extras = load_market(raw, resolved, config_path) table = run_horse_race(prices, raw, **extras) out_dir.mkdir(parents=True, exist_ok=True) table.to_csv(out_dir / "model_comparison.csv", index=False) @@ -64,94 +86,6 @@ def compare_command(config_path: Path, out_dir: Path) -> int: return 0 -def _load_prices(raw: dict, config_path: Path): - input_cfg = raw.get("input") - if not isinstance(input_cfg, dict) or not isinstance(input_cfg.get("path"), str): - raise ValueError("input.path is required") - prices = load_prices( - resolve_path(str(input_cfg["path"]), config_path), - date_col=str(input_cfg.get("date_col", "date")), - fmt=str(input_cfg.get("format", "wide")), - ) - if input_cfg.get("start"): - prices = prices.loc[str(input_cfg["start"]) :] - if input_cfg.get("end"): - prices = prices.loc[: str(input_cfg["end"])] - if prices.empty: - raise ValueError("input date range contains no prices") - return prices - - -def _load_market(raw: dict, resolved: dict, config_path: Path) -> tuple: - prices = _load_prices(raw, config_path) - extras: dict = { - "regime_history": None, - "regime_snapshot": None, - "macro": None, - "signal_panel": None, - "macro_history": None, - "cash_yield": None, - "futures_price": None, - "futures_prices": None, - "amounts": None, - "peg": None, - } - if resolved["regime"]["history"]: - extras["regime_history"] = load_scale_history( - resolve_path(resolved["regime"]["history"], config_path) - ) - if resolved["regime"]["snapshot"]: - extras["regime_snapshot"] = read_position_scale( - resolve_path(resolved["regime"]["snapshot"], config_path) - ) - if resolved["macro"]["context"]: - extras["macro"] = read_macro_context( - resolve_path(resolved["macro"]["context"], config_path) - ) - if resolved["macro"].get("history"): - extras["macro_history"] = load_macro_history( - resolve_path(resolved["macro"]["history"], config_path) - ) - signal_path = (raw.get("signals") or {}).get("path") - if signal_path: - extras["signal_panel"] = load_signal_panel(resolve_path(str(signal_path), config_path)) - if resolved["valuation"] is not None: - column = str(resolved["valuation"]["column"]) - panel = extras["signal_panel"] - if panel is None or column not in panel.columns: - raise ValueError(f"valuation column {column} is missing from the signal panel") - extras["peg"] = panel[column] - activity_path = (raw.get("activity") or {}).get("path") - if activity_path: - extras["amounts"] = load_signal_panel(resolve_path(str(activity_path), config_path)) - if resolved["cash"]["mode"] == "yield": - column = str(resolved["cash"]["yield_column"]) - if column not in prices.columns: - raise ValueError(f"cash yield column {column} is missing from prices") - extras["cash_yield"] = prices[column] - prices = prices.drop(columns=[column]) - elif resolved["cash"]["mode"] == "price": - column = str(resolved["cash"]["yield_column"]) - if column not in prices.columns: - raise ValueError(f"cash price column {column} is missing from prices") - extras["cash_yield"] = prices[column].astype(float).ffill().pct_change() - prices = prices.drop(columns=[column]) - if resolved["overlay"]["mode"] == "futures": - futures_path = (raw.get("futures") or {}).get("path") - if futures_path: - extras["futures_prices"] = load_signal_panel( - resolve_path(str(futures_path), config_path) - ) - else: - columns = list(resolved["overlay"]["contracts"]) - missing = [column for column in columns if column not in prices.columns] - if missing: - raise ValueError(f"futures price columns {missing} are missing from prices") - extras["futures_prices"] = prices[columns] - prices = prices.drop(columns=columns) - return prices, extras - - def _first_model(raw: dict) -> dict: models = (raw.get("comparison") or {}).get("models") or [] specs = raw.get("models") or {} diff --git a/src/quant_timing/config.py b/src/quant_timing/config.py index 79309d9..4285907 100644 --- a/src/quant_timing/config.py +++ b/src/quant_timing/config.py @@ -9,7 +9,9 @@ def load_yaml(path: Path) -> dict[str, Any]: with path.open(encoding="utf-8") as handle: - payload = yaml.safe_load(handle) or {} + payload = yaml.safe_load(handle) + if payload is None: + payload = {} if not isinstance(payload, dict): raise ValueError(f"config must be a mapping: {path}") return payload @@ -49,6 +51,9 @@ def resolve_config(raw: dict[str, Any]) -> dict[str, Any]: """Validate an explicit timing config. Missing policy is rejected, not defaulted into a signal.""" if not isinstance(raw, dict): raise ValueError("config must be a mapping") + for name in ("input", "signals", "activity", "futures"): + if raw.get(name) is not None and not isinstance(raw[name], dict): + raise ValueError(f"{name} must be a mapping") market = raw.get("market") if not isinstance(market, str) or not market or market == "CASH": raise ValueError("market must be a non-empty sleeve name other than CASH") diff --git a/src/quant_timing/export.py b/src/quant_timing/export.py index 8139466..d064221 100644 --- a/src/quant_timing/export.py +++ b/src/quant_timing/export.py @@ -49,7 +49,9 @@ def exit_code(summary: dict[str, Any], decision: dict[str, Any]) -> int: return 0 -def write_run(result: StudyResult, prices: pd.DataFrame, out_dir: Path) -> dict[str, Any]: +def write_run( + result: StudyResult, prices: pd.DataFrame, out_dir: Path, *, input_context: dict | None = None +) -> dict[str, Any]: """Validate a complete staged run, then publish it with one directory rename.""" out_dir = Path(out_dir) _require_empty_destination(out_dir) @@ -57,6 +59,8 @@ def write_run(result: StudyResult, prices: pd.DataFrame, out_dir: Path) -> dict[ with TemporaryDirectory(prefix=f".{out_dir.name}-", dir=out_dir.parent) as directory: staged = Path(directory) decision = _write_staged_run(result, prices, staged) + if input_context is not None: + _write_json(staged / "run_context.json", input_context) _require_empty_destination(out_dir) if out_dir.exists(): out_dir.rmdir() # Removes only an empty destination; never existing run contents. diff --git a/src/quant_timing/inputs.py b/src/quant_timing/inputs.py new file mode 100644 index 0000000..1e2ac51 --- /dev/null +++ b/src/quant_timing/inputs.py @@ -0,0 +1,110 @@ +"""Resolve and load the same local sources for research and read-only preflight.""" + +from __future__ import annotations + +from pathlib import Path + +from quant_timing.io import ( + load_macro_history, + load_prices, + load_scale_history, + load_signal_panel, + read_macro_context, + read_position_scale, + resolve_path, +) + + +def input_paths(raw: dict, resolved: dict, config_path: Path) -> dict[str, Path]: + sources = {} + for section, key, required in ( + ("input", "path", True), + ("signals", "path", False), + ("activity", "path", False), + ("regime", "history", False), + ("regime", "snapshot", False), + ("macro", "context", False), + ("macro", "history", False), + ("futures", "path", False), + ): + if section == "futures" and resolved["overlay"]["mode"] != "futures": + continue + mapping = raw.get(section, {}) + if mapping is None and not required: + continue + if not isinstance(mapping, dict): + raise ValueError(f"{section} must be a mapping") + value = mapping.get(key) + if value is None and not required: + continue + if not isinstance(value, str) or not value.strip(): + raise ValueError(f"{section}.{key} must be a non-empty path") + sources[f"{section}.{key}"] = resolve_path(value, config_path) + return sources + + +def load_market( + raw: dict, resolved: dict, config_path: Path, *, paths: dict[str, Path] | None = None +) -> tuple: + paths = input_paths(raw, resolved, config_path) if paths is None else paths + input_cfg = raw["input"] + prices = load_prices( + paths["input.path"], + date_col=str(input_cfg.get("date_col", "date")), + fmt=str(input_cfg.get("format", "wide")), + ) + if input_cfg.get("start"): + prices = prices.loc[str(input_cfg["start"]) :] + if input_cfg.get("end"): + prices = prices.loc[: str(input_cfg["end"])] + if prices.empty: + raise ValueError("input date range contains no prices") + extras: dict = { + "regime_history": None, + "regime_snapshot": None, + "macro": None, + "signal_panel": None, + "macro_history": None, + "cash_yield": None, + "futures_price": None, + "futures_prices": None, + "amounts": None, + "peg": None, + } + for source, target, reader in ( + ("regime.history", "regime_history", load_scale_history), + ("regime.snapshot", "regime_snapshot", read_position_scale), + ("macro.context", "macro", read_macro_context), + ("macro.history", "macro_history", load_macro_history), + ("signals.path", "signal_panel", load_signal_panel), + ("activity.path", "amounts", load_signal_panel), + ): + if source in paths: + extras[target] = reader(paths[source]) + if resolved["valuation"] is not None: + column = str(resolved["valuation"]["column"]) + panel = extras["signal_panel"] + if panel is None or column not in panel.columns: + raise ValueError(f"valuation column {column} is missing from the signal panel") + extras["peg"] = panel[column] + if resolved["cash"]["mode"] in {"yield", "price"}: + column = str(resolved["cash"]["yield_column"]) + if column not in prices.columns: + raise ValueError( + f"cash {resolved['cash']['mode']} column {column} is missing from prices" + ) + extras["cash_yield"] = prices[column] + if resolved["cash"]["mode"] == "price": + extras["cash_yield"] = prices[column].astype(float).ffill().pct_change() + prices = prices.drop(columns=[column]) + if resolved["overlay"]["mode"] == "futures": + if "futures.path" in paths: + extras["futures_prices"] = load_signal_panel(paths["futures.path"]) + else: + columns = list(resolved["overlay"]["contracts"]) + missing = [column for column in columns if column not in prices.columns] + if missing: + raise ValueError(f"futures price columns {missing} are missing from prices") + extras["futures_prices"] = prices[columns] + prices = prices.drop(columns=columns) + return prices, extras diff --git a/src/quant_timing/preflight.py b/src/quant_timing/preflight.py new file mode 100644 index 0000000..1bfe4ed --- /dev/null +++ b/src/quant_timing/preflight.py @@ -0,0 +1,112 @@ +"""Read-only structural checks; no signal generation or research acceptance.""" + +from __future__ import annotations + +from dataclasses import dataclass +from pathlib import Path + +import pandas as pd + +from quant_timing.config import load_yaml, resolve_config +from quant_timing.contract import file_sha256, json_sha256 +from quant_timing.inputs import input_paths, load_market +from quant_timing.study import validate_study_inputs +from quant_timing.walkforward import iter_folds + + +def identify_sources(paths: dict[str, Path]) -> dict[str, dict]: + identities = {} + for name, path in paths.items(): + stat = path.stat() + digest = file_sha256(path) + final = path.stat() + if (stat.st_size, stat.st_mtime_ns) != (final.st_size, final.st_mtime_ns): + raise ValueError(f"source changed while being read: {name}") + identities[name] = { + "path": str(path.resolve()), + "size": stat.st_size, + "mtime_ns": stat.st_mtime_ns, + "sha256": digest, + } + return identities + + +@dataclass(frozen=True) +class ResearchInputs: + raw: dict + config: dict + prices: pd.DataFrame + extras: dict + sources: dict[str, Path] + identities: dict[str, dict] + evidence_kind: str + + def verify(self) -> None: + if identify_sources(self.sources) != self.identities: + raise ValueError("research sources changed during preparation or execution") + + def describe(self) -> dict: + folds = iter_folds(self.prices.index, **self.config["validation"]) + return { + "schema_version": "quant-timing.preflight/v1", + "software_preflight": "not_run", + "structural_inputs_valid": True, + "read_only": True, + "investable": False, + "evidence_kind": self.evidence_kind, + "rows": len(self.prices), + "symbols": len(self.prices.columns), + "folds": len(folds), + "observed_window": { + "start": self.prices.index[0].isoformat(), + "end": self.prices.index[-1].isoformat(), + }, + "effective_config": self.raw, + "effective_config_sha256": json_sha256(self.raw), + "input_files": self.identities, + "performance_basis": "descriptive_full_sample_not_walk_forward_acceptance", + "acceptance": "walk_forward_folds_and_causal_audit", + "orders": "research_target_not_routed", + "limitations": [ + "No signals, weights, backtest, leakage audit or position_scale are produced", + "Folds are structural windows, not evidence of scored or profitable decisions", + "Dynamic coverage, macro policy and latest publication gates run during research", + "Source kind is a declaration, not independent market-data certification", + "Inputs are re-read at execution; preflight does not lock source files", + ], + } + + def preflight(self) -> dict: + folds = iter_folds(self.prices.index, **self.config["validation"]) + if not any(fold["decision_dates"][0] < self.prices.index[-1] for fold in folds): + raise ValueError("insufficient history for a walk-forward fold with a later return") + report = self.describe() + report["software_preflight"] = "pass" + return report + + +def prepare_inputs(config_path: Path) -> ResearchInputs: + config_path = config_path.resolve() + sources = {"config": config_path} + identities = identify_sources(sources) + raw = load_yaml(config_path) + config = resolve_config(raw) + source = raw.get("source", {}) + if not isinstance(source, dict): + raise ValueError("source must be a mapping") + kind = source.get("evidence_kind", "unspecified") + if not isinstance(kind, str) or kind not in { + "synthetic", + "retrospective", + "user_provided", + "unspecified", + }: + raise ValueError("source.evidence_kind is unsupported") + market_paths = input_paths(raw, config, config_path) + sources.update(market_paths) + identities.update(identify_sources(market_paths)) + prices, extras = load_market(raw, config, config_path, paths=market_paths) + validate_study_inputs(prices, config, **extras) + prepared = ResearchInputs(raw, config, prices, extras, sources, identities, kind) + prepared.verify() + return prepared diff --git a/src/quant_timing/study.py b/src/quant_timing/study.py index 642b6d4..3376c96 100644 --- a/src/quant_timing/study.py +++ b/src/quant_timing/study.py @@ -55,7 +55,20 @@ def run_study( audit: bool = True, ) -> StudyResult: config = resolve_config(raw_config) - _require_columns(prices, config) + validate_study_inputs( + prices, + config, + regime_history=regime_history, + regime_snapshot=regime_snapshot, + macro=macro, + signal_panel=signal_panel, + macro_history=macro_history, + cash_yield=cash_yield, + futures_price=futures_price, + futures_prices=futures_prices, + amounts=amounts, + peg=peg, + ) external, snapshot = _external_scales(config, regime_history, regime_snapshot) context = normalize_macro(macro) position = build_position(prices[config["market"]], config["position"], external) @@ -175,13 +188,52 @@ def run_study( ) -def _require_columns(prices: pd.DataFrame, config: dict[str, Any]) -> None: +def validate_study_inputs( + prices: pd.DataFrame, + config: dict[str, Any], + *, + regime_history=None, + regime_snapshot=None, + macro=None, + signal_panel=None, + macro_history=None, + cash_yield=None, + futures_price=None, + futures_prices=None, + amounts=None, + peg=None, +) -> None: + """Check static research requirements without producing decisions or positions.""" + if prices.empty: + raise ValueError("price panel is empty") required = {config["market"]} if config["style"]: required.update(style_sleeves(config["style"])) missing = required - set(prices.columns) if missing: raise ValueError(f"price panel is missing {sorted(missing)}") + _external_scales(config, regime_history, regime_snapshot) + normalize_macro(macro) + if config["valuation"] is not None and peg is None: + raise ValueError("valuation peg series was not loaded") + if config["cash"]["mode"] != "zero" and cash_yield is None: + raise ValueError("cash yield series was not loaded") + if config["overlay"]["mode"] == "futures": + _futures_frame(futures_prices, futures_price, prices.index, config["overlay"]["contracts"]) + if config["style"]: + for pair in config["style"]["pairs"]: + if pair["signal"] != "momentum": + column = str(pair["signal_column"]) + if signal_panel is None or column not in signal_panel: + raise ValueError(f"style signal column {column} is missing") + for group in config["style"]["groups"]: + if group["signal"] != "momentum": + for member in group["members"]: + column = f"{group['name']}.{member}" + if signal_panel is None or column not in signal_panel: + raise ValueError(f"style signal column {column} is missing") + if group["benchmark"] == "amount_share" and amounts is None: + raise ValueError(f"style group {group['name']} needs an amount panel") def _external_scales( diff --git a/tests/test_preflight.py b/tests/test_preflight.py new file mode 100644 index 0000000..5939468 --- /dev/null +++ b/tests/test_preflight.py @@ -0,0 +1,310 @@ +from __future__ import annotations + +import json + +import pandas as pd +import pytest +import yaml + +import quant_timing.cli as cli +import quant_timing.preflight as preflight +import quant_timing.study as study +from quant_timing.contract import validate_standard_run +from quant_timing.export import write_run +from quant_timing.preflight import identify_sources, prepare_inputs +from tests.support import sample_prices, timing_config + + +@pytest.fixture +def config_file(tmp_path): + prices = tmp_path / "prices.csv" + sample_prices().to_csv(prices, index_label="date") + config = timing_config() + config["input"] = {"path": "prices.csv"} + config["source"] = {"evidence_kind": "synthetic"} + path = tmp_path / "study.yaml" + save_config(path, config) + return path + + +def save_config(path, config): + path.write_text(yaml.safe_dump(config, sort_keys=False), encoding="utf-8") + + +def test_preflight_is_read_only_and_does_not_compute(config_file, monkeypatch, capsys): + before = identify_sources({p.name: p for p in config_file.parent.iterdir()}) + + def forbidden(*args, **kwargs): + pytest.fail("preflight must not run models, simulate, audit or export") + + for module, names in ( + (cli, ("run_study", "write_run")), + (study, ("build_position", "style_internal_weights", "simulate", "_audit")), + ): + for name in names: + monkeypatch.setattr(module, name, forbidden) + assert cli.main(["preflight", "--config", str(config_file)]) == 0 + report = json.loads(capsys.readouterr().out) + assert report["software_preflight"] == "pass" + assert report["read_only"] and not report["investable"] + assert report["evidence_kind"] == "synthetic" + assert report["rows"] == len(sample_prices()) + assert report["folds"] > 0 + assert report["performance_basis"] == "descriptive_full_sample_not_walk_forward_acceptance" + after = identify_sources({p.name: p for p in config_file.parent.iterdir()}) + assert after == before + + +def test_native_run_matches_existing_research_api(config_file, tmp_path): + prepared = prepare_inputs(config_file) + expected = study.run_study(prepared.prices, prepared.raw, **prepared.extras) + write_run(expected, prepared.prices, tmp_path / "expected") + actual = tmp_path / "actual" + assert cli.main(["run", "--config", str(config_file), "--out", str(actual)]) == 0 + validate_standard_run(actual) + for source in (tmp_path / "expected").rglob("*.csv"): + assert ( + source.read_bytes() == (actual / source.relative_to(tmp_path / "expected")).read_bytes() + ) + for name in ("summary.json", "leakage_audit.json"): + assert (actual / "validation" / name).read_bytes() == ( + tmp_path / "expected" / "validation" / name + ).read_bytes() + context = json.loads((actual / "run_context.json").read_text()) + assert ( + context["input_checks"]["effective_config_sha256"] + == prepared.describe()["effective_config_sha256"] + ) + assert context["input_checks"]["input_files"] == prepared.identities + prepared.verify() + + +@pytest.mark.parametrize("payload", ["false", "0", "[]", "a: ["]) +def test_malformed_configuration_is_not_success(tmp_path, payload, capsys): + path = tmp_path / "invalid.yaml" + path.write_text(payload) + assert cli.main(["preflight", "--config", str(path)]) == 2 + assert not capsys.readouterr().out + assert set(tmp_path.iterdir()) == {path} + + +@pytest.mark.parametrize("kind", [None, True, "real", "pit_certified", []]) +def test_source_declaration_is_not_guessed(config_file, kind): + raw = yaml.safe_load(config_file.read_text()) + raw["source"] = {"evidence_kind": kind} + save_config(config_file, raw) + with pytest.raises(ValueError, match="evidence_kind"): + prepare_inputs(config_file) + + +def test_old_source_mode_remains_unspecified(config_file): + raw = yaml.safe_load(config_file.read_text()) + raw["source"] = {"mode": "real-retrospective-price-only"} + save_config(config_file, raw) + assert prepare_inputs(config_file).preflight()["evidence_kind"] == "unspecified" + + +def test_short_history_preflight_rejects_but_run_keeps_blocked_evidence(config_file, capsys): + raw = yaml.safe_load(config_file.read_text()) + raw["validation"]["train_size"] = 10000 + save_config(config_file, raw) + assert cli.main(["preflight", "--config", str(config_file)]) == 2 + assert "insufficient history" in capsys.readouterr().err + output = config_file.parent / "blocked" + assert cli.main(["run", "--config", str(config_file), "--out", str(output)]) == 2 + assert "insufficient_history" in capsys.readouterr().err + assert not (output / "position_scale.json").exists() + assert json.loads((output / "decision.json").read_text())["action"] == "blocked" + validate_standard_run(output) + + +def test_static_pass_does_not_bypass_latest_warmup_gate(config_file, capsys): + raw = yaml.safe_load(config_file.read_text()) + raw["position"]["vol_lookback"] = 10000 + save_config(config_file, raw) + assert prepare_inputs(config_file).preflight()["software_preflight"] == "pass" + output = config_file.parent / "warmup" + assert cli.main(["run", "--config", str(config_file), "--out", str(output)]) == 2 + assert "warmup" in capsys.readouterr().err + assert not (output / "position_scale.json").exists() + validate_standard_run(output) + + +def test_incomplete_macro_retains_hold_previous(config_file): + context = config_file.parent / "macro.json" + context.write_text(json.dumps({"complete": False, "values": {}, "unavailable": {}})) + raw = yaml.safe_load(config_file.read_text()) + raw["macro"] = {"context": "macro.json", "incomplete_policy": "hold_previous"} + save_config(config_file, raw) + assert prepare_inputs(config_file).preflight()["software_preflight"] == "pass" + output = config_file.parent / "held" + assert cli.main(["run", "--config", str(config_file), "--out", str(output)]) == 0 + assert json.loads((output / "decision.json").read_text())["action"] == "hold_previous" + assert not (output / "position_scale.json").exists() + + +def test_all_declared_sources_are_identified(config_file): + root = config_file.parent + prices = sample_prices() + index = prices.index + panel = pd.DataFrame({"peg": 2.0, "value_growth": 0.1, "IF": 100.0}, index=index) + panel.to_csv(root / "signals.csv", index_label="date") + (prices * 100).to_csv(root / "amounts.csv", index_label="date") + pd.DataFrame({"position_scale": 0.8}, index=index).to_csv( + root / "scale.csv", index_label="date" + ) + (root / "macro.json").write_text(json.dumps({"complete": True, "values": {}})) + pd.DataFrame( + {"date": ["2020-01-01"], "series": ["x"], "value": [1], "available_at": ["2020-01-02"]} + ).to_csv(root / "macro.csv", index=False) + raw = yaml.safe_load(config_file.read_text()) + raw.update( + { + "signals": {"path": "signals.csv"}, + "activity": {"path": "amounts.csv"}, + "regime": {"combine": "cap", "history": "scale.csv"}, + "macro": {"context": "macro.json", "history": "macro.csv"}, + "futures": {"path": "signals.csv"}, + "overlay": {"mode": "futures", "contracts": ["IF"], "margin_rate": 0.1}, + "valuation": { + "column": "peg", + "lookback": 20, + "expensive_percentile": 0.2, + "scale_cap": 0.6, + }, + } + ) + save_config(config_file, raw) + prepared = prepare_inputs(config_file) + assert set(prepared.preflight()["input_files"]) == { + "config", + "input.path", + "signals.path", + "activity.path", + "regime.history", + "macro.context", + "macro.history", + "futures.path", + } + assert prepared.extras["futures_prices"].equals(panel) + pd.testing.assert_frame_equal(prepared.prices, prices, check_freq=False, rtol=1e-14, atol=1e-14) + + +@pytest.mark.parametrize("missing", ["market", "style", "signal", "futures", "cash"]) +def test_missing_native_inputs_rejected(config_file, missing): + raw = yaml.safe_load(config_file.read_text()) + if missing == "market": + raw["market"] = "absent" + elif missing == "style": + raw["style"]["pairs"][0]["left"] = "absent" + elif missing == "signal": + raw["style"]["pairs"][0]["signal"] = "revision" + elif missing == "futures": + raw["overlay"] = {"mode": "futures", "contracts": ["IF"], "margin_rate": 0.1} + else: + raw["cash"] = {"mode": "price", "yield_column": "absent"} + save_config(config_file, raw) + with pytest.raises(ValueError, match="missing"): + prepare_inputs(config_file) + + +@pytest.mark.parametrize("phase", ["hash", "load", "research"]) +def test_source_change_prevents_success(config_file, monkeypatch, phase): + path = config_file.parent / "prices.csv" + + def change(): + path.write_bytes(path.read_bytes() + b"\n") + + if phase == "hash": + original = preflight.file_sha256 + + def digest(source): + value = original(source) + if source == path: + change() + return value + + monkeypatch.setattr(preflight, "file_sha256", digest) + elif phase == "load": + original = preflight.load_market + + def loader(*args, **kwargs): + value = original(*args, **kwargs) + change() + return value + + monkeypatch.setattr(preflight, "load_market", loader) + else: + original = cli.run_study + + def research(*args, **kwargs): + value = original(*args, **kwargs) + change() + return value + + monkeypatch.setattr(cli, "run_study", research) + output = config_file.parent / "result" + assert cli.main(["run", "--config", str(config_file), "--out", str(output)]) == 2 + assert not output.exists() + + +def test_output_cannot_contain_inputs(config_file, monkeypatch): + monkeypatch.setattr(cli, "run_study", lambda *args, **kwargs: pytest.fail("must reject first")) + before = config_file.read_bytes() + assert cli.main(["run", "--config", str(config_file), "--out", str(config_file.parent)]) == 2 + assert config_file.read_bytes() == before + + +def test_paths_still_resolve_from_original_config(config_file, tmp_path, monkeypatch): + nested = tmp_path / "other" + nested.mkdir() + monkeypatch.chdir(nested) + prepared = prepare_inputs(config_file) + assert prepared.sources["input.path"] == config_file.parent / "prices.csv" + + +@pytest.mark.parametrize("section", ["signals", "activity", "futures", "macro", "regime"]) +def test_optional_null_sources_keep_existing_semantics(config_file, section): + raw = yaml.safe_load(config_file.read_text()) + raw[section] = None + save_config(config_file, raw) + assert prepare_inputs(config_file).preflight()["software_preflight"] == "pass" + + +@pytest.mark.parametrize("section", ["input", "signals", "activity", "futures"]) +def test_non_mapping_source_is_a_clear_input_error(config_file, section, capsys): + raw = yaml.safe_load(config_file.read_text()) + raw[section] = ["bad"] + save_config(config_file, raw) + assert cli.main(["preflight", "--config", str(config_file)]) == 2 + assert f"{section} must be a mapping" in capsys.readouterr().err + + +def test_snapshot_and_date_selection_are_shared(config_file): + prices = sample_prices() + raw = yaml.safe_load(config_file.read_text()) + raw["input"]["start"] = str(prices.index[10].date()) + raw["input"]["end"] = str(prices.index[-10].date()) + raw["regime"] = {"combine": "cap", "snapshot": "scale.json"} + (config_file.parent / "scale.json").write_text('{"position_scale": 0.7}') + save_config(config_file, raw) + prepared = prepare_inputs(config_file) + assert len(prepared.prices) == len(prices) - 19 + assert prepared.extras["regime_snapshot"] == 0.7 + assert "regime.snapshot" in prepared.preflight()["input_files"] + + +def test_context_write_failure_does_not_publish_scale(config_file, monkeypatch): + import quant_timing.export as export + + original = export._write_json + + def fail_context(path, payload): + if path.name == "run_context.json": + raise OSError("context failed") + return original(path, payload) + + monkeypatch.setattr(export, "_write_json", fail_context) + output = config_file.parent / "failed-export" + assert cli.main(["run", "--config", str(config_file), "--out", str(output)]) == 2 + assert not output.exists()