Skip to content

"Vibe-Trading: Your Personal Trading Agent"

fix(correlation): resolve bare tickers so the matrix stops failing with "Fetched: []"

Carlse854606586fe
diff --git a/agent/backtest/correlation.py b/agent/backtest/correlation.py
index 0b3d78e4d..24db8d9a1 100644
--- a/agent/backtest/correlation.py
+++ b/agent/backtest/correlation.py
@@ -6,32 +6,84 @@ over a configurable lookback window. Used by the /correlation API endpoint.
from __future__ import annotations
+import logging
from typing import Dict, Literal
import pandas as pd
import numpy as np
from scipy.stats import spearmanr
+logger = logging.getLogger(__name__)
+
def infer_market(code: str) -> str:
- """Infer market key from a ticker symbol."""
- code_upper = code.upper()
+ """Infer market key from a ticker symbol.
+
+ Resolution order:
+
+ 1. Crypto pair spellings (``BTC-USDT``, ``ETH/USD`` …).
+ 2. Explicit exchange suffix — always authoritative (``.HK``, ``.SH``/
+ ``.SZ``/``.BJ``, ``.US``). Bare HK and A-share codes are both purely
+ numeric, so the suffix is the only reliable disambiguator.
+ 3. Bare numeric codes by digit length: A-share codes are exactly 6 digits
+ (600000, 000001, 300750, 688981, 830799); HK codes are at most 5
+ (700, 0700, 9988, 3690). Prefix alone cannot tell them apart — both
+ markets use leading 0 and 3.
+ 4. Anything else (alphabetic tickers) is a US equity.
+ """
+ code_upper = code.strip().upper()
crypto_suffixes = ("USDT", "BTC", "ETH", "BNB", "SOL", "ADA", "DOGE")
if any(code_upper.endswith(s) for s in crypto_suffixes) or "/" in code:
return "crypto"
- # Check .HK suffix FIRST so leading-zero tickers like 0700.HK / 0005.HK
- # are correctly classified before the A-share prefix checks
if code_upper.endswith(".HK"):
return "hk_equity"
- if code_upper.startswith(("6", "000", "001", "002")):
- return "a_share"
- if code_upper.startswith(("0", "399")):
+ if code_upper.endswith((".SH", ".SZ", ".BJ")):
return "a_share"
- if code_upper.startswith(("0", "1", "2", "3", "4")):
- return "hk_equity"
+ if code_upper.endswith(".US"):
+ return "us_equity"
+ if code_upper.isdigit():
+ if len(code_upper) == 6:
+ return "a_share"
+ if len(code_upper) <= 5:
+ return "hk_equity"
return "us_equity"
+def _normalize_symbol(code: str, market: str) -> str:
+ """Convert a user-supplied code to the project's canonical loader symbol.
+
+ The data loaders key US/HK/A-share instruments by an exchange-suffixed
+ symbol (``AAPL.US``, ``0700.HK``, ``600000.SH``); a bare ticker such as
+ ``AAPL`` or ``600000`` matches no loader and fetches nothing. Crypto pairs
+ (``BTC-USDT``) are already canonical, and any code that already carries a
+ ``.`` suffix is left untouched.
+
+ Args:
+ code: The raw code as typed by the user (e.g. ``AAPL``, ``600000``).
+ market: The market key from :func:`infer_market`.
+
+ Returns:
+ The canonical symbol the market's loaders expect.
+ """
+ cleaned = code.strip()
+ # Crypto pairs and anything already exchange-qualified pass through as-is.
+ if market == "crypto" or "." in cleaned:
+ return cleaned
+ upper = cleaned.upper()
+ if market == "us_equity":
+ return f"{upper}.US"
+ if market == "hk_equity":
+ return f"{upper}.HK"
+ if market == "a_share":
+ # 6xxxxx -> Shanghai; 4xxxxx / 8xxxxx -> Beijing; else (0/3) Shenzhen.
+ if upper[:1] == "6":
+ return f"{upper}.SH"
+ if upper[:1] in ("4", "8"):
+ return f"{upper}.BJ"
+ return f"{upper}.SZ"
+ return cleaned
+
+
def _rolling_correlation_matrix(
price_series: Dict[str, pd.DataFrame],
window: int,
@@ -140,37 +192,54 @@ def compute_correlation_matrix(
start_date = (datetime.now() - timedelta(days=days + 60)).strftime("%Y-%m-%d")
# Import here to avoid circular
- from backtest.loaders.registry import resolve_loader
+ from backtest.loaders import registry
+ registry._ensure_registered()
price_series: Dict[str, pd.DataFrame] = {}
for code in codes:
market = infer_market(code)
- try:
- loader = resolve_loader(market)
- except Exception:
- # Fall back to yfinance for us_equity / hk_equity
+ # Loaders key instruments by the canonical exchange-suffixed symbol
+ # (AAPL.US / 600000.SH); a bare ticker fetches nothing. Fetch under the
+ # normalized symbol but keep the user's original code as the label.
+ symbol = _normalize_symbol(code, market)
+
+ # Walk the market's full fallback chain until a loader actually
+ # returns data. A loader can be "available" yet still serve nothing
+ # (network error, unsupported symbol), so stopping at the first
+ # available loader — as resolve_loader does — would silently drop
+ # the asset even when a later loader could serve it.
+ for name in registry.FALLBACK_CHAINS.get(market, []):
+ loader_cls = registry.LOADER_REGISTRY.get(name)
+ if loader_cls is None:
+ continue
try:
- from backtest.loaders.registry import LOADER_REGISTRY
- if "yfinance" in LOADER_REGISTRY:
- loader = LOADER_REGISTRY["yfinance"]()
- else:
- continue
- except Exception:
+ loader = loader_cls()
+ except Exception as exc:
+ logger.debug("correlation: loader %s failed to construct: %s", name, exc)
continue
-
- try:
- result = loader.fetch(
- codes=[code],
- start_date=start_date,
- end_date=end_date,
- interval="1D",
- fields=["trade_date", "open", "high", "low", "close", "volume"],
+ if not loader.is_available():
+ continue
+ try:
+ result = loader.fetch(
+ codes=[symbol],
+ start_date=start_date,
+ end_date=end_date,
+ interval="1D",
+ fields=["trade_date", "open", "high", "low", "close", "volume"],
+ )
+ except Exception as exc:
+ logger.warning("correlation: %s fetch via %s failed: %s", symbol, name, exc)
+ continue
+ if symbol in result and not result[symbol].empty:
+ price_series[code] = result[symbol]
+ break
+ logger.warning("correlation: %s returned no data via %s", symbol, name)
+ else:
+ logger.warning(
+ "correlation: no loader in the %s chain returned data for %s "
+ "(normalized from %r)", market, symbol, code,
)
- if code in result and not result[code].empty:
- price_series[code] = result[code]
- except Exception:
- continue
if len(price_series) < 2:
raise ValueError(
diff --git a/agent/tests/test_correlation.py b/agent/tests/test_correlation.py
index 2799c6f93..4b7b0f99b 100644
--- a/agent/tests/test_correlation.py
+++ b/agent/tests/test_correlation.py
@@ -5,6 +5,7 @@ import pandas as pd
import pytest
from backtest.correlation import (
+ _normalize_symbol,
_rolling_correlation_matrix,
infer_market,
)
@@ -35,6 +36,120 @@ class TestInferMarket:
# .HK suffix should be checked before A-share numeric prefix checks
assert infer_market("000001.HK") == "hk_equity"
+ def test_bare_hk_tickers_by_digit_length(self):
+ # HK codes are <=5 digits; A-share codes are exactly 6 digits. A bare
+ # short numeric code must classify as HK, not A-share / US.
+ assert infer_market("0700") == "hk_equity" # 腾讯
+ assert infer_market("0005") == "hk_equity" # 汇丰
+ assert infer_market("0001") == "hk_equity" # 长和
+ assert infer_market("0388") == "hk_equity" # 港交所
+ assert infer_market("3690") == "hk_equity" # 美团
+ assert infer_market("9988") == "hk_equity" # 阿里 (starts with 9)
+ assert infer_market("700") == "hk_equity" # unpadded form
+
+ def test_bare_a_share_tickers_by_digit_length(self):
+ # Exactly-6-digit bare codes are A-share regardless of prefix.
+ assert infer_market("600000") == "a_share" # 浦发银行 沪
+ assert infer_market("000001") == "a_share" # 平安银行 深
+ assert infer_market("300750") == "a_share" # 宁德时代 创业板
+ assert infer_market("688981") == "a_share" # 中芯国际 科创板
+ assert infer_market("830799") == "a_share" # 北交所
+ assert infer_market("399001") == "a_share" # 深证成指
+
+ def test_explicit_suffix_always_wins(self):
+ assert infer_market("600519.SH") == "a_share"
+ assert infer_market("000001.SZ") == "a_share"
+ assert infer_market("830799.BJ") == "a_share"
+ assert infer_market("AAPL.US") == "us_equity"
+ assert infer_market("9988.HK") == "hk_equity"
+
+
+class TestNormalizeSymbol:
+ def test_bare_us_equity_gets_us_suffix(self):
+ # Regression: bare US tickers were passed to loaders that require the
+ # canonical ``.US`` form, so the correlation matrix fetched nothing.
+ assert _normalize_symbol("AAPL", "us_equity") == "AAPL.US"
+ assert _normalize_symbol("SPY", "us_equity") == "SPY.US"
+
+ def test_bare_a_share_gets_exchange_suffix(self):
+ assert _normalize_symbol("600000", "a_share") == "600000.SH"
+ assert _normalize_symbol("000001", "a_share") == "000001.SZ"
+ assert _normalize_symbol("300750", "a_share") == "300750.SZ"
+ assert _normalize_symbol("830799", "a_share") == "830799.BJ"
+
+ def test_already_suffixed_passes_through(self):
+ assert _normalize_symbol("AAPL.US", "us_equity") == "AAPL.US"
+ assert _normalize_symbol("600000.SH", "a_share") == "600000.SH"
+ assert _normalize_symbol("0700.HK", "hk_equity") == "0700.HK"
+
+ def test_crypto_passes_through(self):
+ assert _normalize_symbol("BTC-USDT", "crypto") == "BTC-USDT"
+ assert _normalize_symbol("ETH-USDT", "crypto") == "ETH-USDT"
+
+ def test_bare_hk_gets_hk_suffix(self):
+ assert _normalize_symbol("0700", "hk_equity") == "0700.HK"
+
+ def test_case_and_whitespace_normalized(self):
+ assert _normalize_symbol(" aapl ", "us_equity") == "AAPL.US"
+
+
+class TestFetchFallsThroughChain:
+ """A loader that is available but returns no data must not end the search.
+
+ Regression: HK codes silently vanished from the matrix whenever the first
+ loader in the market chain (eastmoney) hit a network error, even though
+ the next loader (yahoo) could serve the symbol.
+ """
+
+ @staticmethod
+ def _price_df(n=60):
+ dates = pd.date_range("2024-01-01", periods=n, freq="D")
+ rng = np.random.default_rng(7)
+ return pd.DataFrame(
+ {"close": np.cumsum(rng.standard_normal(n)) + 100},
+ index=pd.Index(dates, name="trade_date"),
+ )
+
+ def test_falls_through_to_next_loader_when_first_returns_empty(self, monkeypatch):
+ from backtest.loaders import registry
+ from backtest.correlation import compute_correlation_matrix
+
+ good_df = self._price_df()
+
+ class EmptyLoader:
+ name = "fake_empty"
+ markets = {"us_equity"}
+
+ def is_available(self):
+ return True
+
+ def fetch(self, codes, start_date, end_date, *, interval="1D", fields=None):
+ return {} # available but serves nothing (e.g. network error)
+
+ class GoodLoader:
+ name = "fake_good"
+ markets = {"us_equity"}
+
+ def is_available(self):
+ return True
+
+ def fetch(self, codes, start_date, end_date, *, interval="1D", fields=None):
+ return {c: good_df.copy() for c in codes}
+
+ monkeypatch.setattr(registry, "_registered", True)
+ monkeypatch.setattr(
+ registry, "LOADER_REGISTRY",
+ {"fake_empty": EmptyLoader, "fake_good": GoodLoader},
+ )
+ monkeypatch.setattr(
+ registry, "FALLBACK_CHAINS",
+ {"us_equity": ["fake_empty", "fake_good"]},
+ )
+
+ result = compute_correlation_matrix(codes=["AAPL", "SPY"], days=30)
+ assert result["labels"] == ["AAPL", "SPY"]
+ assert result["matrix"][0][1] == pytest.approx(1.0) # identical series
+
class TestRollingCorrelationMatrix:
def _make_price_df(self, closes):