Skip to content

"Vibe-Trading: Your Personal Trading Agent"

fix(backtest): serve a local: code from the local loader only, as its bare symbol (#1467)

Haozhe Wua7f7dff9cbe0
diff --git a/agent/backtest/engines/_market_hooks.py b/agent/backtest/engines/_market_hooks.py
index 4a206e498..071baefb4 100644
--- a/agent/backtest/engines/_market_hooks.py
+++ b/agent/backtest/engines/_market_hooks.py
@@ -194,6 +194,7 @@ def code_currency(code: str) -> str:
than a guess, so a homogeneous set still compares equal while a mixed
one cannot pass a same-currency check by accident.
"""
+ code = strip_local_prefix(code)
market = _detect_market(code)
if market in _MARKET_CURRENCY:
return _MARKET_CURRENCY[market]
@@ -211,6 +212,22 @@ def code_currency(code: str) -> str:
return _FUTURES_EXCHANGE_CURRENCY.get(exchange, "USD")
return f"UNKNOWN:{market}"
+def strip_local_prefix(code: str) -> str:
+ """Return the instrument symbol behind a ``local:`` routing prefix.
+
+ ``local:AAPL.US`` asks for the user's own ``AAPL.US`` dataset. The prefix
+ chooses the loader; it is not part of the instrument, so market rules,
+ price caliber and result keys must all see ``AAPL.US``.
+
+ Args:
+ code: Ticker / symbol string, optionally prefixed with ``local:``.
+
+ Returns:
+ The symbol without the prefix, or ``code`` unchanged.
+ """
+ return code.split(":", 1)[1] if code[:6].lower() == "local:" else code
+
+
def _detect_market(code: str) -> str:
"""Infer market type from symbol format.
@@ -227,8 +244,9 @@ def _detect_market(code: str) -> str:
``=F`` (futures) and ``=X`` (forex) notations are recognized;
any other unknown format defaults to ``a_share``.
"""
+ symbol = strip_local_prefix(code)
for pattern, market in _MARKET_PATTERNS:
- if pattern.match(code):
+ if pattern.match(symbol):
return market
return "a_share"
@@ -248,7 +266,7 @@ def _is_china_futures(code: str) -> bool:
Returns:
True if it looks like a Chinese futures contract.
"""
- parts = code.upper().split(".")
+ parts = strip_local_prefix(code).upper().split(".")
if len(parts) == 2:
# Has an exchange suffix — trust it. CN exchange = True, anything
# else = False. Without this guard the product-code heuristic below
diff --git a/agent/backtest/runner.py b/agent/backtest/runner.py
index 6155f6e70..1b9226e37 100644
--- a/agent/backtest/runner.py
+++ b/agent/backtest/runner.py
@@ -40,6 +40,7 @@ from backtest.engines._market_hooks import ( # noqa: F401 (re-exported)
_detect_market,
_detect_submarket,
_is_china_futures,
+ strip_local_prefix,
)
from backtest.rebalance_mask import RebalanceMask, validate_rebalance_mask
@@ -1442,15 +1443,37 @@ def _fetch_auto(codes: List[str], config: dict, interval: str = "1D") -> dict:
interval: Bar interval string.
Returns:
- Merged ``code -> DataFrame`` map.
+ Merged ``code -> DataFrame`` map, keyed by bare symbol: a ``local:``
+ code is served only by the local loader and keyed without the prefix.
"""
- market_groups = _group_codes_by_market(codes)
merged = {}
served_by: set[str] = set()
caliber_stamps: dict[str, tuple[str, str]] = {}
start_date = config.get("start_date", "")
end_date = config.get("end_date", "")
+ # A ``local:`` code names the user's own dataset. It is served by the local
+ # loader or not at all: routing it by market would send ``local:AAPL.US``
+ # down the US network chain, which the README promises never happens (#1467).
+ local_codes = [code for code in codes if strip_local_prefix(code) != code]
+ if local_codes:
+ # ``local`` never degrades to a network loader; an unconfigured Data
+ # Bridge raises here with its own hint.
+ local_loader = get_loader_cls_with_fallback("local")()
+ stripped = [strip_local_prefix(code) for code in local_codes]
+ local_result = local_loader.fetch(stripped, start_date, end_date, interval=interval)
+ missing_local = [code for code in local_codes if strip_local_prefix(code) not in local_result]
+ if missing_local:
+ raise NoAvailableSourceError(
+ f"incomplete data for source=local; missing symbols: {missing_local}"
+ )
+ local_name = str(getattr(local_loader, "name", "local") or "local")
+ served_by.add(local_name)
+ for code in local_result:
+ caliber_stamps[code] = (local_name, price_caliber(local_name, _detect_market(code)))
+ merged.update(local_result)
+
+ market_groups = _group_codes_by_market([code for code in codes if code not in set(local_codes)])
for market, market_codes in market_groups.items():
try:
loader = resolve_loader(market)
@@ -1528,15 +1551,37 @@ def fetch_data_map(config: dict) -> DataFetchResult:
Returns:
Data and effective routing metadata. The input config is not mutated.
+ A ``local:`` code comes back as its bare symbol in both ``codes`` and
+ ``data_map``.
+
+ Raises:
+ ValueError: If a ``local:`` code is requested from a source other than
+ ``local`` / ``auto``, or one symbol is requested both with and
+ without the prefix.
+ NoAvailableSourceError: If a requested symbol cannot be served.
"""
config = copy.deepcopy(config)
source = str(config.get("source") or "tushare")
codes = list(config.get("codes") or [])
interval = str(config.get("interval") or "1D")
+ # ``local:`` picks the loader; the instrument is the bare symbol. Everything
+ # downstream (engine, signals, artifacts, run card) sees the bare symbol, so
+ # a contradictory request is refused here rather than half-served.
+ prefixed = [code for code in codes if strip_local_prefix(code) != code]
+ if prefixed and source not in ("local", "auto"):
+ raise ValueError(
+ f"local: codes need source='local' or 'auto', not {source!r}: {prefixed}"
+ )
+ bare = [strip_local_prefix(code) for code in codes]
+ repeated = sorted({symbol for symbol in bare if bare.count(symbol) > 1})
+ if repeated:
+ raise ValueError(f"symbols requested more than once (with and without local:): {repeated}")
+
caliber_stamps: dict[str, tuple[str, str]] = {}
if source == "auto":
data_map = _fetch_auto(codes, config, interval)
+ codes = bare
loader: Any = _AutoLoader(data_map)
# Prefer the loaders that actually served rows; the symbol-pattern guess
# is only a fallback for a stubbed/patched fetcher that recorded nothing.
@@ -1568,6 +1613,10 @@ def fetch_data_map(config: dict) -> DataFetchResult:
fields=config.get("extra_fields") or None,
interval=interval,
)
+ # The local loader keys ``local:AAPL.US`` by ``AAPL.US``. Compare and
+ # continue with the bare symbol, or a served symbol is counted as
+ # missing and sent down a network chain (#1467).
+ codes = [strip_local_prefix(code) for code in codes]
for code in data_map:
caliber_stamps[code] = (
served_by,
diff --git a/agent/tests/test_local_prefix_routing.py b/agent/tests/test_local_prefix_routing.py
new file mode 100644
index 000000000..35d4bce92
--- /dev/null
+++ b/agent/tests/test_local_prefix_routing.py
@@ -0,0 +1,155 @@
+"""A ``local:`` code is the user's own dataset, served locally or not at all (#1467).
+
+The prefix picks the loader; the instrument is the bare symbol. The backtest
+runner used to compare the local loader's ``AAPL.US`` key against the requested
+``local:AAPL.US``, count a served symbol as missing, and send it down a network
+fallback chain. In ``auto`` mode the prefix was ignored and the code was routed
+as an A-share. The README promises that an explicit ``local:`` symbol never
+silently falls back to a network source.
+"""
+
+from __future__ import annotations
+
+from pathlib import Path
+
+import pandas as pd
+import pytest
+import yaml
+
+import backtest.loaders.local_loader as local_loader
+import backtest.runner as runner
+from backtest.engines._market_hooks import _is_china_futures, code_currency
+from backtest.loaders.base import NoAvailableSourceError
+from backtest.loaders.registry import _ensure_registered
+
+pytestmark = pytest.mark.unit
+
+_START, _END = "2026-01-01", "2026-01-06"
+
+
+def _configure_local(monkeypatch: pytest.MonkeyPatch, tmp_path: Path, symbols: list[str]) -> None:
+ """Point the local loader at a temp config serving ``symbols`` from CSV."""
+ sources = []
+ for symbol in symbols:
+ path = tmp_path / f"{symbol}.csv"
+ path.write_text(
+ "date,open,high,low,close,volume\n"
+ "2026-01-02,10,11,9,10.5,1000\n"
+ "2026-01-05,10.5,12,10,11.5,1200\n"
+ "2026-01-06,11.5,12,11,11.8,900\n",
+ encoding="utf-8",
+ )
+ sources.append({"symbol": symbol, "type": "csv", "path": str(path)})
+ config_path = tmp_path / "config.yaml"
+ config_path.write_text(yaml.safe_dump({"sources": sources}), encoding="utf-8")
+ monkeypatch.setattr(local_loader, "_CONFIG_PATH", config_path)
+
+
+class _NetworkLoader:
+ """Stands in for every network loader and records what it was asked for."""
+
+ name = "fakenet"
+ calls: list[list[str]] = []
+
+ def is_available(self) -> bool:
+ return True
+
+ def fetch(self, codes, start_date, end_date, fields=None, interval="1D"):
+ type(self).calls.append(list(codes))
+ index = pd.to_datetime(["2026-01-02", "2026-01-05"])
+ frame = pd.DataFrame(
+ {"open": [5.0, 5.2], "high": [5.5, 5.6], "low": [4.8, 5.0], "close": [5.1, 5.3], "volume": [10, 12]},
+ index=index,
+ )
+ return {code: frame.copy() for code in codes if not code.lower().startswith("local:")}
+
+
+def network(monkeypatch: pytest.MonkeyPatch) -> type[_NetworkLoader]:
+ """Route every market chain and resolver to the recording network loader."""
+ _ensure_registered()
+ _NetworkLoader.calls = []
+ real_get_loader = runner._get_loader
+ # Any non-local source resolves to the recorder, so a regression can never
+ # reach a real endpoint from this suite.
+ monkeypatch.setattr(
+ runner, "_get_loader", lambda source: real_get_loader(source) if source == "local" else _NetworkLoader
+ )
+ monkeypatch.setitem(runner.LOADER_REGISTRY, "fakenet", _NetworkLoader)
+ monkeypatch.setattr(runner, "FALLBACK_CHAINS", {m: ["fakenet"] for m in ("us_equity", "a_share", "hk_equity")})
+ monkeypatch.setattr(runner, "resolve_loader", lambda market: _NetworkLoader())
+ return _NetworkLoader
+
+
+ ("code", "market"),
+ [("local:AAPL.US", "us_equity"), ("LOCAL:00700.HK", "hk_equity"), ("local:600519.SH", "a_share")],
+)
+def test_market_rules_follow_the_bare_symbol(code: str, market: str) -> None:
+ assert runner._detect_market(code) == market
+
+
+def test_currency_and_futures_checks_follow_the_bare_symbol() -> None:
+ assert code_currency("local:AAPL.US") == "USD"
+ assert code_currency("local:00700.HK") == "HKD"
+ assert code_currency("local:EURUSD") == "USD" # a forex pair's quote currency is parsed from the symbol
+ assert _is_china_futures("local:RB2410") is True
+
+
[email protected]("source", ["local", "auto"])
+def test_a_served_local_code_comes_back_as_its_bare_symbol_without_network(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch, network: type[_NetworkLoader], source: str
+) -> None:
+ _configure_local(monkeypatch, tmp_path, ["AAPL.US"])
+
+ result = runner.fetch_data_map(
+ {"source": source, "codes": ["local:AAPL.US"], "start_date": _START, "end_date": _END}
+ )
+
+ assert result.codes == ["AAPL.US"]
+ assert list(result.data_map) == ["AAPL.US"]
+ assert list(result.data_map["AAPL.US"]["close"]) == [10.5, 11.5, 11.8]
+ assert result.effective_sources == ["local"]
+ assert network.calls == []
+
+
+def test_auto_serves_local_codes_locally_and_the_rest_from_their_chain(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch, network: type[_NetworkLoader]
+) -> None:
+ _configure_local(monkeypatch, tmp_path, ["AAPL.US"])
+
+ result = runner.fetch_data_map(
+ {"source": "auto", "codes": ["local:AAPL.US", "MSFT.US"], "start_date": _START, "end_date": _END}
+ )
+
+ assert result.codes == ["AAPL.US", "MSFT.US"]
+ assert list(result.data_map["AAPL.US"]["close"]) == [10.5, 11.5, 11.8]
+ assert list(result.data_map["MSFT.US"]["close"]) == [5.1, 5.3]
+ assert network.calls == [["MSFT.US"]]
+ assert sorted(result.effective_sources) == ["fakenet", "local"]
+
+
+def test_auto_refuses_a_local_code_the_dataset_lacks_instead_of_fetching_it(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch, network: type[_NetworkLoader]
+) -> None:
+ _configure_local(monkeypatch, tmp_path, ["AAPL.US"])
+
+ with pytest.raises(NoAvailableSourceError, match=r"source=local; missing symbols: \['local:NOPE.US'\]"):
+ runner.fetch_data_map(
+ {"source": "auto", "codes": ["local:AAPL.US", "local:NOPE.US"], "start_date": _START, "end_date": _END}
+ )
+ assert network.calls == []
+
+
+def test_a_local_code_from_a_network_source_is_refused(network: type[_NetworkLoader]) -> None:
+ with pytest.raises(ValueError, match="need source='local' or 'auto'"):
+ runner.fetch_data_map({"source": "yahoo", "codes": ["local:AAPL.US"], "start_date": _START, "end_date": _END})
+ assert network.calls == []
+
+
+def test_one_symbol_with_and_without_the_prefix_is_refused(network: type[_NetworkLoader]) -> None:
+ with pytest.raises(ValueError, match=r"requested more than once .*\['AAPL.US'\]"):
+ runner.fetch_data_map(
+ {"source": "auto", "codes": ["local:AAPL.US", "AAPL.US"], "start_date": _START, "end_date": _END}
+ )
+ assert network.calls == []