Skip to content

"Vibe-Trading: Your Personal Trading Agent"

fix(loaders): serve futures from a chain that implements them

Haozhe Wu703fb5018bcb
diff --git a/agent/backtest/engines/_market_hooks.py b/agent/backtest/engines/_market_hooks.py
index 78e57653e..4a206e498 100644
--- a/agent/backtest/engines/_market_hooks.py
+++ b/agent/backtest/engines/_market_hooks.py
@@ -22,6 +22,32 @@ from backtest.models import Position
# ── Symbol -> market classification (shared by runner.py + composite.py) ──
+# Known Chinese-futures product codes — used as a heuristic when a symbol
+# lacks an exchange suffix (e.g. bare ``RB2410``, ``IF2406``). Without this
+# table composite.py was misrouting such bare codes to GlobalFutures.
+# Stored lowercase; ``_is_china_futures`` lowercases the extracted product
+# before lookup so callers can pass any case (``RB2410`` and ``rb2410``
+# both resolve correctly).
+_CN_FUTURES_PRODUCTS = {
+ "if", "ic", "ih", "im", "t", "tf", "ts", "tl",
+ "au", "ag", "cu", "al", "zn", "pb", "ni", "sn", "ss",
+ "rb", "hc", "i", "j", "jm",
+ "sc", "fu", "lu", "bu", "nr",
+ "c", "cs", "m", "y", "a", "p", "jd", "lh",
+ "cf", "sr", "ta", "ma", "ap", "rm", "oi",
+ "pp", "l", "v", "eg", "eb", "pf", "sa", "fg", "ur",
+ "si", "lc",
+}
+
+
+#: The main continuous contract, spelled ``<product>0`` (``RB0``, ``IF0``).
+#: Built from the product whitelist rather than a width rule, because a
+#: bare ``<letters>0`` is otherwise indistinguishable from an ordinary
+#: ticker; anchoring on the whitelist leaves no collision surface.
+_CN_FUTURES_MAIN_PATTERN = r"^(?:{})0$".format(
+ "|".join(sorted(_CN_FUTURES_PRODUCTS, key=len, reverse=True))
+)
+
_MARKET_PATTERNS = [
(re.compile(r"^\d{6}\.(SZ|SH|BJ)$", re.I), "a_share"),
(re.compile(r"^(51|15|56)\d{4}\.(SZ|SH)$", re.I), "a_share"),
@@ -76,6 +102,12 @@ _MARKET_PATTERNS = [
r"^[A-Z]{1,4}(?:[FGHJKMNQUVXZ]\d{1,2}|\d{4})\.(CME|CBOT|NYMEX|COMEX|ICE|EUREX)$",
re.I,
), "futures"),
+ # China futures: main continuous contract (RB0, IF0, MA0). Dated contracts
+ # live ~240 trading days (RB2601 measured at 242), so any backtest longer
+ # than a contract cycle has to name the rolled series. It fell through to
+ # the a_share default, which put a leveraged futures series under T+1 and
+ # no shorting, and kept it out of the futures loader chain entirely.
+ (re.compile(_CN_FUTURES_MAIN_PATTERN, re.I), "futures"),
# Forex pairs: XXX/YYY or XXXXXX.FX
(re.compile(r"^[A-Z]{3}/[A-Z]{3}$"), "forex"),
(re.compile(r"^[A-Z]{6}\.FX$"), "forex"),
@@ -179,24 +211,6 @@ def code_currency(code: str) -> str:
return _FUTURES_EXCHANGE_CURRENCY.get(exchange, "USD")
return f"UNKNOWN:{market}"
-# Known Chinese-futures product codes — used as a heuristic when a symbol
-# lacks an exchange suffix (e.g. bare ``RB2410``, ``IF2406``). Without this
-# table composite.py was misrouting such bare codes to GlobalFutures.
-# Stored lowercase; ``_is_china_futures`` lowercases the extracted product
-# before lookup so callers can pass any case (``RB2410`` and ``rb2410``
-# both resolve correctly).
-_CN_FUTURES_PRODUCTS = {
- "if", "ic", "ih", "im", "t", "tf", "ts", "tl",
- "au", "ag", "cu", "al", "zn", "pb", "ni", "sn", "ss",
- "rb", "hc", "i", "j", "jm",
- "sc", "fu", "lu", "bu", "nr",
- "c", "cs", "m", "y", "a", "p", "jd", "lh",
- "cf", "sr", "ta", "ma", "ap", "rm", "oi",
- "pp", "l", "v", "eg", "eb", "pf", "sa", "fg", "ur",
- "si", "lc",
-}
-
-
def _detect_market(code: str) -> str:
"""Infer market type from symbol format.
diff --git a/agent/backtest/loaders/akshare_loader.py b/agent/backtest/loaders/akshare_loader.py
index b773198af..7f40ee66b 100644
--- a/agent/backtest/loaders/akshare_loader.py
+++ b/agent/backtest/loaders/akshare_loader.py
@@ -7,10 +7,12 @@ data aggregator covering Chinese and global markets. No API token required.
from __future__ import annotations
import logging
+import re
from typing import Dict, List, Optional
import pandas as pd
+from backtest.engines._market_hooks import _detect_market, _is_china_futures
from backtest.loaders._symbol_utils import _is_etf_listed
from backtest.loaders.base import cached_loader_fetch, validate_date_range
from backtest.loaders.registry import register
@@ -52,6 +54,18 @@ def _is_crypto(code: str) -> bool:
return "-USDT" in code.upper() or "/USDT" in code.upper()
+#: Sina takes the bare contract code. Passing the exchange suffix through does
+#: not return an empty frame — ``futures_zh_daily_sina("RB2601.SHFE")`` raises
+#: ``ValueError: Length mismatch`` from inside akshare, so the suffix has to be
+#: stripped here rather than discovered as a fetch failure.
+def _sina_contract(code: str) -> str:
+ """Return the bare uppercase contract code Sina's endpoints expect."""
+ return code.split(".")[0].upper()
+
+
+_CN_FUTURES_MAIN_RE = re.compile(r"^[A-Z]{1,2}0$")
+
+
@@ -157,6 +171,18 @@ class DataLoader:
if _is_forex(code):
_require_daily_interval(interval, "forex")
return self._fetch_forex(ak, code, start_date, end_date)
+ if _is_china_futures(code):
+ _require_daily_interval(interval, "futures")
+ return self._fetch_china_futures(ak, code, start_date, end_date)
+ if _detect_market(code) == "futures":
+ # A futures contract Sina does not carry (CL2412.NYMEX, ESZ4).
+ # Returning None hands the symbol to the next link in the chain;
+ # letting it reach the A-share default below priced a USD-quoted
+ # global contract off ``stock_zh_a_hist`` without erroring (#1395).
+ logger.warning(
+ "akshare serves Chinese futures only; %s has no akshare source", code
+ )
+ return None
# Default: try A-share
return self._fetch_a_share(ak, code, start_date, end_date, interval)
@@ -261,6 +287,63 @@ class DataLoader:
return None
return self._normalize(df, date_col="日期")
+ def _fetch_china_futures(
+ self, ak, code: str, start_date: str, end_date: str,
+ ) -> Optional[pd.DataFrame]:
+ """Fetch a Chinese futures contract from Sina's token-free endpoints.
+
+ Two contract forms arrive here, and they use different endpoints with
+ different payload shapes:
+
+ * Dated (``RB2601``, ``IF2512.CFFEX``) -> ``futures_zh_daily_sina``,
+ which takes *no* date range and serves the contract's whole life, so
+ the requested window is applied here. Columns are already English.
+ * Main continuous (``RB0``) -> ``futures_main_sina``, which does take a
+ range and answers in Chinese column names carrying a ``价`` suffix
+ (``开盘价``), distinct from the ``开盘`` spelling ``_normalize``
+ knows from the equity endpoints.
+
+ Args:
+ ak: The imported ``akshare`` module.
+ code: Contract code, with or without an exchange suffix.
+ start_date: YYYY-MM-DD, inclusive.
+ end_date: YYYY-MM-DD, inclusive.
+
+ Returns:
+ OHLCV frame indexed by trade date, or None when Sina carries no
+ series for the contract.
+ """
+ symbol = _sina_contract(code)
+ try:
+ if _CN_FUTURES_MAIN_RE.match(symbol):
+ raw = ak.futures_main_sina(
+ symbol=symbol,
+ start_date=start_date.replace("-", ""),
+ end_date=end_date.replace("-", ""),
+ )
+ if raw is None or raw.empty:
+ return None
+ raw = raw.rename(columns={
+ "开盘价": "开盘", "最高价": "最高",
+ "最低价": "最低", "收盘价": "收盘",
+ })
+ return self._normalize(raw, date_col="日期")
+
+ raw = ak.futures_zh_daily_sina(symbol=symbol)
+ except Exception as exc: # noqa: BLE001 - one bad contract must not raise
+ # akshare raises rather than returning empty for a code Sina does
+ # not list (a ZCE three-digit delivery month such as ``MA605``, or
+ # a stray exchange suffix), so this is the not-found path too.
+ logger.warning("akshare futures fetch failed for %s: %s", code, exc)
+ return None
+
+ if raw is None or raw.empty:
+ return None
+ df = self._normalize(raw, date_col="date")
+ # The dated endpoint ignores the window, so slice it here; without this
+ # a one-month request came back with the contract's entire history.
+ return df.loc[str(start_date):str(end_date)]
+
@staticmethod
def _normalize(df: pd.DataFrame, date_col: str = "日期") -> pd.DataFrame:
"""Normalize AKShare DataFrame to standard OHLCV schema.
diff --git a/agent/backtest/loaders/registry.py b/agent/backtest/loaders/registry.py
index 46bde2bdc..82ac852d1 100644
--- a/agent/backtest/loaders/registry.py
+++ b/agent/backtest/loaders/registry.py
@@ -173,7 +173,13 @@ FALLBACK_CHAINS: dict[str, list[str]] = {
"vietnam_equity": ["yahoo", "yfinance", "local"],
# OKX first (native), then dedicated Binance, then generic CCXT / Yahoo.
"crypto": ["okx", "binance", "ccxt", "yfinance", "local"],
- "futures": ["tushare", "akshare", "local"],
+ # tushare led this chain while implementing no futures endpoint at all
+ # (#1395): ``resolve_loader`` walks FALLBACK_CHAINS and never consults a
+ # loader's ``markets`` set, so trimming that set alone would have left
+ # tushare first in line, returning empty frames before akshare was ever
+ # asked. akshare serves Chinese contracts off the token-free Sina daily
+ # endpoints; a global contract has no network source and reaches ``local``.
+ "futures": ["akshare", "local"],
"fund": ["tushare", "akshare", "local"],
"macro": ["akshare", "tushare", "local"],
# mt5 leads when a local MetaTrader 5 terminal is attached (Windows-only,
diff --git a/agent/backtest/loaders/tushare.py b/agent/backtest/loaders/tushare.py
index 187c1d595..a53d94917 100644
--- a/agent/backtest/loaders/tushare.py
+++ b/agent/backtest/loaders/tushare.py
@@ -118,7 +118,13 @@ class DataLoader:
"""Tushare-backed OHLCV loader."""
name = "tushare"
- markets = {"a_share", "hk_equity", "futures", "fund"}
+ # ``futures`` is deliberately absent (HKUDS/Vibe-Trading#1395). Serving it
+ # needs ``pro.fut_daily``, which sits behind a points tier nothing here
+ # implements; until then a futures ts_code reached the ``else`` branch of
+ # ``_fetch_daily_frame`` and was priced off ``daily()``, the A-share
+ # equity endpoint. Declaring a market whose only path is another market's
+ # endpoint is worse than not declaring it.
+ markets = {"a_share", "hk_equity", "fund"}
# Tushare daily() documents vol in board lots (HKUDS/Vibe-Trading#1062).
# hk_equity (hk_daily) stays undeclared until empirically verified.
volume_units = {"a_share": "lots"}
diff --git a/agent/tests/test_akshare_loader.py b/agent/tests/test_akshare_loader.py
index 98ae27e9f..c370b3890 100644
--- a/agent/tests/test_akshare_loader.py
+++ b/agent/tests/test_akshare_loader.py
@@ -116,6 +116,45 @@ def _stub_a_share_response() -> pd.DataFrame:
})
+def _stub_futures_dated_response() -> pd.DataFrame:
+ """Shape of ``futures_zh_daily_sina`` as the live endpoint returns it.
+
+ English column names, plus ``hold``/``settle`` which the OHLCV schema
+ drops, and — the part that matters — the contract's *whole life*: this
+ endpoint takes no date range, so four days are returned here and the
+ loader is responsible for cutting them to the requested window.
+ """
+ return pd.DataFrame({
+ "date": ["2024-01-02", "2024-01-03", "2024-01-04", "2024-01-05"],
+ "open": [3340.0, 3364.0, 3401.0, 3410.0],
+ "high": [3376.0, 3407.0, 3415.0, 3430.0],
+ "low": [3322.0, 3362.0, 3396.0, 3405.0],
+ "close": [3369.0, 3407.0, 3413.0, 3425.0],
+ "volume": [546, 391, 850, 900],
+ "hold": [361, 641, 784, 810],
+ "settle": [3348.0, 3388.0, 3406.0, 3420.0],
+ })
+
+
+def _stub_futures_main_response() -> pd.DataFrame:
+ """Shape of ``futures_main_sina``: Chinese names carrying a ``价`` suffix.
+
+ ``开盘价`` is NOT the ``开盘`` spelling ``_normalize`` learned from the
+ equity endpoints, so a loader that forwards this frame unmapped selects an
+ empty column set.
+ """
+ return pd.DataFrame({
+ "日期": ["2024-01-02", "2024-01-03"],
+ "开盘价": [3135, 3103],
+ "最高价": [3135, 3119],
+ "最低价": [3097, 3085],
+ "收盘价": [3104, 3111],
+ "成交量": [697016, 841618],
+ "持仓量": [1548351, 1562948],
+ "动态结算价": [3113, 3098],
+ })
+
+
@pytest.fixture
def fake_akshare(monkeypatch: pytest.MonkeyPatch) -> SimpleNamespace:
"""Install a stub `akshare` module with mocked endpoints."""
@@ -125,6 +164,8 @@ def fake_akshare(monkeypatch: pytest.MonkeyPatch) -> SimpleNamespace:
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()),
+ futures_zh_daily_sina=MagicMock(return_value=_stub_futures_dated_response()),
+ futures_main_sina=MagicMock(return_value=_stub_futures_main_response()),
)
monkeypatch.setitem(sys.modules, "akshare", fake)
return fake
@@ -174,3 +215,122 @@ class TestRouting:
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()
+
+
+# ---------------------------------------------------------------------------
+# Futures routing (HKUDS/Vibe-Trading#1395)
+# ---------------------------------------------------------------------------
+
+
+class TestFuturesRouting:
+ """The third instance of this file's founding bug.
+
+ ETFs (#50) and forex (#54) were each masked as broken A-shares by the
+ ``# Default: try A-share`` fallthrough. Futures were the same: the chain
+ named akshare as a futures source, ``markets`` advertised it, and every
+ contract reached ``stock_zh_a_hist``.
+ """
+
+ def test_dated_contract_routes_to_sina_daily(
+ self, fake_akshare: SimpleNamespace
+ ) -> None:
+ loader = DataLoader()
+ df = loader._fetch_one("RB2601", "2024-01-01", "2024-12-31", "1D")
+
+ fake_akshare.futures_zh_daily_sina.assert_called_once_with(symbol="RB2601")
+ fake_akshare.stock_zh_a_hist.assert_not_called()
+ assert df is not None
+ assert list(df.columns) == ["open", "high", "low", "close", "volume"]
+ # hold/settle are not OHLCV and must not survive into the frame.
+ assert "hold" not in df.columns and "settle" not in df.columns
+
+ def test_exchange_suffix_is_stripped_before_the_call(
+ self, fake_akshare: SimpleNamespace
+ ) -> None:
+ """Sina raises on a suffixed code rather than returning empty.
+
+ ``futures_zh_daily_sina("RB2601.SHFE")`` fails inside akshare with
+ ``ValueError: Length mismatch``, so a loader that forwards the suffix
+ turns every exchange-qualified contract into a fetch failure.
+ """
+ loader = DataLoader()
+ loader._fetch_one("rb2601.SHFE", "2024-01-01", "2024-12-31", "1D")
+
+ fake_akshare.futures_zh_daily_sina.assert_called_once_with(symbol="RB2601")
+
+ def test_requested_window_is_applied_to_the_whole_life_frame(
+ self, fake_akshare: SimpleNamespace
+ ) -> None:
+ """The dated endpoint has no date parameters — the slice is ours.
+
+ The stub spans 2024-01-02..2024-01-05; asking for the middle two days
+ must return exactly those. Without the slice a one-month request came
+ back with the contract's entire history.
+ """
+ loader = DataLoader()
+ df = loader._fetch_one("RB2601", "2024-01-03", "2024-01-04", "1D")
+
+ assert df is not None
+ assert [str(d.date()) for d in df.index] == ["2024-01-03", "2024-01-04"]
+
+ def test_main_contract_routes_to_futures_main_sina(
+ self, fake_akshare: SimpleNamespace
+ ) -> None:
+ loader = DataLoader()
+ df = loader._fetch_one("RB0", "2024-01-01", "2024-12-31", "1D")
+
+ fake_akshare.futures_main_sina.assert_called_once_with(
+ symbol="RB0", start_date="20240101", end_date="20241231",
+ )
+ fake_akshare.futures_zh_daily_sina.assert_not_called()
+ fake_akshare.stock_zh_a_hist.assert_not_called()
+ assert df is not None
+ # The 价-suffixed names really were mapped, not silently dropped.
+ assert list(df.columns) == ["open", "high", "low", "close", "volume"]
+ assert df.iloc[0]["close"] == pytest.approx(3104)
+ assert df.iloc[0]["open"] == pytest.approx(3135)
+
+ def test_global_contract_returns_none_instead_of_a_share(
+ self, fake_akshare: SimpleNamespace
+ ) -> None:
+ """The #1395 regression, asserted on the call path.
+
+ Sina carries Chinese exchanges only. A global contract must leave the
+ loader empty-handed so the chain continues to ``local`` — asserting
+ only ``df is None`` would still pass if the A-share endpoint had been
+ called and happened to return nothing.
+ """
+ loader = DataLoader()
+ for code in ("CL2412.NYMEX", "ESZ4", "GCM2025.COMEX"):
+ fake_akshare.stock_zh_a_hist.reset_mock()
+ assert loader._fetch_one(code, "2024-01-01", "2024-12-31", "1D") is None
+ fake_akshare.stock_zh_a_hist.assert_not_called()
+ fake_akshare.futures_zh_daily_sina.assert_not_called()
+
+ def test_unlisted_contract_is_reported_not_raised(
+ self, fake_akshare: SimpleNamespace
+ ) -> None:
+ """akshare raises for a code Sina does not list (e.g. ``MA605``)."""
+ fake_akshare.futures_zh_daily_sina.side_effect = ValueError(
+ "Length mismatch: Expected axis has 0 elements"
+ )
+ loader = DataLoader()
+ assert loader._fetch_one("MA605", "2024-01-01", "2024-12-31", "1D") is None
+
+ def test_futures_reject_non_daily_intervals(
+ self, fake_akshare: SimpleNamespace
+ ) -> None:
+ loader = DataLoader()
+ with pytest.raises(ValueError, match="daily"):
+ loader._fetch_one("RB2601", "2024-01-01", "2024-12-31", "60m")
+
+ def test_a_share_is_untouched_by_the_futures_branch(
+ self, fake_akshare: SimpleNamespace
+ ) -> None:
+ """The other side of the gate: equities must still reach their endpoint."""
+ 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.futures_zh_daily_sina.assert_not_called()
+ fake_akshare.futures_main_sina.assert_not_called()
diff --git a/agent/tests/test_market_detection.py b/agent/tests/test_market_detection.py
index 8b7636cff..e5aa9caa3 100644
--- a/agent/tests/test_market_detection.py
+++ b/agent/tests/test_market_detection.py
@@ -441,3 +441,55 @@ class TestDetectMarketRequired:
assert _detect_market("usdjpy") == "forex"
assert _detect_market("gc=f") == "futures"
assert _detect_market("eurusd=x") == "forex"
+
+
+class TestChinaFuturesMainContract:
+ """#1395 — ``<product>0`` is the rolled series, and it was not routed.
+
+ A dated contract lives about one year (``RB2601`` measured at 242 trading
+ days), so any backtest spanning more than a contract cycle has to name the
+ main continuous series. ``RB0`` matched no pattern and fell to the
+ ``a_share`` default, which both applied T+1 and no-shorting to a leveraged
+ futures series and kept it out of the futures loader chain.
+ """
+
+ @pytest.mark.parametrize("code", [
+ "RB0", # SHFE rebar
+ "rb0", # lowercase — the table is case-insensitive
+ "IF0", # CFFEX index future
+ "T0", # CFFEX 10y treasury, single-letter product
+ "MA0", # ZCE methanol
+ "SI0", # GFEX industrial silicon
+ "V0", # DCE PVC, single-letter product
+ ])
+ def test_main_contract_resolves_to_futures(self, code: str) -> None:
+ assert _detect_market(code) == "futures"
+
+ @pytest.mark.parametrize("code", [
+ "TSLA0", # not a whitelisted product — must stay off the futures path
+ "ABCD0", # NB: "ZZZ0" is genuinely a global month-code contract
+ # (product ZZ, Z = December) under the pre-existing rule,
+ # so it is not a counter-example to this one.
+ "AAPL",
+ "600519.SH",
+ "000001.SZ",
+ ])
+ def test_non_product_codes_do_not_become_futures(self, code: str) -> None:
+ """The other side of the gate.
+
+ The rule is anchored on the product whitelist rather than a width
+ heuristic precisely so an ordinary symbol ending in ``0`` keeps its
+ own market.
+ """
+ assert _detect_market(code) != "futures"
+
+ def test_main_contract_is_recognised_as_chinese(self) -> None:
+ """It must reach ChinaFuturesEngine, not GlobalFutures."""
+ assert _is_china_futures("RB0")
+ assert _is_china_futures("IF0")
+ assert not _is_china_futures("CL2412.NYMEX")
+
+ def test_dated_contracts_keep_their_routing(self) -> None:
+ """Adding the main-contract rule must not disturb the dated forms."""
+ for code in ("RB2601", "rb2410.SHFE", "IF2406.CFFEX", "CL2412.NYMEX", "ESZ4"):
+ assert _detect_market(code) == "futures", code
diff --git a/agent/tests/test_registry.py b/agent/tests/test_registry.py
index 0f7693101..c7a031abe 100644
--- a/agent/tests/test_registry.py
+++ b/agent/tests/test_registry.py
@@ -8,6 +8,7 @@ import pytest
from backtest.loaders.base import DataLoaderProtocol, NoAvailableSourceError
from backtest.loaders.registry import (
+ _ensure_registered,
FALLBACK_CHAINS,
LOADER_REGISTRY,
VALID_SOURCES,
@@ -185,15 +186,40 @@ class TestFallbackChains:
assert "baostock" in FALLBACK_CHAINS["a_share"]
def test_unchanged_chains_preserved(self) -> None:
- """crypto/futures/fund/macro/forex chains must be left untouched."""
+ """crypto/fund/macro/forex chains must be left untouched."""
assert FALLBACK_CHAINS["crypto"] == ["okx", "binance", "ccxt", "yfinance", "local"]
- assert FALLBACK_CHAINS["futures"] == ["tushare", "akshare", "local"]
assert FALLBACK_CHAINS["fund"] == ["tushare", "akshare", "local"]
assert FALLBACK_CHAINS["macro"] == ["akshare", "tushare", "local"]
# mt5 heads the forex chain (terminal feed when attached), degrading to
# the previous chain unchanged.
assert FALLBACK_CHAINS["forex"] == ["mt5", "akshare", "yfinance", "local"]
+ def test_futures_chain_leads_with_a_source_that_implements_futures(self) -> None:
+ """#1395 — tushare led this chain while implementing no futures path.
+
+ ``resolve_loader`` walks FALLBACK_CHAINS and never consults a loader's
+ ``markets`` set, so a loader listed here is asked for the market
+ whether or not it declares it. tushare would have been constructed,
+ found available on any TUSHARE_TOKEN, and returned an empty frame from
+ the A-share ``daily()`` endpoint before akshare was ever reached.
+ """
+ assert FALLBACK_CHAINS["futures"] == ["akshare", "local"]
+ assert "tushare" not in FALLBACK_CHAINS["futures"]
+
+ def test_every_futures_chain_member_declares_the_market(self) -> None:
+ """The invariant #1395 broke, stated directly.
+
+ Written as a closure over the chain rather than a literal, so adding a
+ source that does not serve futures fails here instead of at runtime.
+ """
+ _ensure_registered()
+ for name in FALLBACK_CHAINS["futures"]:
+ loader_cls = LOADER_REGISTRY.get(name)
+ assert loader_cls is not None, f"{name} is in the chain but not registered"
+ assert "futures" in loader_cls.markets, (
+ f"{name} leads the futures chain without declaring the market"
+ )
+
def test_tickerall_is_explicit_only_never_a_fallback(self) -> None:
"""TickerAll is a valid explicit source but must NEVER join an automatic
fallback chain. It reads a user's own broker account over a hosted API, so
diff --git a/agent/tests/test_source_order_overrides.py b/agent/tests/test_source_order_overrides.py
index 075dbae60..cb072e49c 100644
--- a/agent/tests/test_source_order_overrides.py
+++ b/agent/tests/test_source_order_overrides.py
@@ -150,17 +150,15 @@ def test_override_reorders_in_place_for_byname_importers(
The reassignment must be a setitem on the same dict object so those
by-name references observe the new order.
"""
- monkeypatch.setenv("MARKET_DATA_ORDER_FUTURES", "akshare,tushare,local")
+ monkeypatch.setenv("MARKET_DATA_ORDER_FUTURES", "local,akshare")
refresh_source_order_overrides()
- assert FALLBACK_CHAINS["futures"] == ["akshare", "tushare", "local"]
+ assert FALLBACK_CHAINS["futures"] == ["local", "akshare"]
override = registry.get_source_order_override("futures")
- assert override == ["akshare", "tushare", "local"]
+ assert override == ["local", "akshare"]
# Returned copies — callers cannot corrupt internal state.
override.append("zzz")
- assert registry.get_source_order_override("futures") == [
- "akshare", "tushare", "local",
- ]
+ assert registry.get_source_order_override("futures") == ["local", "akshare"]
@pytest.mark.parametrize(