Skip to content

"Vibe-Trading: Your Personal Trading Agent"

feat(financial-statements): UK (.L/.IL) statements + indicators via Yahoo

cgycoreydad208123027
diff --git a/agent/src/tools/financial_statements_tool.py b/agent/src/tools/financial_statements_tool.py
index 1cd42531c..63186b75d 100644
--- a/agent/src/tools/financial_statements_tool.py
+++ b/agent/src/tools/financial_statements_tool.py
@@ -29,6 +29,7 @@ import logging
from typing import Any
from backtest.loaders import sec_frames
+from backtest.loaders import yahoo_client
from backtest.loaders.eastmoney_client import get_json, resolve_secid
from backtest.loaders.sec_edgar_client import cik_for, get_company_facts
from src.agent.tools import BaseTool
@@ -289,6 +290,94 @@ def _fetch_eastmoney_statement(
return {"periods": _cap_periods(periods)}
+# Yahoo quoteSummary module + result-key per statement. UK (.L/.IL) names have
+# no Eastmoney or SEC filing pipeline; Yahoo's crumb-gated quoteSummary serves
+# these histories for LSE/ISE tickers (UK parity, #1206).
+_YAHOO_STATEMENT_MODULES: dict[str, tuple[str, str]] = {
+ "balance": ("balanceSheetHistory", "balanceSheetStatements"),
+ "income": ("incomeStatementHistory", "incomeStatementHistory"),
+ "cashflow": ("cashflowStatementHistory", "cashflowStatements"),
+}
+_YAHOO_INDICATOR_MODULES = ["financialData", "defaultKeyStatistics"]
+# {raw, fmt, longFmt} value shapes; keep the numeric raw only.
+_YAHOO_NUMERIC_KEYS = {"raw", "longFmt", "fmt"}
+
+
+def _yahoo_value(value: Any) -> Any:
+ """Flatten a Yahoo ``{raw, fmt, ...}`` value to plain numbers/integers.
+
+ Args:
+ value: A Yahoo quoteSummary value (``{raw, fmt, longFmt}``) or a
+ scalar (``str``/``int``/``float``/``bool``/``None``).
+
+ Returns:
+ The numeric ``raw`` when present (``None`` when raw is missing), or the
+ scalar itself. Text values like ``"2026-08-24"`` pass through.
+ """
+ if isinstance(value, dict):
+ if "raw" in value:
+ return value.get("raw")
+ return {k: _yahoo_value(v) for k, v in value.items() if k not in _YAHOO_NUMERIC_KEYS}
+ return value
+
+
+def _fetch_yahoo_statement(
+ code: str, *, statement: str, period: str
+) -> dict[str, Any]:
+ """Fetch one UK (.L/.IL) statement/indicators from Yahoo quoteSummary.
+
+ Args:
+ code: UK symbol (e.g. ``"VOD.L"`` or ``"DCC.IL"``).
+ statement: One of :data:`_VALID_STATEMENTS`.
+ period: ``"annual"`` or ``"quarter"`` (Yahoo's history is annual-only;
+ a quarter request returns the annual periods, matching Eastmoney's
+ behavior of degrading gracefully when only one cadence exists).
+
+ Returns:
+ ``{"periods": [...]}`` on success or ``{"error": ...}`` on failure;
+ never raises.
+ """
+ del period # Yahoo statement histories are annual; quarterly is a no-op filter
+ if statement == "indicators":
+ modules = _YAHOO_INDICATOR_MODULES
+ else:
+ module, key = _YAHOO_STATEMENT_MODULES[statement]
+ modules = [module]
+ try:
+ result = yahoo_client.get_quote_summary(code, modules)
+ except Exception as exc: # noqa: BLE001 - one bad fetch must not kill the call
+ logger.warning("yahoo statement fetch failed for %s: %s", code, exc)
+ return {"error": str(exc)}
+
+ if statement == "indicators":
+ record: dict[str, Any] = {}
+ for module in modules:
+ block = result.get(module) or {}
+ for field, value in block.items():
+ if field == "maxAge":
+ continue
+ record[field] = _yahoo_value(value)
+ return {"periods": [record]} if record else {"error": "no indicator data"}
+
+ block = result.get(module) or {}
+ rows = block.get(key) or []
+ periods = []
+ for row in rows:
+ if not isinstance(row, dict):
+ continue
+ flat: dict[str, Any] = {}
+ for field, value in row.items():
+ if field in ("maxAge",):
+ continue
+ flat[field] = _yahoo_value(value)
+ if flat:
+ periods.append(flat)
+ if not periods:
+ return {"error": f"Yahoo returned no {statement} history for {code}"}
+ periods.sort(key=lambda row: str(row.get("endDate") or ""), reverse=True)
+ return {"periods": _cap_periods(periods)}
+
+
def _to_number(value: Any) -> float | None:
"""Coerce a numeric provider cell to float, preserving missing values."""
if value in (None, "", "-"):
@@ -568,7 +657,7 @@ def _fetch_sec_statement(code: str, *, statement: str, period: str) -> dict[str,
def _classify_market(code: str) -> str | None:
- """Classify a symbol's suffix into ``a_share``, ``us``, ``hk``, or ``None``.
+ """Classify a symbol's suffix into ``a_share``, ``us``, ``hk``, ``uk``, or ``None``.
Args:
code: Symbol with a market suffix (e.g. ``"600519.SH"``, ``"AAPL.US"``).
@@ -583,6 +672,9 @@ def _classify_market(code: str) -> str | None:
return "us"
if suffix == "HK":
return "hk"
+ if suffix in ("L", "IL"):
+ # London Stock Exchange / Irish Stock Exchange (#1206).
+ return "uk"
return None
@@ -593,9 +685,10 @@ class FinancialStatementsTool(BaseTool):
description = (
"Fetch a single stock's financial statements: balance sheet, income "
"statement, cash-flow statement, or key per-period indicators (margins, "
- "ROE, EPS, etc.). Markets: A-share (.SH/.SZ/.BJ), US (.US) and "
- "Hong Kong (.HK). US uses SEC EDGAR companyfacts; A-share and HK use "
- "Eastmoney. Reports come back newest-first as flat per-period rows. Use "
+ "ROE, EPS, etc.). Markets: A-share (.SH/.SZ/.BJ), US (.US), "
+ "Hong Kong (.HK) and UK/Irish (.L/.IL). US uses SEC EDGAR companyfacts; "
+ "A-share and HK use Eastmoney; UK uses Yahoo quoteSummary (annual "
+ "history). Reports come back newest-first as flat per-period rows. Use "
'this to read fundamentals before building a valuation or screen. Example: '
'{"code": "600519.SH", "statement": "income", "period": "annual"}.'
)
@@ -606,7 +699,7 @@ class FinancialStatementsTool(BaseTool):
"type": "string",
"description": (
"Single symbol with a market suffix, e.g. '600519.SH', "
- "'000001.SZ', 'AAPL.US', or '00700.HK'."
+ "'000001.SZ', 'AAPL.US', '00700.HK', or 'VOD.L'."
),
},
"statement": {
@@ -673,12 +766,15 @@ class FinancialStatementsTool(BaseTool):
market = _classify_market(code)
if market is None:
return _error(
- "code must carry a supported suffix: .SH/.SZ/.BJ, .US, or .HK"
+ "code must carry a supported suffix: .SH/.SZ/.BJ, .US, .HK, or .L/.IL"
)
if market == "us":
result = _fetch_sec_statement(code, statement=statement, period=period)
source = "sec_edgar"
+ elif market == "uk":
+ result = _fetch_yahoo_statement(code, statement=statement, period=period)
+ source = "yahoo"
else:
result = _fetch_eastmoney_statement(
code, statement=statement, period=period
diff --git a/agent/tests/test_financial_statements_tool.py b/agent/tests/test_financial_statements_tool.py
index 15a983162..5a71e561a 100644
--- a/agent/tests/test_financial_statements_tool.py
+++ b/agent/tests/test_financial_statements_tool.py
@@ -359,3 +359,104 @@ class TestErrorEnvelope:
)
assert payload["ok"] is False
assert "period" in payload["error"]
+
+
+class TestUKYahooStatements:
+ """UK (.L/.IL) routes to Yahoo quoteSummary with flattened raw values."""
+
+ _INCOME_PAYLOAD = {
+ "incomeStatementHistory": {
+ "maxAge": 1,
+ "incomeStatementHistory": [
+ {
+ "maxAge": 1,
+ "endDate": 1743379200,
+ "totalRevenue": {"raw": 37448000000, "fmt": "37.45B"},
+ "netIncome": {"raw": -4169000000, "fmt": "-4.17B"},
+ "currencyCode": "GBp",
+ },
+ {
+ "maxAge": 1,
+ "endDate": 1711843200,
+ "totalRevenue": {"raw": 32907000000, "fmt": "32.91B"},
+ "netIncome": {"raw": 1248000000, "fmt": "1.25B"},
+ },
+ ],
+ }
+ }
+
+ def test_uk_income_uses_yahoo_and_flattens_raw_values(self) -> None:
+ with patch(
+ "src.tools.financial_statements_tool.yahoo_client.get_quote_summary",
+ return_value=self._INCOME_PAYLOAD,
+ ) as mock_qs:
+ text = FinancialStatementsTool().execute(
+ code="VOD.L", statement="income", period="annual"
+ )
+
+ payload = json.loads(text)
+ assert payload["ok"] is True
+ assert payload["source"] == "yahoo"
+ assert payload["market"] == "uk"
+ assert mock_qs.call_args.args == ("VOD.L", ["incomeStatementHistory"])
+ periods = payload["data"]["VOD.L"]["periods"]
+ assert periods[0]["endDate"] == 1743379200
+ assert periods[0]["totalRevenue"] == 37448000000
+ assert periods[0]["netIncome"] == -4169000000
+ # Newest first.
+ assert periods[0]["endDate"] > periods[1]["endDate"]
+
+ def test_uk_il_suffix_routes_to_yahoo(self) -> None:
+ with patch(
+ "src.tools.financial_statements_tool.yahoo_client.get_quote_summary",
+ return_value=self._INCOME_PAYLOAD,
+ ) as mock_qs:
+ FinancialStatementsTool().execute(
+ code="DCC.IL", statement="income", period="annual"
+ )
+ assert mock_qs.call_args.args == ("DCC.IL", ["incomeStatementHistory"])
+
+ def test_uk_indicators_flatten_nested_blocks(self) -> None:
+ payload = {
+ "financialData": {
+ "maxAge": 1,
+ "totalRevenue": {"raw": 40461000704, "longFmt": "40,461,000,704"},
+ "grossMargins": {"raw": 0.3147},
+ },
+ "defaultKeyStatistics": {
+ "maxAge": 1,
+ "returnOnEquity": {"raw": 0.00109},
+ "trailingEps": {"raw": -0.17},
+ },
+ }
+ with patch(
+ "src.tools.financial_statements_tool.yahoo_client.get_quote_summary",
+ return_value=payload,
+ ) as mock_qs:
+ text = FinancialStatementsTool().execute(
+ code="VOD.L", statement="indicators", period="annual"
+ )
+
+ payload_out = json.loads(text)
+ assert payload_out["ok"] is True
+ assert mock_qs.call_args.args == (
+ "VOD.L",
+ ["financialData", "defaultKeyStatistics"],
+ )
+ record = payload_out["data"]["VOD.L"]["periods"][0]
+ assert record["totalRevenue"] == 40461000704
+ assert record["grossMargins"] == 0.3147
+ assert record["returnOnEquity"] == 0.00109
+
+ def test_uk_yahoo_failure_surfaces_ok_false(self) -> None:
+ with patch(
+ "src.tools.financial_statements_tool.yahoo_client.get_quote_summary",
+ side_effect=RuntimeError("crumb expired"),
+ ):
+ text = FinancialStatementsTool().execute(
+ code="VOD.L", statement="balance", period="annual"
+ )
+ payload = json.loads(text)
+ assert payload["ok"] is False
+ assert "crumb expired" in payload["error"]
+ assert "crumb expired" in payload["data"]["VOD.L"]["error"]