Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 3 additions & 2 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
21 changes: 21 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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`时同样不发布新仓位。
全样本曲线仍只作描述,滚动测试折与因果审计单独判断,不据此声称正超额收益。

## 输出

| 文件 | 用途 |
Expand Down
142 changes: 38 additions & 104 deletions src/quant_timing/cli.py
Original file line number Diff line number Diff line change
@@ -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="输出目录")
Expand All @@ -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)
Expand All @@ -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 {}
Expand Down
7 changes: 6 additions & 1 deletion src/quant_timing/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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")
Expand Down
6 changes: 5 additions & 1 deletion src/quant_timing/export.py
Original file line number Diff line number Diff line change
Expand Up @@ -49,14 +49,18 @@ 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)
out_dir.parent.mkdir(parents=True, exist_ok=True)
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.
Expand Down
110 changes: 110 additions & 0 deletions src/quant_timing/inputs.py
Original file line number Diff line number Diff line change
@@ -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
Loading
Loading