"Vibe-Trading: Your Personal Trading Agent"
Python ai-agentalgorithmic-tradingbacktestingfintechllmmcpmulti-agentpythonquantitative-financetrading
feat(alpha): expose the strict bench gate via `alpha bench --strict`
Yufeng He23174f28b789
diff --git a/agent/src/factors/cli_handlers.py b/agent/src/factors/cli_handlers.pyindex 7ae72adaf..2ad46905c 100644--- a/agent/src/factors/cli_handlers.py+++ b/agent/src/factors/cli_handlers.py@@ -16,6 +16,7 @@ Security gates:from __future__ import annotationsimport argparse+import functoolsimport jsonimport sysimport time@@ -510,8 +511,21 @@ def cmd_alpha_bench(args: argparse.Namespace) -> int:from ``src.tools.alpha_bench_tool`` (we do NOT modify that module)."""try:+ if (getattr(args, "oos_split", None) or getattr(args, "random_seeds", 5) != 5) and not getattr(args, "strict", False):+ _err("alpha bench: --oos-split/--random-seeds only take effect with --strict.")+ return 1try:- from src.factors.bench_runner import run_bench+ if getattr(args, "strict", False):+ from src.factors.bench_runner_strict import run_bench_strict++ run_bench = functools.partial(+ run_bench_strict,+ random_control=True,+ n_random_seeds=max(1, int(getattr(args, "random_seeds", 5) or 5)),+ oos_split=getattr(args, "oos_split", None),+ )+ else:+ from src.factors.bench_runner import run_benchexcept ImportError as exc:_err(f"alpha bench failed: bench_runner unavailable ({exc})")return 1@@ -550,10 +564,17 @@ def cmd_alpha_bench(args: argparse.Namespace) -> int:_err(f"alpha bench failed: no alphas registered under zoo={zoo!r}")return 1+ strict_banner = (+ " [strict: random control"+ + (f", oos {args.oos_split}" if getattr(args, "oos_split", None) else "")+ + "]"+ if getattr(args, "strict", False)+ else ""+ )_print(- f"[bold]Bench:[/bold] {n_target} alphas x {args.universe} x {args.period}"+ f"[bold]Bench:[/bold] {n_target} alphas x {args.universe} x {args.period}{strict_banner}"if _console- else f"Bench: {n_target} alphas x {args.universe} x {args.period}"+ else f"Bench: {n_target} alphas x {args.universe} x {args.period}{strict_banner}")_print("[dim]ETA: ~3-5 min (cache hit) / ~10-20 min (cold fetch)[/dim]"@@ -678,6 +699,13 @@ def cmd_alpha_bench(args: argparse.Namespace) -> int:"top": top_rows,"wall_seconds": result.get("wall_seconds"),}+ if getattr(args, "strict", False):+ envelope["strict"] = True+ for key in ("confirmed_alive", "train_only", "reversed_strict", "noise"):+ if key in result:+ envelope[key] = result[key]+ if result.get("oos_split") is not None:+ envelope["oos_split"] = result["oos_split"]if report_path is not None:envelope["report_path"] = str(report_path)print(json.dumps(envelope, indent=2, default=str))@@ -918,6 +946,23 @@ def add_subparser(subparsers: Any) -> argparse.ArgumentParser:help="Period spec: YYYY-YYYY or YYYY-MM-DD/YYYY-MM-DD (e.g. 2020-2025)",)p_bench.add_argument("--top", type=int, default=20, help="Top-N alphas to keep (default: 20)")+ p_bench.add_argument(+ "--strict",+ action="store_true",+ help="Strict gate: mandatory same-universe random control (bench_runner_strict)",+ )+ p_bench.add_argument(+ "--oos-split",+ default=None,+ metavar="YYYY-MM-DD",+ help="Strict mode only: split train/test at this date for the OOS confirmation gate",+ )+ p_bench.add_argument(+ "--random-seeds",+ type=int,+ default=5,+ help="Strict mode only: row-shuffled random controls per alpha (default: 5)",+ )p_bench.add_argument("--yes",action="store_true",diff --git a/agent/tests/test_alpha_bench_strict_cli.py b/agent/tests/test_alpha_bench_strict_cli.pynew file mode 100644index 000000000..c60a00f54--- /dev/null+++ b/agent/tests/test_alpha_bench_strict_cli.py@@ -0,0 +1,187 @@+"""Tests for the ``alpha bench --strict`` CLI wiring (issue #773)."""++from __future__ import annotations++import argparse+import json++import pytest++from src.factors import cli_handlers+++def _ns(**overrides):+ base = dict(+ zoo="alpha101",+ universe="csi300",+ period="2020-2025",+ top=20,+ yes=True,+ strict=False,+ oos_split=None,+ random_seeds=5,+ )+ base.update(overrides)+ return argparse.Namespace(**base)+++def _strict_result():+ return {+ "status": "ok",+ "confirmed_alive": 2,+ "train_only": 1,+ "reversed_strict": 0,+ "noise": 5,+ "oos_split": "2023-01-01",+ "rows": [+ {+ "id": "alpha001",+ "ic_mean": 0.05,+ "ic_std": 0.01,+ "ir": 0.9,+ "ic_positive_ratio": 0.7,+ "ic_count": 100,+ "theme": ["momentum"],+ "formula_latex": "x",+ "_category": "confirmed_alive",+ }+ ],+ "skipped": [],+ "wall_seconds": 1.0,+ }+++def _legacy_result():+ return {+ "status": "ok",+ "alive": 3,+ "rows": [+ {+ "id": "alpha001",+ "ic_mean": 0.05,+ "ic_std": 0.01,+ "ir": 0.9,+ "ic_positive_ratio": 0.7,+ "ic_count": 100,+ "theme": ["momentum"],+ "formula_latex": "x",+ "_category": "alive",+ }+ ],+ "skipped": [],+ "wall_seconds": 1.0,+ }+++def _envelope(out: str) -> dict:+ """Extract the JSON envelope from mixed stdout (banner lines + JSON)."""+ start = out.find("\n{")+ if start < 0:+ start = out.find("{") if out.lstrip().startswith("{") else -1+ if start < 0:+ raise AssertionError(f"no JSON envelope in stdout: {out[:200]!r}")+ else:+ start += 1+ return json.loads(out[start:])+++class _FakeReg:+ def list(self, zoo=None):+ return ["alpha001", "alpha002"]++ def get(self, aid):+ class _Entry:+ zoo = "alpha101"+ meta = {"theme": ["momentum"], "formula_latex": "x"}++ return _Entry()+++def _no_report(monkeypatch, tmp_path):+ """Keep the HTML report side effect contained."""+ import src.tools.alpha_bench_tool as tool++ monkeypatch.setattr(tool, "_default_output_dir", lambda: tmp_path)+++def _reg(monkeypatch):+ monkeypatch.setattr(cli_handlers, "Registry", _FakeReg)+++def _run(capsys, args, monkeypatch):+ import src.factors.bench_runner_strict as strict_mod++ called = {}++ def fake_strict(zoo, universe, period, **kwargs):+ called.update(kwargs)+ return _strict_result()++ monkeypatch.setattr(strict_mod, "run_bench_strict", fake_strict)+ rc = cli_handlers.cmd_alpha_bench(args)+ return rc, called, capsys.readouterr()+++def test_strict_routes_to_strict_runner(capsys, monkeypatch, _reg, _no_report):+ rc, called, cap = _run(capsys, _ns(strict=True, oos_split="2023-01-01", random_seeds=3), monkeypatch)+ assert rc == 0+ assert called["random_control"] is True+ assert called["oos_split"] == "2023-01-01"+ assert called["n_random_seeds"] == 3+ envelope = _envelope(cap.out)+ assert envelope["strict"] is True+ assert envelope["confirmed_alive"] == 2+ assert envelope["noise"] == 5+ assert envelope["oos_split"] == "2023-01-01"+ assert envelope["top"][0]["category"] == "confirmed_alive"+++def test_default_routes_to_legacy_runner(capsys, monkeypatch, _reg, _no_report):+ import src.factors.bench_runner as legacy_mod++ called = {}++ def fake_legacy(**kwargs):+ called.update(kwargs)+ return _legacy_result()++ monkeypatch.setattr(legacy_mod, "run_bench", fake_legacy)+ rc = cli_handlers.cmd_alpha_bench(_ns())+ assert rc == 0+ assert called["zoo"] == "alpha101"+ envelope = _envelope(capsys.readouterr().out)+ assert "strict" not in envelope+ assert envelope["top"][0]["category"] == "alive"+++def test_oos_split_without_strict_is_rejected(capsys, monkeypatch, _reg):+ rc = cli_handlers.cmd_alpha_bench(_ns(oos_split="2023-01-01"))+ assert rc == 1+ assert "--strict" in capsys.readouterr().err+++def test_strict_argparse_flags():+ parser = argparse.ArgumentParser()+ sub = parser.add_subparsers()+ alpha_parser = cli_handlers.add_subparser(sub)+ args = parser.parse_args(+ ["alpha", "bench", "--zoo", "alpha101", "--strict", "--oos-split", "2023-01-01", "--random-seeds", "3"]+ )+ assert args.strict is True+ assert args.oos_split == "2023-01-01"+ assert args.random_seeds == 3+ args_default = parser.parse_args(["alpha", "bench", "--zoo", "alpha101"])+ assert args_default.strict is False+ assert args_default.oos_split is None+ assert args_default.random_seeds == 5+ assert alpha_parser is not None+++def test_strict_result_envelope_marks_counts(capsys, monkeypatch, _reg, _no_report):+ rc, called, cap = _run(capsys, _ns(strict=True), monkeypatch)+ assert rc == 0+ assert called["random_control"] is True+ assert called["oos_split"] is None+ assert called["n_random_seeds"] == 5