Skip to content

"Vibe-Trading: Your Personal Trading Agent"

fix(backtest): honor explicit local source for engine routing and benchmark

xor_xe83e482ef4676
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 94aabc193..c66ee1cfd 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -48,6 +48,10 @@ This project adheres to [Semantic Versioning](https://semver.org/).
of silently returning daily bars (#467, thanks @Shizoqua).
### Fixed
+- Explicit `source: local` backtests now route US/HK equities to the
+ global-equity engine instead of the crypto default, and explicit benchmarks
+ are fetched through the configured source's loader (yfinance remains the
+ fallback), keeping offline runs offline (#550).
- FastMCP transport imports work across both module layouts (#469, thanks
@roberttidball).
- Portfolio optimizers no longer include the decision bar's close-to-close
diff --git a/agent/backtest/benchmark.py b/agent/backtest/benchmark.py
index b9a117dcb..798d7db2e 100644
--- a/agent/backtest/benchmark.py
+++ b/agent/backtest/benchmark.py
@@ -7,7 +7,7 @@ data given a set of strategy codes and a data source.
from __future__ import annotations
from dataclasses import dataclass
-from typing import Optional
+from typing import Any, Optional
import pandas as pd
@@ -42,6 +42,7 @@ def resolve_benchmark(
end_date: str,
interval: str = "1D",
explicit: Optional[str] = None,
+ loader: Optional[Any] = None,
) -> Optional[BenchmarkResult]:
"""Resolve the appropriate benchmark ticker and fetch its return series.
@@ -52,6 +53,9 @@ def resolve_benchmark(
end_date: Backtest end date.
interval: Bar interval (1m / 5m / 15m / 30m / 1H / 4H / 1D).
explicit: Override ticker (e.g. "SPY" passed via config).
+ loader: Loader of the configured data source. When given, the
+ benchmark is fetched through it first, falling back to
+ yfinance if it yields no data.
Returns:
BenchmarkResult with return series and total return, or None if no
@@ -62,7 +66,7 @@ def resolve_benchmark(
return None
try:
- bench_df = _fetch_benchmark(ticker, start_date, end_date, interval)
+ bench_df = _fetch_benchmark(ticker, start_date, end_date, interval, loader=loader)
except Exception:
return None
@@ -134,11 +138,31 @@ def _fetch_benchmark(
start_date: str,
end_date: str,
interval: str,
+ loader: Optional[Any] = None,
) -> pd.DataFrame:
- """Fetch benchmark OHLCV data via yfinance (single symbol, no auth)."""
- loader = YfinanceLoader()
- result = loader.fetch([ticker], start_date, end_date, interval=interval)
+ """Fetch benchmark OHLCV data.
+ Tries the configured source's loader first (when given), so an explicit
+ source such as ``local`` stays offline. Falls back to yfinance
+ (single symbol, no auth) when no loader is given or it yields no data.
+ """
+ if loader is not None:
+ try:
+ df = _extract_frame(
+ loader.fetch([ticker], start_date, end_date, interval=interval),
+ ticker,
+ )
+ except Exception:
+ df = pd.DataFrame()
+ if not df.empty:
+ return df
+
+ result = YfinanceLoader().fetch([ticker], start_date, end_date, interval=interval)
+ return _extract_frame(result, ticker)
+
+
+def _extract_frame(result: Any, ticker: str) -> pd.DataFrame:
+ """Normalise a loader fetch result to a single DataFrame."""
if isinstance(result, dict):
df = result.get(ticker)
elif isinstance(result, pd.DataFrame):
@@ -149,4 +173,4 @@ def _fetch_benchmark(
if df is None or (isinstance(df, pd.DataFrame) and df.empty):
return pd.DataFrame()
- return df
\ No newline at end of file
+ return df
diff --git a/agent/backtest/engines/base.py b/agent/backtest/engines/base.py
index 19f2cf0d0..71c7ec791 100644
--- a/agent/backtest/engines/base.py
+++ b/agent/backtest/engines/base.py
@@ -463,13 +463,18 @@ class BaseEngine(ABC):
bench_ticker = config.get("benchmark")
if bench_ticker and bench_ticker != "auto":
from backtest.benchmark import resolve_benchmark
+ bench_source = config.get("source", "yfinance")
bench_result = resolve_benchmark(
strategy_codes=codes,
- source=config.get("source", "yfinance"),
+ source=bench_source,
start_date=config.get("start_date", ""),
end_date=config.get("end_date", ""),
interval=interval,
explicit=bench_ticker,
+ # Explicit source: fetch the benchmark through its own loader
+ # (keeps e.g. source=local offline). Auto keeps the yfinance
+ # default — its loader only wraps the preloaded strategy data.
+ loader=loader if bench_source != "auto" else None,
)
if bench_result is not None:
bench_ret = bench_result.ret_series.reindex(dates).fillna(0.0)
diff --git a/agent/backtest/runner.py b/agent/backtest/runner.py
index 34195eef1..59817dee0 100644
--- a/agent/backtest/runner.py
+++ b/agent/backtest/runner.py
@@ -991,6 +991,13 @@ def _create_market_engine(source: str, config: dict, codes: List[str]):
market = _detect_submarket(codes)
return GlobalEquityEngine(config, market=market)
else:
+ # Sources without a dedicated branch (local, stooq, ...): follow the
+ # instrument market rather than the loader name, so e.g. a local
+ # AAPL.US dataset gets US-equity execution rules instead of crypto.
+ if markets & {"us_equity", "hk_equity"}:
+ from backtest.engines.global_equity import GlobalEquityEngine
+ market = _detect_submarket(codes)
+ return GlobalEquityEngine(config, market=market)
from backtest.engines.crypto import CryptoEngine
return CryptoEngine(config)
diff --git a/agent/tests/test_local_source_routing.py b/agent/tests/test_local_source_routing.py
new file mode 100644
index 000000000..b0f630d2e
--- /dev/null
+++ b/agent/tests/test_local_source_routing.py
@@ -0,0 +1,115 @@
+"""Tests that an explicit local data source is honored end to end.
+
+Covers the two halves of the bug:
+1. Engine routing follows the instrument market, not the loader name
+ (local AAPL.US -> GlobalEquityEngine, not CryptoEngine).
+2. Benchmark fetch goes through the configured source's loader instead of
+ unconditionally creating a yfinance loader.
+"""
+
+from __future__ import annotations
+
+from typing import Dict, List
+
+import pandas as pd
+import pytest
+
+from backtest.benchmark import resolve_benchmark
+from backtest.engines.crypto import CryptoEngine
+from backtest.engines.global_equity import GlobalEquityEngine
+from backtest.runner import _create_market_engine
+
+
+class TestLocalSourceEngineRouting:
+ def test_local_us_equity_routes_to_global_equity_engine(self) -> None:
+ engine = _create_market_engine("local", {"initial_cash": 100_000}, ["AAPL.US"])
+ assert isinstance(engine, GlobalEquityEngine)
+
+ def test_local_hk_equity_routes_to_global_equity_engine(self) -> None:
+ engine = _create_market_engine("local", {"initial_cash": 100_000}, ["00700.HK"])
+ assert isinstance(engine, GlobalEquityEngine)
+
+ def test_local_crypto_still_routes_to_crypto_engine(self) -> None:
+ engine = _create_market_engine("local", {"initial_cash": 100_000}, ["BTC-USDT"])
+ assert isinstance(engine, CryptoEngine)
+
+
+class _FakeLoader:
+ """Loader stub returning a fixed close series for any requested code."""
+
+ def __init__(self, closes: List[float]) -> None:
+ self._closes = closes
+ self.fetched: List[str] = []
+
+ def fetch(
+ self, codes: List[str], start_date: str, end_date: str, **kwargs: object,
+ ) -> Dict[str, pd.DataFrame]:
+ self.fetched.extend(codes)
+ index = pd.date_range("2023-01-03", periods=len(self._closes), freq="D")
+ return {c: pd.DataFrame({"close": self._closes}, index=index) for c in codes}
+
+
+class _EmptyLoader:
+ def fetch(self, *args: object, **kwargs: object) -> Dict[str, pd.DataFrame]:
+ return {}
+
+
+class TestBenchmarkLoaderForwarding:
+ def test_explicit_source_loader_is_used_instead_of_yfinance(
+ self, monkeypatch: pytest.MonkeyPatch,
+ ) -> None:
+ def _no_network() -> None:
+ raise AssertionError("yfinance loader must not be created")
+
+ monkeypatch.setattr("backtest.benchmark.YfinanceLoader", _no_network)
+
+ loader = _FakeLoader([100.0, 110.0])
+ result = resolve_benchmark(
+ strategy_codes=["AAPL.US"],
+ source="local",
+ start_date="2023-01-03",
+ end_date="2023-01-04",
+ explicit="AAPL.US",
+ loader=loader,
+ )
+
+ assert result is not None
+ assert result.ticker == "AAPL.US"
+ assert loader.fetched == ["AAPL.US"]
+ assert result.total_ret == pytest.approx(0.1)
+
+ def test_falls_back_to_yfinance_when_source_loader_has_no_data(
+ self, monkeypatch: pytest.MonkeyPatch,
+ ) -> None:
+ fallback = _FakeLoader([100.0, 105.0])
+ monkeypatch.setattr("backtest.benchmark.YfinanceLoader", lambda: fallback)
+
+ result = resolve_benchmark(
+ strategy_codes=["AAPL.US"],
+ source="local",
+ start_date="2023-01-03",
+ end_date="2023-01-04",
+ explicit="SPY",
+ loader=_EmptyLoader(),
+ )
+
+ assert result is not None
+ assert fallback.fetched == ["SPY"]
+ assert result.total_ret == pytest.approx(0.05)
+
+ def test_no_loader_keeps_yfinance_default(
+ self, monkeypatch: pytest.MonkeyPatch,
+ ) -> None:
+ fallback = _FakeLoader([100.0, 102.0])
+ monkeypatch.setattr("backtest.benchmark.YfinanceLoader", lambda: fallback)
+
+ result = resolve_benchmark(
+ strategy_codes=["AAPL.US"],
+ source="auto",
+ start_date="2023-01-03",
+ end_date="2023-01-04",
+ explicit="SPY",
+ )
+
+ assert result is not None
+ assert fallback.fetched == ["SPY"]