Skip to content

"Vibe-Trading: Your Personal Trading Agent"

fix(market-data): address review — shared FX canonicalization + index routing

cgycoreybb41643c9715
diff --git a/agent/backtest/engines/_market_hooks.py b/agent/backtest/engines/_market_hooks.py
index 7375894e1..33f3a8e9e 100644
--- a/agent/backtest/engines/_market_hooks.py
+++ b/agent/backtest/engines/_market_hooks.py
@@ -60,7 +60,7 @@ _MARKET_PATTERNS = [
# 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"),
+ (re.compile(r"^[A-Z]{3,6}=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.
diff --git a/agent/backtest/engines/composite.py b/agent/backtest/engines/composite.py
index 6046bc2e3..8ed70ca50 100644
--- a/agent/backtest/engines/composite.py
+++ b/agent/backtest/engines/composite.py
@@ -56,6 +56,9 @@ def _build_rule_engines(config: dict, codes: List[str]) -> Dict[str, BaseEngine]
elif market == "crypto":
from backtest.engines.crypto import CryptoEngine
engines["crypto"] = CryptoEngine(config)
+ elif market == "index":
+ from backtest.engines.global_equity import GlobalEquityEngine
+ engines["index"] = GlobalEquityEngine(config, market="us")
elif market == "forex":
from backtest.engines.forex import ForexEngine
engines["forex"] = ForexEngine(config)
diff --git a/agent/backtest/runner.py b/agent/backtest/runner.py
index 646bfa59a..d27bef7d3 100644
--- a/agent/backtest/runner.py
+++ b/agent/backtest/runner.py
@@ -842,6 +842,7 @@ _MARKET_TO_SOURCE = {
"fund": "tushare",
"macro": "akshare",
"forex": "akshare",
+ "index": "yahoo",
}
@@ -1350,6 +1351,12 @@ def _create_market_engine(source: str, config: dict, codes: List[str]):
if "vietnam_equity" in markets:
from backtest.engines.vietnam_equity import VietnamEquityEngine
return VietnamEquityEngine(config)
+ # Index symbols (^SPX, ^FTSE, ...) — priced like a US/global-listed
+ # instrument (GlobalEquityEngine, US rules) and never the China/crypto
+ # default the source-based fallback would pick.
+ if "index" in markets:
+ from backtest.engines.global_equity import GlobalEquityEngine
+ return GlobalEquityEngine(config, market=_detect_submarket(codes))
# Original routing (Wave 1)
if source in ("okx", "ccxt"):
diff --git a/agent/src/agent/grounding.py b/agent/src/agent/grounding.py
index d207ab8ad..f6f33cee0 100644
--- a/agent/src/agent/grounding.py
+++ b/agent/src/agent/grounding.py
@@ -30,6 +30,7 @@ from dataclasses import asdict, dataclass, field, replace
from datetime import datetime, timezone
from pathlib import Path
from typing import Any, Iterable, Mapping, Sequence
+from src.market_data import canonical_fx_pair
GROUNDING_ARTIFACT = "grounding_evidence.json"
@@ -160,6 +161,7 @@ _CANONICAL_SYMBOL_RE = re.compile(
r"\d{3,6}\.(?:SH|SZ|BJ|SS|HK|KS|KQ)|"
r"[A-Z][A-Z0-9&.-]{0,19}\.(?:US|NS|BO|FX|TO|V)|"
r"[A-Z0-9]{2,15}(?:-|/)(?:USDT|USDC|USD|BTC|ETH)|"
+ r"\^[A-Z0-9&.\-]{1,20}|"
r"[A-Z0-9]{2,15}=[FX]"
r")(?![A-Za-z0-9_])",
re.IGNORECASE,
@@ -570,9 +572,19 @@ def _normalize_symbol(value: Any) -> str:
Kong code zero-padded, and a crypto pair hyphenated. Text that is not a
symbol is returned uppercased and otherwise untouched.
"""
- symbol = str(value or "").strip().upper().replace("/", "-")
+ # A fiat/fiat pair is one FX instrument regardless of spelling: ``GBP/USD``
+ # and ``GBPUSD`` are both ``GBPUSD=X``. Checked BEFORE the slash is
+ # rewritten ("GBP/USD" -> "GBP-USD", the crypto-pair spelling), which
+ # disagreed with the resolver's ``GBPUSD=X`` answer — a contradictory
+ # identity that outranked every later lock and blocked all further tools.
+ raw = str(value or "").strip().upper()
+ fx = canonical_fx_pair(raw)
+ if fx is not None:
+ return fx
+ symbol = raw.replace("/", "-")
if not symbol:
return ""
+
prefixed = _EXCHANGE_PREFIXED_RE.match(symbol)
if prefixed:
return f"{prefixed.group(2)}.{prefixed.group(1)}"
@@ -824,6 +836,10 @@ def _infer_currency(symbol: str) -> str | None:
quote = upper.rsplit(separator, 1)[-1]
if 3 <= len(quote) <= 5:
return quote
+ if upper.endswith("=X"):
+ pair = upper[:-2]
+ if len(pair) == 6:
+ return pair[3:6]
return None
@@ -840,6 +856,8 @@ def _infer_instrument_type(symbol: str, candidate_type: Any = None) -> str:
return "option"
if "forex" in raw or raw == "currency":
return "forex"
+ if "index" in raw:
+ return "index"
upper = _normalize_symbol(symbol)
if upper.endswith("=F"):
return "future"
@@ -847,6 +865,8 @@ def _infer_instrument_type(symbol: str, candidate_type: Any = None) -> str:
return "forex"
if "-" in upper or "/" in upper:
return "crypto"
+ if upper.startswith("^"):
+ return "index"
return "listed_security"
diff --git a/agent/src/config/env_schema.py b/agent/src/config/env_schema.py
index be4ae07f4..ca2c946d3 100644
--- a/agent/src/config/env_schema.py
+++ b/agent/src/config/env_schema.py
@@ -233,6 +233,7 @@ class DataConfig(_EnvBase):
market_data_order_fund: str = Field(alias="MARKET_DATA_ORDER_FUND", default="")
market_data_order_macro: str = Field(alias="MARKET_DATA_ORDER_MACRO", default="")
market_data_order_forex: str = Field(alias="MARKET_DATA_ORDER_FOREX", default="")
+ market_data_order_index: str = Field(alias="MARKET_DATA_ORDER_INDEX", default="")
# ---------------------------------------------------------------------------
diff --git a/agent/src/market_data.py b/agent/src/market_data.py
index 0e8750927..230a8b295 100644
--- a/agent/src/market_data.py
+++ b/agent/src/market_data.py
@@ -63,6 +63,7 @@ def detect_source(code: str) -> str:
return "tushare"
+
def get_loader(source: str):
"""Get loader class via registry with fallback support."""
from backtest.loaders.registry import get_loader_cls_with_fallback
@@ -70,6 +71,45 @@ def get_loader(source: str):
return get_loader_cls_with_fallback(source)
+#: ISO-4217-style fiat codes. A pair whose BOTH legs are fiat is an FX pair,
+#: never a crypto instrument — ``GBP/USD`` used to be classified as the crypto
+#: pair "GBP-USD" (its quote leg USD is a crypto-connector quote asset) by the
+#: symbol-search tool's pair classifier and by the grounding ledger's symbol
+#: scanner, which then disagreed with the search result ("GBPUSD=X") and made
+#: the identity gate flag a conflict. One canonicalization is shared here so
+#: search, fetch and grounding all agree.
+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",
+ }
+)
+
+#: Yahoo-served FX pair symbol forms, canonicalized to ``XXXYYY=X``.
+_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"
+
+
# Canadian venue-alias helper: TSX (.TO) <-> TSX Venture (.V).
#
# A Canadian issuer lists on exactly one of the two venues. When a listing
diff --git "a/agent/src/skills/eastmoney/references/\351\200\211\350\202\241\346\243\200\347\264\242/\344\273\243\347\240\201\346\220\234\347\264\242.md" "b/agent/src/skills/eastmoney/references/\351\200\211\350\202\241\346\243\200\347\264\242/\344\273\243\347\240\201\346\220\234\347\264\242.md"
index 70b5c4d5c..740ff5116 100644
--- "a/agent/src/skills/eastmoney/references/\351\200\211\350\202\241\346\243\200\347\264\242/\344\273\243\347\240\201\346\220\234\347\264\242.md"
+++ "b/agent/src/skills/eastmoney/references/\351\200\211\350\202\241\346\243\200\347\264\242/\344\273\243\347\240\201\346\220\234\347\264\242.md"
@@ -5,6 +5,10 @@
- **东财 suggest** —— 中/英文名与代码,跨 A 股/港股/美股,每条带 `<market>.<code>` 形式的 `QuoteID`。
- **Yahoo v1 search** —— 全球代码/公司名(US、HK、crypto、indices、FX…)。
- **SEC EDGAR company-tickers** —— 为解析出的美股权益代码补 0 填充的 CIK。
+FX 对(`GBP/USD`、`GBPUSD`、`GBPUSD=X`)统一归一为 Yahoo `XXXYYY=X` 形式
+(如 `GBPUSD=X`,market `fx`);指数 `^SPX` 形式原样返回(market `index`)。
+归一候选(source `fx_normalizer`)在 Yahoo 节流/故障时也会返回,二次确认
+后可直接传给 `get_market_data`。
市场:多市场。
限速:东财经 `eastmoney` bucket,Yahoo / SEC 各自 host bucket。
diff --git a/agent/src/tools/symbol_search_tool.py b/agent/src/tools/symbol_search_tool.py
index d9f3649a3..e00bc70cf 100644
--- a/agent/src/tools/symbol_search_tool.py
+++ b/agent/src/tools/symbol_search_tool.py
@@ -31,6 +31,11 @@ from typing import Any, Dict, List, Optional
from backtest.loaders import eastmoney_client, sec_edgar_client, yahoo_client
from src.agent.tools import BaseTool
+from src.market_data import FIAT_CODES, canonical_fx_pair
+
+# Back-compat alias: the search tool's historical name for the shared
+# fiat-pair canonicalizer (search, fetch and grounding share one definition).
+_canonical_fx_pair = canonical_fx_pair
logger = logging.getLogger(__name__)
@@ -75,41 +80,6 @@ _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] = {
@@ -334,14 +304,14 @@ def _canonical_crypto_pair(value: str) -> str | None:
matched = _CRYPTO_PAIR_RE.fullmatch(clean)
if matched:
base, quote = matched.group(1), matched.group(2)
- if base in _FIAT_CODES and quote in _FIAT_CODES:
+ 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:
base = clean[: -len(quote)]
- if base in _FIAT_CODES and quote in _FIAT_CODES:
+ 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
diff --git a/agent/tests/test_agent_grounding.py b/agent/tests/test_agent_grounding.py
index aef2ba4b2..d885843de 100644
--- a/agent/tests/test_agent_grounding.py
+++ b/agent/tests/test_agent_grounding.py
@@ -2471,3 +2471,45 @@ def test_a_us_csv_stem_resolves_to_its_venue_suffix() -> None:
assert _symbol_from_csv_filename("GC_F") == "GC=F"
# A bare name has no venue suffix and must stay unresolvable.
assert _symbol_from_csv_filename("AAPL") is None
+
+
+class TestFiatPairAndIndexNormalization:
+ """Search, fetch and grounding agree on one FX spelling; ^ is a symbol."""
+
+ def test_fiat_pair_spellings_normalize_to_yahoo_form(self) -> None:
+ from src.agent.grounding import _normalize_symbol
+
+ assert _normalize_symbol("GBP/USD") == "GBPUSD=X"
+ assert _normalize_symbol("GBPUSD") == "GBPUSD=X"
+ assert _normalize_symbol("GBPUSD=X") == "GBPUSD=X"
+ # Crypto/metals keep their pair form — not fiat/fiat FX.
+ assert _normalize_symbol("ETH/USD") == "ETH-USD"
+ assert _normalize_symbol("XAU/USD") == "XAU-USD"
+
+ def test_scanned_slashed_pair_matches_resolver_answer(self) -> None:
+ """The query-as-asserted scan must agree with the chosen candidate."""
+ from src.agent.grounding import _scan_symbols
+
+ assert _scan_symbols("use GBP/USD spot") == {"GBPUSD=X"}
+
+ def test_index_symbols_are_scanned_and_typed(self) -> None:
+ from src.agent.grounding import (
+ _infer_currency,
+ _infer_instrument_type,
+ _scan_symbols,
+ )
+
+ assert _scan_symbols("quote ^SPX") == {"^SPX"}
+ assert _infer_instrument_type("^SPX", "INDEX") == "index"
+ assert _infer_instrument_type("^SPX") == "index"
+ assert _infer_currency("GBPUSD=X") == "USD"
+
+ def test_ingest_search_symbol_does_not_create_conflicting_identity(self) -> None:
+ """The flagship regression: ingest('GBP/USD') must lock, never conflict."""
+ from src.agent.grounding import _normalize_symbol
+
+ # Chosen (from search_symbol) and asserted (the query text) must be
+ # the same canonical identity — the comparison in _ingest_resolution.
+ chosen = _normalize_symbol("GBPUSD=X")
+ asserted = _scan_symbols("GBP/USD")
+ assert chosen in asserted
diff --git a/agent/tests/test_env_schema.py b/agent/tests/test_env_schema.py
index b7e60664f..3d592b65e 100644
--- a/agent/tests/test_env_schema.py
+++ b/agent/tests/test_env_schema.py
@@ -128,7 +128,7 @@ class TestEnvConfigDefaults:
for market in (
"a_share", "us_equity", "hk_equity", "india_equity", "kr_equity",
"ca_equity", "vietnam_equity", "crypto", "futures", "fund",
- "macro", "forex",
+ "macro", "forex", "index",
):
assert getattr(c.data, f"market_data_order_{market}") == ""
diff --git a/agent/tests/test_market_data.py b/agent/tests/test_market_data.py
index 92e5d9a0d..ac05b56a3 100644
--- a/agent/tests/test_market_data.py
+++ b/agent/tests/test_market_data.py
@@ -57,6 +57,10 @@ 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"), # abbreviated forex pair
("^SPX", "yahoo"), # index (S&P 500)
("^FTSE", "yahoo"), # index (FTSE 100)
("^VIX", "yahoo"),
@@ -106,36 +110,35 @@ def test_forex_pair_x_classifies_as_forex_not_a_share() -> None:
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] = []
+def test_abbreviated_fx_pair_x_classes_as_forex() -> None:
+ """JPY=X (USD/JPY abbreviation) must not fall to the a_share default."""
+ from backtest.engines._market_hooks import _detect_market, code_currency
- 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
- }
+ assert _detect_market("JPY=X") == "forex"
+ assert _detect_market("EUR=X") == "forex"
+ # The hidden base (JPY=X is USD/JPY) is not derivable — honest UNKNOWN,
+ # not a wrong CNY.
+ assert code_currency("JPY=X") == "UNKNOWN:forex"
- 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,
- )
+def test_index_backtest_routes_to_global_equity_not_china_or_crypto() -> None:
+ """^SPX must never reach ChinaAEngine/CryptoEngine through the runner."""
+ from backtest.engines.global_equity import GlobalEquityEngine
+ from backtest.runner import _MARKET_TO_SOURCE, _create_market_engine, _detect_source
- assert "_unresolved" not in out
- assert "^SPX" in out
- assert seen_sources and seen_sources[0] == "yahoo"
+ assert _detect_source("^SPX") == "yahoo"
+ engine = _create_market_engine("yahoo", {}, ["^SPX"])
+ assert isinstance(engine, GlobalEquityEngine)
+
+
+def test_composite_builds_index_rule_engine() -> None:
+ """A mixed book containing an index gets an index sub-engine, not a drop."""
+ from backtest.engines.global_equity import GlobalEquityEngine
+ from backtest.engines.composite import _build_rule_engines
+
+ engines = _build_rule_engines({}, ["^SPX"])
+ assert "index" in engines
+ assert isinstance(engines["index"], GlobalEquityEngine)
def test_yahoo_loader_accepts_futures_and_forex_suffixes() -> None: