"Vibe-Trading: Your Personal Trading Agent"
Python ai-agentalgorithmic-tradingbacktestingfintechllmmcpmulti-agentpythonquantitative-financetrading
fix(profile): expose listing identity metadata
Lanre Shittu7a0c3bdb6cb1
diff --git a/agent/src/tools/stock_profile_tool.py b/agent/src/tools/stock_profile_tool.pyindex 32d874cfd..c95d0856b 100644--- a/agent/src/tools/stock_profile_tool.py+++ b/agent/src/tools/stock_profile_tool.py@@ -29,6 +29,10 @@ _SECTION_MODULES: Dict[str, str] = {}_ALL_SECTIONS = tuple(_SECTION_MODULES)+# Always fetched (in addition to the requested sections) to carry Yahoo's own+# listing identity: venue and quote currency, kept separate from fundamentals.+_LISTING_MODULE = "price"+# Cap list-valued sections so a verbose payload cannot bloat the envelope._MAX_ROWS = 25@@ -188,6 +192,43 @@ def _recommendation_trend(module: Dict[str, Any]) -> List[Dict[str, Any]]:return rows+def _listing_identity(+ price_module: Dict[str, Any], financial_module: Dict[str, Any]+) -> Dict[str, Any]:+ """Shape Yahoo-declared listing identity, distinct from issuer fundamentals.++ Only fields the provider explicitly supplies are used here; none of this+ is inferred from the ticker suffix or company name. The underlying-issuer+ relationship is included only when Yahoo's payload names one.++ Args:+ price_module: The raw ``price`` quoteSummary module.+ financial_module: The raw ``financialData`` module, or ``{}`` when+ the ``financials`` section was not requested.++ Returns:+ A compact row with the listing symbol, venue, and quote currency,+ plus ``financial_currency``/``underlying_symbol`` when Yahoo supplies+ them.+ """+ row: Dict[str, Any] = {+ "symbol": price_module.get("symbol"),+ "exchange": price_module.get("exchange"),+ "exchange_name": (+ price_module.get("fullExchangeName") or price_module.get("exchangeName")+ ),+ "quote_type": price_module.get("quoteType"),+ "currency": price_module.get("currency"),+ }+ underlying_symbol = price_module.get("underlyingSymbol")+ if underlying_symbol:+ row["underlying_symbol"] = underlying_symbol+ financial_currency = financial_module.get("financialCurrency")+ if financial_currency:+ row["financial_currency"] = financial_currency+ return row++# Section name -> (yahoo module name, shaper). One entry per supported section._SHAPERS = {"key_stats": _key_stats,@@ -246,9 +287,12 @@ class StockProfileTool(BaseTool):"Argentina (BYMA .BA) ""listing from Yahoo Finance: valuation key statistics, analyst price ""targets and earnings/revenue estimates, institutional and insider "- "ownership, and the analyst recommendation trend. Use this for "- "fundamentals and consensus context, not for OHLCV price bars (use "- "get_market_data). Example: get_stock_profile(ticker=\"AAPL.US\", "+ "ownership, and the analyst recommendation trend. Always includes "+ "the listing's own venue and quote currency, kept separate from "+ "issuer fundamentals so a secondary/international listing does not "+ "read as the primary one. Use this for fundamentals and consensus "+ "context, not for OHLCV price bars (use get_market_data). Example: "+ 'get_stock_profile(ticker="AAPL.US", ''sections=["key_stats", "financials"]).')parameters = {@@ -290,7 +334,10 @@ class StockProfileTool(BaseTool):Returns:A JSON envelope string. On success:``{"ok": true, "market": str, "source": "yahoo",- "data": {"ticker": str, "sections": {<name>: <shaped>}}}``.+ "data": {"ticker": str, "listing": {...}, "sections":+ {<name>: <shaped>}}}``. ``listing`` carries Yahoo's own venue and+ quote-currency identity for the instrument, independent of the+ issuer fundamentals in ``sections``.On failure: ``{"ok": false, "error": str}``."""ticker = str(kwargs.get("ticker") or "").strip()@@ -302,7 +349,9 @@ class StockProfileTool(BaseTool):except ValueError as exc:return self._error(str(exc))- modules = [_SECTION_MODULES[name] for name in sections]+ modules = list(+ dict.fromkeys([_LISTING_MODULE, *(_SECTION_MODULES[n] for n in sections)])+ )try:summary = get_quote_summary(ticker, modules)except Exception as exc: # noqa: BLE001 - surface upstream as envelope@@ -314,12 +363,19 @@ class StockProfileTool(BaseTool):module = summary.get(_SECTION_MODULES[name]) or {}shaped[name] = _SHAPERS[name](module if isinstance(module, dict) else {})+ price_module = summary.get(_LISTING_MODULE) or {}+ financial_module = summary.get(_SECTION_MODULES["financials"]) or {}+ listing = _listing_identity(+ price_module if isinstance(price_module, dict) else {},+ financial_module if isinstance(financial_module, dict) else {},+ )+return json.dumps({"ok": True,"market": _market_for(ticker),"source": "yahoo",- "data": {"ticker": ticker, "sections": shaped},+ "data": {"ticker": ticker, "listing": listing, "sections": shaped},},ensure_ascii=False,)diff --git a/agent/tests/test_stock_profile_tool.py b/agent/tests/test_stock_profile_tool.pyindex 7dc1ad794..ba1d54f3b 100644--- a/agent/tests/test_stock_profile_tool.py+++ b/agent/tests/test_stock_profile_tool.py@@ -14,6 +14,14 @@ from src.tools import stock_profile_tool as spdef _sample_summary() -> dict:return {+ "price": {+ "symbol": "AAPL",+ "exchange": "NMS",+ "exchangeName": "NasdaqGS",+ "fullExchangeName": "NasdaqGS",+ "quoteType": "EQUITY",+ "currency": "USD",+ },"defaultKeyStatistics": {"forwardPE": {"raw": 28.5, "fmt": "28.50"},"trailingEps": {"raw": 6.13},@@ -27,6 +35,7 @@ def _sample_summary() -> dict:"recommendationKey": "buy","numberOfAnalystOpinions": {"raw": 40},"returnOnEquity": {"raw": 1.47},+ "financialCurrency": "USD",},"earningsTrend": {"trend": [@@ -97,6 +106,12 @@ class TestStockProfileSuccess:assert data["ticker"] == "AAPL.US"assert set(data["sections"]) == set(sp._ALL_SECTIONS)+ # Listing identity is independent of, and alongside, the sections.+ assert data["listing"]["symbol"] == "AAPL"+ assert data["listing"]["exchange"] == "NMS"+ assert data["listing"]["currency"] == "USD"+ assert data["listing"]["financial_currency"] == "USD"+# raw cells are unwrapped to scalars.assert data["sections"]["key_stats"]["forwardPE"] == 28.5assert data["sections"]["financials"]["recommendationKey"] == "buy"@@ -118,12 +133,13 @@ class TestStockProfileSuccess:rec = data["sections"]["recommendation_trend"][0]assert rec["strong_buy"] == 12- # Default fans out to all six Yahoo modules.+ # Default fans out to all six Yahoo modules, plus the listing module._, args, kwargs = mock_get.mock_calls[0]requested_modules = args[1]assert "defaultKeyStatistics" in requested_modulesassert "recommendationTrend" in requested_modules- assert len(requested_modules) == len(sp._ALL_SECTIONS)+ assert "price" in requested_modules+ assert len(requested_modules) == len(sp._ALL_SECTIONS) + 1def test_section_subset_only_requests_those_modules(self):with patch.object(@@ -140,7 +156,8 @@ class TestStockProfileSuccess:assert list(payload["data"]["sections"]) == ["financials"]_, args, _ = mock_get.mock_calls[0]- assert args[1] == ["financialData"]+ # Listing module is always requested alongside the chosen sections.+ assert args[1] == ["price", "financialData"]def test_missing_module_yields_empty_shaped_section(self):# Yahoo can omit a module for a symbol; shaper must not crash.@@ -188,3 +205,57 @@ def test_uk_ticker_market_label() -> None:assert _market_for("AAPL.US") == "us"assert _market_for("AAPL") == "us"assert _market_for("00700.HK") == "hk"+++def test_listing_identity_independent_of_fundamentals() -> None:+ """A secondary listing keeps the issuer's fundamentals but its own venue (#1567)."""+ primary_summary = _sample_summary()+ with patch.object(sp, "get_quote_summary", return_value=primary_summary):+ primary = json.loads(sp.StockProfileTool().execute(ticker="AAPL.US"))++ secondary_summary = _sample_summary()+ secondary_summary["price"] = {+ "symbol": "GOOGL.BA",+ "exchange": "BUE",+ "exchangeName": "Buenos Aires",+ "fullExchangeName": "Buenos Aires Stock Exchange",+ "quoteType": "EQUITY",+ "currency": "ARS",+ }+ with patch.object(sp, "get_quote_summary", return_value=secondary_summary):+ secondary = json.loads(sp.StockProfileTool().execute(ticker="GOOGL.BA"))++ # Same issuer fundamentals regardless of listing.+ assert primary["data"]["sections"] == secondary["data"]["sections"]++ # Listing identity is independently available and reflects the venue.+ assert primary["data"]["listing"]["currency"] == "USD"+ assert secondary["data"]["listing"]["currency"] == "ARS"+ assert (+ primary["data"]["listing"]["exchange"]+ != secondary["data"]["listing"]["exchange"]+ )+++def test_listing_identity_omits_financial_currency_when_not_fetched() -> None:+ """financial_currency is only surfaced when the financials module is fetched."""+ summary = _sample_summary()+ del summary["financialData"]+ with patch.object(sp, "get_quote_summary", return_value=summary):+ out = sp.StockProfileTool().execute(ticker="AAPL.US", sections=["key_stats"])++ listing = json.loads(out)["data"]["listing"]+ assert "financial_currency" not in listing+++def test_listing_identity_underlying_symbol_only_when_yahoo_supplies_it() -> None:+ """The underlying-issuer link is never inferred, only passed through (#1567)."""+ summary = _sample_summary()+ with patch.object(sp, "get_quote_summary", return_value=summary):+ out = sp.StockProfileTool().execute(ticker="AAPL.US")+ assert "underlying_symbol" not in json.loads(out)["data"]["listing"]++ summary["price"]["underlyingSymbol"] = "AAPL"+ with patch.object(sp, "get_quote_summary", return_value=summary):+ out = sp.StockProfileTool().execute(ticker="AAPL.US")+ assert json.loads(out)["data"]["listing"]["underlying_symbol"] == "AAPL"