"Vibe-Trading: Your Personal Trading Agent"
Python ai-agentalgorithmic-tradingbacktestingfintechllmmcpmulti-agentpythonquantitative-financetrading
Updated for Canada
Will Liao47e0458c94f7
diff --git a/agent/mcp_server.py b/agent/mcp_server.pyindex 7ae9daf2d..602297877 100644--- a/agent/mcp_server.py+++ b/agent/mcp_server.py@@ -1685,13 +1685,13 @@ def get_research_reports(code: str, limit: int = 20) -> str:def get_stock_news(code: str | None = None, scope: str = "stock", limit: int = 20) -> str:"""Fetch recent financial news headlines, read-only and no auth.- Markets: China A-share (SH/SZ/BJ) headlines from Eastmoney; US (.US) and- Hong Kong (.HK) related-instrument matches from Yahoo Finance. Use scope- "stock" with a ``code`` for one security's headlines, or scope "global"- (no code) for broad China-market finance news.+ Markets: China A-share (SH/SZ/BJ) headlines from Eastmoney; US (.US), Hong+ Kong (.HK) and Canada (.TO/.V) related-instrument matches from Yahoo+ Finance. Use scope "stock" with a ``code`` for one security's headlines, or+ scope "global" (no code) for broad China-market finance news.Args:- code: Symbol whose news to fetch (e.g. "600519.SH", "AAPL.US").+ code: Symbol whose news to fetch (e.g. "600519.SH", "AAPL.US", "SGML.V").Required when scope="stock"; ignored when scope="global".scope: "stock" (default) or "global".limit: Maximum number of headlines to return.@@ -1736,12 +1736,14 @@ def get_sec_filings(def get_financial_statements(code: str, statement: str = "indicators", period: str = "annual") -> str:"""Fetch a stock's financial statements or key per-period indicators.- Markets: A-share (.SH/.SZ/.BJ, via Sina), US (.US) and Hong Kong (.HK, via- Eastmoney). Reports come back newest-first as flat per-period rows. Use this- to read fundamentals before building a valuation or screen.+ Markets: A-share (.SH/.SZ/.BJ, via Sina), US (.US), Hong Kong (.HK, via+ Eastmoney) and Canada (.TO/.V, via Yahoo). Reports come back newest-first+ as flat per-period rows. Use this to read fundamentals before building a+ valuation or screen.Args:- code: Single symbol with a market suffix (e.g. "600519.SH", "AAPL.US").+ code: Single symbol with a market suffix (e.g. "600519.SH", "AAPL.US",+ "SGML.V").statement: "balance", "income", "cashflow", or "indicators".period: "annual" or "quarter"."""diff --git a/agent/src/skills/data-routing/SKILL.md b/agent/src/skills/data-routing/SKILL.mdindex 452e9fed4..8444f9a4c 100644--- a/agent/src/skills/data-routing/SKILL.md+++ b/agent/src/skills/data-routing/SKILL.md@@ -57,9 +57,9 @@ is required only where listed (no key listed = free / no auth).| Lockup expiry (限售解禁) | `get_lockup_expiry` | A-share | — || Sector / board taxonomy (板块) | `get_sector_info` | A-share | — || Sell-side research reports | `get_research_reports` | A-share | — |-| Stock news | `get_stock_news` | A-share, US, HK | — |+| Stock news | `get_stock_news` | A-share, US, HK, Canada | — || SEC filings (EDGAR) | `get_sec_filings` | US | — |-| Financial statements | `get_financial_statements` | A-share, US, HK | — |+| Financial statements | `get_financial_statements` | A-share, US, HK, Canada | — || Options chain | `get_options_chain` | US | — || Stock profile / fundamentals | `get_stock_profile` | US | — || Market screen | `screen_market` | A-share | — |@@ -69,10 +69,12 @@ is required only where listed (no key listed = free / no auth).Notes:- `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).+ (ticker -> CIK -> XBRL concepts), A-share/HK statements from the Eastmoney+ datacenter report API (per-market F10 report names), and Canada (.TO/.V)+ statements from Yahoo Finance quoteSummary history modules.- `get_stock_news` routes A-share (SH/SZ/BJ) to an Eastmoney news client and- US (.US) / HK (.HK) to a Yahoo search client; a failure on one upstream is+ US (.US) / HK (.HK) / Canada (.TO/.V) to a Yahoo search client; a failure on+ one upstream isreturned as an error envelope, never raised, so a single bad symbol neveraborts a batch.diff --git "a/agent/src/skills/eastmoney/references/\347\240\224\346\212\245\350\210\206\346\203\205/\350\264\242\347\273\217\346\226\260\351\227\273.md" "b/agent/src/skills/eastmoney/references/\347\240\224\346\212\245\350\210\206\346\203\205/\350\264\242\347\273\217\346\226\260\351\227\273.md"index 545cd59e1..003def08e 100644--- "a/agent/src/skills/eastmoney/references/\347\240\224\346\212\245\350\210\206\346\203\205/\350\264\242\347\273\217\346\226\260\351\227\273.md"+++ "b/agent/src/skills/eastmoney/references/\347\240\224\346\212\245\350\210\206\346\203\205/\350\264\242\347\273\217\346\226\260\351\227\273.md"@@ -2,30 +2,31 @@工具:`get_stock_news`(`src.tools.stock_news_tool.StockNewsTool`)描述:两路公开免鉴权新闻面封在同一 BaseTool 下:+- **A 股(及一般中国市场财经)头条** —— 东财免费 `search-api` 新闻列表端点。按源 IP 限流,故走 `eastmoney` 节流客户端。-- **美 / 港头条** —— Yahoo Finance 公开 search 端点(`backtest.loaders.yahoo_client.search`,自身 per-host 节流),返回相关标的匹配。-两种 scope:`stock`(默认,单只证券,需 `code`)、`global`(宽口径市场头条,无需 `code`)。-市场:A 股(.SH/.SZ/.BJ → 东财)、美股(.US)/港股(.HK → Yahoo)。-限速:东财经 `eastmoney` bucket、Yahoo 经其 host bucket。+- **美 / 港 / 加头条** —— Yahoo Finance 公开 search 端点(`backtest.loaders.yahoo_client.search`,自身 per-host 节流),返回相关标的匹配。+ 两种 scope:`stock`(默认,单只证券,需 `code`)、`global`(宽口径市场头条,无需 `code`)。+ 市场:A 股(.SH/.SZ/.BJ → 东财)、美股(.US)/港股(.HK)/加拿大(.TO/.V → Yahoo)。+ 限速:东财经 `eastmoney` bucket、Yahoo 经其 host bucket。<br>**端点**-| 上游 | 端点 URL |-| ---- | -------- |-| 东财新闻 | `https://search-api-web.eastmoney.com/search/jsonp` |-| Yahoo search | 经 `backtest.loaders.yahoo_client.search()` |+| 上游 | 端点 URL |+| ------------ | --------------------------------------------------- |+| 东财新闻 | `https://search-api-web.eastmoney.com/search/jsonp` |+| Yahoo search | 经 `backtest.loaders.yahoo_client.search()` |<br>**输入参数(工具入参)**-名称 | 类型 | 必选 | 描述----- | ---- | ---- | -----scope | str | N | `"stock"`(默认,单只证券,需 `code`)或 `"global"`(宽口径中国市场财经,默认查询词 `财经`)。-code | str | scope=stock 必选 | symbol,如 `600519.SH` / `AAPL.US` / `00700.HK`。后缀选上游:SH/SZ/BJ → 东财;US/HK → Yahoo。-limit | int | N | 返回头条数上限(1–50,默认 20)。+| 名称 | 类型 | 必选 | 描述 |+| ----- | ---- | ---------------- | ----------------------------------------------------------------------------------------------------------------------- |+| scope | str | N | `"stock"`(默认,单只证券,需 `code`)或 `"global"`(宽口径中国市场财经,默认查询词 `财经`)。 |+| code | str | scope=stock 必选 | symbol,如 `600519.SH` / `AAPL.US` / `00700.HK` / `TD.TO` / `SGML.V`。后缀选上游:SH/SZ/BJ → 东财;US/HK/TO/V → Yahoo。 |+| limit | int | N | 返回头条数上限(1–50,默认 20)。 |<br>@@ -39,20 +40,20 @@ limit | int | N | 返回头条数上限(1–50,默认 20)。东财文章(`result.cmsArticleWebOld[]`,源字段 → 输出键):-源字段 | 输出键 | 描述----- | ---- | -----title | title | 标题-url | url | 链接-mediaName | source | 媒体名-date | published | 发布时间-content | snippet | 正文(裁剪至 280 字符)+| 源字段 | 输出键 | 描述 |+| --------- | --------- | ----------------------- |+| title | title | 标题 |+| url | url | 链接 |+| mediaName | source | 媒体名 |+| date | published | 发布时间 |+| content | snippet | 正文(裁剪至 280 字符) |Yahoo 匹配(相关标的):-字段 | 描述----- | -----title | shortname/longname/symbol 之一-symbol / exchange / quote_type | 标的代码 / 交易所 / 类型+| 字段 | 描述 |+| ------------------------------ | ------------------------------ |+| title | shortname/longname/symbol 之一 |+| symbol / exchange / quote_type | 标的代码 / 交易所 / 类型 |信封:`{"ok": true, "market": <market>, "source": "eastmoney"|"yahoo", "data": {"scope", ("code"), "articles":[...]}}`。market 为 `a_share`/`us`/`hk`/`global`。diff --git a/agent/src/tools/block_trades_tool.py b/agent/src/tools/block_trades_tool.pyindex c0d075a60..fda6510bf 100644--- a/agent/src/tools/block_trades_tool.py+++ b/agent/src/tools/block_trades_tool.py@@ -230,7 +230,8 @@ class BlockTradesTool(BaseTool):"ok": False,"error": (f"{symbol!r} is not a resolvable A-share symbol "- "(use .SH/.SZ/.BJ)"+ "(use .SH/.SZ/.BJ); Canada (.TO/.V) is not a "+ "block-trade market on Eastmoney"),},ensure_ascii=False,diff --git a/agent/src/tools/financial_statements_tool.py b/agent/src/tools/financial_statements_tool.pyindex 1cd42531c..832c5d1f7 100644--- a/agent/src/tools/financial_statements_tool.py+++ b/agent/src/tools/financial_statements_tool.py@@ -12,10 +12,15 @@ key per-period indicators from a market-appropriate public source:* **Hong Kong** (``.HK``) — Eastmoney's HK F10 financial-report datasets,filtered on the bare ``SECURITY_CODE``; ``indicators`` reads themain-indicator dataset.+* **Canada** (``.TO`` / ``.V``) — Yahoo Finance quoteSummary history modules+ (``incomeStatementHistory`` / ``balanceSheetHistory`` /+ ``cashflowStatementHistory``) via :mod:`backtest.loaders.yahoo_client`;+ values are native CAD.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"``).+(``host_key="sec"``); Canada requests go through the throttled Yahoo+:func:`backtest.loaders.yahoo_client.get_quote_summary` (``host_key="yahoo"``).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@@ -26,9 +31,10 @@ from __future__ import annotationsimport jsonimport logging+from datetime import datetime, timezonefrom typing import Any-from backtest.loaders import sec_frames+from backtest.loaders import sec_frames, yahoo_clientfrom backtest.loaders.eastmoney_client import get_json, resolve_secidfrom backtest.loaders.sec_edgar_client import cik_for, get_company_factsfrom src.agent.tools import BaseTool@@ -101,6 +107,249 @@ _SEC_CONCEPTS: dict[str, tuple[str, ...]] = {),}+# --- Yahoo (Canada .TO/.V) financial history ------------------------------++# Yahoo quoteSummary history module names by (statement, period). Each returns+# a list of per-period rows; every field is {"raw": number, "fmt": "..."}.+_YAHOO_HISTORY_MODULES: dict[str, dict[str, str]] = {+ "balance": {+ "annual": "balanceSheetHistory",+ "quarter": "balanceSheetHistoryQuarterly",+ },+ "income": {+ "annual": "incomeStatementHistory",+ "quarter": "incomeStatementHistoryQuarterly",+ },+ "cashflow": {+ "annual": "cashflowStatementHistory",+ "quarter": "cashflowStatementHistoryQuarterly",+ },+}++# Curated field reads per statement: output key -> candidate Yahoo field names.+_YAHOO_ROW_FIELDS: dict[str, tuple[tuple[str, tuple[str, ...]], ...]] = {+ "balance": (+ ("assets", ("totalAssets",)),+ ("current_assets", ("totalCurrentAssets",)),+ ("cash", ("cashAndCashEquivalents", "cash")),+ ("liabilities", ("totalLiabilitiesNetMinorityInterest", "totalLiabilities")),+ ("current_liabilities", ("totalCurrentLiabilities",)),+ ("long_term_debt", ("longTermDebt", "longTermDebtCurrentAndNoncurrent")),+ ("stockholders_equity", ("stockholdersEquity", "totalStockholderEquity")),+ ),+ "income": (+ ("revenue", ("totalRevenue",)),+ ("gross_profit", ("grossProfit",)),+ ("operating_income", ("operatingIncome",)),+ ("ebitda", ("ebitda",)),+ ("net_income", ("netIncome",)),+ ("eps_diluted", ("dilutedEPS",)),+ ("eps_basic", ("basicEPS",)),+ ),+ "cashflow": (+ ("operating_cash_flow", ("totalCashFromOperatingActivities", "operatingCashflow")),+ ("investing_cash_flow", ("totalCashflowsFromInvestingActivities", "investingCashflow")),+ ("financing_cash_flow", ("totalCashFromFinancingActivities", "financingCashflow")),+ ("capex", ("capitalExpenditures",)),+ ("free_cash_flow", ("freeCashFlow",)),+ ),+ "indicators": (+ ("revenue", ("totalRevenue",)),+ ("gross_profit", ("grossProfit",)),+ ("operating_income", ("operatingIncome",)),+ ("net_income", ("netIncome",)),+ ("eps_diluted", ("dilutedEPS",)),+ ("assets", ("totalAssets",)),+ ("liabilities", ("totalLiabilitiesNetMinorityInterest", "totalLiabilities")),+ ("stockholders_equity", ("stockholdersEquity", "totalStockholderEquity")),+ ("operating_cash_flow", ("totalCashFromOperatingActivities", "operatingCashflow")),+ ("free_cash_flow", ("freeCashFlow",)),+ ),+}+++def _yahoo_raw(row: dict[str, Any], *keys: str) -> float | None:+ """Return the first present field's ``raw`` numeric value, else ``None``."""+ for key in keys:+ value = row.get(key)+ if isinstance(value, dict) and value.get("raw") is not None:+ try:+ return float(value["raw"])+ except (TypeError, ValueError):+ return None+ return None+++def _yahoo_end_date(row: dict[str, Any]) -> str:+ """Extract a row's report date (``endDate.fmt``) or the ISO date of raw epoch."""+ end = row.get("endDate")+ if isinstance(end, dict):+ fmt = end.get("fmt")+ if fmt:+ return str(fmt)+ raw = end.get("raw")+ if raw is not None:+ try:+ return datetime.fromtimestamp(+ float(raw), tz=timezone.utc+ ).strftime("%Y-%m-%d")+ except (TypeError, ValueError, OSError):+ pass+ return ""+++def _yahoo_history_rows(summary: dict[str, Any], module: str) -> list[dict[str, Any]]:+ """Return the per-period rows under a quoteSummary history module."""+ payload = summary.get(module)+ if not isinstance(payload, dict):+ return []+ rows = payload.get(module)+ return [r for r in rows if isinstance(r, dict)] if isinstance(rows, list) else []+++def _merge_yahoo_histories(+ summary: dict[str, Any], period: str+) -> list[dict[str, Any]]:+ """Merge the three history modules into one row per report date (indicators)."""+ merged: dict[str, dict[str, Any]] = {}+ for statement in ("income", "balance", "cashflow"):+ module = _YAHOO_HISTORY_MODULES[statement][period]+ for row in _yahoo_history_rows(summary, module):+ date = _yahoo_end_date(row)+ if not date:+ continue+ merged.setdefault(date, {"endDate": row.get("endDate")}).update(row)+ return list(merged.values())+++# QuoteSummary snapshot modules used as a fallback when a statement's history+# module is empty (balance/cashflow history is frequently empty for Canadian+# issuers). Fields: output key -> (source module, Yahoo field).+_YAHOO_SNAPSHOT_MODULES = ("financialData", "defaultKeyStatistics")++_YAHOO_SNAPSHOT_FIELDS: dict[str, tuple[tuple[str, str, str], ...]] = {+ "balance": (+ ("cash", "financialData", "totalCash"),+ ("total_debt", "financialData", "totalDebt"),+ ("current_ratio", "financialData", "currentRatio"),+ ("quick_ratio", "financialData", "quickRatio"),+ ("debt_to_equity", "financialData", "debtToEquity"),+ ("book_value", "defaultKeyStatistics", "bookValue"),+ ),+ "income": (+ ("revenue", "financialData", "totalRevenue"),+ ("gross_profit", "financialData", "grossProfits"),+ ("ebitda", "financialData", "ebitda"),+ ("net_income", "defaultKeyStatistics", "netIncomeToCommon"),+ ("eps_diluted", "defaultKeyStatistics", "trailingEps"),+ ),+ "cashflow": (+ ("operating_cash_flow", "financialData", "operatingCashflow"),+ ("free_cash_flow", "financialData", "freeCashflow"),+ ("ebitda", "financialData", "ebitda"),+ ("cash", "financialData", "totalCash"),+ ),+ "indicators": (+ ("revenue", "financialData", "totalRevenue"),+ ("gross_profit", "financialData", "grossProfits"),+ ("ebitda", "financialData", "ebitda"),+ ("net_income", "defaultKeyStatistics", "netIncomeToCommon"),+ ("eps_diluted", "defaultKeyStatistics", "trailingEps"),+ ("cash", "financialData", "totalCash"),+ ("total_debt", "financialData", "totalDebt"),+ ("book_value", "defaultKeyStatistics", "bookValue"),+ ("operating_cash_flow", "financialData", "operatingCashflow"),+ ("free_cash_flow", "financialData", "freeCashflow"),+ ("return_on_equity", "financialData", "returnOnEquity"),+ ("return_on_assets", "financialData", "returnOnAssets"),+ ),+}+++def _yahoo_snapshot_row(+ summary: dict[str, Any], statement: str+) -> dict[str, Any]:+ """Build a single ``report_date: "latest"`` row from quoteSummary snapshots."""+ fields = _YAHOO_SNAPSHOT_FIELDS.get(statement)+ if not fields:+ return {}+ record: dict[str, Any] = {+ "report_date": "latest",+ "currency": "CAD",+ "snapshot": True,+ }+ for key, module, field in fields:+ mod = summary.get(module)+ if isinstance(mod, dict):+ value = mod.get(field)+ if isinstance(value, dict) and value.get("raw") is not None:+ try:+ record[key] = round(float(value["raw"]), 4)+ except (TypeError, ValueError):+ pass+ return record+++def _fetch_yahoo_statement(+ code: str, *, statement: str, period: str+) -> dict[str, Any]:+ """Fetch a Canadian (.TO/.V) statement from Yahoo quoteSummary.++ Per-period rows come from the statement's history module when Yahoo+ provides one (income history is reliably populated; balance/cashflow+ history is frequently empty for Canadian issuers). When the history+ yields no rows, a single ``report_date: "latest"`` snapshot row is built+ from ``financialData`` / ``defaultKeyStatistics`` so the envelope is never+ empty.++ Returns:+ ``{"periods": [...]}`` on success or ``{"error": ...}`` on failure.+ Each period is a flat dict keyed by the ``_YAHOO_*_FIELDS`` output+ names plus ``report_date`` and ``currency`` (CAD).+ """+ if statement == "indicators":+ modules = list(+ {+ _YAHOO_HISTORY_MODULES[s][period]+ for s in ("balance", "income", "cashflow")+ }+ )+ else:+ modules = [_YAHOO_HISTORY_MODULES[statement][period]]+ if statement in ("balance", "cashflow"):+ modules.extend(_YAHOO_SNAPSHOT_MODULES)+ try:+ summary = yahoo_client.get_quote_summary(code, modules)+ except Exception as exc: # noqa: BLE001 - surface as envelope+ return {"error": f"yahoo quoteSummary failed for {code}: {exc}"}+ if not summary:+ return {"error": f"yahoo returned no quoteSummary result for '{code}'"}++ field_map = _YAHOO_ROW_FIELDS.get(statement, _YAHOO_ROW_FIELDS["indicators"])+ if statement == "indicators":+ rows = _merge_yahoo_histories(summary, period)+ else:+ rows = _yahoo_history_rows(summary, _YAHOO_HISTORY_MODULES[statement][period])++ periods: list[dict[str, Any]] = []+ for row in rows:+ record = {"report_date": _yahoo_end_date(row), "currency": "CAD"}+ for key, candidates in field_map:+ value = _yahoo_raw(row, *candidates)+ if value is not None:+ record[key] = round(value, 4)+ if record.get("report_date"):+ periods.append(record)++ if not periods:+ snapshot = _yahoo_snapshot_row(summary, statement)+ if snapshot:+ periods.append(snapshot)++ periods.sort(key=lambda r: str(r.get("report_date") or ""), reverse=True)+ return {"periods": _cap_periods(periods)}++# --- Shared limits / validation ------------------------------------------_VALID_STATEMENTS = ("balance", "income", "cashflow", "indicators")@@ -583,6 +832,8 @@ def _classify_market(code: str) -> str | None:return "us"if suffix == "HK":return "hk"+ if suffix in ("TO", "V"):+ return "ca"return None@@ -593,11 +844,12 @@ 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 Canada (.TO/.V). US uses SEC EDGAR companyfacts; "+ "A-share and HK use Eastmoney; Canada uses Yahoo Finance (CAD). "+ "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"}.'+ '{"code": "SGML.V", "statement": "income", "period": "annual"}.')parameters = {"type": "object",@@ -606,7 +858,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 'SGML.V'."),},"statement": {@@ -673,12 +925,18 @@ 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 .TO/.V")if market == "us":result = _fetch_sec_statement(code, statement=statement, period=period)source = "sec_edgar"+ elif market == "ca":+ result = _fetch_yahoo_statement(+ code, statement=statement, period=period+ )+ source = "yahoo"else:result = _fetch_eastmoney_statement(code, statement=statement, period=perioddiff --git a/agent/src/tools/fund_flow_tool.py b/agent/src/tools/fund_flow_tool.pyindex fb736f1eb..4051d2729 100644--- a/agent/src/tools/fund_flow_tool.py+++ b/agent/src/tools/fund_flow_tool.py@@ -97,6 +97,12 @@ def _fetch_symbol_flow(symbol: str, *, period: str, days: int) -> dict[str, Any]A per-symbol result dict carrying either ``rows`` on success or an``error`` string on failure. Never raises for a single symbol."""+ suffix = symbol.rpartition(".")[2].strip().upper()+ if suffix in ("TO", "V"):+ return {+ "symbol": symbol,+ "error": "Eastmoney capital flow does not cover Canada (.TO/.V)",+ }secid = resolve_secid(symbol)if secid is None:if period == "daily":diff --git a/agent/src/tools/research_reports_tool.py b/agent/src/tools/research_reports_tool.pyindex 612d7f3b6..f487826a4 100644--- a/agent/src/tools/research_reports_tool.py+++ b/agent/src/tools/research_reports_tool.py@@ -108,6 +108,12 @@ class ResearchReportsTool(BaseTool):suffix = code.rpartition(".")[2]if suffix not in _A_SHARE_SUFFIXES:+ if suffix in ("TO", "V"):+ return _error(+ f"research reports cover China A-shares only; Canada "+ f"(.TO/.V) is not published by the Eastmoney/THS providers "+ f"(got '{code}')"+ )return _error(f"research reports are China A-share only (.SH/.SZ/.BJ); got '{code}'")diff --git a/agent/src/tools/shareholder_count_tool.py b/agent/src/tools/shareholder_count_tool.pyindex 9dfb78466..367f11bff 100644--- a/agent/src/tools/shareholder_count_tool.py+++ b/agent/src/tools/shareholder_count_tool.py@@ -89,6 +89,12 @@ class ShareholderCountTool(BaseTool):suffix = code.rpartition(".")[2]if suffix not in _A_SHARE_SUFFIXES:+ if suffix in ("TO", "V"):+ return _error(+ f"shareholder count covers China A-shares only; Canada "+ f"(.TO/.V) is not published by the Eastmoney provider "+ f"(got '{code}')"+ )return _error(f"shareholder count is China A-share only (.SH/.SZ/.BJ); got '{code}'")diff --git a/agent/src/tools/stock_news_tool.py b/agent/src/tools/stock_news_tool.pyindex 3cff06686..7f0473733 100644--- a/agent/src/tools/stock_news_tool.py+++ b/agent/src/tools/stock_news_tool.py@@ -7,8 +7,8 @@ Two public, no-auth news surfaces are wrapped behind one BaseTool contract:surface it rate-limits by source IP, so the request routes through the frozen,IP-throttled :mod:`backtest.loaders.eastmoney_client` rather than touching thehost directly.-* US / HK headlines come from Yahoo Finance's public v1 search-news surface via- the frozen, IP-throttled :mod:`backtest.loaders.yahoo_client`.+* US / HK / Canada headlines come from Yahoo Finance's public v1 search-news+ surface via the frozen, IP-throttled :mod:`backtest.loaders.yahoo_client`.The tool never re-implements provider plumbing and never issues an un-throttledrequest: every outbound call goes through a frozen client.@@ -41,8 +41,9 @@ _EM_NEWS_URL = "https://search-api-web.eastmoney.com/search/jsonp"# A-share / China-market suffixes that route to the Eastmoney news surface._EM_SUFFIXES = ("SH", "SZ", "BJ")-# Suffixes that route to Yahoo's search-news surface.-_YAHOO_SUFFIXES = ("US", "HK")+# Suffixes that route to Yahoo's search-news surface. Yahoo carries US, HK and+# Canada (TSX `.TO` / TSX Venture `.V`) tickers verbatim.+_YAHOO_SUFFIXES = ("US", "HK", "TO", "V")# Default broad-market query used when ``scope='global'`` carries no code._GLOBAL_QUERY = "财经"@@ -224,7 +225,7 @@ def _yahoo_article(raw: dict[str, Any]) -> dict[str, Any]:def _fetch_yahoo_news(query: str, limit: int) -> list[dict[str, Any]]:- """Fetch US/HK news articles for a query via Yahoo search.+ """Fetch US/HK/Canada news articles for a query via Yahoo search.Args:query: Free-text search term (bare ticker or keyword).@@ -249,8 +250,9 @@ class StockNewsTool(BaseTool):description = ("Fetch recent financial news headlines, read-only and no auth. Markets: ""China A-share (SH/SZ/BJ) returns Eastmoney news ARTICLES "- "(title/url/source/published/snippet) under 'articles'. US (.US) and Hong "- "Kong (.HK) return Yahoo Finance news articles with the same fields. Use "+ "(title/url/source/published/snippet) under 'articles'. US (.US), Hong "+ "Kong (.HK) and Canada (.TO/.V) return Yahoo Finance news articles "+ "with the same fields. Use ""scope 'stock' with a 'code', or scope 'global' (no code) for broad ""China-market finance articles. "'Example: {"code": "600519.SH", "scope": "stock", "limit": 10}.'@@ -262,9 +264,10 @@ class StockNewsTool(BaseTool):"type": "string","description": ("Symbol whose news to fetch, e.g. '600519.SH', 'AAPL.US', "- "'00700.HK'. Required when scope='stock'; ignored when "- "scope='global'. The exchange suffix selects the upstream: "- "SH/SZ/BJ -> Eastmoney, US/HK -> Yahoo Finance."+ "'00700.HK', 'TD.TO', 'SGML.V'. Required when "+ "scope='stock'; ignored when scope='global'. The exchange "+ "suffix selects the upstream: SH/SZ/BJ -> Eastmoney, "+ "US/HK/TO/V -> Yahoo Finance."),},"scope": {@@ -373,8 +376,9 @@ class StockNewsTool(BaseTool):)def _stock_via_yahoo(self, code: str, query: str, limit: int) -> str:- """Fetch US/HK news articles from Yahoo for one code."""- market = "hk" if _suffix_of(code) == "HK" else "us"+ """Fetch US/HK/Canada news articles from Yahoo for one code."""+ suffix = _suffix_of(code)+ market = "hk" if suffix == "HK" else "ca" if suffix in ("TO", "V") else "us"try:articles = _fetch_yahoo_news(query, limit)except Exception as exc: # noqa: BLE001 - surface any fetch failure as envelopediff --git a/agent/tests/test_financial_statements_tool.py b/agent/tests/test_financial_statements_tool.pyindex 15a983162..86f00dad2 100644--- a/agent/tests/test_financial_statements_tool.py+++ b/agent/tests/test_financial_statements_tool.py@@ -100,6 +100,68 @@ _SEC_FACTS = {}+_YAHOO_SUMMARY = {+ "incomeStatementHistory": {+ "incomeStatementHistory": [+ {+ "endDate": {"raw": 1735689600, "fmt": "2024-12-31"},+ "totalRevenue": {"raw": 1000000000.0, "fmt": "1B"},+ "grossProfit": {"raw": 600000000.0},+ "operatingIncome": {"raw": 300000000.0},+ "netIncome": {"raw": 200000000.0},+ "dilutedEPS": {"raw": 1.2},+ },+ {+ "endDate": {"raw": 1704067200, "fmt": "2023-12-31"},+ "totalRevenue": {"raw": 900000000.0},+ "netIncome": {"raw": 150000000.0},+ "dilutedEPS": {"raw": 0.9},+ },+ ]+ },+ "balanceSheetHistory": {+ "balanceSheetHistory": [+ {+ "endDate": {"raw": 1735689600, "fmt": "2024-12-31"},+ "totalAssets": {"raw": 2500000000.0},+ "totalLiabilitiesNetMinorityInterest": {"raw": 1200000000.0},+ "stockholdersEquity": {"raw": 1300000000.0},+ }+ ]+ },+ "cashflowStatementHistory": {+ "cashflowStatementHistory": [+ {+ "endDate": {"raw": 1735689600, "fmt": "2024-12-31"},+ "totalCashFromOperatingActivities": {"raw": 400000000.0},+ "totalCashflowsFromInvestingActivities": {"raw": -150000000.0},+ "totalCashFromFinancingActivities": {"raw": -200000000.0},+ "capitalExpenditures": {"raw": -100000000.0},+ }+ ]+ },+ "financialData": {+ "totalCash": {"raw": 3852000.0},+ "totalDebt": {"raw": 136872992.0},+ "totalRevenue": {"raw": 104681000.0},+ "grossProfits": {"raw": 22590000.0},+ "ebitda": {"raw": 2581000.0},+ "operatingCashflow": {"raw": 1894000.0},+ "freeCashflow": {"raw": 20125250.0},+ "returnOnEquity": {"raw": -0.49056998},+ "returnOnAssets": {"raw": -0.01263},+ "currentRatio": {"raw": 0.324},+ "quickRatio": {"raw": 0.143},+ "debtToEquity": {"raw": 189.062},+ },+ "defaultKeyStatistics": {+ "bookValue": {"raw": 0.9122103},+ "netIncomeToCommon": {"raw": -43781000.0},+ "trailingEps": {"raw": -0.55},+ },+}++class TestSuccessEnvelope:"""A resolvable symbol yields the ok envelope with parsed periods."""@@ -208,6 +270,83 @@ class TestSuccessEnvelope:)+class TestCanadaViaYahoo:+ """Canada (.TO/.V) routes to Yahoo quoteSummary history modules."""++ def test_ca_income_uses_yahoo_and_parses_periods(self):+ with patch(+ "src.tools.financial_statements_tool.yahoo_client.get_quote_summary",+ return_value=_YAHOO_SUMMARY,+ ) as mock_qs:+ text = FinancialStatementsTool().execute(+ code="SGML.V", statement="income", period="annual"+ )++ mock_qs.assert_called_once_with("SGML.V", ["incomeStatementHistory"])+ payload = json.loads(text)+ assert payload["ok"] is True+ assert payload["market"] == "ca"+ assert payload["source"] == "yahoo"+ periods = payload["data"]["SGML.V"]["periods"]+ assert periods[0]["report_date"] == "2024-12-31"+ assert periods[0]["revenue"] == 1000000000.0+ assert periods[0]["currency"] == "CAD"++ def test_ca_indicators_merge_all_histories(self):+ with patch(+ "src.tools.financial_statements_tool.yahoo_client.get_quote_summary",+ return_value=_YAHOO_SUMMARY,+ ) as mock_qs:+ text = FinancialStatementsTool().execute(+ code="SGML.V", statement="indicators", period="annual"+ )++ modules = mock_qs.call_args.args[1]+ assert set(modules) == {+ "incomeStatementHistory",+ "balanceSheetHistory",+ "cashflowStatementHistory",+ }+ payload = json.loads(text)+ row = payload["data"]["SGML.V"]["periods"][0]+ assert row["revenue"] == 1000000000.0+ assert row["assets"] == 2500000000.0+ assert row["operating_cash_flow"] == 400000000.0++ def test_ca_balance_falls_back_to_snapshot_when_history_empty(self):+ summary = dict(_YAHOO_SUMMARY)+ summary["balanceSheetHistory"] = {"balanceSheetHistory": []}+ with patch(+ "src.tools.financial_statements_tool.yahoo_client.get_quote_summary",+ return_value=summary,+ ) as mock_qs:+ text = FinancialStatementsTool().execute(+ code="SGML.V", statement="balance", period="annual"+ )++ modules = mock_qs.call_args.args[1]+ assert "balanceSheetHistory" in modules+ assert {"financialData", "defaultKeyStatistics"} <= set(modules)+ payload = json.loads(text)+ assert payload["ok"] is True+ row = payload["data"]["SGML.V"]["periods"][0]+ assert row["report_date"] == "latest"+ assert row["snapshot"] is True+ assert row["cash"] == 3852000.0+ assert row["total_debt"] == 136872992.0++ def test_ca_quote_summary_failure_surfaces_error(self):+ with patch(+ "src.tools.financial_statements_tool.yahoo_client.get_quote_summary",+ side_effect=RuntimeError("yahoo 401"),+ ):+ text = FinancialStatementsTool().execute(code="SGML.V")++ payload = json.loads(text)+ assert payload["ok"] is False+ assert "yahoo" in payload["error"]++class TestAllFailedSurfacesError:"""When the fetch fails for every requested code, the envelope is ok=false.diff --git a/agent/tests/test_stock_news_tool.py b/agent/tests/test_stock_news_tool.pyindex a92cebe6c..d00587477 100644--- a/agent/tests/test_stock_news_tool.py+++ b/agent/tests/test_stock_news_tool.py@@ -85,6 +85,8 @@ class TestHelpers:def test_suffix_of(self) -> None:assert _suffix_of("600519.SH") == "SH"assert _suffix_of("AAPL.US") == "US"+ assert _suffix_of("TD.TO") == "TO"+ assert _suffix_of("SGML.V") == "V"assert _suffix_of("NOSUFFIX") == ""def test_bare_query(self) -> None:@@ -206,6 +208,19 @@ class TestExecuteSuccess:assert out["source"] == "yahoo"assert out["data"]["articles"][0]["title"] == "Apple unveils new products"+ def test_ca_stock_via_yahoo_returns_articles(self) -> None:+ tool = StockNewsTool()+ with patch.object(+ yahoo_client, "search_news", return_value=_yahoo_news()[:1]+ ) as srch:+ out = json.loads(tool.execute(code="SGML.V"))++ srch.assert_called_once_with("SGML", 20)+ assert out["ok"] is True+ assert out["market"] == "ca"+ assert out["source"] == "yahoo"+ assert out["data"]["articles"][0]["title"] == "Apple unveils new products"+def test_yahoo_empty_news_returns_empty_articles(self) -> None:with patch.object(yahoo_client, "search_news", return_value=[]):out = json.loads(StockNewsTool().execute(code="AAPL.US"))