Skip to content

"Vibe-Trading: Your Personal Trading Agent"

Merge PR #2067: align factor research modes across entry points

Haozhe Wuefd83d14d166
diff --cc agent/mcp_server.py
index 1ebd25a82,6a5b0ca57..6d5848b36
--- a/agent/mcp_server.py
+++ b/agent/mcp_server.py
@@@ -82,6 -82,7 +82,7 @@@ from src.market_data import
detect_source,
get_loader,
)
-from src.factors.research_contract import RESEARCH_STAGES
++from src.factors.research_contract import RESEARCH_MODES, RESEARCH_STAGES
mcp = FastMCP("Vibe-Trading", version=APP_VERSION)
@@@ -962,6 -963,7 +963,8 @@@ def alpha_bench
top: int = 20,
horizon: int = 1,
output_dir: str | None = None,
+ research_stage: str = "single_factor_evaluation",
++ research_mode: str = "explore",
) -> str:
"""Benchmark one Alpha Zoo alpha or a complete zoo on a universe.
@@@ -976,6 -978,7 +979,8 @@@
non-overlapping (end-anchored); 21 ≈ monthly, the conventional
horizon for fundamental factors. Range 1-252.
output_dir: Optional directory for the generated HTML report.
+ research_stage: Stage recorded in the factor-research contract.
++ research_mode: Declared mode; metadata only, not locked-evaluation enforcement.
"""
if not alpha_id and not zoo:
return json.dumps(
@@@ -1035,6 -1038,15 +1040,15 @@@
ensure_ascii=False,
)
- if research_stage not in RESEARCH_STAGES:
++ if research_stage not in RESEARCH_STAGES or research_mode not in RESEARCH_MODES:
+ return json.dumps(
+ {
+ "status": "error",
- "error": "MCP alpha_bench research_stage is not supported",
++ "error": "MCP alpha_bench research_stage or research_mode is not supported",
+ },
+ ensure_ascii=False,
+ )
+
params: dict[str, Any] = {
"universe": universe,
"period": period,
@@@ -1045,6 -1057,10 +1059,12 @@@
params["alpha_id"] = alpha_id
if zoo is not None:
params["zoo"] = zoo
+ # Keep the legacy wire payload byte-for-byte stable when callers use the
+ # default stage; newer clients can opt into the additive research contract.
+ if research_stage != "single_factor_evaluation":
+ params["research_stage"] = research_stage
++ if research_mode != "explore":
++ params["research_mode"] = research_mode
if output_dir:
from src.config.paths import get_runtime_root
diff --cc agent/src/factors/bench_runner_strict.py
index 5cfec2d05,e4c03758f..d5cec754e
--- a/agent/src/factors/bench_runner_strict.py
+++ b/agent/src/factors/bench_runner_strict.py
@@@ -329,6 -330,10 +330,10 @@@ def run_bench_strict
horizon: int = 1,
on_progress: ProgressCb | None = None,
registry: Registry | None = None,
- research_mode: str = "explore",
++ research_mode: str = "strict",
+ research_stage: str = "single_factor_evaluation",
+ research_lineage: Iterable[str | Mapping[str, Any]] | None = None,
+ research_transformations: Iterable[str | Mapping[str, Any]] | None = None,
) -> dict[str, Any]:
"""Strict-mode bench: like ``run_bench`` but with mandatory random control.
diff --cc agent/src/factors/cli_handlers.py
index 5d080b147,8d6e69a83..caf71160d
--- a/agent/src/factors/cli_handlers.py
+++ b/agent/src/factors/cli_handlers.py
@@@ -67,6 -67,7 +67,7 @@@ except Exception: # pragma: no cover �
from src.factors.compare_runner import SORT_KEYS as _COMPARE_SORT_KEYS, compare_alphas
from src.factors.registry import Registry, RegistryError
-from src.factors.research_contract import RESEARCH_STAGES
++from src.factors.research_contract import RESEARCH_MODES, RESEARCH_STAGES
# Resolve repo root once: this file lives at
@@@ -603,11 -604,20 +604,22 @@@ def cmd_alpha_bench(args: argparse.Name
oos_split=getattr(args, "oos_split", None),
training_cutoff=getattr(args, "training_cutoff", None),
horizon=horizon,
+ research_stage=getattr(
+ args, "research_stage", "single_factor_evaluation"
+ ),
++ research_mode=getattr(args, "research_mode", None) or "strict",
)
else:
from src.factors.bench_runner import run_bench as _run_bench_plain
- run_bench = functools.partial(_run_bench_plain, horizon=horizon)
+ run_bench = functools.partial(
+ _run_bench_plain,
+ horizon=horizon,
+ research_stage=getattr(
+ args, "research_stage", "single_factor_evaluation"
+ ),
++ research_mode=getattr(args, "research_mode", None) or "explore",
+ )
except ImportError as exc:
_err(f"alpha bench failed: bench_runner unavailable ({exc})")
return 1
@@@ -1122,6 -1132,12 +1134,16 @@@ def add_subparser(subparsers: Any) -> a
default=5,
help="Strict mode only: row-shuffled random controls per alpha (default: 5)",
)
++ p_bench.add_argument(
++ "--research-mode", choices=RESEARCH_MODES, default=None,
++ help="Declared research mode (default: strict for --strict, otherwise explore; does not enforce locked evaluation)",
++ )
+ p_bench.add_argument(
+ "--research-stage",
+ choices=RESEARCH_STAGES,
+ default="single_factor_evaluation",
+ help="Research stage recorded in the factor-research contract",
+ )
p_bench.add_argument(
"--yes",
action="store_true",
diff --cc agent/src/skills/factor-research/references/research_contract.md
index 000000000,5cc25146c..aff3d6e20
mode 000000,100644..100644
--- a/agent/src/skills/factor-research/references/research_contract.md
+++ b/agent/src/skills/factor-research/references/research_contract.md
@@@ -1,0 -1,58 +1,59 @@@
+ # Factor-research run contract
+
+ The factor bench entry points attach an additive `meta.research` object to
+ their existing result envelope. The contract is versioned as
+ `factor-research.run/v1` and is defined by
+ `src.factors.research_contract.build_research_contract`.
+
+ ```json
+ {
+ "schema": "factor-research.run/v1",
+ "mode": "explore",
+ "stage": "single_factor_evaluation",
+ "universe": "csi300",
+ "period": "2020-2025",
+ "factor_ids": ["alpha101_001"],
+ "factor_count": 1,
+ "lineage": [
+ {"kind": "alpha_registry", "zoo": "alpha101"}
+ ],
+ "transformations": [],
+ "evaluation": {
+ "horizon": 1,
+ "forward_return_sampling": "daily",
+ "method": "rank_ic"
+ },
+ "locked_test": {}
+ }
+ ```
+
+ ## Modes and stages
+
+ `mode` records the intended evidence standard:
+
+ - `explore`: exploratory research; warnings and incomplete provenance may be
+ acceptable while developing a signal.
+ - `strict`: a research result intended for stronger data and statistical
+ review.
+ - `locked`: a result intended for a locked evaluation set.
+
+ In v1 these values are declarations only. They do not change IC calculations,
-factor weights, or backtest behavior. The public CLI and MCP surfaces expose
-the stage label only; programmatic callers may set a mode for future policy
-experiments. A later policy layer can enforce the modes without changing the
-result schema.
++factor weights, or backtest behavior. CLI, agent tools and MCP expose both mode
++and stage. The strict runner and `alpha bench --strict` default to `strict`;
++the ordinary runner defaults to `explore`. An explicit `--research-mode`
++overrides that label. A later policy layer can enforce modes without changing
++the result schema; `locked` currently declares intent, never certification.
+
+ `stage` identifies where the result sits in the factor lifecycle:
+ `factor_screening`, `single_factor_evaluation`, `neutralization`,
+ `combination`, `composite_evaluation`, `backtest`, or `monitoring`.
+
+ ## Lineage and transformations
+
+ Both `lineage` and `transformations` accept either a short string or a JSON
+ object. Use an object when a future stage needs to record artifact IDs,
+ parameter hashes, controls, weights, or diagnostic paths. Keep large panels and
+ raw data outside the contract; reference them by stable artifact path or hash.
+
+ The contract is additive. Existing consumers can ignore `meta.research`, while
+ new consumers can use `schema` to opt into the structured fields.
diff --cc agent/src/tools/alpha_bench_tool.py
index 3d3e36bc3,ab1afecc8..1483aa616
--- a/agent/src/tools/alpha_bench_tool.py
+++ b/agent/src/tools/alpha_bench_tool.py
@@@ -1476,6 -1507,12 +1507,16 @@@ class AlphaBenchTool(BaseTool)
"conventional horizon for fundamental factors. Range 1-252."
),
},
+ "research_stage": {
+ "type": "string",
+ "enum": list(RESEARCH_STAGES),
+ "default": "single_factor_evaluation",
+ "description": "Stage recorded in the factor-research contract.",
+ },
++ "research_mode": {
++ "type": "string", "enum": list(RESEARCH_MODES), "default": "explore",
++ "description": "Declared research mode; metadata only, does not enforce locked evaluation.",
++ },
"output_dir": {
"type": "string",
"description": "Where to write the HTML report; default ~/.vibe-trading/reports/.",
diff --cc agent/tests/test_research_contract_integration.py
index 000000000,7ff54f037..5fdfc69fc
mode 000000,100644..100644
--- a/agent/tests/test_research_contract_integration.py
+++ b/agent/tests/test_research_contract_integration.py
@@@ -1,0 -1,144 +1,157 @@@
+ """Entry-point coverage for the factor-research run contract.
+
+ These tests exercise both bench runners with an injected in-memory registry and
+ panel. They verify the contract survives the runner's public result envelope
+ without making network requests or depending on the bundled alpha catalogue.
+ """
+
+ from __future__ import annotations
+
++import argparse
+ from typing import Any
+
+ import numpy as np
+ import pandas as pd
+ import pytest
+
+ from src.factors.bench_runner import run_bench
+ from src.factors.bench_runner_strict import run_bench_strict
+
+
+ def _panel(n_rows: int = 48, n_symbols: int = 6) -> dict[str, Any]:
+ rng = np.random.default_rng(2026)
+ index = pd.date_range("2024-01-01", periods=n_rows, freq="D")
+ symbols = [f"S{i}" for i in range(n_symbols)]
+ close = pd.DataFrame(
+ 100.0 + np.cumsum(rng.normal(size=(n_rows, n_symbols)), axis=0),
+ index=index,
+ columns=symbols,
+ )
+ return {
+ "close": close,
+ "open": close,
+ "high": close * 1.01,
+ "low": close * 0.99,
+ "volume": pd.DataFrame(1_000_000.0, index=index, columns=symbols),
+ "_meta": {"source": "test-panel"},
+ }
+
+
+ class _Registry:
+ """Small registry slice consumed by both bench runners."""
+
+ ids = ["alpha_a", "alpha_b"]
+
+ def list(self, *, zoo: str) -> list[str]: # noqa: ARG002
+ return list(self.ids)
+
+ def get(self, alpha_id: str) -> Any:
+ class _Handle:
+ meta = {
+ "theme": ["test"],
+ "formula_latex": "close",
+ "columns_required": [],
+ }
+
+ _Handle.alpha_id = alpha_id
+ return _Handle()
+
+ def compute(self, alpha_id: str, panel: dict[str, Any]) -> pd.DataFrame:
+ close = panel["close"]
+ if alpha_id == "alpha_a":
+ return close
+ # Keep the second factor distinct while retaining a fully populated
+ # cross-section for Spearman IC calculations.
+ return close.rank(axis=1, method="first")
+
+
+ def _patch_plain_runner(monkeypatch: pytest.MonkeyPatch) -> None:
+ panel = _panel()
+ monkeypatch.setattr(
+ "src.factors.bench_runner._load_universe_panel",
+ lambda universe, period: panel, # noqa: ARG005
+ )
+ monkeypatch.setattr(
+ "src.factors.bench_runner._compute_forward_returns",
+ lambda panel_in, horizon=1: panel_in["close"].pct_change(fill_method=None).shift(-1),
+ )
+
+
+ def _patch_strict_runner(monkeypatch: pytest.MonkeyPatch) -> None:
+ panel = _panel()
+ monkeypatch.setattr(
+ "src.factors.bench_runner_strict._load_universe_panel",
+ lambda universe, period: panel, # noqa: ARG005
+ )
+ monkeypatch.setattr(
+ "src.factors.bench_runner_strict._compute_forward_returns",
+ lambda panel_in, horizon=1: panel_in["close"].pct_change(fill_method=None).shift(-1),
+ )
+
+
+ def test_plain_runner_emits_research_contract(monkeypatch: pytest.MonkeyPatch) -> None:
+ _patch_plain_runner(monkeypatch)
+
+ result = run_bench(
+ "test_zoo",
+ "mock",
+ "2024-2024",
+ registry=_Registry(),
+ research_stage="neutralization",
+ research_lineage=["raw_alpha_library"],
+ research_transformations=[{"kind": "neutralization", "controls": ["size"]}],
+ horizon=21,
+ )
+
+ assert result["status"] == "ok"
+ research = result["meta"]["research"]
+ assert research["schema"] == "factor-research.run/v1"
++ assert research["mode"] == "explore"
+ assert research["stage"] == "neutralization"
+ assert research["factor_ids"] == ["alpha_a", "alpha_b"]
+ assert research["factor_count"] == 2
+ assert research["lineage"] == [{"id": "raw_alpha_library"}]
+ assert research["transformations"] == [
+ {"kind": "neutralization", "controls": ["size"]}
+ ]
+ assert research["evaluation"] == {
+ "horizon": 21,
+ "forward_return_sampling": "non_overlapping",
+ "method": "rank_ic",
+ }
+
+
+ def test_strict_runner_emits_research_contract(monkeypatch: pytest.MonkeyPatch) -> None:
+ _patch_strict_runner(monkeypatch)
+
+ result = run_bench_strict(
+ "test_zoo",
+ "mock",
+ "2024-2024",
+ random_control=False,
+ registry=_Registry(),
+ research_stage="composite_evaluation",
+ research_lineage=[{"kind": "combined_factor", "id": "combo_1"}],
+ research_transformations=["walk_forward_combination"],
+ )
+
+ assert result["status"] == "ok"
+ research = result["meta"]["research"]
+ assert research["schema"] == "factor-research.run/v1"
++ assert research["mode"] == "strict"
+ assert research["stage"] == "composite_evaluation"
+ assert research["factor_ids"] == ["alpha_a", "alpha_b"]
+ assert research["evaluation"]["method"] == "rank_ic"
+ assert research["evaluation"]["horizon"] == 1
+ assert research["lineage"] == [{"kind": "combined_factor", "id": "combo_1"}]
+ assert research["transformations"] == [{"id": "walk_forward_combination"}]
++
++
++def test_cli_can_explicitly_label_research_mode():
++ from src.factors.cli_handlers import add_subparser
++
++ parser = argparse.ArgumentParser()
++ add_subparser(parser.add_subparsers())
++ args = parser.parse_args(["alpha", "bench", "--zoo", "alpha101", "--universe", "csi300",
++ "--period", "2024-2024", "--research-mode", "locked"])
++ assert args.research_mode == "locked"