"Vibe-Trading: Your Personal Trading Agent"
Python ai-agentalgorithmic-tradingbacktestingfintechllmmcpmulti-agentpythonquantitative-financetrading
feat(autopilot): scaffold signal engine + auto-link backtest metrics (Phase 3) (#267)
卫斯李2e7761a55499
diff --git a/agent/src/tools/autopilot_tool.py b/agent/src/tools/autopilot_tool.pyindex ad6b3c49e..b0a489dc6 100644--- a/agent/src/tools/autopilot_tool.py+++ b/agent/src/tools/autopilot_tool.py@@ -2,6 +2,9 @@Phase 1: Connects the Hypothesis Registry to the Research Goal runtime.Phase 2: Auto-generates backtest config.json from hypothesis metadata.+Phase 3: Scaffolds a contract-correct signal_engine.py stub and links+ backtest run-card metrics back to the hypothesis, closing the+ hypothesis -> backtest -> evidence loop."""from __future__ import annotations@@ -368,3 +371,296 @@ class GenerateBacktestConfigTool(BaseTool):except Exception as exc:return _error(exc)+++_SIGNAL_ENGINE_TEMPLATE = '''"""Auto-scaffolded signal engine for hypothesis {hypothesis_id}.++Title: {title}++Implement your signal in ``SignalEngine.generate``. The default below holds+no position (a flat 0.0 signal) so the backtest runner contract is satisfied+and you can run a smoke backtest immediately, then replace the body with real+logic derived from the signal definition.+"""++from __future__ import annotations++import pandas as pd+++class SignalEngine:+ """Signal engine consumed by the backtest runner.++ The runner instantiates this class with no arguments and calls+ ``generate(data_map)`` once per backtest.+ """++ def generate(self, data_map: dict[str, "pd.DataFrame"]) -> dict[str, "pd.Series"]:+ """Return a signal Series per code.++ Signal definition to implement:+ {signal_definition}++ Args:+ data_map: Mapping of code -> OHLCV (and any factor) DataFrame.++ Returns:+ Mapping of code -> pd.Series of target signals aligned to the+ frame index. The default returns a flat 0.0 (no position) signal.+ """+ signals: dict[str, "pd.Series"] = {{}}+ for code, frame in data_map.items():+ signals[code] = pd.Series(0.0, index=frame.index)+ return signals+'''+++class ScaffoldSignalEngineTool(BaseTool):+ """Write a contract-correct ``signal_engine.py`` stub for a hypothesis.++ The backtest runner requires a ``SignalEngine`` class that is+ constructible with no arguments and exposes ``generate(self, data_map)``.+ This tool emits exactly that, with a runnable flat-signal default and the+ hypothesis ``signal_definition`` embedded as a docstring, so the agent can+ fill in real logic instead of re-deriving the boilerplate.+ """++ name = "scaffold_signal_engine"+ description = (+ "Write a contract-correct code/signal_engine.py stub into a backtest "+ "run directory for a saved hypothesis. The stub satisfies the backtest "+ "runner contract (no-arg SignalEngine, generate(data_map) -> dict of "+ "pd.Series) with a flat no-position default and the signal_definition "+ "embedded as a docstring. Replace the generate body with real logic, "+ "then call backtest(run_dir=...)."+ )+ is_readonly = False+ repeatable = True+ parameters = {+ "type": "object",+ "properties": {+ "hypothesis_id": {+ "type": "string",+ "description": "ID of a previously created research hypothesis",+ },+ "run_dir": {+ "type": "string",+ "description": "Backtest run directory (from generate_backtest_config)",+ },+ "overwrite": {+ "type": "boolean",+ "description": "Overwrite an existing signal_engine.py (default false)",+ },+ },+ "required": ["hypothesis_id", "run_dir"],+ }++ def execute(self, **kwargs: Any) -> str:+ try:+ hypothesis_id = str(kwargs.get("hypothesis_id", "")).strip()+ if not hypothesis_id:+ return json.dumps(+ {"status": "error", "error": "hypothesis_id is required"},+ ensure_ascii=False,+ )++ run_dir_raw = str(kwargs.get("run_dir", "")).strip()+ if not run_dir_raw:+ return json.dumps(+ {"status": "error", "error": "run_dir is required"},+ ensure_ascii=False,+ )++ from src.tools.path_utils import safe_run_dir++ try:+ run_path = safe_run_dir(run_dir_raw)+ except ValueError as exc:+ return json.dumps(+ {"status": "error", "error": str(exc)}, ensure_ascii=False+ )++ hypothesis = _get_hypothesis(hypothesis_id)+ if hypothesis is None:+ return json.dumps(+ {+ "status": "error",+ "error": f"Hypothesis not found: {hypothesis_id}",+ "hint": "Use search_hypotheses to list available hypotheses.",+ },+ ensure_ascii=False,+ )++ overwrite = bool(kwargs.get("overwrite", False))+ code_dir = run_path / "code"+ code_dir.mkdir(parents=True, exist_ok=True)+ signal_path = code_dir / "signal_engine.py"+ if signal_path.exists() and not overwrite:+ return json.dumps(+ {+ "status": "error",+ "error": f"signal_engine.py already exists: {signal_path}",+ "hint": "Pass overwrite=true to replace it.",+ },+ ensure_ascii=False,+ )++ signal_definition = (+ hypothesis.signal_definition.strip()+ or "(no signal_definition set on the hypothesis)"+ )+ source = _SIGNAL_ENGINE_TEMPLATE.format(+ hypothesis_id=hypothesis.hypothesis_id,+ title=hypothesis.title,+ signal_definition=signal_definition,+ )+ signal_path.write_text(source, encoding="utf-8")++ return _ok(+ {+ "signal_engine_path": str(signal_path),+ "run_dir": str(run_path),+ "hypothesis": {+ "hypothesis_id": hypothesis.hypothesis_id,+ "title": hypothesis.title,+ "signal_definition": hypothesis.signal_definition,+ },+ "next_step": (+ "Stub written with a flat no-position default. Edit the "+ "generate() body to implement the signal_definition, then "+ "call backtest(run_dir=...)."+ ),+ }+ )++ except Exception as exc:+ return _error(exc)+++class LinkAutopilotBacktestTool(BaseTool):+ """Read run_card.json metrics and link the run to a hypothesis.++ After a backtest completes, its metrics live in ``run_card.json``. The+ existing ``link_backtest`` tool requires the agent to hand-extract that+ metrics dict. This tool reads the run card, extracts the scalar metrics,+ and links the run in one step, returning the metrics for thesis evaluation.+ """++ name = "link_autopilot_backtest"+ description = (+ "Read run_card.json from a completed backtest run directory, extract "+ "its metrics, and link the run to a research hypothesis. Returns the "+ "metrics so you can evaluate them against the thesis. Use this after "+ "the backtest tool succeeds."+ )+ is_readonly = False+ repeatable = True+ parameters = {+ "type": "object",+ "properties": {+ "hypothesis_id": {+ "type": "string",+ "description": "ID of the hypothesis this backtest tests",+ },+ "run_dir": {+ "type": "string",+ "description": "Backtest run directory containing run_card.json",+ },+ "notes": {+ "type": "string",+ "description": "Optional note about this backtest link",+ },+ },+ "required": ["hypothesis_id", "run_dir"],+ }++ def execute(self, **kwargs: Any) -> str:+ try:+ hypothesis_id = str(kwargs.get("hypothesis_id", "")).strip()+ if not hypothesis_id:+ return json.dumps(+ {"status": "error", "error": "hypothesis_id is required"},+ ensure_ascii=False,+ )++ run_dir_raw = str(kwargs.get("run_dir", "")).strip()+ if not run_dir_raw:+ return json.dumps(+ {"status": "error", "error": "run_dir is required"},+ ensure_ascii=False,+ )++ from src.tools.path_utils import safe_run_dir++ try:+ run_path = safe_run_dir(run_dir_raw)+ except ValueError as exc:+ return json.dumps(+ {"status": "error", "error": str(exc)}, ensure_ascii=False+ )++ card_path = run_path / "run_card.json"+ if not card_path.exists():+ return json.dumps(+ {+ "status": "error",+ "error": f"run_card.json not found in {run_path}",+ "hint": "Run the backtest tool first; it writes run_card.json.",+ },+ ensure_ascii=False,+ )++ try:+ card = json.loads(card_path.read_text(encoding="utf-8"))+ except json.JSONDecodeError as exc:+ return json.dumps(+ {+ "status": "error",+ "error": f"run_card.json parse error: {exc}",+ },+ ensure_ascii=False,+ )++ warning: str | None = None+ metrics = card.get("metrics") if isinstance(card, dict) else None+ if not isinstance(metrics, dict):+ metrics = {}+ warning = "run_card.json had no 'metrics' object; linked with empty metrics"++ try:+ hypothesis = HypothesisRegistry().link_backtest(+ hypothesis_id,+ backtest_run_dir=str(run_path),+ metrics=metrics,+ notes=str(kwargs.get("notes", "")),+ )+ except KeyError:+ return json.dumps(+ {+ "status": "error",+ "error": f"Hypothesis not found: {hypothesis_id}",+ "hint": "Use search_hypotheses to list available hypotheses.",+ },+ ensure_ascii=False,+ )++ payload: dict[str, Any] = {+ "metrics": metrics,+ "run_dir": str(run_path),+ "hypothesis": {+ "hypothesis_id": hypothesis.hypothesis_id,+ "title": hypothesis.title,+ "status": hypothesis.status,+ "run_cards_count": len(hypothesis.run_cards),+ },+ "next_step": (+ "Backtest linked. Evaluate the metrics against the thesis, "+ "then record_evidence / add_goal_evidence to close the loop."+ ),+ }+ if warning:+ payload["warning"] = warning+ return _ok(payload)++ except Exception as exc:+ return _error(exc)diff --git a/agent/tests/test_autopilot_phase3.py b/agent/tests/test_autopilot_phase3.pynew file mode 100644index 000000000..877d0016e--- /dev/null+++ b/agent/tests/test_autopilot_phase3.py@@ -0,0 +1,264 @@+"""Tests for Research Autopilot Phase 3 tools.++Covers ``scaffold_signal_engine`` (contract-correct stub generation) and+``link_autopilot_backtest`` (run-card metrics -> hypothesis link) in+``src.tools.autopilot_tool``.+"""++from __future__ import annotations++import importlib.util+import inspect+import json+from pathlib import Path++import pandas as pd+import pytest++from src.hypotheses import HypothesisRegistry+from src.tools.autopilot_tool import (+ LinkAutopilotBacktestTool,+ ScaffoldSignalEngineTool,+ _get_hypothesis,+)+++def isolated_env(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Path:+ """Isolate the hypothesis registry and allow tmp_path as a run root."""+ monkeypatch.setenv(+ "VIBE_TRADING_HYPOTHESES_PATH", str(tmp_path / "hypotheses.json")+ )+ monkeypatch.setenv("VIBE_TRADING_ALLOWED_RUN_ROOTS", str(tmp_path))+ return tmp_path+++def _make_hypothesis(**overrides) -> str:+ registry = HypothesisRegistry()+ kwargs = dict(+ title="A-share momentum",+ thesis="Cross-sectional momentum persists in large caps.",+ universe="CSI 300",+ signal_definition="rank(returns_20d) top decile",+ data_sources=["akshare"],+ )+ kwargs.update(overrides)+ return registry.create(**kwargs).hypothesis_id+++def _run_dir(base: Path) -> Path:+ d = base / "runs" / "autopilot_test"+ d.mkdir(parents=True, exist_ok=True)+ return d+++# --------------------------------------------------------------------------+# scaffold_signal_engine+# --------------------------------------------------------------------------+++def test_scaffold_requires_hypothesis_id(isolated_env: Path) -> None:+ result = json.loads(+ ScaffoldSignalEngineTool().execute(+ hypothesis_id="", run_dir=str(_run_dir(isolated_env))+ )+ )+ assert result["status"] == "error"+ assert "hypothesis_id is required" in result["error"]+++def test_scaffold_requires_run_dir(isolated_env: Path) -> None:+ hyp_id = _make_hypothesis()+ result = json.loads(+ ScaffoldSignalEngineTool().execute(hypothesis_id=hyp_id, run_dir="")+ )+ assert result["status"] == "error"+ assert "run_dir is required" in result["error"]+++def test_scaffold_rejects_path_outside_run_roots(isolated_env: Path) -> None:+ hyp_id = _make_hypothesis()+ result = json.loads(+ ScaffoldSignalEngineTool().execute(+ hypothesis_id=hyp_id, run_dir="/etc/evil_run"+ )+ )+ assert result["status"] == "error"+ assert "run roots" in result["error"]+++def test_scaffold_unknown_hypothesis(isolated_env: Path) -> None:+ result = json.loads(+ ScaffoldSignalEngineTool().execute(+ hypothesis_id="hyp_missing", run_dir=str(_run_dir(isolated_env))+ )+ )+ assert result["status"] == "error"+ assert "not found" in result["error"]+++def test_scaffold_writes_contract_correct_stub(isolated_env: Path) -> None:+ hyp_id = _make_hypothesis()+ run_dir = _run_dir(isolated_env)+ result = json.loads(+ ScaffoldSignalEngineTool().execute(+ hypothesis_id=hyp_id, run_dir=str(run_dir)+ )+ )++ assert result["status"] == "ok"+ signal_path = Path(result["signal_engine_path"])+ assert signal_path.exists()+ assert signal_path == run_dir / "code" / "signal_engine.py"++ # The signal_definition is embedded for the agent to implement against.+ text = signal_path.read_text(encoding="utf-8")+ assert "rank(returns_20d) top decile" in text++ # The stub must satisfy the backtest runner contract: a SignalEngine+ # class instantiable with no args, with a callable generate(data_map).+ spec = importlib.util.spec_from_file_location("scaffolded_engine", signal_path)+ module = importlib.util.module_from_spec(spec)+ spec.loader.exec_module(module)+ engine_cls = module.SignalEngine++ init_sig = inspect.signature(engine_cls.__init__)+ required = [+ p.name+ for p in init_sig.parameters.values()+ if p.name != "self" and p.default is inspect.Parameter.empty+ and p.kind not in (inspect.Parameter.VAR_POSITIONAL, inspect.Parameter.VAR_KEYWORD)+ ]+ assert required == [] # runner can call SignalEngine()+ assert callable(getattr(engine_cls, "generate", None))++ # The flat default returns a dict of pd.Series aligned to the input index.+ idx = pd.date_range("2020-01-01", periods=5)+ data_map = {"000300.SH": pd.DataFrame({"close": range(5)}, index=idx)}+ out = engine_cls().generate(data_map)+ assert set(out) == {"000300.SH"}+ assert isinstance(out["000300.SH"], pd.Series)+ assert (out["000300.SH"] == 0.0).all()+ assert list(out["000300.SH"].index) == list(idx)+++def test_scaffold_refuses_overwrite_by_default(isolated_env: Path) -> None:+ hyp_id = _make_hypothesis()+ run_dir = _run_dir(isolated_env)+ tool = ScaffoldSignalEngineTool()+ first = json.loads(tool.execute(hypothesis_id=hyp_id, run_dir=str(run_dir)))+ assert first["status"] == "ok"++ # Mark the file so we can detect an unwanted overwrite.+ signal_path = Path(first["signal_engine_path"])+ signal_path.write_text("# user edits\n", encoding="utf-8")++ second = json.loads(tool.execute(hypothesis_id=hyp_id, run_dir=str(run_dir)))+ assert second["status"] == "error"+ assert "already exists" in second["error"]+ assert signal_path.read_text(encoding="utf-8") == "# user edits\n"++ third = json.loads(+ tool.execute(hypothesis_id=hyp_id, run_dir=str(run_dir), overwrite=True)+ )+ assert third["status"] == "ok"+ assert "SignalEngine" in signal_path.read_text(encoding="utf-8")+++# --------------------------------------------------------------------------+# link_autopilot_backtest+# --------------------------------------------------------------------------+++def _write_run_card(run_dir: Path, metrics: dict | None) -> None:+ card: dict = {"schema_version": 1, "run_dir": str(run_dir)}+ if metrics is not None:+ card["metrics"] = metrics+ (run_dir / "run_card.json").write_text(+ json.dumps(card, ensure_ascii=False), encoding="utf-8"+ )+++def test_link_requires_run_dir(isolated_env: Path) -> None:+ hyp_id = _make_hypothesis()+ result = json.loads(+ LinkAutopilotBacktestTool().execute(hypothesis_id=hyp_id, run_dir="")+ )+ assert result["status"] == "error"+ assert "run_dir is required" in result["error"]+++def test_link_missing_run_card(isolated_env: Path) -> None:+ hyp_id = _make_hypothesis()+ run_dir = _run_dir(isolated_env)+ result = json.loads(+ LinkAutopilotBacktestTool().execute(+ hypothesis_id=hyp_id, run_dir=str(run_dir)+ )+ )+ assert result["status"] == "error"+ assert "run_card.json not found" in result["error"]+++def test_link_corrupt_run_card(isolated_env: Path) -> None:+ hyp_id = _make_hypothesis()+ run_dir = _run_dir(isolated_env)+ (run_dir / "run_card.json").write_text("{not json", encoding="utf-8")+ result = json.loads(+ LinkAutopilotBacktestTool().execute(+ hypothesis_id=hyp_id, run_dir=str(run_dir)+ )+ )+ assert result["status"] == "error"+ assert "parse error" in result["error"]+++def test_link_unknown_hypothesis(isolated_env: Path) -> None:+ run_dir = _run_dir(isolated_env)+ _write_run_card(run_dir, {"sharpe": 1.2})+ result = json.loads(+ LinkAutopilotBacktestTool().execute(+ hypothesis_id="hyp_missing", run_dir=str(run_dir)+ )+ )+ assert result["status"] == "error"+ assert "not found" in result["error"]+++def test_link_extracts_metrics_and_links(isolated_env: Path) -> None:+ hyp_id = _make_hypothesis()+ run_dir = _run_dir(isolated_env)+ _write_run_card(run_dir, {"sharpe": 1.42, "total_return": 0.31})++ result = json.loads(+ LinkAutopilotBacktestTool().execute(+ hypothesis_id=hyp_id, run_dir=str(run_dir), notes="phase3 link"+ )+ )++ assert result["status"] == "ok"+ assert result["metrics"] == {"sharpe": 1.42, "total_return": 0.31}+ assert result["hypothesis"]["run_cards_count"] == 1++ # The link is persisted on the hypothesis run_cards.+ reloaded = _get_hypothesis(hyp_id)+ assert len(reloaded.run_cards) == 1+ card = reloaded.run_cards[0]+ assert card["backtest_run_dir"] == str(run_dir)+ assert card["metrics"] == {"sharpe": 1.42, "total_return": 0.31}+++def test_link_absent_metrics_degrades_with_warning(isolated_env: Path) -> None:+ hyp_id = _make_hypothesis()+ run_dir = _run_dir(isolated_env)+ _write_run_card(run_dir, None) # no metrics key++ result = json.loads(+ LinkAutopilotBacktestTool().execute(+ hypothesis_id=hyp_id, run_dir=str(run_dir)+ )+ )+ assert result["status"] == "ok"+ assert result["metrics"] == {}+ assert "warning" in result+ assert "empty metrics" in result["warning"]