Skip to content

"Vibe-Trading: Your Personal Trading Agent"

fix(loader): route ETFs and forex correctly in AKShare; harden registry fallback

warren618aae5a7ec1adb
diff --git a/agent/backtest/loaders/akshare_loader.py b/agent/backtest/loaders/akshare_loader.py
index a6436e2eb..43d052e7e 100644
--- a/agent/backtest/loaders/akshare_loader.py
+++ b/agent/backtest/loaders/akshare_loader.py
@@ -39,6 +39,38 @@ def _is_crypto(code: str) -> bool:
return "-USDT" in code.upper() or "/USDT" in code.upper()
+# Exchange-listed ETF / LOF prefix codes:
+# SH: 50/51/52/56/58 (ETFs), SZ: 15/16 (ETFs + LOFs).
+# Issue #50 — these symbols look like A-shares (.SH / .SZ) but stock_zh_a_hist
+# can't price them; route through fund_etf_hist_sina instead.
+_ETF_PREFIXES = frozenset({"15", "16", "50", "51", "52", "56", "58"})
+
+
+def _is_etf_listed(code: str) -> bool:
+ """Detect exchange-listed ETF / LOF symbols (e.g. 518880.SH, 159915.SZ)."""
+ upper = code.upper()
+ if not upper.endswith((".SH", ".SZ")):
+ return False
+ digits = upper.split(".")[0]
+ if len(digits) != 6 or not digits.isdigit():
+ return False
+ return digits[:2] in _ETF_PREFIXES
+
+
+def _is_forex(code: str) -> bool:
+ """Detect forex pairs by matching against AKShare's symbol_market_map.
+
+ Issue #54 — forex symbols (EURUSD, GBPUSD, etc.) have no exchange suffix
+ and previously fell through to the A-share endpoint.
+ """
+ upper = code.upper().removesuffix(".FX")
+ try:
+ from akshare.forex.cons import symbol_market_map
+ except Exception:
+ return False
+ return upper in symbol_market_map
+
+
@register
class DataLoader:
"""AKShare universal OHLCV loader (free, no auth)."""
@@ -97,12 +129,17 @@ class DataLoader:
"""Fetch a single symbol."""
import akshare as ak
+ # ETF check must precede A-share — 518880.SH ends with .SH but is an ETF.
+ if _is_etf_listed(code):
+ return self._fetch_etf(ak, code, start_date, end_date)
if _is_a_share(code):
return self._fetch_a_share(ak, code, start_date, end_date, interval)
if _is_us(code):
return self._fetch_us(ak, code, start_date, end_date)
if _is_hk(code):
return self._fetch_hk(ak, code, start_date, end_date)
+ if _is_forex(code):
+ return self._fetch_forex(ak, code, start_date, end_date)
# Default: try A-share
return self._fetch_a_share(ak, code, start_date, end_date, interval)
@@ -145,6 +182,49 @@ class DataLoader:
continue
return None
+ def _fetch_etf(self, ak, code: str, start_date: str, end_date: str) -> Optional[pd.DataFrame]:
+ """Fetch exchange-listed ETF / LOF via fund_etf_hist_sina.
+
+ Sina symbol format is ``sh518880`` / ``sz159915``. The endpoint returns
+ the full history; we filter to the requested window after fetching.
+ """
+ digits, _, suffix = code.upper().partition(".")
+ symbol = f"{suffix.lower()}{digits}"
+ df = ak.fund_etf_hist_sina(symbol=symbol)
+ if df is None or df.empty:
+ return None
+ df = self._normalize(df, date_col="date")
+ # fund_etf_hist_sina returns full history — clip to window.
+ return df.loc[start_date:end_date]
+
+ def _fetch_forex(self, ak, code: str, start_date: str, end_date: str) -> Optional[pd.DataFrame]:
+ """Fetch forex pair via forex_hist_em.
+
+ Columns returned are 日期 / 代码 / 名称 / 今开 / 最新价 / 最高 / 最低 / 振幅
+ — note ``最新价`` (latest) plays the role of close. Volume isn't reported,
+ so we synthesize a zero column to satisfy the OHLCV contract.
+ """
+ symbol = code.upper().removesuffix(".FX")
+ df = ak.forex_hist_em(symbol=symbol)
+ if df is None or df.empty:
+ return None
+ df = df.rename(columns={
+ "日期": "trade_date",
+ "今开": "open",
+ "最新价": "close",
+ "最高": "high",
+ "最低": "low",
+ })
+ df["trade_date"] = pd.to_datetime(df["trade_date"])
+ df = df.set_index("trade_date").sort_index()
+ df["volume"] = 0.0
+ for col in ("open", "high", "low", "close"):
+ df[col] = pd.to_numeric(df[col], errors="coerce")
+ df = df[["open", "high", "low", "close", "volume"]].dropna(
+ subset=["open", "high", "low", "close"]
+ )
+ return df.loc[start_date:end_date]
+
def _fetch_hk(self, ak, code: str, start_date: str, end_date: str) -> Optional[pd.DataFrame]:
"""Fetch HK stock via stock_hk_hist."""
symbol = code.replace(".HK", "").zfill(5)
diff --git a/agent/backtest/loaders/registry.py b/agent/backtest/loaders/registry.py
index 973cca600..4ba7d6dd7 100644
--- a/agent/backtest/loaders/registry.py
+++ b/agent/backtest/loaders/registry.py
@@ -99,8 +99,15 @@ def resolve_loader(market: str) -> Any:
for name in chain:
if name not in LOADER_REGISTRY:
continue
- loader = LOADER_REGISTRY[name]()
tried.append(name)
+ # Issue #50 — some loaders (e.g. Tushare) call into the SDK during
+ # __init__ and raise on missing credentials. Treat that the same as
+ # is_available()=False so the fallback chain keeps walking.
+ try:
+ loader = LOADER_REGISTRY[name]()
+ except Exception as exc:
+ logger.debug("loader %s failed to construct: %s", name, exc)
+ continue
if loader.is_available():
return loader
raise NoAvailableSourceError(
@@ -126,8 +133,12 @@ def get_loader_cls_with_fallback(source: str) -> Type[Any]:
raise NoAvailableSourceError(f"Unknown data source: {source}")
loader_cls = LOADER_REGISTRY[source]
- instance = loader_cls()
- if instance.is_available():
+ try:
+ instance = loader_cls()
+ except Exception as exc:
+ logger.debug("loader %s failed to construct: %s", source, exc)
+ instance = None
+ if instance is not None and instance.is_available():
return loader_cls
# Source unavailable — try same-market fallback
diff --git a/agent/tests/test_akshare_loader.py b/agent/tests/test_akshare_loader.py
new file mode 100644
index 000000000..d24f71a3c
--- /dev/null
+++ b/agent/tests/test_akshare_loader.py
@@ -0,0 +1,172 @@
+"""Tests for AKShare loader symbol routing.
+
+Pins issues #50 (ETF) and #54 (forex): the previous _fetch_one routed every
+unrecognized code to stock_zh_a_hist, masking ETFs (518880.SH) and forex pairs
+(EURUSD) as broken A-shares. These tests use mocks so they don't hit the
+network — real-data smoke is in tests/_smoke_akshare_real.py if/when needed.
+"""
+
+from __future__ import annotations
+
+import sys
+from types import SimpleNamespace
+from unittest.mock import MagicMock
+
+import pandas as pd
+import pytest
+
+from backtest.loaders.akshare_loader import (
+ DataLoader,
+ _is_a_share,
+ _is_etf_listed,
+ _is_forex,
+ _is_hk,
+ _is_us,
+)
+
+
+# ---------------------------------------------------------------------------
+# Predicate tests
+# ---------------------------------------------------------------------------
+
+
+class TestIsETFListed:
+ @pytest.mark.parametrize("code", [
+ "518880.SH", # gold ETF (issue #50)
+ "510300.SH", # CSI 300 ETF
+ "159915.SZ", # ChiNext ETF
+ "161005.SZ", # LOF
+ ])
+ def test_etf_codes_match(self, code: str) -> None:
+ assert _is_etf_listed(code)
+
+ @pytest.mark.parametrize("code", [
+ "600519.SH", # Moutai — A-share, not ETF
+ "000001.SZ", # Ping An Bank — A-share
+ "300750.SZ", # CATL — ChiNext stock
+ "AAPL.US", # not Chinese
+ "EURUSD", # forex
+ "12345.SH", # malformed
+ "5188800.SH", # too long
+ ])
+ def test_non_etf_codes_skip(self, code: str) -> None:
+ assert not _is_etf_listed(code)
+
+
+class TestIsForex:
+ def test_eurusd_matches(self) -> None:
+ assert _is_forex("EURUSD")
+
+ def test_lowercase_matches(self) -> None:
+ assert _is_forex("eurusd")
+
+ def test_fx_suffix_matches(self) -> None:
+ assert _is_forex("EURUSD.FX")
+
+ def test_a_share_does_not_match(self) -> None:
+ assert not _is_forex("600519.SH")
+
+ def test_unknown_pair_does_not_match(self) -> None:
+ # "ZZZZZZ" isn't in akshare's symbol_market_map
+ assert not _is_forex("ZZZZZZ")
+
+
+# ---------------------------------------------------------------------------
+# Routing tests — verify _fetch_one dispatches to the right endpoint without
+# actually hitting AKShare.
+# ---------------------------------------------------------------------------
+
+
+def _stub_etf_response() -> pd.DataFrame:
+ return pd.DataFrame({
+ "date": pd.to_datetime(["2024-01-02", "2024-01-03"]),
+ "open": [5.0, 5.1],
+ "high": [5.2, 5.3],
+ "low": [4.9, 5.0],
+ "close": [5.15, 5.25],
+ "volume": [1000, 1100],
+ })
+
+
+def _stub_forex_response() -> pd.DataFrame:
+ return pd.DataFrame({
+ "日期": pd.to_datetime(["2024-01-02", "2024-01-03"]),
+ "代码": ["EURUSD", "EURUSD"],
+ "名称": ["欧元兑美元", "欧元兑美元"],
+ "今开": [1.10, 1.11],
+ "最新价": [1.105, 1.115],
+ "最高": [1.12, 1.13],
+ "最低": [1.09, 1.10],
+ "振幅": [0.5, 0.4],
+ })
+
+
+def _stub_a_share_response() -> pd.DataFrame:
+ return pd.DataFrame({
+ "日期": pd.to_datetime(["2024-01-02"]),
+ "开盘": [1700.0],
+ "最高": [1720.0],
+ "最低": [1690.0],
+ "收盘": [1710.0],
+ "成交量": [100000],
+ })
+
+
+def fake_akshare(monkeypatch: pytest.MonkeyPatch) -> SimpleNamespace:
+ """Install a stub `akshare` module with mocked endpoints."""
+ fake = SimpleNamespace(
+ fund_etf_hist_sina=MagicMock(return_value=_stub_etf_response()),
+ forex_hist_em=MagicMock(return_value=_stub_forex_response()),
+ stock_zh_a_hist=MagicMock(return_value=_stub_a_share_response()),
+ stock_us_hist=MagicMock(return_value=pd.DataFrame()),
+ stock_hk_hist=MagicMock(return_value=pd.DataFrame()),
+ )
+ monkeypatch.setitem(sys.modules, "akshare", fake)
+ return fake
+
+
+class TestRouting:
+ def test_etf_routes_to_fund_etf_hist_sina(self, fake_akshare: SimpleNamespace) -> None:
+ loader = DataLoader()
+ df = loader._fetch_one("518880.SH", "2024-01-01", "2024-12-31", "1D")
+
+ fake_akshare.fund_etf_hist_sina.assert_called_once_with(symbol="sh518880")
+ fake_akshare.stock_zh_a_hist.assert_not_called()
+ assert df is not None
+ assert list(df.columns) == ["open", "high", "low", "close", "volume"]
+ assert len(df) == 2
+
+ def test_etf_sz_uses_sz_prefix(self, fake_akshare: SimpleNamespace) -> None:
+ loader = DataLoader()
+ loader._fetch_one("159915.SZ", "2024-01-01", "2024-12-31", "1D")
+
+ fake_akshare.fund_etf_hist_sina.assert_called_once_with(symbol="sz159915")
+
+ def test_forex_routes_to_forex_hist_em(self, fake_akshare: SimpleNamespace) -> None:
+ loader = DataLoader()
+ df = loader._fetch_one("EURUSD", "2024-01-01", "2024-12-31", "1D")
+
+ fake_akshare.forex_hist_em.assert_called_once_with(symbol="EURUSD")
+ fake_akshare.stock_zh_a_hist.assert_not_called()
+ assert df is not None
+ assert list(df.columns) == ["open", "high", "low", "close", "volume"]
+ # forex has no volume — should be zero-filled
+ assert (df["volume"] == 0.0).all()
+ # 最新价 → close mapping
+ assert df.iloc[0]["close"] == pytest.approx(1.105)
+
+ def test_forex_strips_fx_suffix(self, fake_akshare: SimpleNamespace) -> None:
+ loader = DataLoader()
+ loader._fetch_one("EURUSD.FX", "2024-01-01", "2024-12-31", "1D")
+ fake_akshare.forex_hist_em.assert_called_once_with(symbol="EURUSD")
+
+ def test_a_share_still_routes_to_stock_zh_a_hist(
+ self, fake_akshare: SimpleNamespace
+ ) -> None:
+ loader = DataLoader()
+ loader._fetch_one("600519.SH", "2024-01-01", "2024-12-31", "1D")
+
+ fake_akshare.stock_zh_a_hist.assert_called_once()
+ fake_akshare.fund_etf_hist_sina.assert_not_called()
+ fake_akshare.forex_hist_em.assert_not_called()
diff --git a/agent/tests/test_registry.py b/agent/tests/test_registry.py
index a357dce2d..a1c1b403e 100644
--- a/agent/tests/test_registry.py
+++ b/agent/tests/test_registry.py
@@ -46,6 +46,23 @@ class _FakeUnavailableLoader:
return {}
+class _FakeInitErrorLoader:
+ """Mimics Tushare with a missing token: blows up inside ``__init__``."""
+
+ name = "fake_init_error"
+ markets = {"a_share"}
+ requires_auth = True
+
+ def __init__(self) -> None:
+ raise RuntimeError("api init error — TUSHARE_TOKEN not set")
+
+ def is_available(self) -> bool: # pragma: no cover — never reached
+ return False
+
+ def fetch(self, codes, start_date, end_date, *, interval="1D", fields=None):
+ return {}
+
+
class _FakeCryptoLoader:
name = "fake_crypto"
markets = {"crypto"}
@@ -177,3 +194,33 @@ class TestGetLoaderWithFallback:
with patch.dict(FALLBACK_CHAINS, {"a_share": ["fake_unavailable"]}):
with pytest.raises(NoAvailableSourceError):
get_loader_cls_with_fallback("fake_unavailable")
+
+
+# ---------------------------------------------------------------------------
+# Issue #50 — loaders that explode in __init__ (e.g. Tushare with no token)
+# must not poison the fallback chain.
+# ---------------------------------------------------------------------------
+
+
+class TestInitErrorFallback:
+ def test_resolve_loader_skips_init_error(self) -> None:
+ with patch.dict(LOADER_REGISTRY, {
+ "fake_init_error": _FakeInitErrorLoader,
+ "fake_available": _FakeAvailableLoader,
+ }, clear=True):
+ with patch.dict(FALLBACK_CHAINS, {
+ "a_share": ["fake_init_error", "fake_available"],
+ }):
+ loader = resolve_loader("a_share")
+ assert loader.name == "fake_available"
+
+ def test_get_loader_cls_falls_back_when_requested_init_errors(self) -> None:
+ with patch.dict(LOADER_REGISTRY, {
+ "fake_init_error": _FakeInitErrorLoader,
+ "fake_available": _FakeAvailableLoader,
+ }, clear=True):
+ with patch.dict(FALLBACK_CHAINS, {
+ "a_share": ["fake_init_error", "fake_available"],
+ }):
+ cls = get_loader_cls_with_fallback("fake_init_error")
+ assert cls is _FakeAvailableLoader