"Vibe-Trading: Your Personal Trading Agent"
Python ai-agentalgorithmic-tradingbacktestingfintechllmmcpmulti-agentpythonquantitative-financetrading
fix(tools): route US statements to SEC EDGAR
Haozhe Wub4430b3b402b
diff --git a/agent/src/skills/data-routing/SKILL.md b/agent/src/skills/data-routing/SKILL.mdindex 8193a3aff..0f21cdd99 100644--- a/agent/src/skills/data-routing/SKILL.md+++ b/agent/src/skills/data-routing/SKILL.md@@ -66,9 +66,9 @@ is required only where listed (no key listed = free / no auth).| iWenCai NL search (问财) | `iwencai_search` | A-share | `VIBE_TRADING_IWENCAI_KEY` |Notes:-- `get_financial_statements` reads A-share, US, and HK statements via the- Eastmoney datacenter report API (per-market F10 report names) — an IP-throttled- client, not the OHLCV loader of the same name.+- `get_financial_statements` reads US statements from SEC EDGAR companyfacts+ (ticker -> CIK -> XBRL concepts) and A-share/HK statements from the Eastmoney+ datacenter report API (per-market F10 report names).- `get_stock_news` routes A-share (SH/SZ/BJ) to an Eastmoney news client andUS (.US) / HK (.HK) to a Yahoo search client; a failure on one upstream isreturned as an error envelope, never raised, so a single bad symbol neverdiff --git a/agent/src/skills/eastmoney/SKILL.md b/agent/src/skills/eastmoney/SKILL.mdindex b6e9c29ea..08e652a16 100644--- a/agent/src/skills/eastmoney/SKILL.md+++ b/agent/src/skills/eastmoney/SKILL.md@@ -1,7 +1,7 @@---name: eastmoneycategory: data-source-description: 东方财富(Eastmoney)免费免鉴权数据接口,覆盖资金流向、龙虎榜、融资融券、大宗交易、股东户数、限售解禁、行业概念板块、券商研报、财经新闻、美股/港股三大报表+主要指标、全市场选股与代码搜索。所有请求经共享 IP 限速层节流(东财按源 IP 限流并临时封禁突发请求),通过 Vibe-Trading 工具直接调用,无需 token。+description: 东方财富(Eastmoney)免费免鉴权数据接口,覆盖资金流向、龙虎榜、融资融券、大宗交易、股东户数、限售解禁、行业概念板块、券商研报、财经新闻、A股/港股三大报表+主要指标、全市场选股与代码搜索;美股财报由 get_financial_statements 转 SEC EDGAR。东财请求经共享 IP 限速层节流(东财按源 IP 限流并临时封禁突发请求),通过 Vibe-Trading 工具直接调用,无需 token。---# Eastmoney(东方财富)@@ -45,7 +45,7 @@ resolve_secid("AAPL.US") # -> "105.AAPL"(经 suggest 端点解析并进程- [资金流向 + 板块联动研究](eastmoney/scripts/fund_flow_example.py)- [龙虎榜 + 大宗交易 + 融资融券披露面研究](eastmoney/scripts/disclosure_example.py)-- [研报舆情 + 美股/港股财报基本面研究](eastmoney/scripts/fundamentals_example.py)+- [研报舆情 + 财报基本面研究](eastmoney/scripts/fundamentals_example.py)- [代码搜索 + 全市场选股](eastmoney/scripts/screen_search_example.py)## 接口列表@@ -84,11 +84,11 @@ resolve_secid("AAPL.US") # -> "105.AAPL"(经 suggest 端点解析并进程| `get_research_reports` | [券商研报](eastmoney/references/研报舆情/券商研报.md) | A股 | 券商研报列表(标题/机构/分析师/评级/EPS·PE 预测)+ 同花顺一致预期 EPS || `get_stock_news` | [财经新闻](eastmoney/references/研报舆情/财经新闻.md) | A股/港股/美股 | 个股新闻或全市场财经快讯(A 股走东财,美/港走 Yahoo) |-### 财务报表(美股 / 港股)+### 财务报表(A 股 / 港股;美股走 SEC)| 工具 | 标题(详细文档) | 市场 | 描述 || ---- | -------------- | ---- | ---- |-| `get_financial_statements` | [三大报表与主要指标](eastmoney/references/财务报表/三大报表与主要指标.md) | 美股/港股(东财)·A股(新浪) | 资产负债表/利润表/现金流量表/主要指标(GMAININDICATOR) |+| `get_financial_statements` | [三大报表与主要指标](eastmoney/references/财务报表/三大报表与主要指标.md) | A股/港股(东财)·美股(SEC EDGAR) | 资产负债表/利润表/现金流量表/主要指标;美股不再走东财 |### 选股检索diff --git "a/agent/src/skills/eastmoney/references/\350\264\242\345\212\241\346\212\245\350\241\250/\344\270\211\345\244\247\346\212\245\350\241\250\344\270\216\344\270\273\350\246\201\346\214\207\346\240\207.md" "b/agent/src/skills/eastmoney/references/\350\264\242\345\212\241\346\212\245\350\241\250/\344\270\211\345\244\247\346\212\245\350\241\250\344\270\216\344\270\273\350\246\201\346\214\207\346\240\207.md"index b2252de8c..0b2ae92a4 100644--- "a/agent/src/skills/eastmoney/references/\350\264\242\345\212\241\346\212\245\350\241\250/\344\270\211\345\244\247\346\212\245\350\241\250\344\270\216\344\270\273\350\246\201\346\214\207\346\240\207.md"+++ "b/agent/src/skills/eastmoney/references/\350\264\242\345\212\241\346\212\245\350\241\250/\344\270\211\345\244\247\346\212\245\350\241\250\344\270\216\344\270\273\350\246\201\346\214\207\346\240\207.md"@@ -2,11 +2,11 @@工具:`get_financial_statements`(`src.tools.financial_statements_tool.FinancialStatementsTool`)描述:取单只股票的资产负债表 / 利润表 / 现金流量表 / 主要指标,按 symbol 后缀选上游:-- **美股(.US)与港股(.HK)** —— 东财 datacenter 报表接口;三大报表来自分市场财报数据集,`indicators` 读主要指标数据集(GMAININDICATOR)。-- **A 股(.SH / .SZ / .BJ)** —— 新浪 `quotes.sina.cn` 公司财务 openapi(`sina` host bucket 节流)。+- **美股(.US)** —— SEC EDGAR companyfacts:ticker 解析到 CIK,再读取 XBRL us-gaap concepts,聚合成逐期扁平行。+- **A 股(.SH / .SZ / .BJ)与港股(.HK)** —— 东财 datacenter 报表接口;三大报表来自分市场财报数据集,`indicators` 读主要指标数据集(GMAININDICATOR)。报表以"最新在前"的扁平逐期行返回。-市场:美股/港股(东财)、A 股(新浪)。-限速:东财经 `eastmoney`、新浪经 `sina`,均 per-host 节流。+市场:美股(SEC EDGAR)、A 股/港股(东财)。+限速:SEC 经 `sec` bucket,东财经 `eastmoney` bucket,均 per-host 节流。<br>@@ -14,19 +14,19 @@| 市场 | 端点 || ---- | ---- |-| 美股/港股 | `https://datacenter.eastmoney.com/securities/api/data/v1/get` |-| A 股 | `https://quotes.sina.cn/cn/api/openapi.php/CompanyFinanceService.<method>` |+| 美股 | `https://data.sec.gov/api/xbrl/companyfacts/CIK##########.json` |+| A 股/港股 | `https://datacenter.eastmoney.com/securities/api/data/v1/get` |**东财 reportName(market_group → statement → reportName)**-statement | us(105/106/107) | hk(116)+statement | a(0/1) | hk(116)---- | ---- | -----balance | `RPT_USF10_FN_BALANCE` | `RPT_HKF10_FN_BALANCE`-income | `RPT_USF10_FN_INCOME` | `RPT_HKF10_FN_INCOME`-cashflow | `RPT_USF10_FN_CASHFLOW` | `RPT_HKF10_FN_CASHFLOW`-indicators | `RPT_USF10_FN_GMAININDICATOR` | `RPT_HKF10_FN_GMAININDICATOR`+balance | `RPT_F10_FINANCE_GBALANCE` | `RPT_HKF10_FN_BALANCE`+income | `RPT_F10_FINANCE_GINCOME` | `RPT_HKF10_FN_INCOME`+cashflow | `RPT_F10_FINANCE_GCASHFLOW` | `RPT_HKF10_FN_CASHFLOW`+indicators | `RPT_F10_FINANCE_MAINFINADATA` | `RPT_HKF10_FN_GMAININDICATOR`-**新浪 method(A 股)**:balance=`getBalanceSheet`、income=`getProfitStatement`、cashflow=`getCashFlow`、indicators=`getFinanceIndex`。+**SEC concepts(美股)**:按 statement 读取一组常见 us-gaap concepts,例如 income 包含 `Revenues` / `RevenueFromContractWithCustomerExcludingAssessedTax` / `NetIncomeLoss` / EPS,balance 包含 `Assets` / `Liabilities` / `StockholdersEquity`,cashflow 包含经营/投资/融资现金流。缺失 concept 会被跳过,不使整个工具失败。<br>@@ -42,16 +42,16 @@ period | str | N | `annual`(年报)或 `quarter`(季报),默认 `annua**端点查询参数**-东财:`reportName=<上表>`、`columns=ALL`、`filter=(SECURITY_CODE="<bare>")(REPORT_TYPE="0"|"1")`(annual=0 / quarter=1)、`sortColumns=REPORT_DATE`、`sortTypes=-1`、`pageNumber=1`、`pageSize=40`、`source=F10`、`client=PC`。-新浪:`symbol=<sh/sz/bj+code>`、`paperType=1`(年)|`2`(季)、`num=40`;headers 带 `Referer: https://quotes.sina.cn/`。+SEC:先查 ticker->CIK,再取 companyfacts;`annual` 保留 `fp=FY` 或 `form=10-K` 的点,`quarter` 返回完整逐期点。+东财:`reportName=<上表>`、`columns=ALL`、A 股 `filter=(SECUCODE="<code>")`,港股 `filter=(SECURITY_CODE="<bare>")`,`sortColumns=REPORT_DATE`、`sortTypes=-1`、`pageNumber=1`、`pageSize=40`、`source=F10`、`client=PC`。<br>**返回字段**-报表逐期行为扁平 `字段名 → 值` 的原始 provider 字段(东财用 SECURITY_CODE/REPORT_DATE/REPORT_TYPE 等英文键,新浪用其 openapi 键),工具**不重命名透传**。防爆上限:每只股票最多 40 期,每期最多 200 个字段。+报表逐期行为扁平 `字段名 → 值`。A 股/港股保留东财原始字段;美股逐期行包含 `REPORT_DATE` / `FISCAL_YEAR` / `FISCAL_PERIOD` / `FORM` / `ACCESSION`,以及 us-gaap concept 名称和值,`_units` 记录每个 concept 的单位。防爆上限:每只股票最多 40 期,每期最多 200 个字段。-信封:`{"ok": true, "market": "a_share"|"us"|"hk", "source": "sina"|"eastmoney", "statement": <statement>, "period": <period>, "data": {code: {"periods": [...]} | {"error": ...}}}`。单只 symbol 失败以 per-symbol `error` 上报,不抛异常。+信封:`{"ok": true, "market": "a_share"|"us"|"hk", "source": "sec_edgar"|"eastmoney", "statement": <statement>, "period": <period>, "data": {code: {"periods": [...]} | {"error": ...}}}`。单只 symbol 失败以 per-symbol `error` 上报,不抛异常。<br>@@ -64,6 +64,6 @@ from src.tools.financial_statements_tool import FinancialStatementsToolprint(FinancialStatementsTool().execute(code="AAPL.US", statement="income", period="annual"))# 港股主要指标(GMAININDICATOR)print(FinancialStatementsTool().execute(code="00700.HK", statement="indicators"))-# A 股资产负债表(新浪)+# A 股资产负债表(东财)print(FinancialStatementsTool().execute(code="600519.SH", statement="balance"))```diff --git a/agent/src/skills/eastmoney/scripts/fundamentals_example.py b/agent/src/skills/eastmoney/scripts/fundamentals_example.pyindex 374815855..75d263953 100644--- a/agent/src/skills/eastmoney/scripts/fundamentals_example.py+++ b/agent/src/skills/eastmoney/scripts/fundamentals_example.py@@ -1,9 +1,10 @@#!/usr/bin/env python3# -*- coding: utf-8 -*--"""研报舆情 + 美股/港股财报基本面研究示例。+"""研报舆情 + 跨源财报基本面研究示例。运行前提:在 agent/ 目录下执行(导入根为 agent/)。无需 token。-研报/财报经东方财富(及新浪/同花顺)共享 IP 限速层节流。+研报走东方财富;财报由 get_financial_statements 按市场路由+(美股 SEC EDGAR,A 股/港股东财),并经共享 per-host 限速层节流。"""import json@@ -26,7 +27,7 @@ def broker_consensus(code: str, limit: int = 10) -> None:def us_hk_indicators(code: str) -> None:- """打印美股/港股主要指标(GMAININDICATOR)的最新报告期。"""+ """打印美股/港股主要指标的最新报告期。"""envelope = json.loads(FinancialStatementsTool().execute(code=code, statement="indicators", period="annual"diff --git a/agent/src/tools/financial_statements_tool.py b/agent/src/tools/financial_statements_tool.pyindex 9aa98a404..5561e63d7 100644--- a/agent/src/tools/financial_statements_tool.py+++ b/agent/src/tools/financial_statements_tool.py@@ -1,21 +1,21 @@"""Read-only financial-statements tool: three statements + key indicators.Pulls a single stock's balance sheet, income statement, cash-flow statement, or-key per-period indicators from Eastmoney's free, no-auth datacenter report API,-picking the per-market report dataset from the symbol's market suffix:+key per-period indicators from a market-appropriate public source:* **A-share** (``.SH`` / ``.SZ`` / ``.BJ``) — Eastmoney's A-share F10 reportdatasets (``RPT_F10_FINANCE_*``), filtered on the dotted ``SECUCODE`` (e.g.``600519.SH``). The legacy Sina ``quotes.sina.cn`` company-finance openapireturned a graceful-empty masking an upstream failure, so the A-share path now- shares the Eastmoney transport with US/HK.-* **US** (``.US``) and **Hong Kong** (``.HK``) — Eastmoney's per-market F10- financial-report datasets, filtered on the bare ``SECURITY_CODE``; ``indicators``- reads the main-indicator dataset.+ shares the Eastmoney transport with HK.+* **US** (``.US``) — SEC EDGAR companyfacts XBRL, resolved by ticker->CIK.+* **Hong Kong** (``.HK``) — Eastmoney's HK F10 financial-report datasets,+ filtered on the bare ``SECURITY_CODE``; ``indicators`` reads the+ main-indicator dataset.-All requests go through :func:`backtest.loaders.eastmoney_client.get_json`-(Eastmoney bans bursting clients, so every call is throttled under-``host_key="eastmoney"``).+Eastmoney requests go through :func:`backtest.loaders.eastmoney_client.get_json`+(``host_key="eastmoney"``); SEC requests go through the shared EDGAR client+(``host_key="sec"``).The tool is read-only and self-contained: ``execute`` returns a JSON-stringenvelope and never raises for a recoverable per-request failure — a bad symbol@@ -29,6 +29,7 @@ import loggingfrom typing import Anyfrom backtest.loaders.eastmoney_client import get_json, resolve_secid+from backtest.loaders.sec_edgar_client import cik_for, get_company_factsfrom src.agent.tools import BaseToollogger = logging.getLogger(__name__)@@ -36,11 +37,11 @@ logger = logging.getLogger(__name__)# --- Eastmoney datacenter report API --------------------------------------# Eastmoney datacenter report API. The three statements and the main-indicator-# dataset are addressed by report name, which differs by market (A / US / HK).+# dataset are addressed by report name, which differs by market (A / HK)._EM_REPORT_URL = "https://datacenter.eastmoney.com/securities/api/data/v1/get"# (market_prefix_group, statement) -> Eastmoney report name. ``a`` covers the-# mainland exchanges (markets 0/1); ``us`` covers 105/106/107; ``hk`` covers 116.+# mainland exchanges (markets 0/1); ``hk`` covers 116._EM_REPORT_NAME: dict[str, dict[str, str]] = {"a": {"balance": "RPT_F10_FINANCE_GBALANCE",@@ -48,12 +49,6 @@ _EM_REPORT_NAME: dict[str, dict[str, str]] = {"cashflow": "RPT_F10_FINANCE_GCASHFLOW","indicators": "RPT_F10_FINANCE_MAINFINADATA",},- "us": {- "balance": "RPT_USF10_FN_BALANCE",- "income": "RPT_USF10_FN_INCOME",- "cashflow": "RPT_USF10_FN_CASHFLOW",- "indicators": "RPT_USF10_FN_GMAININDICATOR",- },"hk": {"balance": "RPT_HKF10_FN_BALANCE","income": "RPT_HKF10_FN_INCOME",@@ -62,12 +57,48 @@ _EM_REPORT_NAME: dict[str, dict[str, str]] = {},}-# Eastmoney mainland A-share markets (SZ/BJ = 0, SH = 1), US markets-# (NASDAQ / NYSE / AMEX), and the HK market.+# Eastmoney mainland A-share markets (SZ/BJ = 0, SH = 1) and the HK market._EM_A_MARKETS = ("0", "1")-_EM_US_MARKETS = ("105", "106", "107")_EM_HK_MARKET = "116"+_SEC_CONCEPTS: dict[str, tuple[str, ...]] = {+ "balance": (+ "Assets",+ "AssetsCurrent",+ "CashAndCashEquivalentsAtCarryingValue",+ "Liabilities",+ "LiabilitiesCurrent",+ "LongTermDebtAndFinanceLeaseObligationsCurrentAndNoncurrent",+ "StockholdersEquity",+ ),+ "income": (+ "Revenues",+ "RevenueFromContractWithCustomerExcludingAssessedTax",+ "GrossProfit",+ "OperatingIncomeLoss",+ "NetIncomeLoss",+ "EarningsPerShareBasic",+ "EarningsPerShareDiluted",+ ),+ "cashflow": (+ "NetCashProvidedByUsedInOperatingActivities",+ "NetCashProvidedByUsedInInvestingActivities",+ "NetCashProvidedByUsedInFinancingActivities",+ "PaymentsToAcquirePropertyPlantAndEquipment",+ "CashCashEquivalentsRestrictedCashAndRestrictedCashEquivalentsPeriodIncreaseDecreaseIncludingExchangeRateEffect",+ ),+ "indicators": (+ "Revenues",+ "RevenueFromContractWithCustomerExcludingAssessedTax",+ "NetIncomeLoss",+ "Assets",+ "Liabilities",+ "StockholdersEquity",+ "EarningsPerShareDiluted",+ "WeightedAverageNumberOfDilutedSharesOutstanding",+ ),+}+# --- Shared limits / validation ------------------------------------------_VALID_STATEMENTS = ("balance", "income", "cashflow", "indicators")@@ -120,21 +151,17 @@ def _cap_periods(periods: list[dict[str, Any]]) -> list[dict[str, Any]]:def _eastmoney_market_group(secid: str) -> str | None:- """Classify an Eastmoney secid into the ``a``, ``us``, or ``hk`` report group.+ """Classify an Eastmoney secid into the ``a`` or ``hk`` report group.Args:- secid: Eastmoney secid (e.g. ``"1.600519"``, ``"105.AAPL"`` or- ``"116.00700"``).+ secid: Eastmoney secid (e.g. ``"1.600519"`` or ``"116.00700"``).Returns:- ``"a"``, ``"us"``, ``"hk"``, or ``None`` when the market prefix is- unrecognized.+ ``"a"``, ``"hk"``, or ``None`` when the market prefix is unrecognized."""market = secid.split(".", 1)[0]if market in _EM_A_MARKETS:return "a"- if market in _EM_US_MARKETS:- return "us"if market == _EM_HK_MARKET:return "hk"return None@@ -165,8 +192,8 @@ def _eastmoney_filter(group: str, code: str, secid: str) -> str:"""Build the datacenter ``filter`` clause for one market group.The A-share F10 datasets key on the dotted ``SECUCODE`` (e.g.- ``600519.SH``), whereas the US/HK datasets key on the bare ``SECURITY_CODE``- carried in the secid (e.g. ``AAPL`` / ``00700``). No ``REPORT_TYPE`` clause+ ``600519.SH``), whereas the HK datasets key on the bare ``SECURITY_CODE``+ carried in the secid (e.g. ``00700``). No ``REPORT_TYPE`` clauseis emitted: Eastmoney stores ``REPORT_TYPE`` as locale text (年报 / 一季报)or a ``2026/Q1`` string that differs by market and report, so a numericfilter matched zero rows. Period selection is done client-side instead@@ -193,7 +220,7 @@ def _filter_by_period(Eastmoney returns a mixed newest-first series (annual + interim reports).For ``annual`` we keep only fiscal-year-end rows (``REPORT_DATE`` ending- ``-12-31``); if none match — e.g. a US issuer whose fiscal year does not end+ ``-12-31``); if none match — e.g. an issuer whose fiscal year does not endin December — we fall back to the full series rather than drop all data.``quarter`` returns the full newest-first series unchanged.@@ -217,10 +244,10 @@ def _filter_by_period(def _fetch_eastmoney_statement(code: str, *, statement: str, period: str) -> dict[str, Any]:- """Fetch one A-share/US/HK statement from Eastmoney, shaped into a result dict.+ """Fetch one A-share/HK statement from Eastmoney, shaped into a result dict.Args:- code: Symbol (e.g. ``"600519.SH"``, ``"AAPL.US"`` or ``"00700.HK"``).+ code: Symbol (e.g. ``"600519.SH"`` or ``"00700.HK"``).statement: One of :data:`_VALID_STATEMENTS`.period: ``"annual"`` or ``"quarter"``.@@ -234,7 +261,7 @@ def _fetch_eastmoney_statement(group = _eastmoney_market_group(secid)if group is None:- return {"error": "symbol is not an A-share, US, or Hong Kong instrument"}+ return {"error": "symbol is not an A-share or Hong Kong instrument"}params = {"reportName": _EM_REPORT_NAME[group][statement],@@ -257,6 +284,102 @@ def _fetch_eastmoney_statement(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, "", "-"):+ return None+ try:+ return float(value)+ except (TypeError, ValueError):+ return None+++def _pick_sec_unit(units: dict[str, Any]) -> tuple[str, list[Any]]:+ """Pick the SEC XBRL unit bucket with the most reported rows."""+ best_key = ""+ best_rows: list[Any] = []+ for key, rows in units.items():+ if isinstance(rows, list) and len(rows) >= len(best_rows):+ best_key, best_rows = str(key), rows+ return best_key, best_rows+++def _sec_period_matches(row: dict[str, Any], period: str) -> bool:+ """Return whether a SEC fact row belongs in the requested cadence."""+ if period != "annual":+ return True+ fp = str(row.get("fp") or "").upper()+ form = str(row.get("form") or "").upper()+ return fp == "FY" or form == "10-K"+++def _fetch_sec_statement(code: str, *, statement: str, period: str) -> dict[str, Any]:+ """Fetch one US statement from SEC companyfacts, shaped as flat periods.++ Args:+ code: US symbol with ``.US`` suffix, e.g. ``"AAPL.US"``.+ statement: One of :data:`_VALID_STATEMENTS`.+ period: ``"annual"`` or ``"quarter"``.++ Returns:+ ``{"periods": [...]}`` on success or ``{"error": ...}`` on failure.+ """+ ticker = code.rsplit(".", 1)[0].strip().upper()+ try:+ cik = cik_for(ticker)+ except Exception as exc: # noqa: BLE001 - surface provider failures as envelope+ logger.warning("SEC ticker lookup failed for %s: %s", code, exc)+ return {"error": f"SEC ticker lookup failed: {exc}"}+ if not cik:+ return {"error": "ticker not found in SEC company table"}++ try:+ facts = get_company_facts(cik)+ except Exception as exc: # noqa: BLE001 - one bad fetch must not kill the call+ logger.warning("SEC companyfacts fetch failed for %s: %s", code, exc)+ return {"error": f"SEC companyfacts request failed: {exc}"}++ gaap = (facts.get("facts") or {}).get("us-gaap") if isinstance(facts, dict) else None+ if not isinstance(gaap, dict):+ return {"periods": []}++ periods_by_key: dict[tuple[Any, ...], dict[str, Any]] = {}+ for concept_name in _SEC_CONCEPTS[statement]:+ concept = gaap.get(concept_name)+ units = concept.get("units") if isinstance(concept, dict) else None+ if not isinstance(units, dict):+ continue+ unit_key, rows = _pick_sec_unit(units)+ for row in rows:+ if not isinstance(row, dict) or not _sec_period_matches(row, period):+ continue+ end = row.get("end")+ value = _to_number(row.get("val"))+ if not end or value is None:+ continue+ key = (end, row.get("fy"), row.get("fp"), row.get("form"), row.get("accn"))+ period_row = periods_by_key.setdefault(+ key,+ {+ "REPORT_DATE": end,+ "FISCAL_YEAR": row.get("fy"),+ "FISCAL_PERIOD": row.get("fp"),+ "FORM": row.get("form"),+ "ACCESSION": row.get("accn"),+ "_units": {},+ },+ )+ period_row[concept_name] = value+ period_row["_units"][concept_name] = unit_key++ periods = sorted(+ periods_by_key.values(),+ key=lambda row: str(row.get("REPORT_DATE") or ""),+ reverse=True,+ )+ return {"periods": _cap_periods(periods)}++def _classify_market(code: str) -> str | None:"""Classify a symbol's suffix into ``a_share``, ``us``, ``hk``, or ``None``.@@ -284,10 +407,10 @@ class FinancialStatementsTool(BaseTool):"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), all via Eastmoney. 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"}.'+ "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 "+ 'this to read fundamentals before building a valuation or screen. Example: '+ '{"code": "600519.SH", "statement": "income", "period": "annual"}.')parameters = {"type": "object",@@ -357,9 +480,14 @@ class FinancialStatementsTool(BaseTool):"code must carry a supported suffix: .SH/.SZ/.BJ, .US, or .HK")- result = _fetch_eastmoney_statement(- code, statement=statement, period=period- )+ if market == "us":+ result = _fetch_sec_statement(code, statement=statement, period=period)+ source = "sec_edgar"+ else:+ result = _fetch_eastmoney_statement(+ code, statement=statement, period=period+ )+ source = "eastmoney"# The fetch failed for every requested code (here, the single ``code``)# iff its result carries an ``error``. Surface that as a top-level@@ -368,7 +496,7 @@ class FinancialStatementsTool(BaseTool):envelope: dict[str, Any] = {"ok": not all_failed,"market": market,- "source": "eastmoney",+ "source": source,"statement": statement,"period": period,"data": {code: result},diff --git a/agent/tests/test_financial_statements_tool.py b/agent/tests/test_financial_statements_tool.pyindex c2ef9604e..15a983162 100644--- a/agent/tests/test_financial_statements_tool.py+++ b/agent/tests/test_financial_statements_tool.py@@ -1,8 +1,8 @@"""Tests for financial_statements_tool: envelope shape, dispatch, isolation.-All HTTP is mocked at the functions the tool imports — every market routes-through the Eastmoney client's ``get_json`` / ``resolve_secid`` — so no test-touches a live endpoint.+All HTTP is mocked at the functions the tool imports. A-share/HK route through+Eastmoney ``get_json`` / ``resolve_secid``; US routes through SEC EDGAR+``cik_for`` / ``get_company_facts``. No test touches a live endpoint."""from __future__ import annotations@@ -31,6 +31,74 @@ _EM_A_PAYLOAD = {}}+_SEC_FACTS = {+ "facts": {+ "us-gaap": {+ "Revenues": {+ "label": "Revenues",+ "units": {+ "USD": [+ {+ "end": "2023-09-30",+ "val": 383285000000,+ "fy": 2023,+ "fp": "FY",+ "form": "10-K",+ "accn": "a1",+ },+ {+ "end": "2024-09-28",+ "val": 391035000000,+ "fy": 2024,+ "fp": "FY",+ "form": "10-K",+ "accn": "a2",+ },+ ]+ },+ },+ "NetIncomeLoss": {+ "label": "Net Income",+ "units": {+ "USD": [+ {+ "end": "2024-06-29",+ "val": 21448000000,+ "fy": 2024,+ "fp": "Q3",+ "form": "10-Q",+ "accn": "q3",+ },+ {+ "end": "2024-09-28",+ "val": 93736000000,+ "fy": 2024,+ "fp": "FY",+ "form": "10-K",+ "accn": "a2",+ },+ ]+ },+ },+ "Assets": {+ "label": "Assets",+ "units": {+ "USD": [+ {+ "end": "2024-09-28",+ "val": 364980000000,+ "fy": 2024,+ "fp": "FY",+ "form": "10-K",+ "accn": "a2",+ },+ ]+ },+ },+ }+ }+}+class TestSuccessEnvelope:"""A resolvable symbol yields the ok envelope with parsed periods."""@@ -60,36 +128,67 @@ class TestSuccessEnvelope:assert periods[0]["REPORT_DATE"] == "2024-12-31"# A-share balance sheet hits the A-share F10 report, filtered on the- # dotted SECUCODE (not the bare SECURITY_CODE used for US/HK).+ # dotted SECUCODE (not the bare SECURITY_CODE used for HK).sent_params = mock_get.call_args.kwargs["params"]assert sent_params["reportName"] == "RPT_F10_FINANCE_GBALANCE"assert 'SECUCODE="600519.SH"' in sent_params["filter"]assert "SECURITY_CODE" not in sent_params["filter"]- def test_us_uses_eastmoney_report_api(self):+ def test_us_uses_sec_companyfacts(self):with patch("src.tools.financial_statements_tool.resolve_secid",- return_value="105.AAPL",- ), patch(+ ) as mock_resolve, patch("src.tools.financial_statements_tool.get_json",- return_value=_EM_PAYLOAD,- ) as mock_get:+ ) as mock_get, patch(+ "src.tools.financial_statements_tool.cik_for",+ return_value="0000320193",+ ) as mock_cik, patch(+ "src.tools.financial_statements_tool.get_company_facts",+ return_value=_SEC_FACTS,+ ) as mock_facts:text = FinancialStatementsTool().execute(- code="AAPL.US", statement="income", period="quarter"+ code="AAPL.US", statement="income", period="annual")+ mock_cik.assert_called_once_with("AAPL")+ mock_facts.assert_called_once_with("0000320193")+ mock_resolve.assert_not_called()+ mock_get.assert_not_called()+payload = json.loads(text)assert payload["ok"] is Trueassert payload["market"] == "us"- assert payload["source"] == "eastmoney"+ assert payload["source"] == "sec_edgar"periods = payload["data"]["AAPL.US"]["periods"]- assert periods[0]["REPORT_DATE"] == "2024-12-31"+ assert periods[0]["REPORT_DATE"] == "2024-09-28"+ assert periods[0]["FORM"] == "10-K"+ assert periods[0]["Revenues"] == 391035000000.0+ assert periods[0]["NetIncomeLoss"] == 93736000000.0+ assert periods[0]["_units"] == {+ "Revenues": "USD",+ "NetIncomeLoss": "USD",+ }- # US income report name + bare code filter were passed through.- sent_params = mock_get.call_args.kwargs["params"]- assert sent_params["reportName"] == "RPT_USF10_FN_INCOME"- assert 'SECURITY_CODE="AAPL"' in sent_params["filter"]+ def test_us_quarter_keeps_10q_points(self):+ with patch(+ "src.tools.financial_statements_tool.cik_for",+ return_value="0000320193",+ ), patch(+ "src.tools.financial_statements_tool.get_company_facts",+ return_value=_SEC_FACTS,+ ):+ text = FinancialStatementsTool().execute(+ code="AAPL.US", statement="income", period="quarter"+ )++ payload = json.loads(text)+ periods = payload["data"]["AAPL.US"]["periods"]+ dates = [row["REPORT_DATE"] for row in periods]+ assert "2024-06-29" in dates+ q3 = next(row for row in periods if row["REPORT_DATE"] == "2024-06-29")+ assert q3["FORM"] == "10-Q"+ assert q3["NetIncomeLoss"] == 21448000000.0def test_hk_indicators_use_hk_report_name(self):with patch(@@ -136,15 +235,15 @@ class TestAllFailedSurfacesError:def test_unresolvable_us_symbol_yields_ok_false(self):with patch(- "src.tools.financial_statements_tool.resolve_secid",+ "src.tools.financial_statements_tool.cik_for",return_value=None,):text = FinancialStatementsTool().execute(code="ZZZZ.US")payload = json.loads(text)assert payload["ok"] is False- assert payload["error"] == "unresolvable symbol"- assert payload["data"]["ZZZZ.US"]["error"] == "unresolvable symbol"+ assert payload["error"] == "ticker not found in SEC company table"+ assert payload["data"]["ZZZZ.US"]["error"] == "ticker not found in SEC company table"def test_empty_a_share_payload_yields_no_periods_but_ok_true(self):# An empty-but-well-formed payload is data (zero periods), not a fetch@@ -168,7 +267,7 @@ class TestPeriodSelection:"""Period is chosen client-side. Eastmoney's REPORT_TYPE is locale text(年报 / 一季报) or a market-specific string (2026/Q1), so no REPORT_TYPEfilter is sent; 'annual' keeps fiscal-year-end rows, falling back to the- full series when an issuer has no December year-end (e.g. a US fiscal year).+ full series when an issuer has no December year-end."""_MIXED = {@@ -217,10 +316,10 @@ class TestPeriodSelection:def test_annual_falls_back_when_no_december_year_end(self):payload, _ = self._run(- self._NO_YEAR_END, period="annual", code="AAPL.US", secid="105.AAPL"+ self._NO_YEAR_END, period="annual", code="00700.HK", secid="116.00700")# No -12-31 row -> return the full series rather than drop all data.- assert len(payload["data"]["AAPL.US"]["periods"]) == 2+ assert len(payload["data"]["00700.HK"]["periods"]) == 2def test_a_share_indicators_use_mainfinadata_report(self):_, mock_get = self._run(self._MIXED, period="annual", statement="indicators")