Skip to content

"Vibe-Trading: Your Personal Trading Agent"

fix(data): repair HK fallback routing + tencent HK source (closes #998, #999) (#1000)

shadowinlife31869da68cea
diff --git a/README.md b/README.md
index 8bfb0e74b..c9f5e0a33 100644
--- a/README.md
+++ b/README.md
@@ -338,10 +338,10 @@ One `get_market_data` call, **23 free market-data sources** (plus the optional *
| Source | Markets | Auth | Role |
|--------|---------|------|------|
-| `tencent` · `mootdx` | A-share | none | never IP-banned (`mootdx` = 通达信 TCP) |
+| `tencent` · `mootdx` | A-share + HK | none | never IP-banned (`mootdx` = 通达信 TCP) |
| `eastmoney` | A / US / HK | none | OHLCV + deep fundamentals & flow tools (throttled) |
| `baostock` · `akshare` | A (+ US/HK/futures/macro/fx) | none | free fallbacks |
-| `tushare` | A / futures / fund / macro | token | richest A-share |
+| `tushare` | A / HK / futures / fund / macro | token | richest A-share |
| `yahoo` · `sina` · `stooq` | US (/HK) | none | direct chart/quotes/options · K-line to 1984 · EOD CSV |
| `yfinance` | US / HK | none | wrapper |
| `longbridge` | US / HK | App Key + App Secret + Access Token | optional historical OHLCV source; install the optional SDK |
@@ -358,7 +358,7 @@ One `get_market_data` call, **23 free market-data sources** (plus the optional *
- **A-share** → `tencent` · `mootdx` · `eastmoney` · `baostock` · `akshare` · `tushare` · `local`
- **US** → `yahoo` · `stooq` · `sina` · `eastmoney` · `yfinance` · `tiingo` · `fmp` · `finnhub` · `alphavantage` · `longbridge` · `akshare` · `local`
-- **HK** → `eastmoney` · `yahoo` · `futu` · `yfinance` · `akshare` · `longbridge` · `local`
+- **HK** → `tencent` · `eastmoney` · `yahoo` · `futu` · `akshare` · `yfinance` · `tushare` · `longbridge` · `local`
- **India (NSE/BSE)** → `yahoo` · `yfinance` · `india_broker` · `local`
- **Korea (KOSPI/KOSDAQ)** → `pykrx` · `yahoo` · `yfinance` · `local`
- **Crypto** → `okx` · `ccxt` · `binance` · `yfinance` · `local`
diff --git a/README_ar.md b/README_ar.md
index f670e33e1..98bdc6e01 100644
--- a/README_ar.md
+++ b/README_ar.md
@@ -339,10 +339,10 @@ vibe-trading run -p "Analyze my trading behavior, extract my shadow strategy, an
| Source | Markets | Auth | Role |
|--------|---------|------|------|
-| `tencent` · `mootdx` | A-share | none | never IP-banned (`mootdx` = 通达信 TCP) |
+| `tencent` · `mootdx` | A-share + HK | none | never IP-banned (`mootdx` = 通达信 TCP) |
| `eastmoney` | A / US / HK | none | OHLCV + deep fundamentals & flow tools (throttled) |
| `baostock` · `akshare` | A (+ US/HK/futures/macro/fx) | none | free fallbacks |
-| `tushare` | A / futures / fund / macro | token | richest A-share |
+| `tushare` | A / HK / futures / fund / macro | token | richest A-share |
| `yahoo` · `sina` · `stooq` | US (/HK) | none | direct chart/quotes/options · K-line to 1984 · EOD CSV |
| `yfinance` | US / HK | none | wrapper |
| `longbridge` | US / HK | App Key + App Secret + Access Token | مصدر OHLCV تاريخي اختياري؛ ثبّت الـ SDK الاختياري |
@@ -359,7 +359,7 @@ vibe-trading run -p "Analyze my trading behavior, extract my shadow strategy, an
- **أسهم A** → `tencent` · `mootdx` · `eastmoney` · `baostock` · `akshare` · `tushare` · `local`
- **أسهم US** → `yahoo` · `stooq` · `sina` · `eastmoney` · `yfinance` · `tiingo` · `fmp` · `finnhub` · `alphavantage` · `longbridge` · `akshare` · `local`
-- **أسهم HK** → `eastmoney` · `yahoo` · `futu` · `yfinance` · `akshare` · `longbridge` · `local`
+- **أسهم HK** → `tencent` · `eastmoney` · `yahoo` · `futu` · `akshare` · `yfinance` · `tushare` · `longbridge` · `local`
- **أسهم الهند (NSE/BSE)** → `yahoo` · `yfinance` · `india_broker` · `local`
- **كوريا (KOSPI/KOSDAQ)** → `pykrx` · `yahoo` · `yfinance` · `local`
- **الكريبتو** → `okx` · `ccxt` · `binance` · `yfinance` · `local`
diff --git a/README_ja.md b/README_ja.md
index d8cbad5d1..44352afae 100644
--- a/README_ja.md
+++ b/README_ja.md
@@ -339,10 +339,10 @@ vibe-trading run -p "Analyze my trading behavior, extract my shadow strategy, an
| Source | Markets | Auth | Role |
|--------|---------|------|------|
-| `tencent` · `mootdx` | A-share | none | never IP-banned (`mootdx` = 通达信 TCP) |
+| `tencent` · `mootdx` | A-share + HK | none | never IP-banned (`mootdx` = 通达信 TCP) |
| `eastmoney` | A / US / HK | none | OHLCV + deep fundamentals & flow tools (throttled) |
| `baostock` · `akshare` | A (+ US/HK/futures/macro/fx) | none | free fallbacks |
-| `tushare` | A / futures / fund / macro | token | richest A-share |
+| `tushare` | A / HK / futures / fund / macro | token | richest A-share |
| `yahoo` · `sina` · `stooq` | US (/HK) | none | direct chart/quotes/options · K-line to 1984 · EOD CSV |
| `yfinance` | US / HK | none | wrapper |
| `longbridge` | US / HK | App Key + App Secret + Access Token | optional historical OHLCV source; install the optional SDK |
@@ -359,7 +359,7 @@ vibe-trading run -p "Analyze my trading behavior, extract my shadow strategy, an
- **A 株** → `tencent` · `mootdx` · `eastmoney` · `baostock` · `akshare` · `tushare` · `local`
- **米国株** → `yahoo` · `stooq` · `sina` · `eastmoney` · `yfinance` · `tiingo` · `fmp` · `finnhub` · `alphavantage` · `longbridge` · `akshare` · `local`
-- **香港株** → `eastmoney` · `yahoo` · `futu` · `yfinance` · `akshare` · `longbridge` · `local`
+- **香港株** → `tencent` · `eastmoney` · `yahoo` · `futu` · `akshare` · `yfinance` · `tushare` · `longbridge` · `local`
- **インド株(NSE/BSE)** → `yahoo` · `yfinance` · `india_broker` · `local`
- **韓国(KOSPI/KOSDAQ)** → `pykrx` · `yahoo` · `yfinance` · `local`
- **暗号資産** → `okx` · `ccxt` · `binance` · `yfinance` · `local`
diff --git a/README_ko.md b/README_ko.md
index bf4296c8e..0f6e8844c 100644
--- a/README_ko.md
+++ b/README_ko.md
@@ -339,10 +339,10 @@ vibe-trading run -p "Analyze my trading behavior, extract my shadow strategy, an
| Source | Markets | Auth | Role |
|--------|---------|------|------|
-| `tencent` · `mootdx` | A-share | none | never IP-banned (`mootdx` = 通达信 TCP) |
+| `tencent` · `mootdx` | A-share + HK | none | never IP-banned (`mootdx` = 通达信 TCP) |
| `eastmoney` | A / US / HK | none | OHLCV + deep fundamentals & flow tools (throttled) |
| `baostock` · `akshare` | A (+ US/HK/futures/macro/fx) | none | free fallbacks |
-| `tushare` | A / futures / fund / macro | token | richest A-share |
+| `tushare` | A / HK / futures / fund / macro | token | richest A-share |
| `yahoo` · `sina` · `stooq` | US (/HK) | none | direct chart/quotes/options · K-line to 1984 · EOD CSV |
| `yfinance` | US / HK | none | wrapper |
| `longbridge` | US / HK | App Key + App Secret + Access Token | optional historical OHLCV source; install the optional SDK |
@@ -359,7 +359,7 @@ vibe-trading run -p "Analyze my trading behavior, extract my shadow strategy, an
- **A주** → `tencent` · `mootdx` · `eastmoney` · `baostock` · `akshare` · `tushare` · `local`
- **미국** → `yahoo` · `stooq` · `sina` · `eastmoney` · `yfinance` · `tiingo` · `fmp` · `finnhub` · `alphavantage` · `longbridge` · `akshare` · `local`
-- **홍콩** → `eastmoney` · `yahoo` · `futu` · `yfinance` · `akshare` · `longbridge` · `local`
+- **홍콩** → `tencent` · `eastmoney` · `yahoo` · `futu` · `akshare` · `yfinance` · `tushare` · `longbridge` · `local`
- **인도 (NSE/BSE)** → `yahoo` · `yfinance` · `india_broker` · `local`
- **한국 (KOSPI/KOSDAQ)** → `pykrx` · `yahoo` · `yfinance` · `local`
- **크립토** → `okx` · `ccxt` · `binance` · `yfinance` · `local`
diff --git a/README_zh.md b/README_zh.md
index f58410a43..b4fb6d823 100644
--- a/README_zh.md
+++ b/README_zh.md
@@ -338,10 +338,10 @@ vibe-trading run -p "Analyze my trading behavior, extract my shadow strategy, an
| Source | Markets | Auth | Role |
|--------|---------|------|------|
-| `tencent` · `mootdx` | A-share | none | never IP-banned (`mootdx` = 通达信 TCP) |
+| `tencent` · `mootdx` | A-share + HK | none | never IP-banned (`mootdx` = 通达信 TCP) |
| `eastmoney` | A / US / HK | none | OHLCV + deep fundamentals & flow tools (throttled) |
| `baostock` · `akshare` | A (+ US/HK/futures/macro/fx) | none | free fallbacks |
-| `tushare` | A / futures / fund / macro | token | richest A-share |
+| `tushare` | A / HK / futures / fund / macro | token | richest A-share |
| `yahoo` · `sina` · `stooq` | US (/HK) | none | direct chart/quotes/options · K-line to 1984 · EOD CSV |
| `yfinance` | US / HK | none | wrapper |
| `longbridge` | 美股 / 港股 | App Key + App Secret + Access Token | 可选历史 OHLCV 数据源;需安装可选 SDK |
@@ -358,7 +358,7 @@ vibe-trading run -p "Analyze my trading behavior, extract my shadow strategy, an
- **A股** → `tencent` · `mootdx` · `eastmoney` · `baostock` · `akshare` · `tushare` · `local`
- **美股** → `yahoo` · `stooq` · `sina` · `eastmoney` · `yfinance` · `tiingo` · `fmp` · `finnhub` · `alphavantage` · `longbridge` · `akshare` · `local`
-- **港股** → `eastmoney` · `yahoo` · `futu` · `yfinance` · `akshare` · `longbridge` · `local`
+- **港股** → `tencent` · `eastmoney` · `yahoo` · `futu` · `akshare` · `yfinance` · `tushare` · `longbridge` · `local`
- **印度(NSE/BSE)** → `yahoo` · `yfinance` · `india_broker` · `local`
- **韩国(KOSPI/KOSDAQ)** → `pykrx` · `yahoo` · `yfinance` · `local`
- **加密** → `okx` · `ccxt` · `binance` · `yfinance` · `local`
diff --git a/agent/backtest/loaders/registry.py b/agent/backtest/loaders/registry.py
index 8887eaec4..7d1968533 100644
--- a/agent/backtest/loaders/registry.py
+++ b/agent/backtest/loaders/registry.py
@@ -136,7 +136,10 @@ _NO_NETWORK_FALLBACK_SOURCES: frozenset[str] = frozenset({"local", "qveris"}) #
FALLBACK_CHAINS: dict[str, list[str]] = {
"a_share": ["tencent", "mootdx", "eastmoney", "baostock", "akshare", "tushare", "local"],
"us_equity": ["yahoo", "stooq", "sina", "eastmoney", "yfinance", "tiingo", "fmp", "finnhub", "alphavantage", "longbridge", "akshare", "local"],
- "hk_equity": ["eastmoney", "yahoo", "futu", "yfinance", "akshare", "longbridge", "local"],
+ # HK: tencent leads (no observed IP ban); akshare (Eastmoney-backed)
+ # precedes the Yahoo-SDK family, which is blocked from mainland IPs;
+ # tushare hk_daily is key-gated.
+ "hk_equity": ["tencent", "eastmoney", "yahoo", "futu", "akshare", "yfinance", "tushare", "longbridge", "local"],
"india_equity": ["yahoo", "yfinance", "india_broker", "local"],
"kr_equity": ["pykrx", "yahoo", "yfinance", "local"],
# OKX first (native), then dedicated Binance, then generic CCXT / Yahoo.
diff --git a/agent/backtest/loaders/tencent_loader.py b/agent/backtest/loaders/tencent_loader.py
index 10dad96a5..7e140356f 100644
--- a/agent/backtest/loaders/tencent_loader.py
+++ b/agent/backtest/loaders/tencent_loader.py
@@ -1,10 +1,11 @@
-"""Tencent Finance loader: free, no-auth A-share data via HTTP API.
+"""Tencent Finance loader: free, no-auth A-share / HK data via HTTP API.
Uses Tencent's ifzq.gtimg.cn API which is not blocked by eastmoney's CDN.
-Covers: A-shares (SH/SZ). No API token required.
+Covers: A-shares (SH/SZ) and HK equities. No API token required.
API format:
https://web.ifzq.gtimg.cn/appstock/app/fqkline/get?param=sh601595,day,2026-06-01,2026-06-13,500,qfq
+ https://web.ifzq.gtimg.cn/appstock/app/fqkline/get?param=hk00700,day,2026-06-01,2026-06-13,500,qfq
"""
from __future__ import annotations
@@ -27,12 +28,16 @@ def _is_a_share(code: str) -> bool:
return code.upper().endswith((".SZ", ".SH"))
+def _is_hk_equity(code: str) -> bool:
+ return code.upper().endswith(".HK")
+
+
@register
class DataLoader:
- """Tencent Finance A-share OHLCV loader (free, HTTP, no auth)."""
+ """Tencent Finance A-share / HK OHLCV loader (free, HTTP, no auth)."""
name = "tencent"
- markets = {"a_share"}
+ markets = {"a_share", "hk_equity"}
requires_auth = False
def is_available(self) -> bool:
@@ -82,7 +87,7 @@ class DataLoader:
def _fetch_one(
self, code: str, start_date: str, end_date: str,
) -> Optional[pd.DataFrame]:
- if not _is_a_share(code):
+ if not _is_a_share(code) and not _is_hk_equity(code):
return None
parts = code.upper().split(".")
@@ -93,6 +98,9 @@ class DataLoader:
tencent_code = f"sh{symbol}"
elif suffix == "SZ":
tencent_code = f"sz{symbol}"
+ elif suffix == "HK":
+ # Tencent expects a zero-padded 5-digit HK code (hk00700).
+ tencent_code = f"hk{symbol.zfill(5)}"
else:
return None
diff --git a/agent/backtest/loaders/tushare.py b/agent/backtest/loaders/tushare.py
index 518ecd2fc..66bed702f 100644
--- a/agent/backtest/loaders/tushare.py
+++ b/agent/backtest/loaders/tushare.py
@@ -118,7 +118,7 @@ class DataLoader:
"""Tushare-backed OHLCV loader."""
name = "tushare"
- markets = {"a_share", "futures", "fund"}
+ markets = {"a_share", "hk_equity", "futures", "fund"}
requires_auth = True
def is_available(self) -> bool:
@@ -145,10 +145,10 @@ class DataLoader:
interval: str = "1D",
fields: Optional[List[str]] = None,
) -> Dict[str, pd.DataFrame]:
- """Fetch A-share bars via Tushare API.
+ """Fetch A-share / HK equity bars via Tushare API.
Args:
- codes: Stock codes (e.g. ``000001.SZ``).
+ codes: Stock codes (e.g. ``000001.SZ``, ``00700.HK``).
start_date: Start date (YYYY-MM-DD).
end_date: End date (YYYY-MM-DD).
fields: Extra fundamental columns (daily only).
diff --git a/agent/src/market_data.py b/agent/src/market_data.py
index f3debc86e..528f76d9e 100644
--- a/agent/src/market_data.py
+++ b/agent/src/market_data.py
@@ -13,16 +13,16 @@ logger = logging.getLogger(__name__)
DEFAULT_MAX_ROWS = 250
-# Symbol -> preferred source. The matched source is the head of its market's
+# Symbol -> preferred source. The matched source is a member of its market's
# fallback chain (registry.FALLBACK_CHAINS), so an unavailable preferred source
-# still degrades gracefully to the rest of the chain. US/HK equities route to
-# the throttle-tolerant Yahoo public endpoint first (lower IP-ban risk than the
-# yfinance SDK), A-shares to the Tencent quote endpoint.
+# still degrades gracefully to the rest of the chain. US equities route to the
+# throttle-tolerant Yahoo public endpoint first (lower IP-ban risk than the
+# yfinance SDK), A-shares and HK equities to the never-banned Tencent endpoint.
_SOURCE_PATTERNS = [
(re.compile(r"^local:", re.I), "local"),
(re.compile(r"^\d{6}\.(SZ|SH|BJ)$", re.I), "tencent"),
(re.compile(r"^[A-Z]+\.US$", re.I), "yahoo"),
- (re.compile(r"^\d{3,5}\.HK$", re.I), "yahoo"),
+ (re.compile(r"^\d{3,5}\.HK$", re.I), "tencent"),
# India: NSE (RELIANCE.NS) / BSE (500325.BO). Tickers may carry '&' and '-'
# (e.g. M&M.NS, BAJAJ-AUTO.NS). Served by Yahoo's public chart endpoint.
(re.compile(r"^[A-Z0-9&.\-]+\.(NS|BO)$", re.I), "yahoo"),
@@ -102,7 +102,7 @@ def fetch_market_data(
max_rows: int = DEFAULT_MAX_ROWS,
loader_resolver: Callable[[str], type] = get_loader,
fallback_chain_provider: Callable[[str], list[str]] | None = None,
- max_fallback_attempts: int = 3,
+ max_fallback_attempts: int = 5,
include_provenance: bool = False,
) -> dict[str, Any]:
"""Fetch normalized OHLCV data through the repository loader layer.
@@ -113,6 +113,7 @@ def fetch_market_data(
OKX → Binance → CCXT → Yahoo). At most ``max_fallback_attempts`` retries
are attempted before the symbol is recorded as ``_unresolved``.
"""
+ from backtest.engines._market_hooks import _detect_market
from backtest.loaders.base import NoAvailableSourceError
from backtest.loaders.registry import FALLBACK_CHAINS
@@ -125,29 +126,35 @@ def fetch_market_data(
for code in codes
}
- if source == "auto":
- groups: dict[str, list[str]] = {}
- for code in codes:
- src = detect_source(code)
- groups.setdefault(src, []).append(code)
- else:
- groups = {source: list(codes)}
+ groups: dict[tuple[str, str], list[str]] = {}
+ for code in codes:
+ src = detect_source(code) if source == "auto" else source
+ groups.setdefault((src, _detect_market(code)), []).append(code)
- def _chain_for(src: str) -> list[str]:
- """Return the ordered fallback chain for the market containing ``src``.
+ def _chain_for(src: str, market: str) -> list[str]:
+ """Return the ordered fallback chain for ``src``.
+
+ Prefers the chain of the symbol's own market when ``src`` is a member
+ of it. Matching by source name alone is ambiguous — ``yahoo`` appears
+ in the US, HK, India and Korea chains, and a first-match lookup would
+ send HK symbols down the US chain, exhausting the attempt budget on
+ US-only sources.
Falls back to ``[src]`` so an explicit source outside any chain still
gets at least one attempt.
"""
if fallback_chain_provider is not None:
return fallback_chain_provider(src)
- for market, chain in FALLBACK_CHAINS.items():
+ market_chain = FALLBACK_CHAINS.get(market, [])
+ if src in market_chain:
+ return market_chain
+ for chain in FALLBACK_CHAINS.values():
if src in chain:
return chain
return [src]
- for src, src_codes in groups.items():
- chain = _chain_for(src)
+ for (src, market), src_codes in groups.items():
+ chain = _chain_for(src, market)
# Start the attempt list with the requested source, then the rest of
# the chain (preserving order, no duplicates).
attempts: list[str] = []
diff --git a/agent/src/skills/data-routing/SKILL.md b/agent/src/skills/data-routing/SKILL.md
index 17a2d93f8..ca9c84140 100644
--- a/agent/src/skills/data-routing/SKILL.md
+++ b/agent/src/skills/data-routing/SKILL.md
@@ -96,7 +96,9 @@ same-market sources automatically. Only set a concrete source when the user asks
baostock / akshare > eastmoney (throttled).
- **US stocks**: stooq / yahoo > tiingo / finnhub / fmp / alphavantage (key-gated) >
sina / eastmoney (throttled) > yfinance.
-- **HK stocks**: tencent > eastmoney / yahoo > yfinance.
+- **HK stocks**: tencent (never banned, daily) > eastmoney / yahoo > futu (local
+ OpenD) > akshare (Eastmoney-backed, daily only) > yfinance > tushare
+ (`TUSHARE_TOKEN`) / longbridge (key-gated).
- **Crypto**: okx (single exchange) > ccxt (multi-exchange).
- **Futures / macro**: tushare > akshare.
- **Forex / metals**: mt5 (local MetaTrader 5 terminal, Windows) > akshare.
diff --git a/agent/tests/test_market_data.py b/agent/tests/test_market_data.py
index 3737d261d..3041051fe 100644
--- a/agent/tests/test_market_data.py
+++ b/agent/tests/test_market_data.py
@@ -37,8 +37,8 @@ from src.market_data import (
("000001.SZ", "tencent"),
("430139.BJ", "tencent"),
("AAPL.US", "yahoo"),
- ("700.HK", "yahoo"),
- ("00700.HK", "yahoo"),
+ ("700.HK", "tencent"),
+ ("00700.HK", "tencent"),
("RELIANCE.NS", "yahoo"), # India NSE
("TCS.NS", "yahoo"),
("M&M.NS", "yahoo"), # ampersand in ticker
@@ -251,6 +251,111 @@ def test_fetch_auto_groups_by_detected_source() -> None:
assert "AAPL.US" in out and "BTC-USDT" in out
+def test_fetch_auto_hk_walks_hk_chain_not_us_chain() -> None:
+ """HK symbols must degrade through the hk_equity chain, not the US one.
+
+ A source-name-only chain lookup would match HK's yahoo membership against
+ the us_equity chain first, where the attempt budget exhausts on the
+ US-only stooq/sina loaders and never reaches eastmoney/akshare.
+ """
+ from backtest.loaders.base import NoAvailableSourceError
+
+ attempts: list[str] = []
+
+ def resolver(src: str):
+ attempts.append(src)
+ if src == "eastmoney":
+ return _StubLoader
+ raise NoAvailableSourceError(f"{src} unavailable in test")
+
+ out = fetch_market_data(
+ codes=["00700.HK"],
+ start_date="2026-01-01",
+ end_date="2026-01-02",
+ source="auto",
+ loader_resolver=resolver,
+ )
+ assert attempts[:2] == ["tencent", "eastmoney"]
+ assert "stooq" not in attempts and "sina" not in attempts
+ assert "_unresolved" not in out
+ assert "00700.HK" in out
+
+
+def test_fetch_auto_hk_akshare_reachable_within_default_budget() -> None:
+ """akshare (Eastmoney-backed HK daily) must be reachable within the
+ default ``max_fallback_attempts`` when every earlier HK source is down."""
+ from backtest.loaders.base import NoAvailableSourceError
+
+ attempts: list[str] = []
+
+ def resolver(src: str):
+ attempts.append(src)
+ if src == "akshare":
+ return _StubLoader
+ raise NoAvailableSourceError(f"{src} unavailable in test")
+
+ out = fetch_market_data(
+ codes=["09988.HK"],
+ start_date="2026-01-01",
+ end_date="2026-01-02",
+ source="auto",
+ loader_resolver=resolver,
+ )
+ assert "_unresolved" not in out
+ assert "09988.HK" in out
+ assert attempts[-1] == "akshare"
+ assert len(attempts) <= 5
+
+
+def test_fetch_auto_india_walks_india_chain() -> None:
+ """India symbols must degrade through the india_equity chain (chain
+ selection is market-aware for every market, not just HK)."""
+ from backtest.loaders.base import NoAvailableSourceError
+
+ attempts: list[str] = []
+
+ def resolver(src: str):
+ attempts.append(src)
+ if src == "yfinance":
+ return _StubLoader
+ raise NoAvailableSourceError(f"{src} unavailable in test")
+
+ out = fetch_market_data(
+ codes=["RELIANCE.NS"],
+ start_date="2026-01-01",
+ end_date="2026-01-02",
+ source="auto",
+ loader_resolver=resolver,
+ )
+ assert attempts == ["yahoo", "yfinance"]
+ assert "_unresolved" not in out
+ assert "RELIANCE.NS" in out
+
+
+def test_fetch_auto_us_still_walks_us_chain() -> None:
+ """US routing is unchanged by the market-aware chain selection."""
+ from backtest.loaders.base import NoAvailableSourceError
+
+ attempts: list[str] = []
+
+ def resolver(src: str):
+ attempts.append(src)
+ if src == "stooq":
+ return _StubLoader
+ raise NoAvailableSourceError(f"{src} unavailable in test")
+
+ out = fetch_market_data(
+ codes=["AAPL.US"],
+ start_date="2026-01-01",
+ end_date="2026-01-02",
+ source="auto",
+ loader_resolver=resolver,
+ )
+ assert attempts[:2] == ["yahoo", "stooq"]
+ assert "_unresolved" not in out
+ assert "AAPL.US" in out
+
+
def test_fetch_loader_error_falls_through_to_unresolved() -> None:
out = fetch_market_data(
codes=["X.US"],
diff --git a/agent/tests/test_registry.py b/agent/tests/test_registry.py
index 50aeccdc5..2802471bf 100644
--- a/agent/tests/test_registry.py
+++ b/agent/tests/test_registry.py
@@ -156,7 +156,7 @@ class TestFallbackChains:
"finnhub", "alphavantage", "longbridge", "akshare", "local",
]
assert FALLBACK_CHAINS["hk_equity"] == [
- "eastmoney", "yahoo", "futu", "yfinance", "akshare", "longbridge", "local",
+ "tencent", "eastmoney", "yahoo", "futu", "akshare", "yfinance", "tushare", "longbridge", "local",
]
def test_us_equity_includes_sina_fallback(self) -> None:
diff --git a/agent/tests/test_tencent_loader.py b/agent/tests/test_tencent_loader.py
index b5f023170..152c8ad83 100644
--- a/agent/tests/test_tencent_loader.py
+++ b/agent/tests/test_tencent_loader.py
@@ -2,11 +2,57 @@
from __future__ import annotations
+import json
+import urllib.request
+
import pandas as pd
from backtest.loaders import tencent_loader
+class _FakeResponse:
+ def __init__(self, payload: str) -> None:
+ self._payload = payload
+
+ def read(self) -> bytes:
+ return self._payload.encode("utf-8")
+
+ def __enter__(self) -> "_FakeResponse":
+ return self
+
+ def __exit__(self, *exc) -> bool:
+ return False
+
+
+def _hk_kline_payload(tencent_code: str) -> str:
+ return json.dumps(
+ {
+ "code": 0,
+ "data": {
+ tencent_code: {
+ "day": [
+ ["2026-01-05", "466.4", "471.8", "475.0", "462.8", "31791979"],
+ ["2026-01-06", "470.0", "475.2", "479.8", "462.0", "31100240"],
+ ]
+ }
+ },
+ }
+ )
+
+
+def _patch_http(monkeypatch, urls: list[str], payload: str) -> None:
+ def fake_urlopen(req, timeout=None): # noqa: ANN001, ANN002
+ urls.append(req.full_url)
+ return _FakeResponse(payload)
+
+ monkeypatch.setattr(urllib.request, "urlopen", fake_urlopen)
+ monkeypatch.setattr(
+ tencent_loader,
+ "cached_loader_fetch",
+ lambda **kwargs: kwargs["fetch"](),
+ )
+
+
def test_intraday_request_does_not_return_daily_bars(monkeypatch) -> None:
calls: list[str] = []
daily = pd.DataFrame(
@@ -40,3 +86,34 @@ def test_intraday_request_does_not_return_daily_bars(monkeypatch) -> None:
assert result == {}
assert calls == []
+
+
+def test_hk_equity_maps_to_hk_prefix_and_parses(monkeypatch) -> None:
+ urls: list[str] = []
+ _patch_http(monkeypatch, urls, _hk_kline_payload("hk00700"))
+
+ result = tencent_loader.DataLoader().fetch(
+ ["00700.HK"], "2026-01-01", "2026-01-31",
+ )
+
+ assert len(urls) == 1
+ assert "param=hk00700,day," in urls[0]
+ df = result["00700.HK"]
+ assert len(df) == 2
+ # Tencent kline rows are [date, open, close, high, low, volume].
+ assert df.iloc[0]["open"] == 466.4
+ assert df.iloc[0]["close"] == 471.8
+ assert df.iloc[0]["high"] == 475.0
+ assert df.iloc[0]["low"] == 462.8
+
+
+def test_short_hk_code_is_zero_padded(monkeypatch) -> None:
+ urls: list[str] = []
+ _patch_http(monkeypatch, urls, _hk_kline_payload("hk00700"))
+
+ result = tencent_loader.DataLoader().fetch(
+ ["700.HK"], "2026-01-01", "2026-01-31",
+ )
+
+ assert "param=hk00700,day," in urls[0]
+ assert "700.HK" in result