Skip to content

"Vibe-Trading: Your Personal Trading Agent"

fix(ui): reconstruct charts through loader registry

Haozhe Wu73c8ba9bcadb
diff --git a/agent/backtest/runner.py b/agent/backtest/runner.py
index c4e708df2..d350ed9ff 100644
--- a/agent/backtest/runner.py
+++ b/agent/backtest/runner.py
@@ -13,6 +13,7 @@ import inspect
import json
import logging
import sys
+from dataclasses import dataclass
from pathlib import Path
from typing import Any, Dict, Iterable, List, Optional
@@ -52,6 +53,17 @@ _PRICE_PANEL_COLUMNS = ("open", "high", "low", "close", "volume", "vwap", "amoun
_FUND_PREFIX = "fund:"
+@dataclass(frozen=True)
+class DataFetchResult:
+ """Market data plus the routing metadata selected by the central registry."""
+
+ data_map: Dict[str, pd.DataFrame]
+ codes: List[str]
+ source: str
+ loader: Any
+ effective_sources: List[str]
+
+
class BacktestConfigSchema(BaseModel):
"""Validates backtest config.json before execution."""
@@ -875,62 +887,19 @@ def main(run_dir: Path) -> None:
print(json.dumps({"error": f"SignalEngine interface error: {exc}"}))
sys.exit(1)
- # Data: auto split vs single loader
+ fetch_result = fetch_data_map(config)
+ data_map = fetch_result.data_map
+ codes = fetch_result.codes
+ source = fetch_result.source
+ loader = fetch_result.loader
+ config["codes"] = codes
+ config["_run_card_effective_sources"] = fetch_result.effective_sources
interval = config.get("interval", "1D")
-
- if source == "auto":
- data_map = _fetch_auto(codes, config, interval)
- else:
- codes = _normalize_codes(codes, source)
- config["codes"] = codes
- LoaderCls = _get_loader(source)
- loader = LoaderCls()
- data_map = loader.fetch(
- codes,
- config.get("start_date", ""),
- config.get("end_date", ""),
- fields=config.get("extra_fields") or None,
- interval=interval,
- )
- if data_map and len(data_map) < len(codes):
- missing = set(codes) - set(data_map.keys())
- logger.warning(
- "source=%s returned data for %d/%d symbols; missing: %s",
- source, len(data_map), len(codes), missing,
- )
- # Runtime fallback: try next sources in chain when primary returns empty
- if not data_map and codes:
- market = _detect_market(codes[0])
- for fb_name in FALLBACK_CHAINS.get(market, []):
- if fb_name == source or fb_name not in LOADER_REGISTRY:
- continue
- fb_loader = LOADER_REGISTRY[fb_name]()
- if not fb_loader.is_available():
- continue
- fb_codes = _normalize_codes(codes, fb_name)
- data_map = fb_loader.fetch(
- fb_codes, config.get("start_date", ""),
- config.get("end_date", ""), interval=interval,
- )
- if data_map:
- logger.info("Runtime fallback: %s -> %s", source, fb_name)
- source = fb_name
- loader = fb_loader
- break
-
- # Loader-boundary OHLC sanity for every source, centralized at the one
- # point all fetch paths converge (auto / single / runtime fallback).
- data_map = _sanitize_data_map(data_map)
if not data_map:
print(json.dumps({"error": "No data fetched"}))
sys.exit(1)
data_map = _maybe_inject_fundamentals_for_factor_panel(data_map, config)
- if source == "auto":
- config["_run_card_effective_sources"] = sorted(_group_codes_by_source(codes))
- else:
- config["_run_card_effective_sources"] = [source]
-
# Engine
engine_type = config.get("engine", "daily")
signal_engine = engine_cls()
@@ -1090,6 +1059,79 @@ def _fetch_auto(codes: List[str], config: dict, interval: str = "1D") -> dict:
return merged
+def fetch_data_map(config: dict) -> DataFetchResult:
+ """Fetch and sanitize bars through the canonical loader registry.
+
+ This is the shared entry point for backtest execution and reconstruction
+ consumers. It preserves auto routing and the runtime fallback chain.
+
+ Args:
+ config: Backtest configuration containing codes, dates, source, and interval.
+
+ Returns:
+ Data and effective routing metadata. The input config is not mutated.
+ """
+ source = str(config.get("source") or "tushare")
+ codes = list(config.get("codes") or [])
+ interval = str(config.get("interval") or "1D")
+
+ if source == "auto":
+ data_map = _fetch_auto(codes, config, interval)
+ loader: Any = _AutoLoader(data_map)
+ else:
+ codes = _normalize_codes(codes, source)
+ loader = _get_loader(source)()
+ data_map = loader.fetch(
+ codes,
+ config.get("start_date", ""),
+ config.get("end_date", ""),
+ fields=config.get("extra_fields") or None,
+ interval=interval,
+ )
+ if data_map and len(data_map) < len(codes):
+ missing = set(codes) - set(data_map)
+ logger.warning(
+ "source=%s returned data for %d/%d symbols; missing: %s",
+ source,
+ len(data_map),
+ len(codes),
+ missing,
+ )
+ if not data_map and codes:
+ market = _detect_market(codes[0])
+ for fallback_source in FALLBACK_CHAINS.get(market, []):
+ if fallback_source == source or fallback_source not in LOADER_REGISTRY:
+ continue
+ fallback_loader = LOADER_REGISTRY[fallback_source]()
+ if not fallback_loader.is_available():
+ continue
+ fallback_codes = _normalize_codes(codes, fallback_source)
+ data_map = fallback_loader.fetch(
+ fallback_codes,
+ config.get("start_date", ""),
+ config.get("end_date", ""),
+ interval=interval,
+ )
+ if data_map:
+ logger.info("Runtime fallback: %s -> %s", source, fallback_source)
+ source = fallback_source
+ codes = fallback_codes
+ loader = fallback_loader
+ break
+
+ data_map = _sanitize_data_map(data_map)
+ effective_sources = (
+ sorted(_group_codes_by_source(codes)) if source == "auto" else [source]
+ )
+ return DataFetchResult(
+ data_map=data_map,
+ codes=codes,
+ source=source,
+ loader=loader,
+ effective_sources=effective_sources,
+ )
+
+
def _sanitize_data_map(data_map: dict) -> dict:
"""Drop structurally-invalid OHLC bars from every fetched frame.
diff --git a/agent/src/ui_services.py b/agent/src/ui_services.py
index 4b4bc4bcc..cf07a3eeb 100644
--- a/agent/src/ui_services.py
+++ b/agent/src/ui_services.py
@@ -450,7 +450,6 @@ def reconstruct_price_series(run_dir: Path) -> List[Dict[str, Any]]:
if not signal_path.exists():
return []
- agent_root = Path(__file__).resolve().parents[1]
try:
from src.providers.llm import _ensure_dotenv
@@ -461,21 +460,21 @@ def reconstruct_price_series(run_dir: Path) -> List[Dict[str, Any]]:
try:
config_data = load_json_file(run_dir / "config.json") or {}
- source = str(config_data.get("source") or "tushare")
- if source == "okx":
- from backtest.loaders.okx import DataLoader
- elif source == "yfinance":
- from backtest.loaders.yfinance_loader import DataLoader
- else:
- from backtest.loaders.tushare import DataLoader
- loader = DataLoader()
- data_map = loader.fetch(codes, fetch_start_date, end_date)
+ from backtest.runner import fetch_data_map
+
+ fetch_config = dict(config_data)
+ fetch_config.update(
+ codes=codes,
+ start_date=fetch_start_date,
+ end_date=end_date,
+ )
+ data_map = fetch_data_map(fetch_config).data_map
except Exception as exc:
print(f"[WARN] reconstruct_price_series: DataLoader failed ({exc})")
return []
if not data_map:
- print(f"[WARN] reconstruct_price_series: DataLoader returned empty")
+ print("[WARN] reconstruct_price_series: DataLoader returned empty")
return []
return _flatten_data_map(data_map, start_date=start_date)
diff --git a/agent/tests/test_ui_services.py b/agent/tests/test_ui_services.py
index e90d69dd8..5e0ea2c6c 100644
--- a/agent/tests/test_ui_services.py
+++ b/agent/tests/test_ui_services.py
@@ -3,19 +3,21 @@
from __future__ import annotations
import json
-import sys
-import types
from pathlib import Path
+from types import SimpleNamespace
import pandas as pd
import pytest
+import backtest.runner as runner
from src.ui_services import reconstruct_price_series
-def test_reconstruct_price_series_preserves_configured_source(
[email protected]("source", ["yahoo", "auto"])
+def test_reconstruct_price_series_uses_central_fetch_router(
tmp_path: Path,
monkeypatch: pytest.MonkeyPatch,
+ source: str,
) -> None:
run_dir = tmp_path / "completed-run"
(run_dir / "code").mkdir(parents=True)
@@ -41,44 +43,105 @@ def test_reconstruct_price_series_preserves_configured_source(
"codes": ["BTC-USDT"],
"start_date": "2026-01-01",
"end_date": "2026-01-02",
- "source": "okx",
+ "source": source,
+ "interval": "1H",
}
),
encoding="utf-8",
)
- selected_sources: list[str] = []
-
- def install_loader(source: str) -> None:
- module = types.ModuleType(f"backtest.loaders.{source}")
-
- class StubLoader:
- def fetch(self, codes, start_date, end_date):
- selected_sources.append(source)
- index = pd.DatetimeIndex([pd.Timestamp("2026-01-01")])
- return {
- codes[0]: pd.DataFrame(
- {
- "open": [1.0],
- "high": [1.0],
- "low": [1.0],
- "close": [1.0],
- "volume": [1.0],
- },
- index=index,
- )
- }
-
- module.DataLoader = StubLoader
- monkeypatch.setitem(sys.modules, module.__name__, module)
-
- install_loader("okx")
- install_loader("tushare")
- llm_module = types.ModuleType("src.providers.llm")
- llm_module._ensure_dotenv = lambda: None
- monkeypatch.setitem(sys.modules, llm_module.__name__, llm_module)
+ routed_configs: list[dict] = []
+ frame = pd.DataFrame(
+ {
+ "open": [1.0],
+ "high": [1.0],
+ "low": [1.0],
+ "close": [1.0],
+ "volume": [1.0],
+ },
+ index=pd.DatetimeIndex([pd.Timestamp("2026-01-01")]),
+ )
+
+ def fake_fetch_data_map(config: dict) -> SimpleNamespace:
+ routed_configs.append(config)
+ return SimpleNamespace(data_map={"BTC-USDT": frame})
+
+ monkeypatch.setattr(runner, "fetch_data_map", fake_fetch_data_map)
rows = reconstruct_price_series(run_dir)
- assert selected_sources == ["okx"]
+ assert routed_configs[0]["source"] == source
+ assert routed_configs[0]["interval"] == "1H"
+ assert routed_configs[0]["codes"] == ["BTC-USDT"]
assert rows[0]["code"] == "BTC-USDT"
+
+
+def test_fetch_data_map_uses_registry_for_nonlegacy_source(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ calls: list[tuple] = []
+ frame = pd.DataFrame(
+ {"open": [1.0], "high": [1.0], "low": [1.0], "close": [1.0]},
+ index=pd.DatetimeIndex([pd.Timestamp("2026-01-01")]),
+ )
+
+ class StubLoader:
+ name = "yahoo"
+
+ def fetch(self, codes, start_date, end_date, **kwargs):
+ calls.append((codes, start_date, end_date, kwargs))
+ return {codes[0]: frame}
+
+ monkeypatch.setattr(runner, "_get_loader", lambda source: StubLoader)
+ config = {
+ "codes": ["AAPL.US"],
+ "start_date": "2026-01-01",
+ "end_date": "2026-01-02",
+ "source": "yahoo",
+ "interval": "1H",
+ }
+ original = dict(config)
+
+ result = runner.fetch_data_map(config)
+
+ assert config == original
+ assert calls == [
+ (
+ ["AAPL.US"],
+ "2026-01-01",
+ "2026-01-02",
+ {"fields": None, "interval": "1H"},
+ )
+ ]
+ assert result.source == "yahoo"
+ assert result.effective_sources == ["yahoo"]
+ assert list(result.data_map) == ["AAPL.US"]
+
+
+def test_fetch_data_map_delegates_auto_routing(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ frame = pd.DataFrame(
+ {"open": [1.0], "high": [1.0], "low": [1.0], "close": [1.0]},
+ index=pd.DatetimeIndex([pd.Timestamp("2026-01-01")]),
+ )
+ calls: list[tuple[list[str], dict, str]] = []
+
+ def fake_fetch_auto(codes: list[str], config: dict, interval: str) -> dict:
+ calls.append((codes, config, interval))
+ return {"AAPL.US": frame}
+
+ monkeypatch.setattr(runner, "_fetch_auto", fake_fetch_auto)
+ config = {
+ "codes": ["AAPL.US"],
+ "start_date": "2026-01-01",
+ "end_date": "2026-01-02",
+ "source": "auto",
+ "interval": "1D",
+ }
+
+ result = runner.fetch_data_map(config)
+
+ assert calls == [(["AAPL.US"], config, "1D")]
+ assert result.source == "auto"
+ assert result.effective_sources == ["yfinance"]