Skip to content

"Vibe-Trading: Your Personal Trading Agent"

fix(backtest): make mootdx & futu first-class config sources

Haozhe Wuf735e4ca510f
diff --git a/agent/backtest/loaders/registry.py b/agent/backtest/loaders/registry.py
index dcfdecd44..ec79707ef 100644
--- a/agent/backtest/loaders/registry.py
+++ b/agent/backtest/loaders/registry.py
@@ -24,6 +24,23 @@ LOADER_REGISTRY: dict[str, Type[Any]] = {}
_registered = False
+# Canonical set of accepted data-source names: every registered loader plus the
+# ``"auto"`` cross-market selector. Single source of truth shared by the backtest
+# config schema (``backtest.runner.BacktestConfigSchema``) and the agent-facing
+# backtest tool (``src.tools.backtest_tool``) so the two can never drift apart.
+# Keep in sync with ``_loader_modules`` below — the regression test
+# ``test_valid_sources_covers_all_registered_loaders`` enforces full coverage.
+VALID_SOURCES: set[str] = {
+ "tushare",
+ "okx",
+ "yfinance",
+ "akshare",
+ "mootdx",
+ "ccxt",
+ "futu",
+ "auto",
+}
+
def register(cls: Type[Any]) -> Type[Any]:
"""Class decorator: register a loader into the global registry.
diff --git a/agent/backtest/metrics.py b/agent/backtest/metrics.py
index 2d687da25..e1cdb7caf 100644
--- a/agent/backtest/metrics.py
+++ b/agent/backtest/metrics.py
@@ -14,15 +14,20 @@ from backtest.models import TradeRecord
# ─── Annualisation factor mapping ───
-_TRADING_DAYS = {"tushare": 252, "yfinance": 252, "okx": 365, "akshare": 252, "ccxt": 365}
+# mootdx (A-share) and futu (HK + A-share) are equity sources, so they mirror
+# the tushare/akshare column: 252 trading days and a 240-minute session. HK
+# sessions are marginally longer (~330 min) — an approximation in line with the
+# rest of this annualisation table; the key fix is that intraday mootdx/futu no
+# longer fall back to the bars_per_day=1 default, which mis-annualised vol/Sharpe.
+_TRADING_DAYS = {"tushare": 252, "yfinance": 252, "okx": 365, "akshare": 252, "ccxt": 365, "mootdx": 252, "futu": 252}
_BARS_PER_DAY = {
- "1m": {"tushare": 240, "okx": 1440, "yfinance": 390, "akshare": 240, "ccxt": 1440},
- "5m": {"tushare": 48, "okx": 288, "yfinance": 78, "akshare": 48, "ccxt": 288},
- "15m": {"tushare": 16, "okx": 96, "yfinance": 26, "akshare": 16, "ccxt": 96},
- "30m": {"tushare": 8, "okx": 48, "yfinance": 13, "akshare": 8, "ccxt": 48},
- "1H": {"tushare": 4, "okx": 24, "yfinance": 7, "akshare": 4, "ccxt": 24},
- "4H": {"tushare": 1, "okx": 6, "yfinance": 2, "akshare": 1, "ccxt": 6},
- "1D": {"tushare": 1, "okx": 1, "yfinance": 1, "akshare": 1, "ccxt": 1},
+ "1m": {"tushare": 240, "okx": 1440, "yfinance": 390, "akshare": 240, "ccxt": 1440, "mootdx": 240, "futu": 240},
+ "5m": {"tushare": 48, "okx": 288, "yfinance": 78, "akshare": 48, "ccxt": 288, "mootdx": 48, "futu": 48},
+ "15m": {"tushare": 16, "okx": 96, "yfinance": 26, "akshare": 16, "ccxt": 96, "mootdx": 16, "futu": 16},
+ "30m": {"tushare": 8, "okx": 48, "yfinance": 13, "akshare": 8, "ccxt": 48, "mootdx": 8, "futu": 8},
+ "1H": {"tushare": 4, "okx": 24, "yfinance": 7, "akshare": 4, "ccxt": 24, "mootdx": 4, "futu": 4},
+ "4H": {"tushare": 1, "okx": 6, "yfinance": 2, "akshare": 1, "ccxt": 6, "mootdx": 1, "futu": 1},
+ "1D": {"tushare": 1, "okx": 1, "yfinance": 1, "akshare": 1, "ccxt": 1, "mootdx": 1, "futu": 1},
}
diff --git a/agent/backtest/runner.py b/agent/backtest/runner.py
index c54659d07..420303c9c 100644
--- a/agent/backtest/runner.py
+++ b/agent/backtest/runner.py
@@ -28,6 +28,7 @@ except ImportError:
from backtest.loaders.registry import (
FALLBACK_CHAINS,
LOADER_REGISTRY,
+ VALID_SOURCES,
get_loader_cls_with_fallback,
resolve_loader,
)
@@ -47,7 +48,6 @@ logger = logging.getLogger(__name__)
_VALID_INTERVALS = {"1m", "5m", "15m", "30m", "1H", "4H", "1D"}
_VALID_ENGINES = {"daily", "options"}
-_VALID_SOURCES = {"tushare", "okx", "yfinance", "akshare", "ccxt", "auto"}
class BacktestConfigSchema(BaseModel):
@@ -98,8 +98,8 @@ class BacktestConfigSchema(BaseModel):
@field_validator("source")
@classmethod
def valid_source(cls, v: str) -> str:
- if v not in _VALID_SOURCES:
- raise ValueError(f"unsupported source {v!r}, must be one of {_VALID_SOURCES}")
+ if v not in VALID_SOURCES:
+ raise ValueError(f"unsupported source {v!r}, must be one of {VALID_SOURCES}")
return v
@field_validator("fundamental_fields")
diff --git a/agent/src/tools/backtest_tool.py b/agent/src/tools/backtest_tool.py
index c224e9745..8808c057a 100644
--- a/agent/src/tools/backtest_tool.py
+++ b/agent/src/tools/backtest_tool.py
@@ -5,6 +5,7 @@ from __future__ import annotations
import json
from pathlib import Path
+from backtest.loaders.registry import VALID_SOURCES
from src.agent.progress import emit_progress
from src.agent.tools import BaseTool
from src.core.runner import Runner
@@ -38,9 +39,8 @@ def run_backtest(run_dir: str) -> str:
if "source" not in config:
return json.dumps({"status": "error", "error": "config.json missing 'source' field (tushare/okx/yfinance)"}, ensure_ascii=False)
- valid_sources = {"tushare", "okx", "yfinance", "akshare", "mootdx", "ccxt", "futu", "auto"}
- if config["source"] not in valid_sources:
- return json.dumps({"status": "error", "error": f"source must be one of {valid_sources}, got: {config['source']}"}, ensure_ascii=False)
+ if config["source"] not in VALID_SOURCES:
+ return json.dumps({"status": "error", "error": f"source must be one of {VALID_SOURCES}, got: {config['source']}"}, ensure_ascii=False)
signal_path = run_path / "code" / "signal_engine.py"
if not signal_path.exists():
diff --git a/agent/tests/test_engine_robustness.py b/agent/tests/test_engine_robustness.py
index 91d834578..7596bedc7 100644
--- a/agent/tests/test_engine_robustness.py
+++ b/agent/tests/test_engine_robustness.py
@@ -355,6 +355,32 @@ class TestBacktestConfigSchema:
source="bloomberg",
)
+ def test_mootdx_and_futu_sources_accepted(self) -> None:
+ """mootdx and futu are registered loaders, so config validation must
+ accept them. Regression: ``_VALID_SOURCES`` drifted and rejected both
+ even though the agent-facing backtest tool already allowed them."""
+ for src in ("mootdx", "futu"):
+ c = BacktestConfigSchema(
+ codes=["000001.SZ"],
+ start_date="2025-01-01",
+ end_date="2025-06-01",
+ source=src,
+ )
+ assert c.source == src
+
+ def test_valid_sources_covers_all_registered_loaders(self) -> None:
+ """Every registered loader name must be an accepted config source, so a
+ new loader can never be silently rejected by the config schema."""
+ from backtest.loaders.registry import (
+ LOADER_REGISTRY,
+ VALID_SOURCES,
+ _ensure_registered,
+ )
+
+ _ensure_registered()
+ missing = set(LOADER_REGISTRY) - VALID_SOURCES
+ assert not missing, f"loaders missing from VALID_SOURCES: {missing}"
+
def test_extra_fields_allowed(self) -> None:
"""Config may contain engine-specific fields not in the schema."""
c = BacktestConfigSchema(
diff --git a/agent/tests/test_metrics.py b/agent/tests/test_metrics.py
index bd4f14135..df32cc169 100644
--- a/agent/tests/test_metrics.py
+++ b/agent/tests/test_metrics.py
@@ -72,6 +72,15 @@ class TestBarsPerYear:
# 365 days × 24 hours/day = 8760
assert calc_bars_per_year("1H", "okx") == 365 * 24
+ def test_minute_mootdx(self) -> None:
+ # mootdx is A-share: 252 trading days × 240 minutes/day (regression —
+ # previously fell back to bars_per_day=1, mis-annualising intraday vol)
+ assert calc_bars_per_year("1m", "mootdx") == 252 * 240
+
+ def test_minute_futu(self) -> None:
+ # futu is equity (HK + A-share): same equity annualisation as akshare
+ assert calc_bars_per_year("1m", "futu") == 252 * 240
+
def test_unknown_source(self) -> None:
# Falls back to 252 trading days
assert calc_bars_per_year("1D", "unknown") == 252