"Vibe-Trading: Your Personal Trading Agent"
Python ai-agentalgorithmic-tradingbacktestingfintechllmmcpmulti-agentpythonquantitative-financetrading
feat: complete TSX and TSXV market support
Haozhe Wucf9c693fb177
diff --git a/README.md b/README.mdindex 8d8f4ece9..40cf1e708 100644--- a/README.md+++ b/README.md@@ -236,7 +236,7 @@<img src="assets/feature-cross-market-data-backtesting.png" height="130" alt="Cross-market data and backtesting"/><br><h3>📊 Cross-Market Data & Backtesting</h3><div align="left">- • A / HK / US / India / Korea equities, crypto, futures, and forex<br>+ • A / HK / US / Canada / India / Korea equities, crypto, futures, and forex<br>• Data fallback and composite backtests<br>• PIT data, validation, and run cards</div>@@ -327,7 +327,7 @@ Most runs follow the same evidence path: route the request, load the right marke| Layer | What happens ||-------|--------------|| **Plan** | Selects the relevant finance skills, tools, data sources, and swarm preset when useful. |-| **Ground** | Pulls A-shares, HK/US equities, crypto, futures, forex, documents, or web context through the available loaders. |+| **Ground** | Pulls A-shares, HK/US/Canada equities, crypto, futures, forex, documents, or web context through the available loaders. || **Execute** | Generates testable strategy code, runs tools, and uses the matching backtest engine or analysis workflow. || **Validate** | Adds metrics, benchmark comparison, Monte Carlo, Bootstrap, Walk-Forward, run cards, and warnings where applicable. || **Deliver** | Returns reports, artifacts, tool traces, and exports for TradingView, TDX, MetaTrader 5, MCP clients, or later sessions. |@@ -344,8 +344,9 @@ One `get_market_data` call, **23 free market-data sources** (plus the optional *| `eastmoney` | A / US / HK | none | OHLCV + deep fundamentals & flow tools (throttled) || `baostock` · `akshare` | A (+ US/HK/futures/macro/fx) | none | free fallbacks || `tushare` | A / HK / futures / fund / macro | token | richest A-share |-| `yahoo` · `sina` · `stooq` | US (/HK) | none | direct chart/quotes/options · K-line to 1984 · EOD CSV |-| `yfinance` | US / HK | none | wrapper |+| `yahoo` | US / HK / Canada | none | direct chart/quotes/options; TSX `.TO` / TSXV `.V` |+| `sina` · `stooq` | US | none | K-line to 1984 · EOD CSV |+| `yfinance` | US / HK / Canada | none | wrapper; TSX `.TO` / TSXV `.V` pass through || `longbridge` | US / HK | App Key + App Secret + Access Token | optional historical OHLCV source; install the optional SDK || `finnhub` · `alphavantage` · `tiingo` · `fmp` | US | key | optional providers || `qveris` | global multi-asset | key · credits | **premium marketplace** — 63+ providers via one key (explicit-only, never in auto fallback) |@@ -556,7 +557,7 @@ Run `vibe-trading alpha list` to browse, `vibe-trading alpha show <id>` for form| Engine | Market | Notes ||--------|--------|-------|| **ChinaA** | A-share | T+1, price limits, pre-ST filter |-| **GlobalEquity** | US / HK | T+0 |+| **GlobalEquity** | US / HK / Canada | same-session trading; market-specific lots, ticks, and costs || **IndiaEquity** | India (NSE/BSE) | T+1, circuit bands, config-driven STT / stamp / SEBI / GST cost stack || **KoreaEquity** | Korea (KRX: KOSPI/KOSDAQ) | long-only, ±30% band judged at execution time on the unified tick grid, 2026 0.20% transaction tax || **Crypto** | crypto spot / USD-M perps | funding settlements, execution/mark split |@@ -643,7 +644,7 @@ vibe-trading-mcp # start MCP server (stdio)> **Supported LLM providers:** OpenRouter, Requesty, OpenAI, Anthropic (native Messages API), DeepSeek, Gemini, Groq, DashScope/Qwen, Zhipu, Moonshot/Kimi, MiniMax, SiliconFlow (CN + Global), Xiaomi MIMO, iFlytek Spark, Z.ai, NVIDIA NIM, Ollama (local). When no `*_BASE_URL` is set, each provider falls back to its canonical endpoint, so just a key is enough. See `.env.example` for config.-> **Tip:** All markets work without any API keys thanks to automatic fallback. yfinance (HK/US), OKX (crypto), mootdx (A-shares, TCP-direct, no IP throttle), and AKShare (A-shares, US, HK, futures, forex) are all free. Tushare token is optional — mootdx is the preferred no-token A-share fallback, with AKShare as a broader backup.+> **Tip:** All markets work without any API keys thanks to automatic fallback. yfinance/Yahoo (HK/US/Canada), OKX (crypto), mootdx (A-shares, TCP-direct, no IP throttle), and AKShare (A-shares, US, HK, futures, forex) are all free. Tushare token is optional — mootdx is the preferred no-token A-share fallback, with AKShare as a broader backup.### Path A: Docker (zero setup)@@ -745,7 +746,7 @@ Copy `agent/.env.example` to `agent/.env` and uncomment the provider block you w<sub>* Ollama does not require an API key. OpenAI Codex uses ChatGPT OAuth and stores tokens via `oauth-cli-kit`, not in `agent/.env`.</sub>-**Free data (no key needed):** A-shares via AKShare, HK/US equities via yfinance, crypto via OKX, 100+ crypto exchanges via CCXT. The system automatically selects the best available source for each market.+**Free data (no key needed):** A-shares via AKShare, HK/US/Canada equities via Yahoo/yfinance, crypto via OKX, 100+ crypto exchanges via CCXT. The system automatically selects the best available source for each market.### 🎯 Recommended Modelsdiff --git a/README_ar.md b/README_ar.mdindex e971f6a13..6276c6878 100644--- a/README_ar.md+++ b/README_ar.md@@ -237,7 +237,7 @@<img src="assets/feature-cross-market-data-backtesting.png" height="130" alt="بيانات واختبارات رجعية عبر الأسواق"/><br><h3>📊 بيانات واختبارات رجعية عبر الأسواق</h3><div align="left">- • أسهم A/HK/US والهند وكوريا، وكريبتو، وعقود آجلة، وفوركس<br>+ • أسهم A/HK/US وكندا والهند وكوريا، وكريبتو، وعقود آجلة، وفوركس<br>• fallback للبيانات واختبارات مركبة<br>• بيانات PIT، وتحقيق، وبطاقات تشغيل</div>@@ -328,7 +328,7 @@ vibe-trading run -p "Analyze my trading behavior, extract my shadow strategy, an| الطبقة | ما يحدث ||-------|--------------|| **Plan** | يختار المهارات المالية والأدوات ومصادر البيانات وإعداد السرب الملائمة عند الحاجة. |-| **Ground** | يجلب أسهم A، وأسهم HK/US، والكريبتو، والعقود الآجلة، والفوركس، والمستندات، أو سياق الويب عبر المحملات المتاحة. |+| **Ground** | يجلب أسهم A، وأسهم HK/US/كندا، والكريبتو، والعقود الآجلة، والفوركس، والمستندات، أو سياق الويب عبر المحملات المتاحة. || **Execute** | يولد كود استراتيجية قابل للاختبار، ويشغل الأدوات، ويستخدم محرك الاختبار الرجعي أو سير التحليل المناسب. || **Validate** | يضيف المقاييس، والمقارنة المعيارية، وMonte Carlo، وBootstrap، وWalk-Forward، وبطاقات التشغيل، والتحذيرات عند اللزوم. || **Deliver** | يعيد التقارير والمخرجات وآثار الأدوات والتصديرات إلى TradingView وTDX وMetaTrader 5 وعملاء MCP أو جلسات لاحقة. |@@ -345,8 +345,9 @@ vibe-trading run -p "Analyze my trading behavior, extract my shadow strategy, an| `eastmoney` | A / US / HK | none | OHLCV + deep fundamentals & flow tools (throttled) || `baostock` · `akshare` | A (+ US/HK/futures/macro/fx) | none | free fallbacks || `tushare` | A / HK / futures / fund / macro | token | richest A-share |-| `yahoo` · `sina` · `stooq` | US (/HK) | none | direct chart/quotes/options · K-line to 1984 · EOD CSV |-| `yfinance` | US / HK | none | wrapper |+| `yahoo` | US / HK / كندا | none | direct chart/quotes/options؛ TSX `.TO` / TSXV `.V` |+| `sina` · `stooq` | US | none | K-line to 1984 · EOD CSV |+| `yfinance` | US / HK / كندا | none | wrapper؛ تمر لواحق TSX `.TO` / TSXV `.V` كما هي || `longbridge` | US / HK | App Key + App Secret + Access Token | مصدر OHLCV تاريخي اختياري؛ ثبّت الـ SDK الاختياري || `finnhub` · `alphavantage` · `tiingo` · `fmp` | US | key | optional providers || `qveris` | أصول عالمية متعددة | key · credits | **سوق مدفوع** — 63+ مزوداً بمفتاح واحد (اختيار صريح فقط، خارج التراجع التلقائي) |@@ -553,7 +554,7 @@ LONGBRIDGE_ACCESS_TOKEN=...| المحرّك | السوق | ملاحظات ||--------|-------|---------|| **ChinaA** | أسهم A | T+1، وحدود السعر، ومرشّح ما قبل ST |-| **GlobalEquity** | US / HK | T+0 |+| **GlobalEquity** | US / HK / كندا | تداول في الجلسة نفسها؛ أحجام وخطوات سعرية وتكاليف حسب السوق || **IndiaEquity** | الهند (NSE/BSE) | T+1، ونطاقات القاطع (circuit)، وحزمة تكاليف STT / الدمغة / SEBI / GST قابلة للتهيئة || **KoreaEquity** | كوريا (KRX: KOSPI/KOSDAQ) | شراء فقط، ونطاق ±30% يُحكم عليه لحظة التنفيذ على شبكة الخطوة السعرية الموحّدة، وضريبة تداول 0.20% لعام 2026 || **Crypto** | crypto فوري / عقود USD-M الدائمة | تسويات التمويل، وفصل سعر التنفيذ عن سعر العلامة |@@ -640,7 +641,7 @@ vibe-trading-mcp # start MCP server (stdio)> **مزودو LLM المدعومون:** OpenRouter, Requesty, OpenAI, Anthropic (Messages API الأصلي), DeepSeek, Gemini, Groq, DashScope/Qwen, Zhipu, Moonshot/Kimi, MiniMax, SiliconFlow (CN + Global), Xiaomi MIMO, iFlytek Spark, Z.ai, NVIDIA NIM, Ollama (local). عند عدم ضبط أي `*_BASE_URL`، يتراجع كل مزوّد إلى نقطة نهايته القانونية، فيكفي مفتاح واحد. راجع `.env.example` للإعداد.-> **نصيحة:** تعمل كل الأسواق دون مفاتيح API بفضل fallback التلقائي. yfinance (HK/US)، وOKX (crypto)، وmootdx (أسهم A، اتصال TCP مباشر بدون قيود IP)، وAKShare (A-shares, US, HK, futures, forex) كلها مجانية. رمز Tushare اختياري — mootdx هو الـ fallback الموصى به لأسهم A بدون رمز، بينما يوفر AKShare احتياطياً أوسع تغطية.+> **نصيحة:** تعمل كل الأسواق دون مفاتيح API بفضل fallback التلقائي. yfinance/Yahoo (HK/US/كندا)، وOKX (crypto)، وmootdx (أسهم A، اتصال TCP مباشر بدون قيود IP)، وAKShare (A-shares, US, HK, futures, forex) كلها مجانية. رمز Tushare اختياري — mootdx هو الـ fallback الموصى به لأسهم A بدون رمز، بينما يوفر AKShare احتياطياً أوسع تغطية.### المسار A: Docker (دون إعداد)diff --git a/README_ja.md b/README_ja.mdindex 3bacf641d..1779ab2e4 100644--- a/README_ja.md+++ b/README_ja.md@@ -237,7 +237,7 @@<img src="assets/feature-cross-market-data-backtesting.png" height="130" alt="Cross-market data and backtesting"/><br><h3>📊 クロスマーケットデータ & バックテスト</h3><div align="left">- • A/HK/US/インド/韓国株式、暗号資産、先物、FX<br>+ • A/HK/US/カナダ/インド/韓国株式、暗号資産、先物、FX<br>• データフォールバックと複合バックテスト<br>• PIT データ、検証、run cards</div>@@ -328,7 +328,7 @@ vibe-trading run -p "Analyze my trading behavior, extract my shadow strategy, an| レイヤー | 何が起きるか ||-------|--------------|| **Plan** | 必要な finance skills、tools、data sources、必要に応じて swarm preset を選びます。 |-| **Ground** | A 株、HK/US 株式、暗号資産、先物、FX、documents、Web context を利用可能な loaders から取得します。 |+| **Ground** | A 株、HK/US/カナダ株式、暗号資産、先物、FX、documents、Web context を利用可能な loaders から取得します。 || **Execute** | テスト可能な strategy code を生成し、tools を実行し、対応する backtest engine または analysis workflow を使います。 || **Validate** | metrics、benchmark comparison、Monte Carlo、Bootstrap、Walk-Forward、run cards、必要な warnings を追加します。 || **Deliver** | TradingView、TDX、MetaTrader 5、MCP clients、後続セッション向けの reports、artifacts、tool traces、exports を返します。 |@@ -345,8 +345,9 @@ vibe-trading run -p "Analyze my trading behavior, extract my shadow strategy, an| `eastmoney` | A / US / HK | none | OHLCV + deep fundamentals & flow tools (throttled) || `baostock` · `akshare` | A (+ US/HK/futures/macro/fx) | none | free fallbacks || `tushare` | A / HK / futures / fund / macro | token | richest A-share |-| `yahoo` · `sina` · `stooq` | US (/HK) | none | direct chart/quotes/options · K-line to 1984 · EOD CSV |-| `yfinance` | US / HK | none | wrapper |+| `yahoo` | US / HK / カナダ | none | direct chart/quotes/options;TSX `.TO` / TSXV `.V` |+| `sina` · `stooq` | US | none | K-line to 1984 · EOD CSV |+| `yfinance` | US / HK / カナダ | none | wrapper;TSX `.TO` / TSXV `.V` はそのまま使用 || `longbridge` | US / HK | App Key + App Secret + Access Token | optional historical OHLCV source; install the optional SDK || `finnhub` · `alphavantage` · `tiingo` · `fmp` | US | key | optional providers || `qveris` | グローバル・マルチアセット | key · credits | **プレミアムマーケットプレイス** — 1つの key で 63+ providers(明示指定のみ、auto フォールバック対象外) |@@ -553,7 +554,7 @@ Paper-vs-live is a **structural per-broker runtime guard** (account-id format, h| Engine | Market | Notes ||--------|--------|-------|| **ChinaA** | A-share | T+1, price limits, pre-ST filter |-| **GlobalEquity** | US / HK | T+0 |+| **GlobalEquity** | US / HK / カナダ | 同一セッション売買、市場別のロット・呼値・コスト || **IndiaEquity** | India (NSE/BSE) | T+1, circuit bands, config-driven STT / stamp / SEBI / GST cost stack || **KoreaEquity** | 韓国(KRX:KOSPI/KOSDAQ) | ロングオンリー、統一呼値グリッド上で ±30% 制限値幅を約定時点に判定、2026 年 0.20% の証券取引税 || **Crypto** | crypto spot / USD-M perps | funding settlements, execution/mark split |@@ -640,7 +641,7 @@ vibe-trading-mcp # start MCP server (stdio)> **Supported LLM providers:** OpenRouter、Requesty、OpenAI、Anthropic(ネイティブ Messages API)、DeepSeek、Gemini、Groq、DashScope/Qwen、Zhipu、Moonshot/Kimi、MiniMax、SiliconFlow(CN + Global)、Xiaomi MIMO、iFlytek Spark、Z.ai、NVIDIA NIM、Ollama(local)。`*_BASE_URL` が未設定の場合、各プロバイダーは canonical なエンドポイントにフォールバックするため、key だけで十分です。設定は `.env.example` を参照してください。-> **Tip:** 自動フォールバックにより、すべての市場は API key なしで利用できます。yfinance(HK/US)、OKX(crypto)、mootdx(A 株、TCP 直結で IP 制限なし)、AKShare(A-shares、US、HK、futures、forex)はすべて無料です。Tushare token は任意で、A 株は mootdx が推奨の no-token fallback、AKShare がより広いカバレッジのバックアップになります。+> **Tip:** 自動フォールバックにより、すべての市場は API key なしで利用できます。yfinance/Yahoo(HK/US/カナダ)、OKX(crypto)、mootdx(A 株、TCP 直結で IP 制限なし)、AKShare(A-shares、US、HK、futures、forex)はすべて無料です。Tushare token は任意で、A 株は mootdx が推奨の no-token fallback、AKShare がより広いカバレッジのバックアップになります。### Path A: Docker(設定ゼロ)diff --git a/README_ko.md b/README_ko.mdindex 0908e3b19..855c27c90 100644--- a/README_ko.md+++ b/README_ko.md@@ -237,7 +237,7 @@<img src="assets/feature-cross-market-data-backtesting.png" height="130" alt="크로스마켓 데이터와 백테스팅"/><br><h3>📊 크로스마켓 데이터 & 백테스팅</h3><div align="left">- • A/HK/US/인도/한국 주식, 크립토, 선물, 외환<br>+ • A/HK/US/캐나다/인도/한국 주식, 크립토, 선물, 외환<br>• 데이터 fallback과 composite backtest<br>• PIT 데이터, 검증, run card</div>@@ -328,7 +328,7 @@ vibe-trading run -p "Analyze my trading behavior, extract my shadow strategy, an| 계층 | 수행 내용 ||------|-----------|| **Plan** | 유용한 경우 관련 finance skills, tools, data sources, swarm preset을 선택합니다. |-| **Ground** | 사용 가능한 loader로 A주, HK/US 주식, 크립토, 선물, 외환, 문서, 웹 컨텍스트를 가져옵니다. |+| **Ground** | 사용 가능한 loader로 A주, HK/US/캐나다 주식, 크립토, 선물, 외환, 문서, 웹 컨텍스트를 가져옵니다. || **Execute** | 테스트 가능한 전략 코드를 생성하고, 도구를 실행하며, 적절한 backtest engine 또는 analysis workflow를 사용합니다. || **Validate** | 지표, benchmark comparison, Monte Carlo, Bootstrap, Walk-Forward, run cards, 관련 warning을 추가합니다. || **Deliver** | TradingView, TDX, MetaTrader 5, MCP client, 이후 세션을 위한 리포트, artifacts, tool traces, exports를 반환합니다. |@@ -345,8 +345,9 @@ vibe-trading run -p "Analyze my trading behavior, extract my shadow strategy, an| `eastmoney` | A / US / HK | none | OHLCV + deep fundamentals & flow tools (throttled) || `baostock` · `akshare` | A (+ US/HK/futures/macro/fx) | none | free fallbacks || `tushare` | A / HK / futures / fund / macro | token | richest A-share |-| `yahoo` · `sina` · `stooq` | US (/HK) | none | direct chart/quotes/options · K-line to 1984 · EOD CSV |-| `yfinance` | US / HK | none | wrapper |+| `yahoo` | US / HK / 캐나다 | none | direct chart/quotes/options; TSX `.TO` / TSXV `.V` |+| `sina` · `stooq` | US | none | K-line to 1984 · EOD CSV |+| `yfinance` | US / HK / 캐나다 | none | wrapper; TSX `.TO` / TSXV `.V` 그대로 사용 || `longbridge` | US / HK | App Key + App Secret + Access Token | optional historical OHLCV source; install the optional SDK || `finnhub` · `alphavantage` · `tiingo` · `fmp` | US | key | optional providers || `qveris` | 글로벌 멀티에셋 | key · credits | **프리미엄 마켓플레이스** — key 하나로 63+ providers (명시 지정 전용, auto 폴백 제외) |@@ -553,7 +554,7 @@ Paper-vs-live는 **구조적 브로커별 런타임 가드**(account-id 형식,| Engine | Market | Notes ||--------|--------|-------|| **ChinaA** | A-share | T+1, price limits, pre-ST filter |-| **GlobalEquity** | US / HK | T+0 |+| **GlobalEquity** | US / HK / 캐나다 | 동일 세션 거래, 시장별 주문 단위·호가·비용 || **IndiaEquity** | India (NSE/BSE) | T+1, circuit bands, config-driven STT / stamp / SEBI / GST cost stack || **KoreaEquity** | 한국 (KRX: KOSPI/KOSDAQ) | 롱 온리, 통합 호가 단위에서 ±30% 가격제한폭을 체결 시점에 판정, 2026년 0.20% 증권거래세 || **Crypto** | crypto spot / USD-M perps | funding settlements, execution/mark split |@@ -640,7 +641,7 @@ vibe-trading-mcp # start MCP server (stdio)> **지원 LLM provider:** OpenRouter, Requesty, OpenAI, Anthropic (native Messages API), DeepSeek, Gemini, Groq, DashScope/Qwen, Zhipu, Moonshot/Kimi, MiniMax, SiliconFlow (CN + Global), Xiaomi MIMO, iFlytek Spark, Z.ai, NVIDIA NIM, Ollama(local). `*_BASE_URL`이 설정되지 않으면 각 provider는 canonical endpoint로 폴백하므로 key만 있으면 충분합니다. 설정은 `.env.example`을 참고하세요.-> **팁:** 자동 fallback 덕분에 모든 시장은 API key 없이도 작동합니다. yfinance(HK/US), OKX(crypto), mootdx(A주, TCP 직결, IP 제한 없음), AKShare(A주, US, HK, futures, forex)는 모두 무료입니다. Tushare token은 선택 사항이며, mootdx가 권장 no-token A주 fallback이고 AKShare는 더 넓은 커버리지의 백업입니다.+> **팁:** 자동 fallback 덕분에 모든 시장은 API key 없이도 작동합니다. yfinance/Yahoo(HK/US/캐나다), OKX(crypto), mootdx(A주, TCP 직결, IP 제한 없음), AKShare(A주, US, HK, futures, forex)는 모두 무료입니다. Tushare token은 선택 사항이며, mootdx가 권장 no-token A주 fallback이고 AKShare는 더 넓은 커버리지의 백업입니다.### 경로 A: Docker (설정 불필요)diff --git a/README_zh.md b/README_zh.mdindex 1cd097761..530d8ee11 100644--- a/README_zh.md+++ b/README_zh.md@@ -236,7 +236,7 @@<img src="assets/feature-cross-market-data-backtesting.png" height="130" alt="Cross-market data and backtesting"/><br><h3>📊 跨市场数据与回测</h3><div align="left">- • A 股、港股、美股、印度、韩国、加密、期货与外汇<br>+ • A 股、港股、美股、加拿大、印度、韩国、加密、期货与外汇<br>• 数据 fallback 与组合回测<br>• PIT 数据、验证与 run cards</div>@@ -327,7 +327,7 @@ vibe-trading run -p "Analyze my trading behavior, extract my shadow strategy, an| 层 | 发生什么 ||----|----------|| **Plan** | 选择相关金融 skills、tools、数据源,以及在有帮助时选择 swarm preset。 |-| **Ground** | 通过可用 loader 拉取 A 股、港股/美股、加密、期货、外汇、文档或网页上下文。 |+| **Ground** | 通过可用 loader 拉取 A 股、港股/美股/加拿大股票、加密、期货、外汇、文档或网页上下文。 || **Execute** | 生成可测试的策略代码,运行工具,并使用匹配的回测引擎或分析工作流。 || **Validate** | 在适用时加入指标、benchmark comparison、Monte Carlo、Bootstrap、Walk-Forward、run cards 和 warnings。 || **Deliver** | 返回报告、artifacts、tool traces,以及面向 TradingView、TDX、MetaTrader 5、MCP clients 或后续 sessions 的导出。 |@@ -344,8 +344,9 @@ vibe-trading run -p "Analyze my trading behavior, extract my shadow strategy, an| `eastmoney` | A / US / HK | none | OHLCV + deep fundamentals & flow tools (throttled) || `baostock` · `akshare` | A (+ US/HK/futures/macro/fx) | none | free fallbacks || `tushare` | A / HK / futures / fund / macro | token | richest A-share |-| `yahoo` · `sina` · `stooq` | US (/HK) | none | direct chart/quotes/options · K-line to 1984 · EOD CSV |-| `yfinance` | US / HK | none | wrapper |+| `yahoo` | 美股 / 港股 / 加拿大 | none | direct chart/quotes/options;TSX `.TO` / TSXV `.V` |+| `sina` · `stooq` | 美股 | none | K-line to 1984 · EOD CSV |+| `yfinance` | 美股 / 港股 / 加拿大 | none | wrapper;TSX `.TO` / TSXV `.V` 原样传递 || `longbridge` | 美股 / 港股 | App Key + App Secret + Access Token | 可选历史 OHLCV 数据源;需安装可选 SDK || `finnhub` · `alphavantage` · `tiingo` · `fmp` | US | key | optional providers || `qveris` | 全球多资产 | key · credits | **付费市场** — 一把 key 通 63+ 家(仅显式选用,绝不进 auto 链) |@@ -550,7 +551,7 @@ LONGBRIDGE_ACCESS_TOKEN=...| 引擎 | 市场 | 说明 ||------|------|------|| **ChinaA** | A 股 | T+1、涨跌停、pre-ST 筛选 |-| **GlobalEquity** | 美股 / 港股 | T+0 |+| **GlobalEquity** | 美股 / 港股 / 加拿大 | 支持日内往返;按市场应用手数、最小价位和成本 || **IndiaEquity** | 印度(NSE/BSE) | T+1、熔断带、config 驱动的 STT / 印花税 / SEBI / GST 成本栈 || **KoreaEquity** | 韩国(KRX:KOSPI/KOSDAQ) | 只做多,统一最小价位网格上于成交时刻判定 ±30% 涨跌停,2026 年 0.20% 证券交易税 || **Crypto** | 加密现货 / USD-M 永续 | 资金费结算、成交价/标记价分离 |@@ -637,7 +638,7 @@ vibe-trading-mcp # start MCP server (stdio)> **支持的 LLM providers:** OpenRouter、Requesty、OpenAI、Anthropic(原生 Messages API)、DeepSeek、Gemini、Groq、DashScope/Qwen、Zhipu、Moonshot/Kimi、MiniMax、SiliconFlow(CN + Global)、Xiaomi MIMO、iFlytek 星火、Z.ai、NVIDIA NIM、Ollama(本地)。未设置 `*_BASE_URL` 时,每个 provider 会回退到其规范端点,因此只需一个 key 即可。配置见 `.env.example`。-> **提示:** 由于自动 fallback,所有市场都可以在没有任何 API key 的情况下工作。yfinance(港/美股)、OKX(加密)、mootdx(A 股,TCP 直连不封 IP)和 AKShare(A 股、美股、港股、期货、外汇)都是免费的。Tushare token 是可选项 —— mootdx 是首选的免 token A 股 fallback,AKShare 作为覆盖更广的兜底。+> **提示:** 由于自动 fallback,所有市场都可以在没有任何 API key 的情况下工作。yfinance/Yahoo(港股/美股/加拿大)、OKX(加密)、mootdx(A 股,TCP 直连不封 IP)和 AKShare(A 股、美股、港股、期货、外汇)都是免费的。Tushare token 是可选项 —— mootdx 是首选的免 token A 股 fallback,AKShare 作为覆盖更广的兜底。### Path A: Docker(零配置)diff --git a/agent/SKILL.md b/agent/SKILL.mdindex 982fa27d0..8e8598f69 100644--- a/agent/SKILL.md+++ b/agent/SKILL.md@@ -8,7 +8,7 @@ dependencies:- vibe-trading-aienv:- name: TUSHARE_TOKEN- description: "Tushare API token for China A-share data (optional — HK/US/crypto work without any key)"+ description: "Tushare API token for China A-share data (optional — HK/US/Canada/crypto work without any key)"required: false- name: OPENAI_API_KEYdescription: "OpenAI-compatible API key — only needed for run_swarm (multi-agent teams). All other tools work without it."@@ -53,11 +53,11 @@ Add to your agent's MCP config:### API Key Requirements-Core research MCP tools work with zero API keys for HK/US/crypto. After `pip install`, backtesting, market data, factor analysis, options pricing, chart patterns, web search, document reading, trade journal analysis, shadow-account extraction/backtest/report, the Alpha Zoo (462 pre-built alphas), and all 89 skills are ready to use. IBKR tools require a local TWS / IB Gateway session; `run_swarm` requires an LLM key.+Core research MCP tools work with zero API keys for HK/US/Canada/crypto. After `pip install`, backtesting, market data, factor analysis, options pricing, chart patterns, web search, document reading, trade journal analysis, shadow-account extraction/backtest/report, the Alpha Zoo (462 pre-built alphas), and all 89 skills are ready to use. IBKR tools require a local TWS / IB Gateway session; `run_swarm` requires an LLM key.| Feature | Key needed | When ||---------|-----------|------|-| HK/US equities & crypto | None | Always free (yfinance / stooq / yahoo + OKX) |+| HK/US/Canada equities & crypto | None | Always free (yfinance / stooq / yahoo + OKX) || China A-share data | None | Free via akshare / baostock / tencent / sina / eastmoney / mootdx fallback (`TUSHARE_TOKEN` optional for premium quality) || Premium US fundamentals/quotes | `FINNHUB_API_KEY` / `ALPHAVANTAGE_API_KEY` / `TIINGO_API_KEY` / `FMP_API_KEY` | Only for optional-key providers (graceful fallback to free sources) || Multi-agent swarm (`run_swarm`) | `OPENAI_API_KEY` + `LANGCHAIN_MODEL_NAME` | Swarm spawns internal LLM workers |@@ -76,6 +76,7 @@ Feed a CSV broker export (同花顺 / 东财 / 富途 / generic), and the agent### BacktestingCreate and run quantitative strategies across 9 engines (ChinaA, GlobalEquity, IndiaEquity, KoreaEquity, Crypto, ChinaFutures, GlobalFutures, Forex + options) with 24 market-data sources (auto-detect + ordered fallback):- **HK/US equities** via yfinance / stooq / yahoo (free, no API key); optionally via **Longbridge** historical OHLCV (`longbridge`, requires the optional SDK and `LONGBRIDGE_APP_KEY` / `LONGBRIDGE_APP_SECRET` / `LONGBRIDGE_ACCESS_TOKEN`). To force it for a run, set `"source": "longbridge"` in `config.json`.+- **Canada equities (TSX/TSXV)** via yahoo / yfinance using Yahoo's canonical `<TICKER>.TO` (TSX, e.g. `TD.TO`) or `<TICKER>.V` (TSXV, e.g. `PNG.V`) suffixes — free, no API key. The GlobalEquity engine uses CAD identity, whole-share orders, configurable Canadian commission/slippage, and the TSX/TSXV price-increment grid.- **India equities (NSE/BSE)** via yahoo / yfinance using `<SYMBOL>.NS` (NSE, e.g. `RELIANCE.NS`) or `<SCRIP>.BO` (BSE, e.g. `500325.BO`) — free, no API key. The `IndiaEquityEngine` models T+1 delivery, no overnight shorts (set `allow_short` for intraday), configurable circuit bands, 1-share lots, and the STT/stamp-duty/exchange/GST cost stack. Optionally back-fill from your live broker via the `india_broker` source (Shoonya/Dhan; requires broker login).- **Korea equities (KRX: KOSPI/KOSDAQ)** via pykrx using `<CODE>.KS` (KOSPI, e.g. `005930.KS`) or `<CODE>.KQ` (KOSDAQ, e.g. `247540.KQ`) — free, no API key (`pip install "vibe-trading-ai[krx]"`; yahoo/yfinance fallback needs no extra). pykrx serves **daily bars only** (an intraday request falls through to another source) and its adjusted series is Naver-backed rather than a verbatim KRX print. The `KoreaEquityEngine` models same-day round trips (no T+1), the ±30% daily price limit measured from the previous close and quantized to the KRX tick grid, tick-rounded fills, the 0.20% sell-side transaction tax (2026 rate), and 1-share lots. It is **long-only**: `allow_short` is refused, because KRX covered-short and uptick rules cannot be enforced on daily bars.- **Cryptocurrency** via OKX or CCXT/100+ exchanges (free, no API key)@@ -193,7 +194,7 @@ Use `load_skill(name)` to access full methodology docs with code templates.| `trading_quote` | Read a quote snapshot from selected connector | Connector app/OAuth || `trading_history` | Read historical bars from selected connector | Connector app/OAuth |-<sub>*A-share symbols require `TUSHARE_TOKEN`. HK/US/crypto are free. Trading connector rows use the selected connector profile, e.g. IBKR local TWS/Gateway or Robinhood MCP OAuth.</sub>+<sub>*A-share symbols require `TUSHARE_TOKEN`. HK/US/Canada/crypto are free. Trading connector rows use the selected connector profile, e.g. IBKR local TWS/Gateway or Robinhood MCP OAuth.</sub>## Quick Start@@ -201,7 +202,7 @@ Use `load_skill(name)` to access full methodology docs with code templates.pip install vibe-trading-ai```-That's it — no API keys needed for HK/US/crypto markets. Start using `backtest`, `get_market_data`, `analyze_options`, `analyze_trade_journal`, `extract_shadow_strategy`, `web_search`, the **Alpha Zoo** (`vibe-trading alpha bench --zoo gtja191 --universe csi300 --period 2018-2025`), and all 89 skills immediately.+That's it — no API keys needed for HK/US/Canada/crypto markets. Start using `backtest`, `get_market_data`, `analyze_options`, `analyze_trade_journal`, `extract_shadow_strategy`, `web_search`, the **Alpha Zoo** (`vibe-trading alpha bench --zoo gtja191 --universe csi300 --period 2018-2025`), and all 89 skills immediately.## Loading Tools from External MCP Serversdiff --git a/agent/backtest/benchmark.py b/agent/backtest/benchmark.pyindex 0b5a68bad..e9cc8da75 100644--- a/agent/backtest/benchmark.py+++ b/agent/backtest/benchmark.py@@ -22,6 +22,7 @@ from backtest.metrics import bar_returns, buy_and_hold_returnMARKET_BENCHMARKS: dict[str, Optional[str]] = {"us_equity": "SPY","hk_equity": "HK.03100", # Hang Seng China Enterprises ETF+ "ca_equity": "XIC.TO", # S&P/TSX Capped Composite ETF"a_share": "000300.SH", # CSI 300 (China A-share core index)"crypto": "BTC-USDT","futures": "ES.CME", # E-mini S&P 500 futures@@ -120,8 +121,8 @@ def _resolve_ticker(ticker = MARKET_BENCHMARKS.get(market)# yfinance is the universal fallback for benchmark fetch- # but it only works for us_equity / hk_equity market types- if ticker and market not in {"us_equity", "hk_equity"}:+ # but it only works for global-equity market types+ if ticker and market not in {"us_equity", "hk_equity", "ca_equity"}:# Only use benchmark if we can actually fetch itpass@@ -135,12 +136,19 @@ def _infer_market(codes: list[str], source: str) -> str:first = codes[0].upper()- if source in ("okx", "ccxt") or "-" in first or "/" in first:- return "crypto"if first.endswith(".US"):return "us_equity"if first.endswith(".HK"):return "hk_equity"+ if first.endswith((".TO", ".V")):+ return "ca_equity"+ if first.endswith((".NS", ".BO")):+ return "india_equity"+ if first.endswith((".KS", ".KQ")):+ return "kr_equity"+ crypto_quotes = ("-USDT", "-USDC", "-USD", "-BTC", "-ETH")+ if source in ("okx", "ccxt", "binance") or "/" in first or first.endswith(crypto_quotes):+ return "crypto"if source in ("tushare", "akshare"):if first.isdigit() and len(first) == 6:return "a_share"diff --git a/agent/backtest/correlation.py b/agent/backtest/correlation.pyindex 81baa04c1..bed2d5b1d 100644--- a/agent/backtest/correlation.py+++ b/agent/backtest/correlation.py@@ -23,8 +23,9 @@ def infer_market(code: str) -> str:1. Crypto pair spellings (``BTC-USDT``, ``ETH/USD`` …).2. Explicit exchange suffix — always authoritative (``.HK``, ``.SH``/- ``.SZ``/``.BJ``, ``.US``). Bare HK and A-share codes are both purely- numeric, so the suffix is the only reliable disambiguator.+ ``.SZ``/``.BJ``, ``.TO``/``.V``, ``.US``). Bare HK and A-share codes+ are both purely numeric, so the suffix is the only reliable+ disambiguator.3. Bare numeric codes by digit length: A-share codes are exactly 6 digits(600000, 000001, 300750, 688981, 830799); HK codes are at most 5(700, 0700, 9988, 3690). Prefix alone cannot tell them apart — bothdiff --git a/agent/backtest/engines/_market_hooks.py b/agent/backtest/engines/_market_hooks.pyindex 03ce263e5..4ef81201d 100644--- a/agent/backtest/engines/_market_hooks.py+++ b/agent/backtest/engines/_market_hooks.py@@ -32,8 +32,8 @@ _MARKET_PATTERNS = [(re.compile(r"^[A-Z0-9&.\-]+\.(NS|BO)$", re.I), "india_equity"),# Korea equities: KOSPI (005930.KS) / KOSDAQ (247540.KQ), 6-digit codes.(re.compile(r"^\d{6}\.(KS|KQ)$", re.I), "kr_equity"),- # Canada equities: TSX (TD.TO) / TSX Venture (SHOP.V). Yahoo carries these- # suffixes verbatim; Canadian symbols settle in CAD.+ # Canada equities: Toronto Stock Exchange (TD.TO) and TSX Venture+ # (PNG.V). Yahoo carries both suffixes verbatim.(re.compile(r"^[A-Z0-9&.\-]+\.(TO|V)$", re.I), "ca_equity"),(re.compile(r"^[A-Z]+-USDT$", re.I), "crypto"),(re.compile(r"^[A-Z]+/USDT$", re.I), "crypto"),@@ -139,7 +139,8 @@ def _detect_market(code: str) -> str:code: Ticker / symbol string.Returns:- Market type (a_share/us_equity/hk_equity/crypto/futures/forex).+ Market type (a_share/us_equity/hk_equity/india_equity/kr_equity/+ ca_equity/crypto/futures/forex).Bare 1-5 letter alphabetic tickers resolve to ``us_equity``;any other unknown format defaults to ``a_share``."""@@ -181,13 +182,13 @@ def _is_china_futures(code: str) -> bool:def _detect_submarket(codes: List[str]) -> str:- """Detect US vs HK from symbol suffixes.+ """Detect US, HK, or Canada from symbol suffixes.Args:codes: Instrument codes.Returns:- ``"hk"`` if any code ends with ``.HK``, else ``"us"``.+ ``"hk"`` for ``.HK``, ``"ca"`` for ``.TO``/``.V``, else ``"us"``."""for code in codes:upper = code.upper()diff --git a/agent/backtest/engines/global_equity.py b/agent/backtest/engines/global_equity.pyindex 30300b157..9c0fe007f 100644--- a/agent/backtest/engines/global_equity.py+++ b/agent/backtest/engines/global_equity.py@@ -1,4 +1,4 @@-"""Global equity (US / HK) backtest engine.+"""Global equity (US / HK / Canada) backtest engine.Market rules:US:@@ -11,22 +11,27 @@ Market rules:- Stamp tax 0.1% bilateral + levies- Lot-size rounding (simplified to 100 shares)- Higher slippage than US+ Canada (TSX / TSX Venture):+ - Same-session round trips and long/short orders supported+ - Whole shares; odd and mixed lots remain executable+ - Broker commission and slippage are config-driven+ - Official TSX/TSXV price-increment grid is applied to fillsIndia (NSE/BSE) is handled by the dedicated ``backtest.engines.india_equity````IndiaEquityEngine`` (T+1 delivery, circuit bands, STT/stamp/GST stack).-Canada (TSX ``.TO`` / TSX Venture ``.V``) runs on US-style rules — fractional-shares, zero commission, US slippage — via ``market="ca"``."""from __future__ import annotations+import math+import pandas as pdfrom backtest.engines.base import BaseEngineclass GlobalEquityEngine(BaseEngine):- """US / HK equity engine, selected by *market* parameter.+ """US / HK / Canada equity engine, selected by *market* parameter.Config keys:- slippage_us: default 0.0005@@ -35,6 +40,8 @@ class GlobalEquityEngine(BaseEngine):- hk_commission: default 0.00015 (万1.5)- hk_levy: default 0.0000565 (SFC + FRC)- hk_settlement: default 0.00002 (CCASS)+ - slippage_ca: defaults to slippage_us+ - ca_commission: broker commission rate, default 0.0"""def __init__(self, config: dict, market: str = "us"):@@ -50,19 +57,31 @@ class GlobalEquityEngine(BaseEngine):self.hk_commission: float = config.get("hk_commission", 0.00015)self.hk_levy: float = config.get("hk_levy", 0.0000565)self.hk_settlement: float = config.get("hk_settlement", 0.00002)+ # Canada defaults. Commission varies by broker, so the model exposes a+ # rate instead of inventing an exchange-wide charge.+ self.slippage_ca: float = config.get("slippage_ca", self.slippage_us)+ self.ca_commission: float = config.get("ca_commission", 0.0)def can_execute(self, symbol: str, direction: int, bar: pd.Series) -> bool:- """US/HK: T+0, both directions allowed."""+ """US/HK/Canada: same-session trading, both directions allowed."""return Truedef round_size(self, raw_size: float, price: float) -> float:- """US: fractional shares (0.01). HK: 100-share lots."""+ """US: fractional; HK: 100-share lots; Canada: whole shares.++ TSX and TSXV accept odd and mixed lots through dedicated facilities,+ so forcing every order to a board lot would reject valid retail trades.+ The exchange still has no native fractional-share order, hence the+ whole-share floor.+ """if self.market == "hk":return max(int(raw_size / 100) * 100, 0)+ if self.market == "ca":+ return float(math.floor(max(raw_size, 0.0)))return round(max(raw_size, 0.0), 2)def calc_commission(self, size: float, price: float, _direction: int, is_open: bool) -> float:- """US: zero commission. HK: stamp tax + levies.+ """US: zero; HK: stamp tax + levies; Canada: configured broker rate.``_direction`` is unused — reserved for future short-borrow fees(US Reg-T margin, HK SBL costs).@@ -74,10 +93,31 @@ class GlobalEquityEngine(BaseEngine):comm += notional * self.hk_levy # SFC + FRC leviescomm += notional * self.hk_settlement # CCASS settlementreturn comm+ if self.market == "ca":+ return size * price * self.ca_commission# US: zero commission (SEC fee negligible)return 0.0def apply_slippage(self, price: float, direction: int) -> float:- """US: low slippage. HK: moderate slippage."""- rate = self.slippage_hk if self.market == "hk" else self.slippage_us- return price * (1 + direction * rate)+ """Apply market slippage and Canada's official price-increment grid."""+ if self.market == "hk":+ rate = self.slippage_hk+ elif self.market == "ca":+ rate = self.slippage_ca+ else:+ rate = self.slippage_us+ slipped = price * (1 + direction * rate)+ if self.market != "ca":+ return slipped++ # TSX/TSXV standard increments: $0.005 below $0.50, otherwise $0.01.+ # Round against the trader: buys/cover orders up, sells/shorts down.+ tick = 0.005 if slipped < 0.50 else 0.01+ units = slipped / tick+ if direction > 0:+ steps = math.ceil(units - 1e-12)+ elif direction < 0:+ steps = math.floor(units + 1e-12)+ else:+ steps = round(units)+ return round(steps * tick, 3 if tick == 0.005 else 2)diff --git a/agent/backtest/loaders/eastmoney_client.py b/agent/backtest/loaders/eastmoney_client.pyindex 83f932868..b84cf49f4 100644--- a/agent/backtest/loaders/eastmoney_client.py+++ b/agent/backtest/loaders/eastmoney_client.py@@ -25,7 +25,7 @@ import loggingimport refrom typing import Any-from backtest.loaders._http import resolve_min_interval, throttled_get+from backtest.loaders._http import resolve_min_interval, throttled_get_jsonlogger = logging.getLogger(__name__)@@ -79,36 +79,27 @@ def _min_interval() -> float:def get_json(url: str, *, params: dict[str, Any]) -> Any:- """Issue a throttled Eastmoney GET and decode the body as JSON or JSONP.-- Eastmoney's search/suggest endpoint returns a JSONP envelope- (``callback({...})``) instead of plain JSON — parsing it with- ``response.json()`` raises ``JSONDecodeError: Expecting value``. This- decode path goes through :func:`_strip_jsonp`, which prefers raw JSON and- only unwraps a real JSONP wrapper, so one path serves both the search- (JSONP) and kline (plain JSON) endpoints.+ """Issue a throttled Eastmoney GET and decode the body as JSON.Args:url: Fully-qualified Eastmoney endpoint URL.params: Query parameters for the request.Returns:- The decoded payload (typically a ``dict``), or ``None`` when the body- is neither valid JSON nor a recognizable JSONP envelope.+ The decoded JSON payload (typically a ``dict``).Raises:requests.RequestException: Network failure, propagated for the caller'sretry policy.requests.HTTPError: Non-2xx response status.+ ValueError: Body is not valid JSON."""- response = throttled_get(+ return throttled_get_json(url,host_key=_HOST_KEY,min_interval=_min_interval(),params=params,)- response.raise_for_status()- return _strip_jsonp(response.text)def _resolve_a_share_secid(code: str, suffix: str) -> str | None:diff --git a/agent/backtest/loaders/registry.py b/agent/backtest/loaders/registry.pyindex ecbfc53e2..1dcb00aa5 100644--- a/agent/backtest/loaders/registry.py+++ b/agent/backtest/loaders/registry.py@@ -142,8 +142,7 @@ FALLBACK_CHAINS: dict[str, list[str]] = {"hk_equity": ["tencent", "eastmoney", "yahoo", "futu", "akshare", "yfinance", "tushare", "longbridge", "local"],"india_equity": ["yahoo", "yfinance", "india_broker", "local"],"kr_equity": ["pykrx", "yahoo", "yfinance", "local"],- # Canada equities: TSX (.TO) / TSX Venture (.V) — Yahoo serves these- # verbatim (ca.yahoo.com = same query API); yfinance is the SDK fallback.+ # TSX (.TO) / TSX Venture (.V): direct Yahoo first, SDK fallback second."ca_equity": ["yahoo", "yfinance", "local"],# OKX first (native), then dedicated Binance, then generic CCXT / Yahoo."crypto": ["okx", "binance", "ccxt", "yfinance", "local"],diff --git a/agent/backtest/loaders/yahoo_client.py b/agent/backtest/loaders/yahoo_client.pyindex 3e4565cd4..5a3bc3586 100644--- a/agent/backtest/loaders/yahoo_client.py+++ b/agent/backtest/loaders/yahoo_client.py@@ -16,9 +16,8 @@ Symbol convention (Vibe-Trading -> Yahoo):* HK ``00700.HK`` -> ``0700.HK`` (Yahoo drops the leading zero to 4 digits)* India ``RELIANCE.NS`` / ``500325.BO`` -> unchanged (Yahoo carries the``.NS``/``.BO`` suffix verbatim)- * Canada ``TD.TO`` / ``SHOP.V`` -> unchanged (Yahoo carries the- ``.TO``/``.V`` suffix verbatim; the ca.yahoo.com portal uses the same- query API)+ * Canada ``TD.TO`` / ``PNG.V`` -> unchanged (Yahoo carries the+ ``.TO``/``.V`` suffix verbatim)* Anything else is passed through unchanged (e.g. ``BTC-USD``, ``^GSPC``).This module is provider-specific glue only; it returns plain Python@@ -73,12 +72,14 @@ def map_symbol(symbol: str) -> str:"""Translate a Vibe-Trading symbol into Yahoo's ticker convention.Args:- symbol: Project-side symbol, e.g. ``AAPL.US``, ``00700.HK``, ``BTC-USD``.+ symbol: Project-side symbol, e.g. ``AAPL.US``, ``00700.HK``, ``TD.TO``,+ or ``BTC-USD``.Returns:The Yahoo ticker: ``.US`` suffix stripped; ``.HK`` codes normalized toa 4-digit base (``00700.HK`` -> ``0700.HK``); India ``.NS``/``.BO`` and- everything else unchanged (Yahoo carries those suffixes verbatim).+ Canada ``.TO``/``.V`` suffixes, plus all other symbols, pass through+ unchanged."""cleaned = symbol.strip()upper = cleaned.upper()diff --git a/agent/backtest/loaders/yahoo_loader.py b/agent/backtest/loaders/yahoo_loader.pyindex 93e58fabb..1ccb531c5 100644--- a/agent/backtest/loaders/yahoo_loader.py+++ b/agent/backtest/loaders/yahoo_loader.py@@ -4,7 +4,7 @@ Wraps the shared :mod:`backtest.loaders.yahoo_client` (the public v8 chartendpoint) rather than the ``yfinance`` package, so it pulls in no newdependency and shares the process-wide throttle/session that keeps Yahoo fromIP-rate-limiting us. Covers US equities (``AAPL.US``), HK equities-(``00700.HK``) and Canada equities (``TD.TO``, ``SHOP.V``); the client maps+(``00700.HK``), and Canadian equities (``TD.TO`` / ``PNG.V``); the client mapseach project symbol to Yahoo's ticker form.The chart endpoint returns each bar's ``trade_date`` as an epoch-second@@ -50,7 +50,9 @@ def _is_supported(code: str) -> bool:no conversion) (#718)."""upper = code.strip().upper()- return upper.endswith((".US", ".HK", ".NS", ".BO", ".KS", ".KQ", ".TO", ".V", "=F", "=X"))+ return upper.endswith(+ (".US", ".HK", ".NS", ".BO", ".KS", ".KQ", ".TO", ".V", "=F", "=X")+ )def _to_yahoo_interval(interval: str) -> str:@@ -170,10 +172,12 @@ def _rows_to_frame(@registerclass DataLoader:- """Yahoo Finance US/HK equity OHLCV loader (free, direct HTTP, no auth)."""+ """Yahoo Finance global-equity OHLCV loader (free, direct HTTP, no auth)."""name = "yahoo"- markets = {"us_equity", "hk_equity", "india_equity", "kr_equity", "ca_equity"}+ markets = {+ "us_equity", "hk_equity", "india_equity", "kr_equity", "ca_equity",+ }requires_auth = Falsedef is_available(self) -> bool:@@ -196,7 +200,8 @@ class DataLoader:"""Fetch OHLCV history keyed by the original project symbols.Args:- codes: Project symbols such as ``AAPL.US`` and ``00700.HK``.+ codes: Project symbols such as ``AAPL.US``, ``00700.HK``, and+ ``TD.TO``.start_date: Inclusive start date (``YYYY-MM-DD``).end_date: Inclusive end date (``YYYY-MM-DD``).interval: Backtest interval such as ``1D`` or ``1H``.diff --git a/agent/backtest/loaders/yfinance_loader.py b/agent/backtest/loaders/yfinance_loader.pyindex 8fd625aee..de2cd088a 100644--- a/agent/backtest/loaders/yfinance_loader.py+++ b/agent/backtest/loaders/yfinance_loader.py@@ -52,7 +52,8 @@ def _to_yfinance_symbol(code: str) -> str:"""Convert project symbols into yfinance symbols.Args:- code: Project symbol, for example ``AAPL.US`` or ``700.HK``.+ code: Project symbol, for example ``AAPL.US``, ``700.HK``, or+ ``TD.TO``.Returns:yfinance-compatible symbol.@@ -69,8 +70,9 @@ def _to_yfinance_symbol(code: str) -> str:return upper[:-5] + "-USD"if upper.endswith("-USDC"):return upper[:-5] + "-USD"- # India NSE/BSE (RELIANCE.NS, 500325.BO) and Korea KRX (005930.KS,- # 247540.KQ): yfinance carries these suffixes as-is.+ # India NSE/BSE (RELIANCE.NS, 500325.BO), Korea KRX (005930.KS,+ # 247540.KQ), and Canada TSX/TSXV (TD.TO, PNG.V): yfinance carries these+ # suffixes as-is.return upper@@ -226,10 +228,12 @@ def _normalize_frame(frame: pd.DataFrame, requested_interval: str) -> pd.DataFra@registerclass DataLoader:- """Fetch HK/US equity bars from Yahoo Finance via yfinance."""+ """Fetch global-equity and crypto bars from Yahoo Finance via yfinance."""name = "yfinance"- markets = {"us_equity", "hk_equity", "india_equity", "kr_equity", "ca_equity", "crypto"}+ markets = {+ "us_equity", "hk_equity", "india_equity", "kr_equity", "ca_equity", "crypto",+ }requires_auth = Falsedef is_available(self) -> bool:@@ -255,7 +259,8 @@ class DataLoader:"""Fetch OHLCV history keyed by the original project symbols.Args:- codes: Project symbols such as ``AAPL.US`` and ``700.HK``.+ codes: Project symbols such as ``AAPL.US``, ``700.HK``, and+ ``TD.TO``.start_date: Start date in ``YYYY-MM-DD`` format.end_date: End date in ``YYYY-MM-DD`` format.fields: Ignored for yfinance; included for interface compatibility.diff --git a/agent/backtest/runner.py b/agent/backtest/runner.pyindex bf4bdfd6a..d3687bf99 100644--- a/agent/backtest/runner.py+++ b/agent/backtest/runner.py@@ -1294,18 +1294,12 @@ def _create_market_engine(source: str, config: dict, codes: List[str]):from backtest.engines.korea_equity import KoreaEquityEnginereturn KoreaEquityEngine(config)- # Canada equity routing — TSX (.TO) / TSX Venture (.V) via Yahoo; uses the- # same GlobalEquityEngine family as US/HK with US-style execution rules.- if "ca_equity" in markets:- from backtest.engines.global_equity import GlobalEquityEngine- return GlobalEquityEngine(config, market="ca")-# Original routing (Wave 1)if source in ("okx", "ccxt"):from backtest.engines.crypto import CryptoEnginereturn CryptoEngine(config)elif source in ("tushare", "akshare"):- if markets & {"us_equity", "hk_equity"}:+ if markets & {"us_equity", "hk_equity", "ca_equity"}:from backtest.engines.global_equity import GlobalEquityEnginemarket = _detect_submarket(codes)return GlobalEquityEngine(config, market=market)@@ -1327,7 +1321,7 @@ def _create_market_engine(source: str, config: dict, codes: List[str]):# Sources without a dedicated branch (local, stooq, ...): follow the# instrument market rather than the loader name, so e.g. a local# AAPL.US dataset gets US-equity execution rules instead of crypto.- if markets & {"us_equity", "hk_equity"}:+ if markets & {"us_equity", "hk_equity", "ca_equity"}:from backtest.engines.global_equity import GlobalEquityEnginemarket = _detect_submarket(codes)return GlobalEquityEngine(config, market=market)diff --git a/agent/mcp_server.py b/agent/mcp_server.pyindex 27af4bcbc..df4c707b4 100644--- a/agent/mcp_server.py+++ b/agent/mcp_server.py@@ -1416,7 +1416,8 @@ def get_market_data("""Fetch OHLCV market data for stocks, crypto, or mixed symbols.Supported sources:- - "yfinance": HK/US/Canada equities (free, e.g. AAPL.US, 700.HK, TD.TO, SHOP.V)+ - "yfinance" / "yahoo": HK/US/Canada equities (free, e.g. AAPL.US,+ 700.HK, TD.TO, PNG.V)- "okx": cryptocurrency (free, e.g. BTC-USDT, ETH-USDT)- "tushare": China A-shares (requires TUSHARE_TOKEN, e.g. 000001.SZ)- "baostock": China A-shares via TCP protocol, bypasses HTTP CDN blocks (e.g. 000001.SZ, 601595.SH)@@ -1427,10 +1428,11 @@ def get_market_data(- "auto": auto-detect based on symbol format (with fallback)Args:- codes: List of symbols (e.g. ["AAPL.US", "BTC-USDT", "000001.SZ"]).+ codes: List of symbols (e.g. ["AAPL.US", "TD.TO", "BTC-USDT", "000001.SZ"]).start_date: Start date (YYYY-MM-DD).end_date: End date (YYYY-MM-DD).- source: Data source ("auto", "yfinance", "okx", "tushare", "baostock", "tencent", "akshare", "ccxt").+ source: Data source. Prefer ``auto``; ``yahoo``/``yfinance`` serve+ Canada, US, and HK equities.interval: Bar size (1m/5m/15m/30m/1H/4H/1D, default "1D").max_rows: Per-symbol row cap (default 250) so the response stayswithin the MCP token budget. A symbol exceeding it returns an@@ -1691,13 +1693,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), 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.+ 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.Args:- code: Symbol whose news to fetch (e.g. "600519.SH", "AAPL.US", "SGML.V").+ code: Symbol whose news to fetch (e.g. "600519.SH", "AAPL.US").Required when scope="stock"; ignored when scope="global".scope: "stock" (default) or "global".limit: Maximum number of headlines to return.@@ -1742,14 +1744,12 @@ 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), 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.+ 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.Args:- code: Single symbol with a market suffix (e.g. "600519.SH", "AAPL.US",- "SGML.V").+ code: Single symbol with a market suffix (e.g. "600519.SH", "AAPL.US").statement: "balance", "income", "cashflow", or "indicators".period: "annual" or "quarter"."""@@ -1826,10 +1826,10 @@ def search_symbol(query: str, limit: int = 10) -> str:"""Resolve a company name or ticker fragment to candidate trading symbols.Returns candidates with their market in the project's symbol convention- (A-shares 600519.SH, Hong Kong 00700.HK, U.S. AAPL.US, plus crypto/index/FX- from Yahoo). Searches Eastmoney and Yahoo and, for U.S. equities, attaches- the SEC CIK. Use this to turn an ambiguous name into a concrete symbol- before calling get_market_data or get_sec_filings.+ (A-shares 600519.SH, Hong Kong 00700.HK, U.S. AAPL.US, Canada TD.TO/PNG.V,+ plus crypto/index/FX from Yahoo). Searches Eastmoney and Yahoo and, for U.S.+ equities, attaches the SEC CIK. Use this to turn an ambiguous name into a+ concrete symbol before calling get_market_data or get_sec_filings.Args:query: Free-text company name or ticker fragment (Chinese or English).diff --git a/agent/src/agent/grounding.py b/agent/src/agent/grounding.pyindex 144cb374a..13db61f80 100644--- a/agent/src/agent/grounding.py+++ b/agent/src/agent/grounding.py@@ -169,22 +169,13 @@ _NUMBER_RE = re.compile(r"(?<![A-Za-z0-9_])[-+]?(?:\d{1,3}(?:,\d{3})+|\d+)(?:\.\d+)?"r"(?![A-Za-z0-9_])")-_DATE_RE = re.compile(- r"\b(?:19|20)\d{2}[-/]\d{1,2}[-/]\d{1,2}"- r"(?:\s*[-–—~至到]\s*(?:0?[1-9]|[12]\d|3[01]))?\b"-)+_DATE_RE = re.compile(r"\b(?:19|20)\d{2}[-/]\d{1,2}[-/]\d{1,2}\b")# A year-less "8/5" is how a trading day is written in running prose, and it# contributed 8 and 5 as candidate prices (#983). The month and day ranges are# bounded, and both sides are fenced off from a longer slash run, so the window# enumeration "20/50/200-day" cannot be mistaken for a date.-#-# A day-range shares the month prefix: "8/10–14" (or "2026-08-10–14") means the-# 10th through 14th, and the tail day was parsed as a price (14.0) that rejected-# the GRID.TO / DCBO.TO drafts. The range tail is optional so a bare "8/10"-# still masks exactly as before._SHORT_DATE_RE = re.compile(- r"(?<![\d/])(?:0?[1-9]|1[0-2])/(?:0?[1-9]|[12]\d|3[01])"- r"(?:\s*[-–—~至到]\s*(?:0?[1-9]|[12]\d|3[01]))?(?![\d/])"+ r"(?<![\d/])(?:0?[1-9]|1[0-2])/(?:0?[1-9]|[12]\d|3[01])(?![\d/])")# A percentage range masks only its upper bound through the "%" tail check# below, because the sign touches the second number: "1–2%" left 1 behind@@ -215,18 +206,13 @@ _AGGREGATE_AMOUNT_RE = re.compile(# two window lengths survive. ASCII units carry a trailing word boundary so# "120 more" is not read as a quantity; the CJK branch cannot, because 周 and# 内 are both word characters and "1–4 周内" must still mask.-#-# Bare 万/萬 is a ten-thousand multiplier and, in the trading-plan domain, is a-# quantity (volume/market-cap/money), never a per-share price: "量 5–10 万" and-# "119 万" must not be read as OHLC claims. Span-local: the unit must follow-# the number, so "收盘 0.49,量 119 万" still masks only the volume._QUANTITY_WITH_UNIT_RE = re.compile(r"\d[\d,]*(?:\.\d+)?"r"(?:\s*/\s*\d[\d,]*(?:\.\d+)?)*"r"(?:\s*[-–—~至]\s*\d[\d,]*(?:\.\d+)?)?"r"\s*[-–—]?\s*"r"(?:"- r"(?:股|手|张|份|口|笔|倍|个月|周|天|日|年|次|万|萬)"+ r"(?:股|手|张|份|口|笔|倍|个月|周|天|日|年|次)"r"|(?:shares?|contracts?|lots?|units?|sessions?|bars?|periods?|"r"wks?|weeks?|months?|days?|years?|yrs?)\b"r")",@@ -249,11 +235,11 @@ _LABELLED_SCORE_RE = re.compile(# unambiguous indicator names are listed: generic words such as "momentum" or# "volatility" sit too close to price prose to mask safely._INDICATOR_VALUE_RE = re.compile(- r"(?:\b(?:rsi|macd|atr|adx|cci|obv|kdj|boll|dif|dea|vix|iv|"- r"sharpe|sortino|beta|sma|ema|wma)\d{0,4}\b|布林(?:带|线)?)"+ r"\b(?:rsi|macd|atr|adx|cci|obv|kdj|boll|dif|dea|vix|iv|"+ r"sharpe|sortino|beta)\b"r"(?:\s*\([^)]{0,20}\))?"r"\s*(?:is|at|of|reads?|=|为|是)?\s*[::]?\s*"- r"[-+]?\d[\d,]*(?:\.\d+)?(?:\s*/\s*[-+]?\d[\d,]*(?:\.\d+)?)*",+ r"[-+]?\d[\d,]*(?:\.\d+)?",re.IGNORECASE,)# A trading plan quotes levels it does not claim to have observed. In the@@ -277,15 +263,15 @@ _INDICATOR_VALUE_RE = re.compile(_PROSPECTIVE_LEVEL_RE = re.compile(r"(?:"# (a) comparison operator immediately before the number- r"(?:>=|<=|≥|≤|>|<|大于|小于|不低于|不高于|高于|低于)\s*(?:C\$|\$)?\s*[-+]?\d[\d,]*(?:\.\d+)?"+ r"(?:>=|<=|≥|≤|>|<|大于|小于|不低于|不高于|高于|低于)\s*[-+]?\d[\d,]*(?:\.\d+)?"r"|"# (b) a level marker introducing the numberr"(?:目标位|目标区|目标价|止损位?|止盈位?|触发价|触发位|触发点|上看|下看|"r"target\s+(?:price|level|zone)|trigger|stop[-\s]?loss|take[-\s]?profit)"- r"\s*(?:为|是|至|到|on|at|of|=)?\s*[::]?\s*(?:C\$|\$)?\s*[-+]?\d[\d,]*(?:\.\d+)?"+ r"\s*(?:为|是|至|到|on|at|of|=)?\s*[::]?\s*[-+]?\d[\d,]*(?:\.\d+)?"r"|"# (c) the number followed by a level marker- r"(?:C\$|\$)?[-+]?\d[\d,]*(?:\.\d+)?\s*(?:一线|附近)?\s*(?:成为?|作为|是)?\s*"+ r"[-+]?\d[\d,]*(?:\.\d+)?\s*(?:一线|附近)?\s*(?:成为?|作为|是)?\s*"r"(?:目标区|目标位|止损位|止盈位)"r"|"# (d) a conditional opener before the number, digits fencing the reach@@ -294,12 +280,6 @@ _PROSPECTIVE_LEVEL_RE = re.compile(r")",re.IGNORECASE,)-# A markdown ordered-list marker ("1. **持仓**: …", "10. 事件") is not a price:-# the standalone integer + period at line start was parsed as a price claim and-# rejected the BLDP.TO draft on its second attempt (#1.0 vs OHLC). Span-local:-# the period must not be followed by a digit, so "3.50" and "1.5" stay checked.-_ORDERED_LIST_MARKER_RE = re.compile(r"(?m)^\s*\d+\.(?!\d)")-# Full-width brackets and enumeration commas delimit prose clauses. ASCII# parentheses are deliberately not separators: an explicit derivation such as# "(8.5 - 7.9) / 2" must stay in one segment for the formula check.@@ -429,53 +409,12 @@ def _price_field_for_path(path: str) -> str | None:return _GENERIC_PRICE_FIELD_ALIASES.get(leaf)-# Trading-plan file stems encode the ticker with ``.``, ``_``, or ``-``-# standing in for the dot: ``als.to-trading-plan...``, ``tf_to-trading-plan...``-# (base has no hyphen), ``btcx-b-to-trading-plan...`` (base is itself-# hyphenated) and ``gldc_v-Weekly...``. The stem's leading token is the-# ticker and it is always terminated by the ``-Weekly`` / ``-trading-plan``-# descriptor, so English prose ending in ``-to`` (``ready-to-go``,-# ``go_to school``) can never be misread as a ticker.-_TRADING_PLAN_TICKER_RE = re.compile(- r"(?<![A-Za-z0-9])([A-Z0-9][A-Z0-9.\-]*?)[._-](TO|V)"- r"(?=[\-_ ]Weekly|[\-_ ]trading[\-_ ]plan)",- re.IGNORECASE,-)---def _is_path_like(text: str) -> bool:- """Return whether *text* looks like it contains a file path."""- return "/" in text or "\\" in text---def _trading_plan_tickers(text: str) -> set[str]:- """Expand trading-plan file stems to canonical symbols.-- ``als.to-trading-plan...``, ``tf_to-trading-plan...``,- ``btcx-b-to-trading-plan...`` and ``gldc_v-Weekly...`` all yield the- canonical ticker (``ALS.TO``, ``TF.TO``, ``BTCX-B.TO``, ``GLDC.V``).- Guarded to path-like text and the ``-Weekly``/``-trading-plan`` descriptor- so English prose ending in ``-to`` is never read as a ticker.- """- blob = text or ""- if not _is_path_like(blob):- return set()- found: set[str] = set()- for match in _TRADING_PLAN_TICKER_RE.finditer(blob):- base = match.group(1).upper()- suffix = match.group(2).upper()- found.add(f"{base}.{suffix}")- return found--def _scan_symbols(text: str) -> set[str]:"""Return the canonical symbols written anywhere in a blob of text."""- found = {+ return {_normalize_symbol(match.group(0))for match in _CANONICAL_SYMBOL_RE.finditer(text or "")}- found.update(_trading_plan_tickers(text))- return founddef _infer_venue(symbol: str) -> str | None:@@ -494,7 +433,7 @@ def _infer_venue(symbol: str) -> str | None:".BO": "bse",".FX": "forex",".TO": "toronto",- ".V": "tsxv",+ ".V": "tsx_venture",}for suffix, venue in suffixes.items():if upper.endswith(suffix):@@ -998,7 +937,8 @@ class GroundingLedger:def _seed_symbols(self, text: str, *, source: str) -> None:"""Lock exact symbols explicitly supplied by a user."""- for symbol in sorted(_scan_symbols(text)):+ for match in _CANONICAL_SYMBOL_RE.finditer(text or ""):+ symbol = _normalize_symbol(match.group(0))key = f"explicit:{symbol}"existing = self._identities.get(key)version = existing.version + 1 if existing else 1@@ -1088,35 +1028,6 @@ class GroundingLedger:chosen = self._choose_candidate(query, candidates)if chosen is None:- # A loose/bare search that came back ambiguous must not demote an- # already-locked identity. When the candidate list contains the- # symbol of an existing lock (bare "GLDC" returning GLDC.V among- # other global GLDC-* instruments while GLDC.V is already locked),- # the shortlist is answered by that lock: record it as superseded- # so the aggregate stays "locked" and already-authorized market- # tools are not blocked for the rest of the run.- locked_matches = sorted(- {- record.symbol- for record in self._identities.values()- if record.status == "locked"- and record.symbol- and any(- _normalize_symbol(candidate.get("symbol")) == record.symbol- for candidate in candidates- )- }- )- if len(locked_matches) == 1:- self._supersede_shortlists(locked_matches[0])- self._identities[key] = IdentityRecord(- query=query,- status="superseded",- source_tool_call_id=call_id,- candidates=candidates,- version=version,- )- returnself._identities[key] = IdentityRecord(query=query,status="ambiguous",@@ -1909,7 +1820,6 @@ class GroundingLedger:masked = _LABELLED_SCORE_RE.sub(" ", masked)masked = _INDICATOR_VALUE_RE.sub(" ", masked)masked = _PROSPECTIVE_LEVEL_RE.sub(" ", masked)- masked = _ORDERED_LIST_MARKER_RE.sub(" ", masked)without_dates = _QUANTITY_WITH_UNIT_RE.sub(" ", masked)values: list[float] = []for match in _NUMBER_RE.finditer(without_dates):diff --git a/agent/src/agent/loop.py b/agent/src/agent/loop.pyindex 75fe01aa0..6c856e813 100644--- a/agent/src/agent/loop.py+++ b/agent/src/agent/loop.py@@ -1272,20 +1272,6 @@ class AgentLoop:batch_identity_status=batch_identity_status,)if not authorization.allowed:- logger.warning(- "grounding gate BLOCKED %s (iter=%s call_id=%s): error_code=%s "- "requested=%s batch_status=%s locked_status=%s locked_symbols=%s "- "reason=%s",- tc.name,- iteration,- tc.id,- authorization.error_code,- sorted(authorization.symbols),- batch_identity_status,- self._grounding.identity_status,- sorted(self._grounding.authorized_symbols),- authorization.message,- )execution_plan.append((tc,diff --git a/agent/src/market_data.py b/agent/src/market_data.pyindex 09eab7d34..d27917e40 100644--- a/agent/src/market_data.py+++ b/agent/src/market_data.py@@ -26,8 +26,7 @@ _SOURCE_PATTERNS = [# India: NSE (RELIANCE.NS) / BSE (500325.BO). Tickers may carry '&' and '-'# (e.g. M&M.NS, BAJAJ-AUTO.NS). Served by Yahoo's public chart endpoint.(re.compile(r"^[A-Z0-9&.\-]+\.(NS|BO)$", re.I), "yahoo"),- # Canada: TSX (TD.TO) / TSX Venture (SHOP.V). Yahoo carries these suffixes- # verbatim — ca.yahoo.com is the same query API as the .com site.+ # Canada: Toronto Stock Exchange (TD.TO) / TSX Venture (PNG.V).(re.compile(r"^[A-Z0-9&.\-]+\.(TO|V)$", re.I), "yahoo"),# Yahoo futures (GC=F, CL=F) and forex (EURUSD=X) suffix conventions —# served verbatim by Yahoo's public chart endpoint (#718). Without these,@@ -210,14 +209,6 @@ def fetch_market_data("fallback_used": bool(used_source and used_source != src),"currency_conversion": "none",}- if data_map:- logger.info(- "market-data resolved symbols=%s via source=%r (detected=%r fallback=%s)",- sorted(data_map),- used_source or src,- src,- bool(used_source and used_source != src),- )unresolved = [codediff --git a/agent/src/skills/cross-market-strategy/SKILL.md b/agent/src/skills/cross-market-strategy/SKILL.mdindex 8134fe856..1a7409fb6 100644--- a/agent/src/skills/cross-market-strategy/SKILL.md+++ b/agent/src/skills/cross-market-strategy/SKILL.md@@ -6,7 +6,7 @@ category: strategy## When to Use-When the user requests a backtest with codes from **different markets** — e.g. `["000001.SZ", "BTC-USDT"]` or `["AAPL.US", "EUR/USD", "600519.SH"]`.+When the user requests a backtest with codes from **different markets** — e.g. `["000001.SZ", "BTC-USDT"]`, `["TD.TO", "PNG.V"]`, or `["AAPL.US", "EUR/USD", "600519.SH"]`.The `CompositeEngine` handles calendar alignment, shared capital, and market rules automatically. The strategy only needs to output per-symbol signals.@@ -103,6 +103,7 @@ def _vol_adjust(self, signals, data_map):| `000001.SZ`, `600519.SH` | A-share || `AAPL.US` | US equity || `700.HK` | HK equity |+| `TD.TO`, `PNG.V` | Canada equity (TSX / TSXV) || `BTC-USDT` | Crypto || `IF2406.CFFEX` | China futures || `ESZ4` | Global futures |diff --git a/agent/src/skills/cross-market-strategy/example_signal_engine.py b/agent/src/skills/cross-market-strategy/example_signal_engine.pyindex 4ea196bc9..b75e43112 100644--- a/agent/src/skills/cross-market-strategy/example_signal_engine.py+++ b/agent/src/skills/cross-market-strategy/example_signal_engine.py@@ -1,6 +1,6 @@"""Cross-market strategy example: vol-adjusted dual-MA with per-market parameters.-Supports any combination of A-shares, crypto, US/HK equity, forex, and futures.+Supports any combination of A-shares, crypto, US/HK/Canada equity, forex, and futures.The CompositeEngine handles calendar alignment, market rules, and shared capital."""@@ -16,6 +16,7 @@ MARKET_PARAMS = {"crypto": {"ma_fast": 7, "ma_slow": 25, "vol_lookback": 14},"us_equity": {"ma_fast": 10, "ma_slow": 50, "vol_lookback": 20},"hk_equity": {"ma_fast": 10, "ma_slow": 50, "vol_lookback": 20},+ "ca_equity": {"ma_fast": 10, "ma_slow": 50, "vol_lookback": 20},"forex": {"ma_fast": 10, "ma_slow": 30, "vol_lookback": 20},"futures": {"ma_fast": 5, "ma_slow": 20, "vol_lookback": 20},}@@ -24,6 +25,7 @@ _MARKET_PATTERNS = [(re.compile(r"^\d{6}\.(SZ|SH|BJ)$", re.I), "a_share"),(re.compile(r"^[A-Z]+\.US$", re.I), "us_equity"),(re.compile(r"^\d{3,5}\.HK$", re.I), "hk_equity"),+ (re.compile(r"^[A-Z0-9&.\-]+\.(TO|V)$", re.I), "ca_equity"),(re.compile(r"^[A-Z]+-USDT$", re.I), "crypto"),(re.compile(r"^[A-Z]+/USDT$", re.I), "crypto"),(re.compile(r"^[A-Z]{3}/[A-Z]{3}$"), "forex"),diff --git a/agent/src/skills/data-routing/SKILL.md b/agent/src/skills/data-routing/SKILL.mdindex 8444f9a4c..7c9ef3754 100644--- a/agent/src/skills/data-routing/SKILL.md+++ b/agent/src/skills/data-routing/SKILL.md@@ -21,7 +21,7 @@ per-source skill.|--------|---------|----------------|---------|-------|| tushare | A-shares, funds, futures, macro | Yes (`TUSHARE_TOKEN`) | China network | tushare || akshare | A-shares, US, HK, futures, macro, forex | No | Unrestricted | akshare |-| yfinance | US stocks, HK stocks, Canada (TSX/TSX-V) stocks, ETFs | No | Needs Yahoo access | yfinance |+| yfinance | US, HK, Canada (TSX/TSXV) stocks, ETFs | No | Needs Yahoo access | yfinance || okx | Crypto (OKX exchange) | No | Needs okx.com access | okx-market || ccxt | Crypto (100+ exchanges) | No | Needs exchange access | ccxt || baostock | A-shares (free daily/min) | No | China network | data-routing |@@ -33,7 +33,7 @@ per-source skill.| eastmoney | A-shares, HK, US equities | No (IP-throttled) | Unrestricted | data-routing || sina | US equities (daily OHLCV) | No (IP-throttled) | Unrestricted | data-routing || stooq | US equities (daily OHLCV) | No | Unrestricted | data-routing |-| yahoo | US, HK, Canada (TSX/TSX-V) equities | No (IP-throttled) | Needs Yahoo access | data-routing |+| yahoo | US, HK, Canada (TSX/TSXV) equities | No (IP-throttled) | Needs Yahoo access | data-routing || finnhub | US equities | Yes (`FINNHUB_API_KEY`) | Unrestricted | data-routing || alphavantage | US equities | Yes (`ALPHAVANTAGE_API_KEY`) | Unrestricted | data-routing || tiingo | US equities | Yes (`TIINGO_API_KEY`) | Unrestricted | data-routing |@@ -57,24 +57,22 @@ 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, Canada | — |+| Stock news | `get_stock_news` | A-share, US, HK | — || SEC filings (EDGAR) | `get_sec_filings` | US | — |-| Financial statements | `get_financial_statements` | A-share, US, HK, Canada | — |+| Financial statements | `get_financial_statements` | A-share, US, HK | — || Options chain | `get_options_chain` | US | — || Stock profile / fundamentals | `get_stock_profile` | US | — || Market screen | `screen_market` | A-share | — |-| Symbol search | `search_symbol` | A-share, US | — |+| Symbol search | `search_symbol` | A-share, US, HK, Canada, crypto/index/FX | — || Macro / FRED series | `get_macro_series` | Macro (US/global) | `FRED_API_KEY` || iWenCai NL search (问财) | `iwencai_search` | A-share | `VIBE_TRADING_IWENCAI_KEY` |Notes:- `get_financial_statements` reads US statements from SEC EDGAR companyfacts- (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.+ (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 and- US (.US) / HK (.HK) / Canada (.TO/.V) to a Yahoo search client; a failure on- one upstream is+ US (.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 neveraborts a batch.@@ -101,6 +99,8 @@ same-market sources automatically. Only set a concrete source when the user asks- **HK stocks**: tencent (never banned, daily) > eastmoney / yahoo > futu (localOpenD) > akshare (Eastmoney-backed, daily only) > yfinance > tushare(`TUSHARE_TOKEN`) / longbridge (key-gated).+- **Canada (TSX/TSXV)**: yahoo > yfinance > local; use Yahoo's canonical+ `.TO` / `.V` suffixes (for example `TD.TO`, `PNG.V`).- **Crypto**: okx (single exchange) > ccxt (multi-exchange).- **Futures / macro**: tushare > akshare.- **Forex / metals**: mt5 (local MetaTrader 5 terminal, Windows) > akshare.@@ -112,6 +112,7 @@ same-market sources automatically. Only set a concrete source when the user asks| A-shares | `NNNNNN.SZ/SH/BJ` | 000001.SZ, 600000.SH, 430139.BJ || US stocks | `TICKER.US` | AAPL.US, MSFT.US || HK stocks | `NNNNN.HK` | 00700.HK, 09988.HK |+| Canada TSX / TSXV | `TICKER.TO` / `TICKER.V` | TD.TO, BBD-B.TO, PNG.V || Crypto | `SYMBOL-USDT` | BTC-USDT, ETH-USDT || Futures | `XXNNNN.EXCHANGE` | CU2406.SHFE || Forex | `XXX/YYY` | USD/CNY, EUR/USD |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 003def08e..545cd59e1 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,31 +2,30 @@工具:`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)/加拿大(.TO/.V → 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 → 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` / `TD.TO` / `SGML.V`。后缀选上游:SH/SZ/BJ → 东财;US/HK/TO/V → Yahoo。 |-| limit | int | N | 返回头条数上限(1–50,默认 20)。 |+名称 | 类型 | 必选 | 描述+---- | ---- | ---- | ----+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)。<br>@@ -40,20 +39,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/skills/strategy-generate/SKILL.md b/agent/src/skills/strategy-generate/SKILL.mdindex 51fbd7289..23a2e2501 100644--- a/agent/src/skills/strategy-generate/SKILL.md+++ b/agent/src/skills/strategy-generate/SKILL.md@@ -84,6 +84,7 @@ Self-check after writing `signal_engine.py`:- 6-digit China A-share codes → automatically append suffix: codes starting with `600/601/603` → `.SH`, all others → `.SZ`- US stocks: uppercase letters + `.US`, such as `AAPL.US` (`yfinance` converts automatically)- Hong Kong stocks: digits + `.HK`, such as `700.HK` (`yfinance` converts automatically)+- Canadian stocks: Yahoo ticker + `.TO` for TSX or `.V` for TSXV, such as `TD.TO` or `PNG.V`- Cryptocurrencies: `BTC-USDT` format (OKX spot pairs, **must use the hyphen `-`, not slash `/`**)- The user may write `BTC/USDT`, but `config.json` must use `"BTC-USDT"`@@ -102,9 +103,10 @@ Self-check after writing `signal_engine.py`:| `^\d{6}\.(SZ\|SH\|BJ)$` | China A-shares | tushare | `extra_fields`: pe, pb, pe_ttm, ps_ttm, dv_ttm, total_mv, circ_mv, roe; `fundamental_fields`: income/balancesheet/cashflow/fina_indicator || `^[A-Z]+\.US$` | US stocks | yfinance | - || `^\d{3,5}\.HK$` | Hong Kong stocks | yfinance | - |+| `^[A-Z0-9&.-]+\.(TO\|V)$` | Canadian stocks (TSX / TSXV) | yahoo / yfinance | - || `^[A-Z]+-USDT$` | Cryptocurrency | okx | - |-**`extra_fields` selection logic**: only China A-shares (`tushare`) support daily valuation fields. If the strategy needs `PE/PB/ROE` and similar daily_basic fields, specify them in `config.json.extra_fields` and `DataLoader` will retrieve them automatically. Hong Kong stocks, US stocks, and crypto do not support `extra_fields`.+**`extra_fields` selection logic**: only China A-shares (`tushare`) support daily valuation fields. If the strategy needs `PE/PB/ROE` and similar daily_basic fields, specify them in `config.json.extra_fields` and `DataLoader` will retrieve them automatically. Hong Kong, US, Canadian stocks, and crypto do not support `extra_fields`.**`fundamental_fields` selection logic**: use this for China A-share financial statement pre-filters. The runner queries `income`, `balancesheet`, `cashflow`, and/or `fina_indicator` through the Tushare fundamental provider, then merges rows into daily bars only after their announcement/disclosure date. Output columns are prefixed by table name, for example `income_total_revenue`, `income_n_income`, `balancesheet_total_hldr_eqy_exc_min_int`, and `fina_indicator_roe`.diff --git a/agent/src/skills/yfinance/SKILL.md b/agent/src/skills/yfinance/SKILL.mdindex 7fc5230f2..2bb85aa24 100644--- a/agent/src/skills/yfinance/SKILL.md+++ b/agent/src/skills/yfinance/SKILL.md@@ -1,13 +1,13 @@---name: yfinance-description: yfinance global market data interface — retrieve OHLCV, financials, insider transactions, and institutional holdings for US stocks, HK stocks, ETFs, and indices via Yahoo Finance. Free, no API key required.+description: yfinance global market data interface — retrieve OHLCV and research data for US, HK, and Canadian stocks, ETFs, and indices via Yahoo Finance. Free, no API key required.category: data-source---# yfinance## Overview-yfinance is an open-source Python wrapper for Yahoo Finance, providing global market data (US stocks, HK stocks, ETFs, indices) including historical and real-time quotes. **Completely free, no registration or API key required.**+yfinance is an open-source Python wrapper for Yahoo Finance, providing global market data (US, HK, and Canadian stocks, ETFs, indices) including historical and real-time quotes. **Completely free, no registration or API key required.**The project has a built-in yfinance DataLoader (`backtest/loaders/yfinance_loader.py`). When backtesting, set `source: "yfinance"` or `source: "auto"` to invoke it automatically.@@ -38,8 +38,9 @@ one you need rather than loading them all:> form for any new reference docs.The Yahoo client uses the project ticker convention (`AAPL.US` → `AAPL`,-`00700.HK` → `0700.HK`); see the [Ticker Format Conversion](#ticker-format-conversion)-table below — the same rules apply across all of the interfaces above.+`00700.HK` → `0700.HK`, `TD.TO` and `PNG.V` pass through); see the+[Ticker Format Conversion](#ticker-format-conversion) table below — the same+rules apply across all of the interfaces above.## Quick Start@@ -47,7 +48,7 @@ Preferred OHLCV tool call:```json{- "codes": ["AAPL.US", "700.HK"],+ "codes": ["AAPL.US", "700.HK", "TD.TO", "PNG.V"],"start_date": "2025-01-01","end_date": "2026-01-01","source": "yfinance",@@ -61,7 +62,12 @@ If you must write a Python script for OHLCV, use the DataLoader instead of raw `from backtest.loaders.registry import get_loader_cls_with_fallbackloader = get_loader_cls_with_fallback("yfinance")()-data = loader.fetch(["AAPL.US", "700.HK"], "2025-01-01", "2026-01-01", interval="1D")+data = loader.fetch(+ ["AAPL.US", "700.HK", "TD.TO", "PNG.V"],+ "2025-01-01",+ "2026-01-01",+ interval="1D",+)for symbol, df in data.items():print(symbol, df.tail())@@ -77,11 +83,14 @@ The project uses a unified ticker format. The DataLoader automatically converts| `MSFT.US` | `MSFT` | US stock || `700.HK` | `0700.HK` | HK stock || `9988.HK` | `9988.HK` | HK stock |+| `TD.TO` | `TD.TO` | Toronto Stock Exchange stock |+| `PNG.V` | `PNG.V` | TSX Venture stock || `SPY.US` | `SPY` | US ETF |**Rules:**- US stocks: strip the `.US` suffix → use the raw ticker- HK stocks: keep `.HK`, pad the number to 4 digits (`700` → `0700`)+- Canadian stocks: keep `.TO` (TSX) or `.V` (TSXV) unchanged## Supported Data Types@@ -241,7 +250,7 @@ eurusd = yf.download("EURUSD=X", start="2025-01-01", end="2026-01-01", progress=}```-`source: "auto"` routes automatically by ticker format: A-shares → tushare, HK/US stocks → yfinance, crypto → OKX.+`source: "auto"` routes automatically by ticker format: A-shares → the China fallback chain, HK stocks → the HK chain, Canadian `.TO`/`.V` stocks → Yahoo/yfinance, and crypto → OKX.## Notesdiff --git a/agent/src/swarm/grounding.py b/agent/src/swarm/grounding.pyindex 10d3c5033..97eb634eb 100644--- a/agent/src/swarm/grounding.py+++ b/agent/src/swarm/grounding.py@@ -12,7 +12,8 @@ What this module does---------------------* Scans every value in ``user_vars`` for tokens that match one of thedata-source-suffixed symbol shapes the loaders already understand- (``NVDA.US``, ``700.HK``, ``600519.SH``, ``BTC-USDT``, etc.).+ (``NVDA.US``, ``700.HK``, ``TD.TO``, ``PNG.V``, ``600519.SH``,+ ``BTC-USDT``, etc.).* Pulls the last ``DEFAULT_WINDOW_DAYS`` of OHLCV for each detectedsymbol via ``backtest.loaders.registry.resolve_loader`` with``source="auto"``. Failures (delisted ticker, network blip) are@@ -78,8 +79,7 @@ _SYMBOL_PATTERNS: tuple[re.Pattern[str], ...] = (re.compile(r"\b[A-Z]{1,5}\.US\b"),re.compile(r"\b\d{3,5}\.HK\b"),re.compile(r"\b\d{6}\.(?:SZ|SH|BJ)\b"),- # Canada: TSX (.TO) / TSX Venture (.V) — served by Yahoo, same loader family.- re.compile(r"\b[A-Z]{1,6}\.(?:TO|V)\b"),+ re.compile(r"\b[A-Z0-9&.-]+\.(?:TO|V)\b"),re.compile(r"\b[A-Z]{2,6}-USDT\b"),)@@ -95,7 +95,7 @@ _BARE_US_TICKER_PATTERN = re.compile(r"(?<![\w.])[A-Z]{2,5}(?!\w)(?!\.\w)")_BARE_TICKER_STOPWORDS = frozenset({# geography / venues / index & data providers"US", "USA", "UK", "EU", "HK", "CN", "JP", "NYSE", "AMEX", "SSE", "SZSE",- "HKEX", "SPX", "NDX", "DJI", "DJIA", "HSI", "CSI", "FTSE", "MSCI", "VIX",+ "HKEX", "TSX", "TSXV", "SPX", "NDX", "DJI", "DJIA", "HSI", "CSI", "FTSE", "MSCI", "VIX",# instruments / structures"ETF", "ETN", "ADR", "IPO", "REIT", "BOND", "SWAP", "PERP",# macro / institutionsdiff --git a/agent/src/tools/block_trades_tool.py b/agent/src/tools/block_trades_tool.pyindex fda6510bf..c0d075a60 100644--- a/agent/src/tools/block_trades_tool.py+++ b/agent/src/tools/block_trades_tool.py@@ -230,8 +230,7 @@ class BlockTradesTool(BaseTool):"ok": False,"error": (f"{symbol!r} is not a resolvable A-share symbol "- "(use .SH/.SZ/.BJ); Canada (.TO/.V) is not a "- "block-trade market on Eastmoney"+ "(use .SH/.SZ/.BJ)"),},ensure_ascii=False,diff --git a/agent/src/tools/financial_statements_tool.py b/agent/src/tools/financial_statements_tool.pyindex 832c5d1f7..1cd42531c 100644--- a/agent/src/tools/financial_statements_tool.py+++ b/agent/src/tools/financial_statements_tool.py@@ -12,15 +12,10 @@ 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"``); Canada requests go through the throttled Yahoo-:func:`backtest.loaders.yahoo_client.get_quote_summary` (``host_key="yahoo"``).+(``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@@ -31,10 +26,9 @@ from __future__ import annotationsimport jsonimport logging-from datetime import datetime, timezonefrom typing import Any-from backtest.loaders import sec_frames, yahoo_client+from backtest.loaders import sec_framesfrom 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@@ -107,249 +101,6 @@ _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")@@ -832,8 +583,6 @@ def _classify_market(code: str) -> str | None:return "us"if suffix == "HK":return "hk"- if suffix in ("TO", "V"):- return "ca"return None@@ -844,12 +593,11 @@ 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), 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 "+ "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 "'this to read fundamentals before building a valuation or screen. Example: '- '{"code": "SGML.V", "statement": "income", "period": "annual"}.'+ '{"code": "600519.SH", "statement": "income", "period": "annual"}.')parameters = {"type": "object",@@ -858,7 +606,7 @@ class FinancialStatementsTool(BaseTool):"type": "string","description": ("Single symbol with a market suffix, e.g. '600519.SH', "- "'000001.SZ', 'AAPL.US', '00700.HK', or 'SGML.V'."+ "'000001.SZ', 'AAPL.US', or '00700.HK'."),},"statement": {@@ -925,18 +673,12 @@ class FinancialStatementsTool(BaseTool):market = _classify_market(code)if market is None:return _error(- "code must carry a supported suffix: "- ".SH/.SZ/.BJ, .US, .HK, or .TO/.V"+ "code must carry a supported suffix: .SH/.SZ/.BJ, .US, or .HK")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 4051d2729..fb736f1eb 100644--- a/agent/src/tools/fund_flow_tool.py+++ b/agent/src/tools/fund_flow_tool.py@@ -97,12 +97,6 @@ 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/market_data_tool.py b/agent/src/tools/market_data_tool.pyindex b77c7e7c9..c088ebd1d 100644--- a/agent/src/tools/market_data_tool.py+++ b/agent/src/tools/market_data_tool.py@@ -2,14 +2,11 @@from __future__ import annotations-import loggingfrom typing import Anyfrom src.agent.tools import BaseToolfrom src.market_data import DEFAULT_MAX_ROWS, fetch_market_data_json-logger = logging.getLogger(__name__)-class MarketDataTool(BaseTool):"""Fetch normalized OHLCV data through repository loaders."""@@ -26,7 +23,10 @@ class MarketDataTool(BaseTool):"codes": {"type": "array","items": {"type": "string"},- "description": 'Symbols such as ["AAPL.US"], ["700.HK"], ["BTC-USDT"].',+ "description": (+ 'Symbols such as ["AAPL.US"], ["700.HK"], ["TD.TO"], '+ '["PNG.V"], or ["BTC-USDT"].'+ ),},"start_date": {"type": "string",@@ -64,7 +64,8 @@ class MarketDataTool(BaseTool):"Data source. 'auto' detects from symbol format with fallback. ""Use 'longbridge' explicitly for US/HK OHLCV through the ""Longbridge OpenAPI (requires Longbridge credentials). "- "Free, no key: yfinance/yahoo (US/HK/Canada equities; Canada via .TO/.V), okx/ccxt "+ "Free, no key: yfinance/yahoo (US/HK/Canada equities; "+ "Canada uses .TO/.V), okx/ccxt ""(crypto), baostock/tencent/eastmoney/sina/akshare/mootdx ""(China A-shares), stooq (global EOD), pykrx (Korea KRX daily ""bars for <CODE>.KS / <CODE>.KQ; needs the optional pykrx "@@ -91,15 +92,6 @@ class MarketDataTool(BaseTool):repeatable = Truedef execute(self, **kwargs: Any) -> str:- logger.info(- "get_market_data call: codes=%s start=%s end=%s source=%s interval=%s max_rows=%s",- kwargs["codes"],- kwargs["start_date"],- kwargs["end_date"],- kwargs.get("source", "auto"),- kwargs.get("interval", "1D"),- kwargs.get("max_rows", DEFAULT_MAX_ROWS),- )return fetch_market_data_json(codes=kwargs["codes"],start_date=kwargs["start_date"],diff --git a/agent/src/tools/research_reports_tool.py b/agent/src/tools/research_reports_tool.pyindex f487826a4..612d7f3b6 100644--- a/agent/src/tools/research_reports_tool.py+++ b/agent/src/tools/research_reports_tool.py@@ -108,12 +108,6 @@ 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 367f11bff..9dfb78466 100644--- a/agent/src/tools/shareholder_count_tool.py+++ b/agent/src/tools/shareholder_count_tool.py@@ -89,12 +89,6 @@ 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 7f0473733..3cff06686 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 / Canada headlines come from Yahoo Finance's public v1 search-news- surface via the frozen, IP-throttled :mod:`backtest.loaders.yahoo_client`.+* US / HK 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,9 +41,8 @@ _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 carries US, HK and-# Canada (TSX `.TO` / TSX Venture `.V`) tickers verbatim.-_YAHOO_SUFFIXES = ("US", "HK", "TO", "V")+# Suffixes that route to Yahoo's search-news surface.+_YAHOO_SUFFIXES = ("US", "HK")# Default broad-market query used when ``scope='global'`` carries no code._GLOBAL_QUERY = "财经"@@ -225,7 +224,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/Canada news articles for a query via Yahoo search.+ """Fetch US/HK news articles for a query via Yahoo search.Args:query: Free-text search term (bare ticker or keyword).@@ -250,9 +249,8 @@ 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), Hong "- "Kong (.HK) and Canada (.TO/.V) return Yahoo Finance news articles "- "with the same fields. Use "+ "(title/url/source/published/snippet) under 'articles'. US (.US) and Hong "+ "Kong (.HK) 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}.'@@ -264,10 +262,9 @@ class StockNewsTool(BaseTool):"type": "string","description": ("Symbol whose news to fetch, e.g. '600519.SH', 'AAPL.US', "- "'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."+ "'00700.HK'. Required when scope='stock'; ignored when "+ "scope='global'. The exchange suffix selects the upstream: "+ "SH/SZ/BJ -> Eastmoney, US/HK -> Yahoo Finance."),},"scope": {@@ -376,9 +373,8 @@ class StockNewsTool(BaseTool):)def _stock_via_yahoo(self, code: str, query: str, limit: int) -> str:- """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"+ """Fetch US/HK news articles from Yahoo for one code."""+ market = "hk" if _suffix_of(code) == "HK" else "us"try:articles = _fetch_yahoo_news(query, limit)except Exception as exc: # noqa: BLE001 - surface any fetch failure as envelopediff --git a/agent/src/tools/symbol_search_tool.py b/agent/src/tools/symbol_search_tool.pyindex 8055009e9..43e9ba293 100644--- a/agent/src/tools/symbol_search_tool.py+++ b/agent/src/tools/symbol_search_tool.py@@ -8,7 +8,7 @@ hits a provider un-throttled and never re-implements transport plumbing:Hong Kong (.HK) and U.S. (.US) listings, each carrying a fully-qualified``secid`` already in ``<market>.<code>`` form.* :mod:`backtest.loaders.yahoo_client` — Yahoo's v1 search endpoint matches- global tickers/company names (US, HK, crypto, indices, FX, ...).+ global tickers/company names (US, HK, Canada, crypto, indices, FX, ...).* :mod:`backtest.loaders.sec_edgar_client` — the SEC company-tickers tableenriches a resolved U.S. equity ticker with its zero-padded CIK.@@ -73,7 +73,8 @@ class SymbolSearchTool(BaseTool):description = ("Resolve a company name or ticker fragment to candidate trading symbols ""with their market, in the project's symbol convention (A-shares "- "600519.SH, Hong Kong 00700.HK, U.S. AAPL.US, plus crypto/index/FX from "+ "600519.SH, Hong Kong 00700.HK, U.S. AAPL.US, Canada TD.TO/PNG.V, plus "+ "crypto/index/FX from ""Yahoo). Searches Eastmoney (China/HK/US names and tickers) and Yahoo ""(global) and, for U.S. equities, attaches the SEC CIK. Use this to turn ""an ambiguous name into a concrete symbol before calling get_market_data "@@ -288,8 +289,9 @@ def _search_yahoo(query: str) -> tuple[List[Dict[str, Any]], str]:def _yahoo_candidate(quote: Dict[str, Any]) -> Optional[Dict[str, Any]]:"""Map one Yahoo search quote to a normalized candidate, or ``None``.- Yahoo carries US tickers bare and HK tickers as ``0700.HK``. We translate- those into the project convention (``AAPL.US`` / ``00700.HK``) and leave+ Yahoo carries US tickers bare, HK tickers as ``0700.HK``, and Canadian+ listings with ``.TO`` / ``.V`` suffixes. We translate those into the project+ convention (``AAPL.US`` / ``00700.HK`` / ``TD.TO`` / ``PNG.V``) and leaveother instruments (crypto, indices, FX) on their native Yahoo symbol.Args:@@ -319,7 +321,8 @@ def _from_yahoo_symbol(raw_symbol: str, quote: Dict[str, Any]) -> tuple[str, str"""Translate a Yahoo symbol into the project convention + market label.Args:- raw_symbol: The Yahoo-side symbol (e.g. ``AAPL``, ``0700.HK``, ``BTC-USD``).+ 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 acrypto/index instrument via ``quoteType``.@@ -330,9 +333,8 @@ def _from_yahoo_symbol(raw_symbol: str, quote: Dict[str, Any]) -> tuple[str, strif upper.endswith(".HK"):base = raw_symbol[: -len(".HK")].lstrip("0") or "0"return f"{base.zfill(5)}.HK", "hk"- # Canada: TSX (.TO) / TSX Venture (.V) — Yahoo carries these verbatim.if upper.endswith((".TO", ".V")):- return raw_symbol, "ca"+ return upper, "ca"quote_type = str(quote.get("quoteType") or "").strip().upper()if quote_type == "EQUITY" and "." not in raw_symbol and "-" not in raw_symbol:return f"{upper}.US", "us"diff --git a/agent/tests/test_agent_grounding.py b/agent/tests/test_agent_grounding.pyindex 53efc2176..8ce663af6 100644--- a/agent/tests/test_agent_grounding.py+++ b/agent/tests/test_agent_grounding.py@@ -10,7 +10,12 @@ from typing import Any, Callableimport pytestfrom src.agent.context import ContextBuilder-from src.agent.grounding import GroundingLedger+from src.agent.grounding import (+ GroundingLedger,+ _infer_currency,+ _infer_venue,+ _scan_symbols,+)from src.agent.loop import AgentLoop, _is_tool_successfrom src.agent.tools import BaseTool, ToolRegistryfrom src.agent.trace import TraceWriter@@ -164,6 +169,15 @@ def _build_direct_agent(return agent, resolver, market, private_skill, TraceWriter(run_dir)+def test_canadian_symbols_have_grounding_identity() -> None:+ """TSX and TSXV symbols retain venue and CAD identity."""+ assert _scan_symbols("Compare TD.TO with PNG.V") == {"TD.TO", "PNG.V"}+ assert _infer_venue("TD.TO") == "toronto"+ assert _infer_venue("PNG.V") == "tsx_venture"+ assert _infer_currency("TD.TO") == "CAD"+ assert _infer_currency("PNG.V") == "CAD"++def test_ok_false_tool_envelope_is_failure() -> None:"""Business failures must not be recorded as successful tool calls (#886)."""assert _is_tool_success('{"ok": false, "error": "upstream failed"}') is False@@ -432,229 +446,6 @@ def test_locked_symbol_rejects_silent_exchange_suffix_rewrite(assert json.loads(messages[-1]["content"])["error_code"] == "identity_mismatch"-def test_canadian_explicit_symbol_seeds_locked_identity(tmp_path: Path) -> None:- """A user-supplied TD.TO is a canonical symbol the market consumer may use."""- ledger = GroundingLedger(- run_dir=tmp_path,- user_message="请分析 TD.TO 的当前价格",- )-- authorization = ledger.authorize_tool_call(- "get_market_data",- {"codes": ["TD.TO"]},- batch_authorized_symbols=ledger.authorized_symbols,- call_id="prices",- )-- assert ledger.authorized_symbols == {"TD.TO"}- assert authorization.allowed is True---def test_canadian_resolver_lock_authorizes_exact_venue(tmp_path: Path) -> None:- """A resolver lock on DCBO.TO lets get_market_data consume that exact venue."""- ledger = GroundingLedger(- run_dir=tmp_path,- user_message="分析 DCBO.TO",- )- ledger.ingest_tool_result(- tool_name="search_symbol",- arguments={"query": "DCBO"},- result=_resolver_payload("DCBO.TO", query="DCBO"),- call_id="resolver-ca",- success=True,- )-- authorization = ledger.authorize_tool_call(- "get_market_data",- {"codes": ["DCBO.TO"]},- batch_authorized_symbols=ledger.authorized_symbols,- batch_identity_status=ledger.identity_status,- call_id="prices",- )-- assert ledger.identity_status == "locked"- assert authorization.allowed is True---def test_canadian_dual_listing_venue_is_not_silently_rewritten(- tmp_path: Path,-) -> None:- """A locked DCBO.TO identity rejects a consumer switching to DCBO.US."""- ledger = GroundingLedger(- run_dir=tmp_path,- user_message="分析 DCBO.TO",- )- ledger.ingest_tool_result(- tool_name="search_symbol",- arguments={"query": "DCBO"},- result=_resolver_payload("DCBO.TO", query="DCBO"),- call_id="resolver-ca",- success=True,- )-- authorization = ledger.authorize_tool_call(- "get_market_data",- {"codes": ["DCBO.US"]},- batch_authorized_symbols=ledger.authorized_symbols,- batch_identity_status=ledger.identity_status,- call_id="prices",- )-- assert authorization.allowed is False- assert authorization.error_code == "identity_mismatch"---def test_canadian_symbols_are_canonical_and_venue_currency_aware() -> None:- """_scan_symbols / _infer_venue / _infer_currency understand .TO/.V."""- from src.agent.grounding import _infer_currency, _infer_venue, _scan_symbols-- scanned = _scan_symbols("compare TD.TO vs SHOP.V")- assert "TD.TO" in scanned- assert "SHOP.V" in scanned-- assert _infer_venue("TD.TO") == "toronto"- assert _infer_venue("SHOP.V") == "tsxv"- assert _infer_currency("TD.TO") == "CAD"- assert _infer_currency("SHOP.V") == "CAD"---def test_underscore_ticker_in_plan_path_seeds_locked_identity(- tmp_path: Path,-) -> None:- """A plan-file path like gldc_v-Weekly-...md must lock GLDC.V."""- ledger = GroundingLedger(- run_dir=tmp_path,- user_message=(- "Please update C:\\vibe-trading\\vibe-trading-history\\TSX\\2026\\08\\"- "gldc_v-Weekly-2026-08-03.md"- ),- )-- assert ledger.authorized_symbols == {"GLDC.V"}- authorization = ledger.authorize_tool_call(- "get_market_data",- {"codes": ["GLDC.V"]},- batch_authorized_symbols=ledger.authorized_symbols,- call_id="prices",- )- assert authorization.allowed is True---def test_trading_plan_ticker_scan_and_prose_guard() -> None:- """Trading-plan stems scan to canonical symbols; prose is not misread."""- from src.agent.grounding import _scan_symbols-- # Underscore separator.- assert _scan_symbols(- "C:\\vibe-trading\\vibe-trading-history\\TSX\\2026\\07\\"- "tf_to-trading-plan-2026-07-16-to-24.md"- ) == {"TF.TO"}- assert "GLDC.V" in _scan_symbols(- "C:\\vibe-trading\\vibe-trading-history\\TSX\\2026\\08\\"- "gldc_v-Weekly-2026-08-03.md"- )- assert "SGML.V" in _scan_symbols(- "C:\\vibe-trading\\vibe-trading-history\\TSX\\2026\\08\\"- "SGML_V-Weekly-2026-08-03.md"- )- # Hyphen separator, including a base that is itself hyphenated (BTCX-B).- assert _scan_symbols(- "C:\\vibe-trading\\vibe-trading-history\\TSX\\2026\\07\\"- "btcx-b-to-trading-plan-2026-07-13-to-17.md"- ) == {"BTCX-B.TO"}- assert _scan_symbols(- "C:\\vibe-trading\\vibe-trading-history\\TSX\\2026\\07\\"- "aapl-to-trading-plan-2026-07-06-to-10.md"- ) == {"AAPL.TO"}- assert "HIVE.TO" in _scan_symbols(- "C:\\vibe-trading\\vibe-trading-history\\TSX\\2026\\06\\"- "hive-to-trading-plan-2026-july-to-august.md"- )- # Dot separator (also handled by the canonical regex) stays consistent.- assert "BTCX-B.TO" in _scan_symbols(- "C:\\vibe-trading\\vibe-trading-history\\TSX\\2026\\07\\"- "btcx-b.to-trading-plan-2026-07-20-to-24.md"- )- # English prose ending in -to/-v must not become phantom tickers, even- # when the message carries a path elsewhere (no -Weekly/-trading-plan- # descriptor follows the suffix).- assert (- _scan_symbols("go_to school ready_to-go back_to basics C:\\x\\note.md")- == set()- )---def test_locked_symbol_survives_a_later_bare_ambiguous_search(- tmp_path: Path,-) -> None:- """Bare 'GLDC' ambiguity must not demote an already-locked GLDC.V."""- ledger = GroundingLedger(- run_dir=tmp_path,- user_message="请分析 GLDC.V 的当前价格",- )- candidates = [- {"symbol": "GLDCO2.SW", "name": "UBSETF Carbon Compens Gold ETF", "source": "yahoo"},- {"symbol": "GLDCX", "name": "Gabelli Gold Fund Class C", "source": "yahoo"},- {"symbol": "GLDC.V", "name": "CASSIAR GOLD CORP", "source": "yahoo"},- {"symbol": "GLDC.BA", "name": "SPDR GOLD TRUST GDR", "source": "yahoo"},- ]- ledger.ingest_tool_result(- tool_name="search_symbol",- arguments={"query": "GLDC"},- result=_resolver_payload(candidates=candidates, query="GLDC"),- call_id="bare-search",- success=True,- )-- assert ledger.identity_status == "locked"- assert ledger.authorized_symbols == {"GLDC.V"}- authorization = ledger.authorize_tool_call(- "get_market_data",- {"codes": ["GLDC.V"]},- batch_authorized_symbols=ledger.authorized_symbols,- batch_identity_status=ledger.identity_status,- call_id="prices",- )- assert authorization.allowed is True---def test_plan_path_symbol_survives_bare_search_end_to_end(- tmp_path: Path,-) -> None:- """End-to-end: a gldc_v plan path locks GLDC.V; bare GLDC can't demote it."""- ledger = GroundingLedger(- run_dir=tmp_path,- user_message=(- "Please update C:\\vibe-trading\\vibe-trading-history\\TSX\\2026\\08\\"- "gldc_v-Weekly-2026-08-03.md"- ),- )- assert ledger.authorized_symbols == {"GLDC.V"}- candidates = [- {"symbol": "GLDCO2.SW", "name": "UBSETF Carbon Compens Gold ETF", "source": "yahoo"},- {"symbol": "GLDCX", "name": "Gabelli Gold Fund Class C", "source": "yahoo"},- {"symbol": "GLDC.V", "name": "CASSIAR GOLD CORP", "source": "yahoo"},- {"symbol": "GLDC.BA", "name": "SPDR GOLD TRUST GDR", "source": "yahoo"},- ]- ledger.ingest_tool_result(- tool_name="search_symbol",- arguments={"query": "GLDC"},- result=_resolver_payload(candidates=candidates, query="GLDC"),- call_id="bare-search",- success=True,- )-- assert ledger.identity_status == "locked"- authorization = ledger.authorize_tool_call(- "get_market_data",- {"codes": ["GLDC.V"]},- batch_authorized_symbols=ledger.authorized_symbols,- batch_identity_status=ledger.identity_status,- call_id="prices",- )- assert authorization.allowed is True--def test_listed_identity_blocks_private_company_workflow(tmp_path: Path,) -> None:@@ -1295,32 +1086,6 @@ _PLAN_LEVELS_FROM_983 = ["目标位 6.80,止损 5.20","若收盘 5.36 则减仓","target price 6.80 with stop-loss 5.20",- # A `$` currency prefix must not break the mask (false-positive fix,- # observed in the Aug 2026 RXRX/BFLY runs: <$2.86 and 目标价 $3.50 were- # rejected as conflicts because the `$` sat between the operator/marker- # and the digit).- "硬触发: 收盘 <$2.86 且量 >2000 万股",- "收盘 < $2.86 且量 > 2000 万股",- "目标价 $3.50",- "目标价 $3.50 两档挂单",- "触发价 $4.00",- # The CAD `C$` prefix must not break the mask either (DCBO.TO run: a- # "收盘 < C$26.00" hard stop was read as a price claim).- "收盘 < C$26.00 全清",- "收盘低于 C$26.00",- "目标价 C$26.00",- # TA readings on their own scale are masked (布林/SMA/RSI in the DCBO.TO- # draft: "布林 30.98/26.64/22.29", "SMA200 35.78" were read as claims).- "布林 30.98/26.64/22.29(收盘站上上轨)",- "布林带 30.98/26.64/22.29",- "SMA200 35.78(价格在其下)",- "RSI 46.7",- # A day-range shares the month prefix: the "–14" tail of "8/10–14" was- # parsed as a price of 14.0 and rejected the GRID.TO / DCBO.TO drafts.- "8/10–14 每日收盘判定项",- "8/10-14",- "8/10至14",- "2026-08-10–14",]@@ -1330,43 +1095,6 @@ def test_plan_levels_are_not_read_as_observed_price_claims(segment: str) -> Noneassert GroundingLedger._numbers_without_dates_or_percent(segment) == []-# Bare 万/萬 (ten-thousands) is a quantity, never a per-share price: volume-# figures written without the 股 unit ("量 5–10 万", "119 万") were parsed as-# OHLC claims and rejected the FLT.TO draft on the first attempt (Aug 2026).-_VOLUME_QUANTITIES_IN_WAN = [- "量 5–10 万",- "量 5-10 万",- "119 万",- "量 119 萬",- "量 150 万股",- "量 5–10 万股",-]--[email protected]("segment", _VOLUME_QUANTITIES_IN_WAN, ids=range(len(_VOLUME_QUANTITIES_IN_WAN)))-def test_wan_quantities_are_not_read_as_price_claims(segment: str) -> None:- """A volume in ten-thousands is not an observed price claim."""- assert GroundingLedger._numbers_without_dates_or_percent(segment) == []---# A markdown ordered-list item number ("1. 持仓", "10. 事件") is not a price.-# The standalone integer + period at line start was parsed as a price claim of-# 1.0 and rejected the BLDP.TO draft on its second attempt (Aug 2026).-_ORDERED_LIST_MARKERS = [- "1. **持仓**",- "1. 持仓",- "2. GTC 单",- "10. 事件",- " 1. 持仓",-]--[email protected]("segment", _ORDERED_LIST_MARKERS, ids=range(len(_ORDERED_LIST_MARKERS)))-def test_ordered_list_markers_are_not_read_as_price_claims(segment: str) -> None:- """An ordered-list item number asserts nothing about observed data."""- assert GroundingLedger._numbers_without_dates_or_percent(segment) == []--# The other side of the same guard. Every entry here is an assertion about what# the instrument did, and each must survive the mask above — otherwise the# relaxation is a way to state a price without being checked.@@ -1380,26 +1108,6 @@ _ASSERTIONS_THAT_MUST_STAY_CHECKED = [# A conditional opener must not reach back over a quote already made.("收盘 6.03,若跌破 5.36 减仓", [6.03]),("开盘 6.80 最高 7.18 最低 6.68", [6.80, 7.18, 6.68]),- # A `$` alone is NOT prospective: an observed quote written with a- # currency prefix and no marker/operator must stay checked.- ("现价 $5.97", [5.97]),- ("开盘 $6.80 最高 $7.18 最低 $6.68", [6.80, 7.18, 6.68]),- # A 万 quantity must not hide a nearby observed quote (span-local):- # the volume is masked, the close beside it stays checked.- ("收盘 0.49,量 119 万", [0.49]),- # An ordered-list marker must not shield the real price beside it:- # "1." and the 500-share quantity mask, the C$3.72 quote stays checked.- ("1. 持仓: 500 股 @ C$3.72", [3.72]),- # A decimal at line start is not a list marker ("3.50" has a digit after- # the period).- ("3.50 支撑位", [3.5]),- # A real low (低) is NOT an indicator/level mask: it stays checked and, in- # a multi-symbol session, needs its canonical symbol named explicitly.- ("低 19.87(2026-04-13)", [19.87]),- # `C$`/`$` alone (no operator/marker) is not prospective: stays checked.- ("C$26.00 收盘", [26.0]),- # A single short date masks, but the price beside it stays checked.- ("8/10 收 5.00", [5.0]),]diff --git a/agent/tests/test_composite_currency_guard.py b/agent/tests/test_composite_currency_guard.pyindex b99095088..854d37a0b 100644--- a/agent/tests/test_composite_currency_guard.py+++ b/agent/tests/test_composite_currency_guard.py@@ -1,7 +1,7 @@"""Regression tests for the composite engine's single-currency requirement.``CompositeEngine`` keeps one shared capital pool: a single cash scalar and one-equity curve. Before this guard a code set spanning CNY, USD, HKD, INR and KRW+equity curve. Before this guard a code set spanning CNY, USD, HKD, INR, KRW and CADwas summed into that curve as if the units matched, and every metric derivedfrom it was reported without a warning. There is no FX translation layer, sothe engine refuses the run instead.@@ -26,6 +26,8 @@ class TestCodeCurrency:("00700.HK", "HKD"),("RELIANCE.NS", "INR"),("005930.KS", "KRW"),+ ("TD.TO", "CAD"),+ ("PNG.V", "CAD"),("IF2406.CFFEX", "CNY"),],)@@ -66,6 +68,10 @@ class TestRejectMixedCurrency:with pytest.raises(ValueError, match="one settlement currency"):_reject_mixed_currency(["600519.SH", "AAPL.US"])+ def test_canadian_and_us_equities_are_not_summed_without_fx(self):+ with pytest.raises(ValueError, match="one settlement currency"):+ _reject_mixed_currency(["TD.TO", "AAPL.US"])+def test_the_error_names_every_currency_and_its_codes(self):with pytest.raises(ValueError) as excinfo:_reject_mixed_currency(["600519.SH", "AAPL.US", "005930.KS"])diff --git a/agent/tests/test_correlation.py b/agent/tests/test_correlation.pyindex c57e83c3a..820e31945 100644--- a/agent/tests/test_correlation.py+++ b/agent/tests/test_correlation.py@@ -62,6 +62,8 @@ class TestInferMarket:assert infer_market("830799.BJ") == "a_share"assert infer_market("AAPL.US") == "us_equity"assert infer_market("9988.HK") == "hk_equity"+ assert infer_market("TD.TO") == "ca_equity"+ assert infer_market("PNG.V") == "ca_equity"class TestNormalizeSymbol:@@ -81,6 +83,7 @@ class TestNormalizeSymbol:assert _normalize_symbol("AAPL.US", "us_equity") == "AAPL.US"assert _normalize_symbol("600000.SH", "a_share") == "600000.SH"assert _normalize_symbol("0700.HK", "hk_equity") == "0700.HK"+ assert _normalize_symbol("TD.TO", "ca_equity") == "TD.TO"def test_crypto_passes_through(self):assert _normalize_symbol("BTC-USDT", "crypto") == "BTC-USDT"diff --git a/agent/tests/test_dragon_tiger_tool.py b/agent/tests/test_dragon_tiger_tool.pyindex 0d657ee64..c5c836247 100644--- a/agent/tests/test_dragon_tiger_tool.py+++ b/agent/tests/test_dragon_tiger_tool.py@@ -1,8 +1,8 @@"""Tests for the dragon-tiger (龙虎榜) tool.No request leaves the process: the HTTP boundary-(:func:`backtest.loaders.eastmoney_client.get_json` via ``throttled_get``) is-mocked so the real client + tool parsing runs offline.+(:func:`backtest.loaders.eastmoney_client.throttled_get_json`) is mocked so the+real client + tool parsing runs offline."""from __future__ import annotations@@ -17,18 +17,6 @@ from backtest.loaders import eastmoney_clientfrom src.tools.dragon_tiger_tool import DragonTigerTool, _bare_code, _compact_date-class _FakeResponse:- """Minimal requests.Response stand-in for the mocked HTTP boundary."""-- def __init__(self, body: str, status_code: int = 200):- self.text = body- self.status_code = status_code-- def raise_for_status(self) -> None:- if self.status_code >= 400:- raise RuntimeError(f"{self.status_code} Server Error")--def _appearance_payload() -> dict[str, Any]:"""A datacenter appearance payload with two board rows."""return {@@ -106,9 +94,7 @@ class TestExecuteSuccess:def test_full_market_list_no_code(self) -> None:tool = DragonTigerTool()with patch.object(- eastmoney_client,- "throttled_get",- return_value=_FakeResponse(json.dumps(_appearance_payload())),+ eastmoney_client, "throttled_get_json", return_value=_appearance_payload()) as http:out = json.loads(tool.execute(date="2024-01-02"))@@ -130,9 +116,8 @@ class TestExecuteSuccess:def test_with_code_adds_seats(self) -> None:tool = DragonTigerTool()payloads = [_appearance_payload(), _seat_payload()]- responses = [_FakeResponse(json.dumps(p)) for p in payloads]with patch.object(- eastmoney_client, "throttled_get", side_effect=responses+ eastmoney_client, "throttled_get_json", side_effect=payloads) as http:out = json.loads(tool.execute(date="2024-01-02", code="600519.SH"))@@ -159,7 +144,7 @@ class TestExecuteError:tool = DragonTigerTool()with patch.object(eastmoney_client,- "throttled_get",+ "throttled_get_json",side_effect=RuntimeError("eastmoney banned"),), patch("src.tools.dragon_tiger_tool.tushare_fallbacks.fetch_dragon_tiger",@@ -179,7 +164,7 @@ class TestExecuteError:tool = DragonTigerTool()with patch.object(eastmoney_client,- "throttled_get",+ "throttled_get_json",side_effect=RuntimeError("eastmoney banned"),), patch("src.tools.dragon_tiger_tool.tushare_fallbacks.fetch_dragon_tiger",diff --git a/agent/tests/test_eastmoney_client.py b/agent/tests/test_eastmoney_client.pyindex e8218d907..1d090cf7b 100644--- a/agent/tests/test_eastmoney_client.py+++ b/agent/tests/test_eastmoney_client.py@@ -1,11 +1,9 @@"""Tests for eastmoney_client: secid resolution, kline parsing, error paths.-All HTTP is mocked at :func:`backtest.loaders._http.throttled_get` (the raw-response boundary used by the client's ``get_json``), so no test touches a live-Eastmoney endpoint.+All HTTP is mocked at :func:`backtest.loaders._http.throttled_get_json` (imported+into the client module), so no test touches a live Eastmoney endpoint."""-import jsonfrom unittest.mock import patchimport pytest@@ -13,18 +11,6 @@ import pytestfrom backtest.loaders import eastmoney_client as ec-class _FakeResponse:- """Minimal requests.Response stand-in for the mocked HTTP boundary."""-- def __init__(self, body: str, status_code: int = 200):- self.text = body- self.status_code = status_code-- def raise_for_status(self) -> None:- if self.status_code >= 400:- raise RuntimeError(f"{self.status_code} Server Error")--@pytest.fixture(autouse=True)def _clear_us_cache():"""Reset the module-level US secid cache so tests stay independent."""@@ -70,9 +56,7 @@ class TestResolveSecidUS:]}}- with patch.object(- ec, "throttled_get", return_value=_FakeResponse(json.dumps(payload))- ) as mock_get:+ with patch.object(ec, "throttled_get_json", return_value=payload) as mock_get:assert ec.resolve_secid("AAPL.US") == "105.AAPL"# Second call is served from cache: no further HTTP.assert ec.resolve_secid("AAPL.US") == "105.AAPL"@@ -80,7 +64,7 @@ class TestResolveSecidUS:def test_handles_jsonp_wrapped_search_body(self):body = 'cb({"QuotationCodeTable":{"Data":[{"QuoteID":"106.BRK"}]}})'- with patch.object(ec, "throttled_get", return_value=_FakeResponse(body)):+ with patch.object(ec, "throttled_get_json", return_value=body):assert ec.resolve_secid("BRK.US") == "106.BRK"def test_plain_json_body_with_parens_in_values(self):@@ -93,18 +77,18 @@ class TestResolveSecidUS:'{"QuotationCodeTable":{"Data":''[{"QuoteID":"105.AAPL","Name":"Apple Inc. (AAPL) [NASDAQ]"}]}}')- with patch.object(ec, "throttled_get", return_value=_FakeResponse(body)):+ with patch.object(ec, "throttled_get_json", return_value=body):assert ec.resolve_secid("AAPL.US") == "105.AAPL"def test_no_us_candidate_returns_none(self):payload = {"QuotationCodeTable": {"Data": [{"QuoteID": "1.600519"}]}}- with patch.object(- ec, "throttled_get", return_value=_FakeResponse(json.dumps(payload))- ):+ with patch.object(ec, "throttled_get_json", return_value=payload):assert ec.resolve_secid("NOPE.US") is Nonedef test_search_failure_returns_none_without_raising(self):- with patch.object(ec, "throttled_get", side_effect=RuntimeError("banned")):+ with patch.object(+ ec, "throttled_get_json", side_effect=RuntimeError("banned")+ ):assert ec.resolve_secid("AAPL.US") is None@@ -121,9 +105,7 @@ class TestFetchKline:],}}- with patch.object(- ec, "throttled_get", return_value=_FakeResponse(json.dumps(payload))- ) as mock_get:+ with patch.object(ec, "throttled_get_json", return_value=payload) as mock_get:rows = ec.fetch_kline("1.600519", klt=ec.KLT_BY_INTERVAL["1D"])assert rows == [@@ -152,9 +134,7 @@ class TestFetchKline:assert kwargs["params"]["klt"] == "101"def test_empty_data_returns_empty_list(self):- with patch.object(- ec, "throttled_get", return_value=_FakeResponse(json.dumps({"data": None}))- ):+ with patch.object(ec, "throttled_get_json", return_value={"data": None}):assert ec.fetch_kline("1.600519", klt=101) == []def test_malformed_row_is_skipped_not_fatal(self):@@ -166,15 +146,15 @@ class TestFetchKline:]}}- with patch.object(- ec, "throttled_get", return_value=_FakeResponse(json.dumps(payload))- ):+ with patch.object(ec, "throttled_get_json", return_value=payload):rows = ec.fetch_kline("1.600519", klt=101)assert len(rows) == 1assert rows[0]["trade_date"] == "2024-01-03"def test_http_error_propagates(self):- with patch.object(ec, "throttled_get", side_effect=RuntimeError("HTTP 429")):+ with patch.object(+ ec, "throttled_get_json", side_effect=RuntimeError("HTTP 429")+ ):with pytest.raises(RuntimeError, match="429"):ec.fetch_kline("1.600519", klt=101)diff --git a/agent/tests/test_eastmoney_loader.py b/agent/tests/test_eastmoney_loader.pyindex 255b05a0f..5c61efcc6 100644--- a/agent/tests/test_eastmoney_loader.py+++ b/agent/tests/test_eastmoney_loader.py@@ -2,13 +2,12 @@These never touch the network: the cross-market path mocks the shared client(:mod:`backtest.loaders.eastmoney_client`), and the end-to-end path mocks the-HTTP boundary (``throttled_get``) so the real client parsing runs while no+HTTP boundary (``throttled_get_json``) so the real client parsing runs while norequest leaves the process."""from __future__ import annotations-import jsonfrom typing import Listfrom unittest.mock import patch@@ -19,18 +18,6 @@ from backtest.loaders import eastmoney_clientfrom backtest.loaders.eastmoney_loader import DataLoader, _to_compact_date-class _FakeResponse:- """Minimal requests.Response stand-in for the mocked HTTP boundary."""-- def __init__(self, body: str, status_code: int = 200):- self.text = body- self.status_code = status_code-- def raise_for_status(self) -> None:- if self.status_code >= 400:- raise RuntimeError(f"{self.status_code} Server Error")--def _client_rows() -> List[dict]:"""Two ascending bars in eastmoney_client.fetch_kline output shape."""return [@@ -189,9 +176,7 @@ class TestFetchEndToEndHttpMocked:}loader = DataLoader()with patch.object(- eastmoney_client,- "throttled_get",- return_value=_FakeResponse(json.dumps(payload)),+ eastmoney_client, "throttled_get_json", return_value=payload) as http:out = loader.fetch(["600519.SH"], "2024-01-01", "2024-01-31")diff --git a/agent/tests/test_financial_statements_tool.py b/agent/tests/test_financial_statements_tool.pyindex 86f00dad2..15a983162 100644--- a/agent/tests/test_financial_statements_tool.py+++ b/agent/tests/test_financial_statements_tool.py@@ -100,68 +100,6 @@ _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."""@@ -270,83 +208,6 @@ 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_global_equity_engine.py b/agent/tests/test_global_equity_engine.pyindex d6f62f558..641a061a2 100644--- a/agent/tests/test_global_equity_engine.py+++ b/agent/tests/test_global_equity_engine.py@@ -1,9 +1,10 @@-"""Tests for GlobalEquityEngine (US / HK) market rules.+"""Tests for GlobalEquityEngine (US / HK / Canada) market rules.Validates:- US: zero commission, fractional shares, low slippage- HK: stamp tax bilateral, 100-share lots, levies- - T+0 for both markets+ - Canada: whole shares, configurable broker cost, TSX/TSXV tick grid+ - Same-session trading for all three markets- Both directions allowed"""@@ -36,6 +37,12 @@ def _hk_engine(**overrides) -> GlobalEquityEngine:return GlobalEquityEngine(config, market="hk")+def _ca_engine(**overrides) -> GlobalEquityEngine:+ config = {"initial_cash": 500_000}+ config.update(overrides)+ return GlobalEquityEngine(config, market="ca")++# ---------------------------------------------------------------------------# can_execute: T+0 both directions# ---------------------------------------------------------------------------@@ -57,6 +64,11 @@ class TestCanExecute:def test_hk_short(self) -> None:assert _hk_engine().can_execute("0700.HK", -1, _make_bar()) is True+ def test_canada_long_and_short(self) -> None:+ engine = _ca_engine()+ assert engine.can_execute("TD.TO", 1, _make_bar()) is True+ assert engine.can_execute("PNG.V", -1, _make_bar()) is True+# ---------------------------------------------------------------------------# round_size: US fractional vs HK lots@@ -86,6 +98,13 @@ class TestRoundSize:engine = _hk_engine()assert engine.round_size(199.0, 80.0) == 100+ def test_canada_uses_whole_shares_but_keeps_odd_lots(self) -> None:+ engine = _ca_engine()+ assert engine.round_size(19.9, 85.0) == 19.0+ assert engine.round_size(1.1, 85.0) == 1.0+ assert engine.round_size(0.9, 85.0) == 0.0+ assert engine.round_size(-3.0, 85.0) == 0.0+# ---------------------------------------------------------------------------# calc_commission: US zero vs HK complex@@ -131,6 +150,11 @@ class TestCommission:)assert comm == pytest.approx(expected, abs=0.01)+ def test_canada_commission_is_broker_configured(self) -> None:+ engine = _ca_engine(ca_commission=0.001)+ assert engine.calc_commission(100, 25.0, 1, is_open=True) == 2.5+ assert engine.calc_commission(100, 25.0, 1, is_open=False) == 2.5+# ---------------------------------------------------------------------------# apply_slippage: US low vs HK moderate@@ -159,6 +183,25 @@ class TestSlippage:)assert engine.apply_slippage(100.0, 1) == pytest.approx(100.2)+ @pytest.mark.parametrize(+ ("price", "direction", "expected"),+ [+ (10.001, 1, 10.01),+ (10.009, -1, 10.00),+ (0.421, 1, 0.425),+ (0.424, -1, 0.420),+ ],+ )+ def test_canada_rounds_against_trader_on_official_tick_grid(+ self, price: float, direction: int, expected: float,+ ) -> None:+ engine = _ca_engine(slippage_ca=0.0)+ assert engine.apply_slippage(price, direction) == expected++ def test_canada_slippage_is_configurable(self) -> None:+ engine = _ca_engine(slippage_ca=0.001)+ assert engine.apply_slippage(100.0, 1) == 100.1+# ---------------------------------------------------------------------------# Market parameter@@ -173,3 +216,7 @@ class TestMarketParam:def test_hk_market(self) -> None:engine = GlobalEquityEngine({"initial_cash": 100_000}, market="hk")assert engine.market == "hk"++ def test_canada_market(self) -> None:+ engine = GlobalEquityEngine({"initial_cash": 100_000}, market="ca")+ assert engine.market == "ca"diff --git a/agent/tests/test_local_source_routing.py b/agent/tests/test_local_source_routing.pyindex f8081ea8e..9c01fdec7 100644--- a/agent/tests/test_local_source_routing.py+++ b/agent/tests/test_local_source_routing.py@@ -29,6 +29,11 @@ class TestLocalSourceEngineRouting:engine = _create_market_engine("local", {"initial_cash": 100_000}, ["00700.HK"])assert isinstance(engine, GlobalEquityEngine)+ def test_local_canadian_equity_routes_to_canadian_global_rules(self) -> None:+ engine = _create_market_engine("local", {"initial_cash": 100_000}, ["TD.TO"])+ assert isinstance(engine, GlobalEquityEngine)+ assert engine.market == "ca"+def test_local_crypto_still_routes_to_crypto_engine(self) -> None:engine = _create_market_engine("local", {"initial_cash": 100_000}, ["BTC-USDT"])assert isinstance(engine, CryptoEngine)@@ -76,6 +81,23 @@ class _SwappedNetworkLoader:class TestBenchmarkLoaderForwarding:+ def test_canadian_equity_uses_canadian_benchmark(+ self, monkeypatch: pytest.MonkeyPatch,+ ) -> None:+ fallback = _FakeLoader([100.0, 103.0])+ monkeypatch.setattr("backtest.benchmark.YfinanceLoader", lambda: fallback)++ result = resolve_benchmark(+ strategy_codes=["BBD-B.TO"],+ source="yahoo",+ start_date="2023-01-03",+ end_date="2023-01-04",+ )++ assert result is not None+ assert result.ticker == "XIC.TO"+ assert fallback.fetched == ["XIC.TO"]+def test_explicit_source_loader_is_used_instead_of_yfinance(self, monkeypatch: pytest.MonkeyPatch,) -> None:diff --git a/agent/tests/test_lockup_expiry_tool.py b/agent/tests/test_lockup_expiry_tool.pyindex ef61fa020..992b1357e 100644--- a/agent/tests/test_lockup_expiry_tool.py+++ b/agent/tests/test_lockup_expiry_tool.py@@ -2,7 +2,7 @@No request ever leaves the process: the success/shape paths mock the sharedclient (:mod:`backtest.loaders.eastmoney_client`), and the end-to-end path mocks-the frozen HTTP boundary (``throttled_get``) so the real client routing and+the frozen HTTP boundary (``throttled_get_json``) so the real client routing andthis tool's parsing both run while nothing hits the network."""@@ -17,18 +17,6 @@ from src.tools import lockup_expiry_toolfrom src.tools.lockup_expiry_tool import LockupExpiryTool-class _FakeResponse:- """Minimal requests.Response stand-in for the mocked HTTP boundary."""-- def __init__(self, body: str, status_code: int = 200):- self.text = body- self.status_code = status_code-- def raise_for_status(self) -> None:- if self.status_code >= 400:- raise RuntimeError(f"{self.status_code} Server Error")--def _payload(rows: list[dict]) -> dict:"""Wrap report rows in the datacenter ``result.data`` envelope."""return {"result": {"data": rows, "count": len(rows)}}@@ -165,9 +153,7 @@ class TestEndToEndHttpMocked:def test_single_code_through_real_client(self) -> None:rows = [_row("600519", "2024-06-01")]with patch.object(- eastmoney_client,- "throttled_get",- return_value=_FakeResponse(json.dumps(_payload(rows))),+ eastmoney_client, "throttled_get_json", return_value=_payload(rows)) as http:out = json.loads(LockupExpiryTool().execute(code="600519"))diff --git a/agent/tests/test_market_data.py b/agent/tests/test_market_data.pyindex 39b283e77..3aebd8e55 100644--- a/agent/tests/test_market_data.py+++ b/agent/tests/test_market_data.py@@ -45,9 +45,8 @@ from src.market_data import (("BAJAJ-AUTO.NS", "yahoo"), # hyphen in ticker("500325.BO", "yahoo"), # India BSE (numeric scrip code)("TD.TO", "yahoo"), # Canada TSX- ("SHOP.TO", "yahoo"),- ("ACDC.V", "yahoo"), # Canada TSX Venture- ("NEXE.V", "yahoo"),+ ("BBD-B.TO", "yahoo"), # hyphenated TSX class symbol+ ("PNG.V", "yahoo"), # Canada TSX Venture("BTC-USDT", "okx"),("ETH/USDT", "ccxt"),("EUR/USD", "mt5"), # forex pair → mt5 chain head (registry fallback)@@ -75,8 +74,8 @@ def test_yahoo_loader_accepts_futures_and_forex_suffixes() -> None:assert _is_supported("GC=F") is Trueassert _is_supported("EURUSD=X") is Trueassert _is_supported("AAPL.US") is True # unchanged- assert _is_supported("TD.TO") is True # Canada TSX- assert _is_supported("SHOP.V") is True # Canada TSX Venture+ assert _is_supported("TD.TO") is True+ assert _is_supported("PNG.V") is Trueassert _is_supported("600519.SH") is False # A-share still not yahoo@@ -100,7 +99,7 @@ def test_fetch_market_data_auto_routes_yahoo_suffix_symbols() -> None:return _StubLoaderout = fetch_market_data(- codes=["GC=F", "EURUSD=X"],+ codes=["GC=F", "EURUSD=X", "TD.TO", "PNG.V"],start_date="2024-01-01",end_date="2024-01-03",source="auto",@@ -108,7 +107,7 @@ def test_fetch_market_data_auto_routes_yahoo_suffix_symbols() -> None:)assert "_unresolved" not in out- assert "GC=F" in out and "EURUSD=X" in out+ assert all(code in out for code in ("GC=F", "EURUSD=X", "TD.TO", "PNG.V"))# First source tried must be yahoo (not tushare/akshare from the China chain).assert seen_sources and seen_sources[0] == "yahoo"diff --git a/agent/tests/test_market_detection.py b/agent/tests/test_market_detection.pyindex 765653d3d..c85f4768a 100644--- a/agent/tests/test_market_detection.py+++ b/agent/tests/test_market_detection.py@@ -70,10 +70,8 @@ class TestDetectMarket:("247540.KQ", "kr_equity"), # KOSDAQ# Canada equity (TSX / TSX Venture)("TD.TO", "ca_equity"),- ("SHOP.TO", "ca_equity"),- ("ENB.TO", "ca_equity"),- ("ACDC.V", "ca_equity"),- ("NEXE.V", "ca_equity"),+ ("BBD-B.TO", "ca_equity"),+ ("PNG.V", "ca_equity"),# Crypto("BTC-USDT", "crypto"),("ETH-USDT", "crypto"),@@ -98,6 +96,7 @@ class TestDetectMarket:assert _detect_market("aapl.us") == "us_equity"assert _detect_market("aapl") == "us_equity"assert _detect_market("btc-usdt") == "crypto"+ assert _detect_market("td.to") == "ca_equity"def test_unknown_defaults_to_a_share(self) -> None:assert _detect_market("UNKNOWN") == "a_share"@@ -132,6 +131,12 @@ class TestBareUsTickerRouting:assert code_currency("AAPL") == "USD"assert code_currency("AAPL.US") == "USD"+ def test_canadian_tickers_route_to_canada_and_cad(self) -> None:+ assert _detect_source("TD.TO") == "yahoo"+ assert _detect_source("PNG.V") == "yahoo"+ assert code_currency("TD.TO") == "CAD"+ assert code_currency("PNG.V") == "CAD"+def test_catch_all_is_lowest_priority(self) -> None:assert _detect_market("600519.SH") == "a_share"assert _detect_market("00700.HK") == "hk_equity"@@ -179,7 +184,7 @@ class TestDetectSource:("005930.KS", "pykrx"),("247540.KQ", "pykrx"),("TD.TO", "yahoo"),- ("SHOP.V", "yahoo"),+ ("PNG.V", "yahoo"),("BTC-USDT", "okx"),("IF2406.CFFEX", "tushare"),("EUR/USD", "akshare"),@@ -196,12 +201,13 @@ class TestDetectSource:class TestGroupCodes:def test_mixed_codes(self) -> None:- codes = ["000001.SZ", "AAPL.US", "BTC-USDT", "0700.HK"]+ codes = ["000001.SZ", "AAPL.US", "BTC-USDT", "0700.HK", "TD.TO"]groups = _group_codes_by_market(codes)assert groups["a_share"] == ["000001.SZ"]assert groups["us_equity"] == ["AAPL.US"]assert groups["crypto"] == ["BTC-USDT"]assert groups["hk_equity"] == ["0700.HK"]+ assert groups["ca_equity"] == ["TD.TO"]def test_same_market(self) -> None:codes = ["000001.SZ", "600519.SH"]diff --git a/agent/tests/test_registry.py b/agent/tests/test_registry.pyindex 08b6013e1..986946c14 100644--- a/agent/tests/test_registry.py+++ b/agent/tests/test_registry.py@@ -132,9 +132,15 @@ class TestProtocol:class TestFallbackChains:def test_all_expected_markets_present(self) -> None:- expected = {"a_share", "us_equity", "hk_equity", "india_equity", "kr_equity", "ca_equity", "crypto", "futures", "fund", "macro", "forex"}+ expected = {+ "a_share", "us_equity", "hk_equity", "india_equity", "kr_equity",+ "ca_equity", "crypto", "futures", "fund", "macro", "forex",+ }assert expected == set(FALLBACK_CHAINS.keys())+ def test_canada_chain_uses_only_compatible_sources(self) -> None:+ assert FALLBACK_CHAINS["ca_equity"] == ["yahoo", "yfinance", "local"]+def test_chains_are_non_empty(self) -> None:for market, chain in FALLBACK_CHAINS.items():assert len(chain) > 0, f"Fallback chain for {market} is empty"diff --git a/agent/tests/test_stock_news_tool.py b/agent/tests/test_stock_news_tool.pyindex d00587477..1e8a176b9 100644--- a/agent/tests/test_stock_news_tool.py+++ b/agent/tests/test_stock_news_tool.py@@ -1,9 +1,9 @@"""Tests for the stock-news tool.No request leaves the process: the Eastmoney HTTP boundary-(:func:`backtest.loaders.eastmoney_client.get_json` via ``throttled_get``) and-the Yahoo :func:`backtest.loaders.yahoo_client.search_news` helper are mocked so-the real client + tool parsing run fully offline.+(:func:`backtest.loaders.eastmoney_client.throttled_get_json`) and the Yahoo+:func:`backtest.loaders.yahoo_client.search_news` helper are mocked so the real+client + tool parsing run fully offline."""from __future__ import annotations@@ -69,24 +69,10 @@ def _yahoo_news() -> list[dict[str, Any]]:]-class _FakeResponse:- """Minimal requests.Response stand-in for the mocked HTTP boundary."""-- def __init__(self, body: str, status_code: int = 200):- self.text = body- self.status_code = status_code-- def raise_for_status(self) -> None:- if self.status_code >= 400:- raise RuntimeError(f"{self.status_code} Server Error")--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:@@ -138,9 +124,7 @@ class TestExecuteSuccess:def test_a_share_stock_news(self) -> None:tool = StockNewsTool()with patch.object(- eastmoney_client,- "throttled_get",- return_value=_FakeResponse(json.dumps(_em_news_payload())),+ eastmoney_client, "throttled_get_json", return_value=_em_news_payload()) as http:out = json.loads(tool.execute(code="600519.SH", scope="stock", limit=10))@@ -161,9 +145,7 @@ class TestExecuteSuccess:def test_global_scope_needs_no_code(self) -> None:tool = StockNewsTool()with patch.object(- eastmoney_client,- "throttled_get",- return_value=_FakeResponse(json.dumps(_em_news_payload())),+ eastmoney_client, "throttled_get_json", return_value=_em_news_payload()):out = json.loads(tool.execute(scope="global"))@@ -208,19 +190,6 @@ 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"))@@ -256,7 +225,7 @@ class TestExecuteError:tool = StockNewsTool()with patch.object(eastmoney_client,- "throttled_get",+ "throttled_get_json",side_effect=RuntimeError("eastmoney banned"),):out = json.loads(tool.execute(code="600519.SH"))diff --git a/agent/tests/test_swarm_grounding.py b/agent/tests/test_swarm_grounding.pyindex e789a6fed..e08f2aaa2 100644--- a/agent/tests/test_swarm_grounding.py+++ b/agent/tests/test_swarm_grounding.py@@ -32,13 +32,21 @@ def test_extract_us_hk_a_share_and_crypto_symbols() -> None:"crypto": "Hedge with BTC-USDT","shenzhen": "000001.SZ for liquidity","beijing": "Listed on 430090.BJ recently",+ "canada": "Compare TD.TO with TSX Venture name PNG.V",}found = grounding.extract_symbols_from_user_vars(user_vars)assert set(found) == {"NVDA.US", "700.HK", "600519.SH", "BTC-USDT", "000001.SZ", "430090.BJ",+ "TD.TO", "PNG.V",}+def test_extract_canadian_class_symbol() -> None:+ assert grounding.extract_symbols_from_user_vars(+ {"target": "Review BBD-B.TO in CAD"}+ ) == ["BBD-B.TO"]++def test_extract_preserves_first_occurrence_order() -> None:user_vars = {"a": "Look at NVDA.US",@@ -112,13 +120,6 @@ def test_extract_does_not_match_substrings_inside_words() -> None:assert grounding.extract_symbols_from_user_vars(user_vars) == []-def test_extract_canadian_tsx_symbols() -> None:- # .TO (TSX) and .V (TSX Venture) are detected as explicit suffixed symbols;- # their bare roots (TD, SHOP) must not leak into bogus .US promotions.- user_vars = {"goal": "analyze TD.TO and SHOP.V positioning"}- assert grounding.extract_symbols_from_user_vars(user_vars) == ["TD.TO", "SHOP.V"]--# --------------------------------------------------------------------------- ## fetch_grounding_data — monkeypatched loader# --------------------------------------------------------------------------- #diff --git a/agent/tests/test_symbol_search_tool.py b/agent/tests/test_symbol_search_tool.pyindex 8682bf5f4..8bc0b7d09 100644--- a/agent/tests/test_symbol_search_tool.py+++ b/agent/tests/test_symbol_search_tool.py@@ -72,36 +72,22 @@ def _yahoo_quotes() -> list:"exchange": "CCC","quoteType": "CRYPTOCURRENCY",},+ {+ "symbol": "TD.TO",+ "shortname": "Toronto-Dominion Bank",+ "exchange": "TOR",+ "quoteType": "EQUITY",+ },+ {+ "symbol": "PNG.V",+ "shortname": "Kraken Robotics Inc.",+ "exchange": "VAN",+ "quoteType": "EQUITY",+ },{"symbol": "", "shortname": "no symbol"}, # dropped]-class TestFromYahooSymbol:- """Yahoo symbol -> project convention, incl. Canadian suffixes."""-- def test_canadian_suffixes_map_to_ca(self):- assert ss._from_yahoo_symbol("DCBO.TO", {"quoteType": "EQUITY"}) == (- "DCBO.TO",- "ca",- )- assert ss._from_yahoo_symbol("ACDC.V", {"quoteType": "EQUITY"}) == (- "ACDC.V",- "ca",- )-- def test_us_equity_still_maps_to_us(self):- assert ss._from_yahoo_symbol("AAPL", {"quoteType": "EQUITY"}) == (- "AAPL.US",- "us",- )-- def test_hk_still_maps_to_hk(self):- assert ss._from_yahoo_symbol("0700.HK", {"quoteType": "EQUITY"}) == (- "00700.HK",- "hk",- )--class TestSymbolSearchSuccess:"""Happy-path fan-out, normalization, merge, and CIK enrichment."""@@ -128,6 +114,9 @@ class TestSymbolSearchSuccess:by_symbol = {c["symbol"]: c for c in data["candidates"]}+ assert by_symbol["TD.TO"]["market"] == "ca"+ assert by_symbol["PNG.V"]["market"] == "ca"+# A-share secid -> 600519.SH, market cn.assert by_symbol["600519.SH"]["market"] == "cn"assert by_symbol["600519.SH"]["name"] == "贵州茅台"diff --git a/agent/tests/test_yahoo_client.py b/agent/tests/test_yahoo_client.pyindex 07abb5b5d..28e2f64ce 100644--- a/agent/tests/test_yahoo_client.py+++ b/agent/tests/test_yahoo_client.py@@ -67,6 +67,8 @@ class TestMapSymbol:def test_passthrough_for_other_symbols(self):assert yahoo_client.map_symbol("BTC-USD") == "BTC-USD"assert yahoo_client.map_symbol("^GSPC") == "^GSPC"+ assert yahoo_client.map_symbol("TD.TO") == "TD.TO"+ assert yahoo_client.map_symbol("PNG.V") == "PNG.V"# ---------------------------------------------------------------------------diff --git a/agent/tests/test_yahoo_loader.py b/agent/tests/test_yahoo_loader.pyindex e826d4238..991a6edc1 100644--- a/agent/tests/test_yahoo_loader.py+++ b/agent/tests/test_yahoo_loader.py@@ -54,7 +54,7 @@ def _intraday_stamped_row(date_str: str, open_, high, low, close, volume):class TestSymbolGating:- """_is_supported accepts US/HK/India suffixes only."""+ """_is_supported accepts the equity suffixes served by Yahoo."""def test_accepts_us(self):assert _is_supported("AAPL.US") is True@@ -69,6 +69,11 @@ class TestSymbolGating:assert _is_supported("reliance.ns") is Trueassert _is_supported("500325.BO") is True+ def test_accepts_canada(self):+ assert _is_supported("TD.TO") is True+ assert _is_supported("PNG.V") is True+ assert _is_supported("bbd-b.to") is True+def test_rejects_others(self):assert _is_supported("601398.SH") is Falseassert _is_supported("BTC-USDT") is Falsediff --git a/agent/tests/test_yfinance_crypto.py b/agent/tests/test_yfinance_crypto.pyindex 4076b1858..42b928f36 100644--- a/agent/tests/test_yfinance_crypto.py+++ b/agent/tests/test_yfinance_crypto.py@@ -35,6 +35,10 @@ class TestToYfinanceSymbolCrypto:def test_us_suffix_stripped(self) -> None:assert _to_yfinance_symbol("AAPL.US") == "AAPL"+ def test_canadian_equities_keep_yahoo_suffix(self) -> None:+ assert _to_yfinance_symbol("TD.TO") == "TD.TO"+ assert _to_yfinance_symbol("PNG.V") == "PNG.V"+def test_whitespace_stripped(self) -> None:assert _to_yfinance_symbol(" BTC-USDT ") == "BTC-USD"@@ -54,6 +58,9 @@ class TestDataLoaderCryptoMarket:def test_hk_equity_still_supported(self) -> None:assert "hk_equity" in DataLoader.markets+ def test_canadian_equity_supported(self) -> None:+ assert "ca_equity" in DataLoader.markets+def test_does_not_require_auth(self) -> None:assert DataLoader.requires_auth is Falsediff --git a/agent/tests/test_yfinance_crypto_routing.py b/agent/tests/test_yfinance_crypto_routing.pyindex 503196418..cf5b66a62 100644--- a/agent/tests/test_yfinance_crypto_routing.py+++ b/agent/tests/test_yfinance_crypto_routing.py@@ -27,6 +27,11 @@ class TestYfinanceCryptoRouting:engine = _create_market_engine("yfinance", {"initial_cash": 100_000}, ["AAPL.US"])assert isinstance(engine, GlobalEquityEngine)+ def test_canadian_equity_routes_to_canadian_global_rules(self) -> None:+ engine = _create_market_engine("yfinance", {"initial_cash": 100_000}, ["TD.TO"])+ assert isinstance(engine, GlobalEquityEngine)+ assert engine.market == "ca"+def test_fee_keys_reach_the_engine(self) -> None:engine = _create_market_engine("yfinance",