"Vibe-Trading: Your Personal Trading Agent"
Python ai-agentalgorithmic-tradingbacktestingfintechllmmcpmulti-agentpythonquantitative-financetrading
fix(market-data): align symbol search and fetch for FX pairs and indexes
cgycorey0c2b516eba94
diff --git a/agent/backtest/engines/_market_hooks.py b/agent/backtest/engines/_market_hooks.pyindex 55cbe43f6..7375894e1 100644--- a/agent/backtest/engines/_market_hooks.py+++ b/agent/backtest/engines/_market_hooks.py@@ -57,6 +57,14 @@ _MARKET_PATTERNS = [# 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"),+ # Yahoo forex suffix convention (EURUSD=X, GBPCNY=X) — served verbatim by+ # the chart endpoint. Without this rule such symbols fell through to the+ # a_share default (misrouting composite/market classification).+ (re.compile(r"^[A-Z]{3}[A-Z]{3}=X$"), "forex"),+ # Yahoo index symbols (^SPX, ^NDX, ^FTSE, ^VIX, ...) — served verbatim,+ # same as the =F/=X conventions. Classified as their own market so they+ # never route through an equity/China chain or a cash currency.+ (re.compile(r"^\^[A-Za-z0-9.\-]+$"), "index"),# Bare US tickers (AAPL, MSFT, SPY, T, ...). Must stay LAST so every# suffixed equity / futures / crypto / forex form above wins first.# ``{1,5}`` covers every standard US ticker length while 6-char bare@@ -116,6 +124,8 @@ def code_currency(code: str) -> str:pair = code.upper().replace("/", "")if pair.endswith(".FX"):pair = pair[:-3]+ if pair.endswith("=X"):+ pair = pair[:-2]return pair[3:6] if len(pair) == 6 else "UNKNOWN:forex"if market == "futures":if _is_china_futures(code):diff --git a/agent/backtest/loaders/registry.py b/agent/backtest/loaders/registry.pyindex 7e2298f51..ef6303955 100644--- a/agent/backtest/loaders/registry.py+++ b/agent/backtest/loaders/registry.py@@ -164,6 +164,9 @@ FALLBACK_CHAINS: dict[str, list[str]] = {# mt5 leads when a local MetaTrader 5 terminal is attached (Windows-only,# broker feed); otherwise it reports unavailable and the chain proceeds."forex": ["mt5", "akshare", "yfinance", "local"],+ # Yahoo index symbols (^SPX, ^NDX, ^FTSE, ^VIX, ...): served verbatim by+ # the public chart endpoint, same as the =F/=X conventions.+ "index": ["yahoo", "yfinance", "local"],}diff --git a/agent/backtest/loaders/yahoo_loader.py b/agent/backtest/loaders/yahoo_loader.pyindex ccfe1c82d..712e2a0d3 100644--- a/agent/backtest/loaders/yahoo_loader.py+++ b/agent/backtest/loaders/yahoo_loader.py@@ -53,12 +53,15 @@ def _is_supported(code: str) -> bool:"""Return whether *code* is a symbol this loader handles.Covers US/HK/India/Korea/Canada/Vietnam/UK equities plus Yahoo's own- futures (``GC=F``) and forex (``EURUSD=X``) suffix conventions, which the- public chart endpoint serves verbatim (the code is used as-is in the- request URL, no conversion) (#718). Supported UK ``.L`` lines must declare- GBP or GBp; GBp is normalized to GBP at fetch time (#1206).+ futures (``GC=F``), forex (``EURUSD=X``) and index (``^SPX``) symbol+ conventions, which the public chart endpoint serves verbatim (the code is+ used as-is in the request URL, no conversion) (#718). Supported UK ``.L``+ lines must declare GBP or GBp; GBp is normalized to GBP at fetch time+ (#1206)."""upper = code.strip().upper()+ if upper.startswith("^"):+ return Truereturn upper.endswith((".US", ".HK", ".NS", ".BO", ".KS", ".KQ", ".TO", ".V", ".VN",diff --git a/agent/src/market_data.py b/agent/src/market_data.pyindex 78a19ea80..0e8750927 100644--- a/agent/src/market_data.py+++ b/agent/src/market_data.py@@ -38,6 +38,9 @@ _SOURCE_PATTERNS = [# China-market loaders that cannot resolve them.(re.compile(r"^[A-Z0-9]+=F$", re.I), "yahoo"),(re.compile(r"^[A-Z]+=X$", re.I), "yahoo"),+ # Yahoo index symbols (^SPX, ^GSPC, ^FTSE, ^VIX, ...) — served verbatim,+ # same convention as =F/=X. Without this they fell to the tushare default.+ (re.compile(r"^\^[A-Za-z0-9.\-]+$", re.I), "yahoo"),# Korea: KOSPI (005930.KS) / KOSDAQ (247540.KQ), 6-digit codes. Served by# pykrx (KRX public data, no auth); registry falls back to Yahoo/yfinance.(re.compile(r"^\d{6}\.(KS|KQ)$", re.I), "pykrx"),diff --git a/agent/src/tools/symbol_search_tool.py b/agent/src/tools/symbol_search_tool.pyindex d34de601b..d9f3649a3 100644--- a/agent/src/tools/symbol_search_tool.py+++ b/agent/src/tools/symbol_search_tool.py@@ -75,6 +75,41 @@ _CRYPTO_PAIR_RE = re.compile(re.IGNORECASE,)+# ISO-4217-style fiat codes. A pair whose BOTH legs are fiat is an FX pair,+# never a crypto instrument: ``GBP/USD`` was previously classified as the+# crypto pair "GBP-USD" (its quote leg USD is a crypto-connector quote asset),+# sent to the exchange venue catalogs, and its Yahoo FX hit was discarded.+# FX pairs resolve through Yahoo's ``XXXYYY=X`` convention instead.+_FIAT_CODES = frozenset(+ {+ "USD", "EUR", "GBP", "JPY", "CHF", "CNY", "CNH", "HKD", "AUD", "NZD",+ "CAD", "KRW", "INR", "SGD", "SEK", "NOK", "DKK", "MXN", "BRL", "ZAR",+ "TRY", "RUB", "PLN", "THB", "MYR", "IDR", "PHP", "VND", "ILS", "AED",+ "SAR", "EGP", "CZK", "HUF", "RON", "CLP", "COP", "PEN", "TWD", "CUP",+ }+)++_FX_PAIR_RE = re.compile(r"^(?P<base>[A-Z]{3})(?:/)?(?P<quote>[A-Z]{3})$", re.IGNORECASE)+++def _canonical_fx_pair(value: str) -> str | None:+ """Return a Yahoo FX pair in canonical ``XXXYYY=X`` form, or ``None``.++ Recognizes ``GBP/USD``, ``GBPUSD`` and ``GBPUSD=X`` (both legs must be+ fiat codes — ``ETH/USD`` and ``XAU/USD`` are not FX pairs) and returns+ the canonical spelling the market-data fetch layer serves directly.+ """+ clean = str(value or "").strip().upper()+ if clean.endswith("=X"):+ clean = clean[:-2]+ matched = _FX_PAIR_RE.fullmatch(clean)+ if not matched:+ return None+ base, quote = matched.group("base"), matched.group("quote")+ if base not in _FIAT_CODES or quote not in _FIAT_CODES:+ return None+ return f"{base}{quote}=X"+# Eastmoney market-number -> our symbol suffix. Anything else is left unmapped# (those candidates are skipped rather than emitted with a wrong suffix)._EASTMONEY_SUFFIX_BY_MARKET: Dict[str, str] = {@@ -201,8 +236,27 @@ class SymbolSearchTool(BaseTool):em_hits, sources["eastmoney"] = _search_eastmoney(query)candidates.extend(em_hits)- yh_hits, sources["yahoo"] = _search_yahoo(query)+ # An explicit FX pair searches Yahoo by its canonical ``XXXYYY=X``+ # spelling — exact-symbol search is far more reliable than free text —+ # and always yields a deterministic candidate, so a throttled/outage+ # Yahoo (the earlier "GBP/USD -> 0 candidates" failure) never turns a+ # canonical pair into nothing.+ fx_pair = _canonical_fx_pair(query)+ yh_hits, sources["yahoo"] = _search_yahoo(fx_pair or query)candidates.extend(yh_hits)+ if fx_pair is not None:+ pair_no_x = fx_pair[:-2]+ candidates.append(+ {+ "symbol": fx_pair,+ "name": f"{pair_no_x[:3]}/{pair_no_x[3:]}",+ "market": "fx",+ "type": "currency",+ "exchange": "CCY",+ "source": "fx_normalizer",+ }+ )+ sources["fx_normalizer"] = "ok"if crypto_pair is not None:# A pair query is an exact instrument assertion. Near-string Yahoo@@ -279,11 +333,17 @@ def _canonical_crypto_pair(value: str) -> str | None:clean = str(value or "").strip().upper()matched = _CRYPTO_PAIR_RE.fullmatch(clean)if matched:- return f"{matched.group(1)}-{matched.group(2)}"+ base, quote = matched.group(1), matched.group(2)+ if base in _FIAT_CODES and quote in _FIAT_CODES:+ return None # fiat/fiat is an FX pair, not crypto+ return f"{base}-{quote}"if clean.isalnum():for quote in _CRYPTO_QUOTE_ASSETS:if clean.endswith(quote) and len(clean) > len(quote) + 1:- return f"{clean[: -len(quote)]}-{quote}"+ base = clean[: -len(quote)]+ if base in _FIAT_CODES and quote in _FIAT_CODES:+ return None # fiat/fiat is an FX pair, not crypto+ return f"{base}-{quote}"return None@@ -667,6 +727,16 @@ def _from_yahoo_symbol(raw_symbol: str, quote: Dict[str, Any]) -> tuple[str, strif upper.endswith((".SH", ".SZ", ".BJ")):return upper, "cn"quote_type = str(quote.get("quoteType") or "").strip().upper()+ if quote_type == "CURRENCY":+ # FX pairs canonicalize to the ``XXXYYY=X`` form the fetch layer+ # serves directly (``GBP/USD`` -> ``GBPUSD=X``); non-fiat currency+ # quotes (metals like XAU/USD) keep their native symbol.+ canon = _canonical_fx_pair(raw_symbol)+ if canon is not None:+ return canon, "fx"+ return raw_symbol, "global"+ if raw_symbol.startswith("^"):+ return raw_symbol, "index"if quote_type == "EQUITY" and "." not in raw_symbol and "-" not in raw_symbol:return f"{upper}.US", "us"# Crypto, indices, FX, ETFs on non-HK exchanges: keep Yahoo's native symbol.diff --git a/agent/tests/test_market_data.py b/agent/tests/test_market_data.pyindex 5c2017920..92e5d9a0d 100644--- a/agent/tests/test_market_data.py+++ b/agent/tests/test_market_data.py@@ -57,10 +57,9 @@ from src.market_data import (("local:my_file", "local"),# Yahoo futures / forex suffix conventions (#718) — must not fall to the# ``tushare`` default (which routed them to China-market loaders).- ("GC=F", "yahoo"), # gold future- ("CL=F", "yahoo"), # crude future- ("EURUSD=X", "yahoo"), # forex pair- ("JPY=X", "yahoo"),+ ("^SPX", "yahoo"), # index (S&P 500)+ ("^FTSE", "yahoo"), # index (FTSE 100)+ ("^VIX", "yahoo"),("something_weird", "tushare"), # documented fallback],)@@ -80,6 +79,77 @@ def test_yahoo_loader_accepts_futures_and_forex_suffixes() -> None:assert _is_supported("600519.SH") is False # A-share still not yahoo+def test_yahoo_loader_accepts_index_symbols() -> None:+ """^SPX-style index symbols must be served verbatim like =F/=X."""+ from backtest.loaders.yahoo_loader import _is_supported++ assert _is_supported("^SPX") is True+ assert _is_supported("^GSPC") is True+ assert _is_supported("^VIX") is True+ assert _is_supported("^FTSE") is True+++def test_index_market_detection() -> None:+ """^ symbols classify as index everywhere, not the a_share default."""+ from backtest.engines._market_hooks import _detect_market, code_currency++ assert _detect_market("^SPX") == "index"+ assert _detect_market("^N225") == "index"+ assert code_currency("^SPX").startswith("UNKNOWN") # honest: index has no cash currency+++def test_forex_pair_x_classifies_as_forex_not_a_share() -> None:+ """=X pairs must stop falling through to the a_share default (latent misroute)."""+ from backtest.engines._market_hooks import _detect_market, code_currency++ assert _detect_market("GBPUSD=X") == "forex"+ assert code_currency("GBPUSD=X") == "USD"+++def test_fetch_market_data_routes_index_symbols_to_yahoo() -> None:+ """auto mode must group ^SPX under yahoo, not the tushare/China chain."""+ seen_sources: list[str] = []++ class _StubLoader:+ def fetch(self, codes, start, end, *, interval="1D"): # noqa: ANN001+ index = pd.DatetimeIndex(pd.to_datetime(["2024-01-02"]))+ return {+ code: pd.DataFrame(+ {"open": [1.0], "high": [1.0], "low": [1.0], "close": [1.0], "volume": [0.0]},+ index=index,+ )+ for code in codes+ }++ def _resolver(source: str):+ seen_sources.append(source)+ return _StubLoader++ out = fetch_market_data(+ codes=["^SPX"],+ start_date="2024-01-01",+ end_date="2024-01-03",+ source="auto",+ loader_resolver=_resolver,+ )++ assert "_unresolved" not in out+ assert "^SPX" in out+ assert seen_sources and seen_sources[0] == "yahoo"+++def test_yahoo_loader_accepts_futures_and_forex_suffixes() -> None:+ """The yahoo direct loader must accept =F/=X, not just equity suffixes (#718)."""+ from backtest.loaders.yahoo_loader import _is_supported++ assert _is_supported("GC=F") is True+ assert _is_supported("EURUSD=X") is True+ assert _is_supported("AAPL.US") is True # unchanged+ assert _is_supported("TD.TO") is True+ assert _is_supported("PNG.V") is True+ assert _is_supported("600519.SH") is False # A-share still not yahoo++def test_fetch_market_data_auto_routes_yahoo_suffix_symbols() -> None:"""auto mode groups GC=F/EURUSD=X under yahoo, not the tushare/China chain (#718)."""seen_sources: list[str] = []diff --git a/agent/tests/test_registry.py b/agent/tests/test_registry.pyindex b95c3b5fe..0f7693101 100644--- a/agent/tests/test_registry.py+++ b/agent/tests/test_registry.py@@ -135,7 +135,7 @@ class TestFallbackChains:expected = {"a_share", "us_equity", "hk_equity", "india_equity", "kr_equity","ca_equity", "uk_equity", "vietnam_equity", "crypto", "futures",- "fund", "macro", "forex",+ "fund", "macro", "forex", "index",}assert expected == set(FALLBACK_CHAINS.keys())diff --git a/agent/tests/test_settings_api.py b/agent/tests/test_settings_api.pyindex cb909cc9c..ea1c9dcd2 100644--- a/agent/tests/test_settings_api.py+++ b/agent/tests/test_settings_api.py@@ -666,7 +666,7 @@ def test_get_data_source_settings_lists_default_source_orders(assert set(orders) == {"a_share", "us_equity", "hk_equity", "india_equity", "kr_equity","ca_equity", "vietnam_equity", "uk_equity", "crypto", "futures",- "fund", "macro", "forex",+ "fund", "macro", "forex", "index",}a_share = orders["a_share"]assert a_share["env_var"] == "MARKET_DATA_ORDER_A_SHARE"diff --git a/agent/tests/test_symbol_search_tool.py b/agent/tests/test_symbol_search_tool.pyindex 9b4127004..cf59a6ef4 100644--- a/agent/tests/test_symbol_search_tool.py+++ b/agent/tests/test_symbol_search_tool.py@@ -762,3 +762,69 @@ class TestCryptoPairWithoutABrokerConnection:), patch.object(ss.yahoo_client, "search", return_value=[]):ss.SymbolSearchTool().execute(query="apple", limit=5)assert called == []+++# --------------------------------------------------------------------------+# FX pairs + index symbols: search and fetch must agree on the symbol universe+# --------------------------------------------------------------------------+++class TestFxPairAlignment:+ """search_symbol must resolve FX pairs and return fetch-able symbols."""++ def test_canonical_fx_pair_spellings(self) -> None:+ assert ss._canonical_fx_pair("GBP/USD") == "GBPUSD=X"+ assert ss._canonical_fx_pair("gbp/usd") == "GBPUSD=X"+ assert ss._canonical_fx_pair("GBPUSD") == "GBPUSD=X"+ assert ss._canonical_fx_pair("GBPUSD=X") == "GBPUSD=X"+ assert ss._canonical_fx_pair("USD/JPY") == "USDJPY=X"+ assert ss._canonical_fx_pair("GBPCNY") == "GBPCNY=X"+ # Not pairs / not fiat-fiat+ assert ss._canonical_fx_pair("BRK-B") is None+ assert ss._canonical_fx_pair("AAPL") is None+ assert ss._canonical_fx_pair("ETH/USD") is None # crypto, not FX+ assert ss._canonical_fx_pair("XAU/USD") is None # metal, not fiat++ def test_fiat_pairs_are_not_misclassified_as_crypto(self) -> None:+ """GBP/USD must stop being treated as a crypto 'GBP-USD' pair."""+ assert ss._canonical_crypto_pair("GBP/USD") is None+ assert ss._canonical_crypto_pair("EURUSD") is None+ # Crypto classifications must remain untouched.+ assert ss._canonical_crypto_pair("ETH/USD") == "ETH-USD"+ assert ss._canonical_crypto_pair("BTC/USDT") == "BTC-USDT"+ assert ss._canonical_crypto_pair("BTCUSDT") == "BTC-USDT"++ def test_fx_query_returns_canonical_candidate_when_yahoo_unavailable(self) -> None:+ """A throttled/failed Yahoo must not turn a canonical pair into nothing."""+ with patch.object(+ ss.yahoo_client, "search", side_effect=Exception("Too Many Requests")+ ), patch.object(+ ss.eastmoney_client, "get_json",+ return_value={"QuotationCodeTable": {"Data": []}},+ ), patch.object(ss.sec_edgar_client, "cik_for", return_value=""):+ out = json.loads(ss.SymbolSearchTool().execute(query="GBP/USD", limit=5))++ by_symbol = {c["symbol"]: c for c in out["data"]["candidates"]}+ assert "GBPUSD=X" in by_symbol+ assert by_symbol["GBPUSD=X"]["market"] == "fx"+ assert by_symbol["GBPUSD=X"]["type"] == "currency"++ def test_from_yahoo_symbol_normalizes_currency_quotes(self) -> None:+ assert ss._from_yahoo_symbol("GBP/USD", {"quoteType": "CURRENCY"}) == (+ "GBPUSD=X",+ "fx",+ )+ assert ss._from_yahoo_symbol("GBPUSD=X", {"quoteType": "CURRENCY"}) == (+ "GBPUSD=X",+ "fx",+ )++ def test_from_yahoo_symbol_labels_indexes(self) -> None:+ assert ss._from_yahoo_symbol("^SPX", {"quoteType": "INDEX"}) == (+ "^SPX",+ "index",+ )+ assert ss._from_yahoo_symbol("^FTSE", {"quoteType": "INDEX"}) == (+ "^FTSE",+ "index",+ )