"Vibe-Trading: Your Personal Trading Agent"
Python ai-agentalgorithmic-tradingbacktestingfintechllmmcpmulti-agentpythonquantitative-financetrading
fix(etf-holdings): accept the .US suffix when matching SEC tickers
Jackzigen52319a51b23b
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex dbd18dbaf..defc2a4e2 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -13,6 +13,9 @@ This project adheres to [Semantic Versioning](https://semver.org/).only place that disagreed: the identity lock then rejected the follow-up call("consumer symbol/venue differs from the locked resolver identity"). ETFs andmutual funds on non-US venues keep their native form (#2084).+- **`etf_holdings` accepts the `.US` market suffix** on US symbols, so the+ identity locked as `QQQ.US` still reaches the SEC series/class ticker `QQQ`+ instead of being reported as an unknown share class.- **Global futures routing and pricing**: digit-bearing contracts such as`M2K=F` and `6EZ2026.CME`, including `local:` inputs, reach the globalfutures engine with their full product code. OJ and ZR use quote-unitdiff --git a/agent/src/tools/etf_holdings_tool.py b/agent/src/tools/etf_holdings_tool.pyindex 517badb60..ac71f90a9 100644--- a/agent/src/tools/etf_holdings_tool.py+++ b/agent/src/tools/etf_holdings_tool.py@@ -467,6 +467,23 @@ def _is_etf_class(record: dict[str, Any]) -> bool:return "ETF" in f"{record.get('series_name') or ''} {record.get('class_name') or ''}".upper()+def _bare_us_ticker(query: str) -> str:+ """Drop the project's ``.US`` suffix so SEC tickers line up.++ The resolver publishes US listings as ``<SYM>.US`` (see+ ``symbol_search_tool._from_yahoo_symbol``), while the SEC series/class+ index stores bare tickers. Without this fold an identical fund looks up as+ ``QQQ.US`` and is reported as "not a fund share class".++ Args:+ query: A ticker, optionally carrying the ``.US`` market suffix.++ Returns:+ The upper-cased ticker with any ``.US`` suffix removed.+ """+ return query.strip().upper().removesuffix(".US")++def _us_match(query: str, limit: int) -> list[dict[str, Any]]:"""Find fund share classes by exact ticker, then by name substring.@@ -485,7 +502,7 @@ def _us_match(query: str, limit: int) -> list[dict[str, Any]]:ahead of other classes."""_, records = _us_series_index()- needle = query.strip().upper()+ needle = _bare_us_ticker(query)exact = [r for r in records if r["ticker"] == needle]if len(exact) >= limit:return exact[:limit]@@ -1363,7 +1380,7 @@ def _holdings_us(symbol: str, top_n: int, offset: int) -> str:matches = _us_match(symbol, 1)except Exception as exc: # noqa: BLE001 - surface as envelopereturn _error(f"SEC series/class index lookup failed: {exc}")- if not matches or matches[0]["ticker"] != symbol.strip().upper():+ if not matches or matches[0]["ticker"] != _bare_us_ticker(symbol):return _error(f"'{symbol}' is not a fund share class in the SEC series/class index. ""Note that unit investment trusts (SPY among them) do not appear there "diff --git a/agent/src/tools/symbol_search_tool.py b/agent/src/tools/symbol_search_tool.pyindex 92ac1654f..ff3d99708 100644--- a/agent/src/tools/symbol_search_tool.py+++ b/agent/src/tools/symbol_search_tool.py@@ -165,10 +165,9 @@ _MARKET_BY_SUFFIX: Dict[str, str] = {"VN": "vn",}-# Quote types Yahoo carries bare for US listings, in addition to equities.-# ETFs and mutual funds are plain US tickers over there (``QQQ``, ``SPY``,-# ``VFIAX``) and the data layer already treats a bare ticker as ``us_equity``;-# only the resolver disagreed, which is what #2084 reported.+# Quote types Yahoo lists under a plain US ticker (``QQQ``, ``SPY``, ``VFIAX``).+# The data layer already treats a bare ticker as ``us_equity``; only the+# resolver used to disagree, which is what #2084 reported._US_LISTED_QUOTE_TYPES = frozenset({"EQUITY", "ETF", "MUTUALFUND"})# Yahoo exchange codes for US venues. Used only to keep a bare symbol that@@ -179,15 +178,17 @@ _US_YAHOO_EXCHANGES = frozenset("NMS", # Nasdaq Global Select"NGM", # Nasdaq Global Market"NCM", # Nasdaq Capital Market- "NAS",+ "NAS", # Nasdaq (unspecified tier)"NYQ", # NYSE+ "NYE", # NYSE (older payload spelling)"PCX", # NYSE Arca (most ETFs)"ASE", # NYSE American"BTS", # Cboe BZX"OQX", # OTCQX"OQB", # OTCQB+ "OBB", # OTC Bulletin Board"PNK", # Pink Sheets- "OTC",+ "OTC", # OTC (unspecified tier)})@@ -861,8 +862,10 @@ def _from_yahoo_symbol(raw_symbol: str, quote: Dict[str, Any]) -> tuple[str, strArgs:raw_symbol: The Yahoo-side symbol (e.g. ``AAPL``, ``0700.HK``,``TD.TO``, ``PNG.V``, or ``BTC-USD``).- quote: The full Yahoo quote, used to distinguish a bare US equity from a- crypto/index instrument via ``quoteType``.+ quote: The full Yahoo quote, used to classify the instrument via+ ``quoteType`` (bare US equity/ETF/fund vs crypto/index/FX) and to+ keep a bare symbol filed under a non-US venue on its native form+ via ``exchange``.Returns:``(symbol, market)`` in the project convention.diff --git a/agent/tests/test_etf_holdings_tool.py b/agent/tests/test_etf_holdings_tool.pyindex 6fa27b3b6..f2798e730 100644--- a/agent/tests/test_etf_holdings_tool.py+++ b/agent/tests/test_etf_holdings_tool.py@@ -450,6 +450,14 @@ class TestUsHoldings:assert "balance" not in holdings[1]assert "ticker" not in holdings[0]+ def test_a_us_suffixed_symbol_still_reaches_the_sec_ticker(self):+ # The resolver publishes US listings as ``<SYM>.US``, so callers pass+ # the suffixed form back in; the SEC index only knows bare tickers.+ with patch.object(etf, "_sec_get_text", side_effect=_sec_router):+ payload = json.loads(EtfHoldingsTool().execute(mode="holdings", symbol="IVV.US"))+ assert payload["ok"] is True+ assert payload["data"]["symbol"] == "IVV"+def test_series_mismatch_refuses_to_attribute_the_filing(self):def router(url, params=None):if "primary_doc" in url:@@ -519,6 +527,11 @@ class TestUsLookup:records = etf._parse_series_index(_SERIES_CSV)assert {r["ticker"] for r in records} == {"IVV", "SOXX"}+ def test_a_us_suffixed_query_still_matches_the_ticker(self):+ with patch.object(etf, "_sec_get_text", side_effect=_sec_router):+ payload = json.loads(EtfHoldingsTool().execute(mode="lookup", query="SOXX.US"))+ assert payload["data"]["matches"][0]["ticker"] == "SOXX"+def test_etf_share_classes_outrank_mutual_fund_classes_on_a_theme_query(self):# Live check: "semiconductor" matches 31 classes, and in filer order the# first eight are Fidelity mutual fund classes, so an unranked defaultdiff --git a/agent/tests/test_symbol_search_tool.py b/agent/tests/test_symbol_search_tool.pyindex ff94bd52a..22a55ad3a 100644--- a/agent/tests/test_symbol_search_tool.py+++ b/agent/tests/test_symbol_search_tool.py@@ -956,6 +956,8 @@ class TestBareUsEtfResolution:("QQQ", {"quoteType": "ETF", "exchange": "NGM"}),("SPY", {"quoteType": "ETF", "exchange": "PCX"}),("VFIAX", {"quoteType": "MUTUALFUND", "exchange": "NAS"}),+ # OTC Bulletin Board listings are US listings too.+ ("ABCD", {"quoteType": "ETF", "exchange": "OBB"}),# Search payloads do not always carry an exchange row.("QQQ", {"quoteType": "ETF"}),],@@ -972,6 +974,16 @@ class TestBareUsEtfResolution:"XIC", {"quoteType": "ETF", "exchange": "TOR"}) == ("XIC", "global")+ def test_bare_equity_on_foreign_venue_is_not_us(self) -> None:+ """A bare non-US equity must not be relabelled as a US listing.++ Before the exchange guard, every bare ``EQUITY`` became ``<SYM>.US``,+ so ``RY`` (Toronto) was published as a US ticker.+ """+ assert ss._from_yahoo_symbol(+ "RY", {"quoteType": "EQUITY", "exchange": "TOR"}+ ) == ("RY", "global")+def test_crypto_and_index_unchanged(self) -> None:assert ss._from_yahoo_symbol("BTC-USD", {"quoteType": "CRYPTOCURRENCY"}@@ -996,7 +1008,9 @@ class TestBareUsEtfResolution:ss.eastmoney_client,"get_json",return_value={"QuotationCodeTable": {"Data": []}},- ), patch.object(ss.yahoo_client, "search", return_value=quotes):+ ), patch.object(ss.yahoo_client, "search", return_value=quotes), patch.object(+ ss.sec_edgar_client, "cik_for", return_value=None+ ):data = json.loads(ss.SymbolSearchTool().execute(query="QQQ"))["data"]row = next(c for c in data["candidates"] if c["symbol"] == "QQQ.US")