Skip to content

"Vibe-Trading: Your Personal Trading Agent"

feat(backtest): add Canada/TSX equity support (.TO/.V routing to GlobalEquityEngine)

Will Liao2d046110c103
diff --git a/agent/backtest/correlation.py b/agent/backtest/correlation.py
index 06a763d2d..81baa04c1 100644
--- a/agent/backtest/correlation.py
+++ b/agent/backtest/correlation.py
@@ -41,6 +41,8 @@ def infer_market(code: str) -> str:
return "a_share"
if code_upper.endswith((".KS", ".KQ")):
return "kr_equity"
+ if code_upper.endswith((".TO", ".V")):
+ return "ca_equity"
if code_upper.endswith(".US"):
return "us_equity"
if code_upper.isdigit():
diff --git a/agent/backtest/engines/_market_hooks.py b/agent/backtest/engines/_market_hooks.py
index 6fcf12c8b..03ce263e5 100644
--- a/agent/backtest/engines/_market_hooks.py
+++ b/agent/backtest/engines/_market_hooks.py
@@ -32,6 +32,9 @@ _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.
+ (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"),
# yfinance's native crypto spelling (BTC-USD, ETH-USD). Distinct from
@@ -67,6 +70,7 @@ _MARKET_CURRENCY = {
"hk_equity": "HKD",
"india_equity": "INR",
"kr_equity": "KRW",
+ "ca_equity": "CAD",
# Every crypto pattern in _MARKET_PATTERNS is USDT-quoted, and USDT is
# carried at its USD peg. This is the one approximation in the table: a
# depeg would make a crypto+US book wrong by the depeg amount, which is
@@ -186,8 +190,11 @@ def _detect_submarket(codes: List[str]) -> str:
``"hk"`` if any code ends with ``.HK``, else ``"us"``.
"""
for code in codes:
- if code.upper().endswith(".HK"):
+ upper = code.upper()
+ if upper.endswith(".HK"):
return "hk"
+ if upper.endswith((".TO", ".V")):
+ return "ca"
return "us"
# ── Crypto: OKX tiered maintenance margin table (simplified) ──
diff --git a/agent/backtest/engines/composite.py b/agent/backtest/engines/composite.py
index c4b37b87b..5cfe50502 100644
--- a/agent/backtest/engines/composite.py
+++ b/agent/backtest/engines/composite.py
@@ -44,6 +44,9 @@ def _build_rule_engines(config: dict, codes: List[str]) -> Dict[str, BaseEngine]
elif market == "kr_equity":
from backtest.engines.korea_equity import KoreaEquityEngine
engines["kr_equity"] = KoreaEquityEngine(config)
+ elif market == "ca_equity":
+ from backtest.engines.global_equity import GlobalEquityEngine
+ engines["ca_equity"] = GlobalEquityEngine(config, market="ca")
elif market == "crypto":
from backtest.engines.crypto import CryptoEngine
engines["crypto"] = CryptoEngine(config)
diff --git a/agent/backtest/engines/global_equity.py b/agent/backtest/engines/global_equity.py
index c6259c673..30300b157 100644
--- a/agent/backtest/engines/global_equity.py
+++ b/agent/backtest/engines/global_equity.py
@@ -14,6 +14,8 @@ Market rules:
India (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
diff --git a/agent/backtest/loaders/eastmoney_client.py b/agent/backtest/loaders/eastmoney_client.py
index b84cf49f4..83f932868 100644
--- a/agent/backtest/loaders/eastmoney_client.py
+++ b/agent/backtest/loaders/eastmoney_client.py
@@ -25,7 +25,7 @@ import logging
import re
from typing import Any
-from backtest.loaders._http import resolve_min_interval, throttled_get_json
+from backtest.loaders._http import resolve_min_interval, throttled_get
logger = logging.getLogger(__name__)
@@ -79,27 +79,36 @@ 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.
+ """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.
Args:
url: Fully-qualified Eastmoney endpoint URL.
params: Query parameters for the request.
Returns:
- The decoded JSON payload (typically a ``dict``).
+ The decoded payload (typically a ``dict``), or ``None`` when the body
+ is neither valid JSON nor a recognizable JSONP envelope.
Raises:
requests.RequestException: Network failure, propagated for the caller's
retry policy.
requests.HTTPError: Non-2xx response status.
- ValueError: Body is not valid JSON.
"""
- return throttled_get_json(
+ response = throttled_get(
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.py
index 7d1968533..ecbfc53e2 100644
--- a/agent/backtest/loaders/registry.py
+++ b/agent/backtest/loaders/registry.py
@@ -142,6 +142,9 @@ 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.
+ "ca_equity": ["yahoo", "yfinance", "local"],
# OKX first (native), then dedicated Binance, then generic CCXT / Yahoo.
"crypto": ["okx", "binance", "ccxt", "yfinance", "local"],
"futures": ["tushare", "akshare", "local"],
diff --git a/agent/backtest/loaders/yahoo_client.py b/agent/backtest/loaders/yahoo_client.py
index 17257d33e..3e4565cd4 100644
--- a/agent/backtest/loaders/yahoo_client.py
+++ b/agent/backtest/loaders/yahoo_client.py
@@ -16,6 +16,9 @@ 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)
* Anything else is passed through unchanged (e.g. ``BTC-USD``, ``^GSPC``).
This module is provider-specific glue only; it returns plain Python
diff --git a/agent/backtest/loaders/yahoo_loader.py b/agent/backtest/loaders/yahoo_loader.py
index 95bd27376..93e58fabb 100644
--- a/agent/backtest/loaders/yahoo_loader.py
+++ b/agent/backtest/loaders/yahoo_loader.py
@@ -3,8 +3,9 @@
Wraps the shared :mod:`backtest.loaders.yahoo_client` (the public v8 chart
endpoint) rather than the ``yfinance`` package, so it pulls in no new
dependency and shares the process-wide throttle/session that keeps Yahoo from
-IP-rate-limiting us. Covers US equities (``AAPL.US``) and HK equities
-(``00700.HK``); the client maps each project symbol to Yahoo's ticker form.
+IP-rate-limiting us. Covers US equities (``AAPL.US``), HK equities
+(``00700.HK``) and Canada equities (``TD.TO``, ``SHOP.V``); the client maps
+each project symbol to Yahoo's ticker form.
The chart endpoint returns each bar's ``trade_date`` as an epoch-second
timestamp; this loader converts those to a tz-naive ``DatetimeIndex`` and clips
@@ -43,13 +44,13 @@ _INTERVAL_MAP = {
def _is_supported(code: str) -> bool:
"""Return whether *code* is a symbol this loader handles.
- Covers US/HK/India/Korea equities plus Yahoo's own futures (``GC=F``) and
- forex (``EURUSD=X``) suffix conventions, which the public chart endpoint
- serves verbatim (the code is used as-is in the request URL, no
- conversion) (#718).
+ Covers US/HK/India/Korea/Canada equities plus Yahoo's own futures
+ (``GC=F``) and forex (``EURUSD=X``) suffix conventions, which the public
+ chart endpoint serves verbatim (the code is used as-is in the request URL,
+ no conversion) (#718).
"""
upper = code.strip().upper()
- return upper.endswith((".US", ".HK", ".NS", ".BO", ".KS", ".KQ", "=F", "=X"))
+ return upper.endswith((".US", ".HK", ".NS", ".BO", ".KS", ".KQ", ".TO", ".V", "=F", "=X"))
def _to_yahoo_interval(interval: str) -> str:
@@ -172,7 +173,7 @@ class DataLoader:
"""Yahoo Finance US/HK equity OHLCV loader (free, direct HTTP, no auth)."""
name = "yahoo"
- markets = {"us_equity", "hk_equity", "india_equity", "kr_equity"}
+ markets = {"us_equity", "hk_equity", "india_equity", "kr_equity", "ca_equity"}
requires_auth = False
def is_available(self) -> bool:
diff --git a/agent/backtest/loaders/yfinance_loader.py b/agent/backtest/loaders/yfinance_loader.py
index 4c924e613..e8e6dc8ae 100644
--- a/agent/backtest/loaders/yfinance_loader.py
+++ b/agent/backtest/loaders/yfinance_loader.py
@@ -224,7 +224,7 @@ class DataLoader:
"""Fetch HK/US equity bars from Yahoo Finance via yfinance."""
name = "yfinance"
- markets = {"us_equity", "hk_equity", "india_equity", "kr_equity", "crypto"}
+ markets = {"us_equity", "hk_equity", "india_equity", "kr_equity", "ca_equity", "crypto"}
requires_auth = False
def is_available(self) -> bool:
diff --git a/agent/backtest/runner.py b/agent/backtest/runner.py
index a24894803..725077dae 100644
--- a/agent/backtest/runner.py
+++ b/agent/backtest/runner.py
@@ -798,6 +798,7 @@ _MARKET_TO_SOURCE = {
"hk_equity": "yfinance",
"india_equity": "yahoo",
"kr_equity": "pykrx",
+ "ca_equity": "yahoo",
"crypto": "okx",
"futures": "tushare",
"fund": "tushare",
@@ -1292,6 +1293,12 @@ def _create_market_engine(source: str, config: dict, codes: List[str]):
from backtest.engines.korea_equity import KoreaEquityEngine
return 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 CryptoEngine
diff --git a/agent/mcp_server.py b/agent/mcp_server.py
index 13aed5fcc..7ae9daf2d 100644
--- a/agent/mcp_server.py
+++ b/agent/mcp_server.py
@@ -1410,7 +1410,7 @@ def get_market_data(
"""Fetch OHLCV market data for stocks, crypto, or mixed symbols.
Supported sources:
- - "yfinance": HK/US equities (free, e.g. AAPL.US, 700.HK)
+ - "yfinance": HK/US/Canada equities (free, e.g. AAPL.US, 700.HK, TD.TO, SHOP.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)
diff --git a/agent/src/agent/grounding.py b/agent/src/agent/grounding.py
index cf22d42da..1e6e378df 100644
--- a/agent/src/agent/grounding.py
+++ b/agent/src/agent/grounding.py
@@ -133,7 +133,7 @@ _GENERIC_PRICE_FIELD_ALIASES = {
_CANONICAL_SYMBOL_RE = re.compile(
r"(?<![A-Za-z0-9_])(?:"
r"\d{3,6}\.(?:SH|SZ|BJ|SS|HK|KS|KQ)|"
- r"[A-Z][A-Z0-9&.-]{0,19}\.(?:US|NS|BO|FX)|"
+ r"[A-Z][A-Z0-9&.-]{0,19}\.(?:US|NS|BO|FX|TO|V)|"
r"[A-Z0-9]{2,15}(?:-|/)(?:USDT|USDC|USD|BTC|ETH)|"
r"[A-Z0-9]{2,15}=[FX]"
r")(?![A-Za-z0-9_])",
@@ -432,6 +432,8 @@ def _infer_venue(symbol: str) -> str | None:
".NS": "nse",
".BO": "bse",
".FX": "forex",
+ ".TO": "toronto",
+ ".V": "tsxv",
}
for suffix, venue in suffixes.items():
if upper.endswith(suffix):
@@ -457,6 +459,8 @@ def _infer_currency(symbol: str) -> str | None:
".KQ": "KRW",
".NS": "INR",
".BO": "INR",
+ ".TO": "CAD",
+ ".V": "CAD",
}
for suffix, currency in suffixes.items():
if upper.endswith(suffix):
diff --git a/agent/src/market_data.py b/agent/src/market_data.py
index 528f76d9e..6f84d49f0 100644
--- a/agent/src/market_data.py
+++ b/agent/src/market_data.py
@@ -26,6 +26,9 @@ _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.
+ (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,
# such symbols fell through to the ``tushare`` default and were routed to
diff --git a/agent/src/skills/data-routing/SKILL.md b/agent/src/skills/data-routing/SKILL.md
index ca9c84140..452e9fed4 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, ETFs | No | Needs Yahoo access | yfinance |
+| yfinance | US stocks, HK stocks, Canada (TSX/TSX-V) 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 equities | No (IP-throttled) | Needs Yahoo access | data-routing |
+| yahoo | US, HK, Canada (TSX/TSX-V) 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 |
@@ -47,7 +47,7 @@ is required only where listed (no key listed = free / no auth).
| Data need | Tool | Market | Env key |
|-----------|------|--------|---------|
-| OHLCV price bars | `get_market_data` | A-share / US / HK / crypto / futures / forex | per-source (see Source Overview) |
+| OHLCV price bars | `get_market_data` | A-share / US / HK / Canada / crypto / futures / forex | per-source (see Source Overview) |
| Fund flow (资金流向) | `get_fund_flow` | A-share, HK, US | — |
| Dragon-tiger (龙虎榜) | `get_dragon_tiger` | A-share | — |
| Northbound flow (北向资金) | `get_northbound_flow` | A-share | — |
diff --git a/agent/src/swarm/grounding.py b/agent/src/swarm/grounding.py
index 67be2b233..10d3c5033 100644
--- a/agent/src/swarm/grounding.py
+++ b/agent/src/swarm/grounding.py
@@ -78,6 +78,8 @@ _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-Z]{2,6}-USDT\b"),
)
diff --git a/agent/src/tools/market_data_tool.py b/agent/src/tools/market_data_tool.py
index 3c24bdcc2..72fd7abd5 100644
--- a/agent/src/tools/market_data_tool.py
+++ b/agent/src/tools/market_data_tool.py
@@ -61,7 +61,7 @@ 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 equities), okx/ccxt "
+ "Free, no key: yfinance/yahoo (US/HK/Canada equities; Canada via .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 "
diff --git a/agent/src/tools/symbol_search_tool.py b/agent/src/tools/symbol_search_tool.py
index ea80d725c..8055009e9 100644
--- a/agent/src/tools/symbol_search_tool.py
+++ b/agent/src/tools/symbol_search_tool.py
@@ -330,6 +330,9 @@ def _from_yahoo_symbol(raw_symbol: str, quote: Dict[str, Any]) -> tuple[str, str
if 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"
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.py
index 01c39d60d..3a9a164c1 100644
--- a/agent/tests/test_agent_grounding.py
+++ b/agent/tests/test_agent_grounding.py
@@ -432,6 +432,92 @@ 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_listed_identity_blocks_private_company_workflow(
tmp_path: Path,
) -> None:
diff --git a/agent/tests/test_dragon_tiger_tool.py b/agent/tests/test_dragon_tiger_tool.py
index c5c836247..0d657ee64 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.throttled_get_json`) is mocked so the
-real client + tool parsing runs offline.
+(:func:`backtest.loaders.eastmoney_client.get_json` via ``throttled_get``) is
+mocked so the real client + tool parsing runs offline.
"""
from __future__ import annotations
@@ -17,6 +17,18 @@ from backtest.loaders import eastmoney_client
from 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 {
@@ -94,7 +106,9 @@ class TestExecuteSuccess:
def test_full_market_list_no_code(self) -> None:
tool = DragonTigerTool()
with patch.object(
- eastmoney_client, "throttled_get_json", return_value=_appearance_payload()
+ eastmoney_client,
+ "throttled_get",
+ return_value=_FakeResponse(json.dumps(_appearance_payload())),
) as http:
out = json.loads(tool.execute(date="2024-01-02"))
@@ -116,8 +130,9 @@ 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_json", side_effect=payloads
+ eastmoney_client, "throttled_get", side_effect=responses
) as http:
out = json.loads(tool.execute(date="2024-01-02", code="600519.SH"))
@@ -144,7 +159,7 @@ class TestExecuteError:
tool = DragonTigerTool()
with patch.object(
eastmoney_client,
- "throttled_get_json",
+ "throttled_get",
side_effect=RuntimeError("eastmoney banned"),
), patch(
"src.tools.dragon_tiger_tool.tushare_fallbacks.fetch_dragon_tiger",
@@ -164,7 +179,7 @@ class TestExecuteError:
tool = DragonTigerTool()
with patch.object(
eastmoney_client,
- "throttled_get_json",
+ "throttled_get",
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.py
index 1d090cf7b..e8218d907 100644
--- a/agent/tests/test_eastmoney_client.py
+++ b/agent/tests/test_eastmoney_client.py
@@ -1,9 +1,11 @@
"""Tests for eastmoney_client: secid resolution, kline parsing, error paths.
-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.
+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.
"""
+import json
from unittest.mock import patch
import pytest
@@ -11,6 +13,18 @@ import pytest
from 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."""
@@ -56,7 +70,9 @@ class TestResolveSecidUS:
]
}
}
- with patch.object(ec, "throttled_get_json", return_value=payload) as mock_get:
+ with patch.object(
+ ec, "throttled_get", return_value=_FakeResponse(json.dumps(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"
@@ -64,7 +80,7 @@ class TestResolveSecidUS:
def test_handles_jsonp_wrapped_search_body(self):
body = 'cb({"QuotationCodeTable":{"Data":[{"QuoteID":"106.BRK"}]}})'
- with patch.object(ec, "throttled_get_json", return_value=body):
+ with patch.object(ec, "throttled_get", return_value=_FakeResponse(body)):
assert ec.resolve_secid("BRK.US") == "106.BRK"
def test_plain_json_body_with_parens_in_values(self):
@@ -77,18 +93,18 @@ class TestResolveSecidUS:
'{"QuotationCodeTable":{"Data":'
'[{"QuoteID":"105.AAPL","Name":"Apple Inc. (AAPL) [NASDAQ]"}]}}'
)
- with patch.object(ec, "throttled_get_json", return_value=body):
+ with patch.object(ec, "throttled_get", return_value=_FakeResponse(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_json", return_value=payload):
+ with patch.object(
+ ec, "throttled_get", return_value=_FakeResponse(json.dumps(payload))
+ ):
assert ec.resolve_secid("NOPE.US") is None
def test_search_failure_returns_none_without_raising(self):
- with patch.object(
- ec, "throttled_get_json", side_effect=RuntimeError("banned")
- ):
+ with patch.object(ec, "throttled_get", side_effect=RuntimeError("banned")):
assert ec.resolve_secid("AAPL.US") is None
@@ -105,7 +121,9 @@ class TestFetchKline:
],
}
}
- with patch.object(ec, "throttled_get_json", return_value=payload) as mock_get:
+ with patch.object(
+ ec, "throttled_get", return_value=_FakeResponse(json.dumps(payload))
+ ) as mock_get:
rows = ec.fetch_kline("1.600519", klt=ec.KLT_BY_INTERVAL["1D"])
assert rows == [
@@ -134,7 +152,9 @@ class TestFetchKline:
assert kwargs["params"]["klt"] == "101"
def test_empty_data_returns_empty_list(self):
- with patch.object(ec, "throttled_get_json", return_value={"data": None}):
+ with patch.object(
+ ec, "throttled_get", return_value=_FakeResponse(json.dumps({"data": None}))
+ ):
assert ec.fetch_kline("1.600519", klt=101) == []
def test_malformed_row_is_skipped_not_fatal(self):
@@ -146,15 +166,15 @@ class TestFetchKline:
]
}
}
- with patch.object(ec, "throttled_get_json", return_value=payload):
+ with patch.object(
+ ec, "throttled_get", return_value=_FakeResponse(json.dumps(payload))
+ ):
rows = ec.fetch_kline("1.600519", klt=101)
assert len(rows) == 1
assert rows[0]["trade_date"] == "2024-01-03"
def test_http_error_propagates(self):
- with patch.object(
- ec, "throttled_get_json", side_effect=RuntimeError("HTTP 429")
- ):
+ with patch.object(ec, "throttled_get", 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.py
index 5c61efcc6..255b05a0f 100644
--- a/agent/tests/test_eastmoney_loader.py
+++ b/agent/tests/test_eastmoney_loader.py
@@ -2,12 +2,13 @@
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_json``) so the real client parsing runs while no
+HTTP boundary (``throttled_get``) so the real client parsing runs while no
request leaves the process.
"""
from __future__ import annotations
+import json
from typing import List
from unittest.mock import patch
@@ -18,6 +19,18 @@ from backtest.loaders import eastmoney_client
from 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 [
@@ -176,7 +189,9 @@ class TestFetchEndToEndHttpMocked:
}
loader = DataLoader()
with patch.object(
- eastmoney_client, "throttled_get_json", return_value=payload
+ eastmoney_client,
+ "throttled_get",
+ return_value=_FakeResponse(json.dumps(payload)),
) as http:
out = loader.fetch(["600519.SH"], "2024-01-01", "2024-01-31")
diff --git a/agent/tests/test_lockup_expiry_tool.py b/agent/tests/test_lockup_expiry_tool.py
index 992b1357e..ef61fa020 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 shared
client (:mod:`backtest.loaders.eastmoney_client`), and the end-to-end path mocks
-the frozen HTTP boundary (``throttled_get_json``) so the real client routing and
+the frozen HTTP boundary (``throttled_get``) so the real client routing and
this tool's parsing both run while nothing hits the network.
"""
@@ -17,6 +17,18 @@ from src.tools import lockup_expiry_tool
from 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)}}
@@ -153,7 +165,9 @@ class TestEndToEndHttpMocked:
def test_single_code_through_real_client(self) -> None:
rows = [_row("600519", "2024-06-01")]
with patch.object(
- eastmoney_client, "throttled_get_json", return_value=_payload(rows)
+ eastmoney_client,
+ "throttled_get",
+ return_value=_FakeResponse(json.dumps(_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.py
index 3041051fe..39b283e77 100644
--- a/agent/tests/test_market_data.py
+++ b/agent/tests/test_market_data.py
@@ -44,6 +44,10 @@ from src.market_data import (
("M&M.NS", "yahoo"), # ampersand in ticker
("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"),
("BTC-USDT", "okx"),
("ETH/USDT", "ccxt"),
("EUR/USD", "mt5"), # forex pair → mt5 chain head (registry fallback)
@@ -71,6 +75,8 @@ def test_yahoo_loader_accepts_futures_and_forex_suffixes() -> None:
assert _is_supported("GC=F") is True
assert _is_supported("EURUSD=X") is True
assert _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("600519.SH") is False # A-share still not yahoo
diff --git a/agent/tests/test_market_detection.py b/agent/tests/test_market_detection.py
index 1c22341b7..765653d3d 100644
--- a/agent/tests/test_market_detection.py
+++ b/agent/tests/test_market_detection.py
@@ -68,6 +68,12 @@ class TestDetectMarket:
# Korea equity (KRX)
("005930.KS", "kr_equity"), # KOSPI
("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"),
# Crypto
("BTC-USDT", "crypto"),
("ETH-USDT", "crypto"),
@@ -172,6 +178,8 @@ class TestDetectSource:
("500325.BO", "yahoo"),
("005930.KS", "pykrx"),
("247540.KQ", "pykrx"),
+ ("TD.TO", "yahoo"),
+ ("SHOP.V", "yahoo"),
("BTC-USDT", "okx"),
("IF2406.CFFEX", "tushare"),
("EUR/USD", "akshare"),
diff --git a/agent/tests/test_registry.py b/agent/tests/test_registry.py
index 2802471bf..08b6013e1 100644
--- a/agent/tests/test_registry.py
+++ b/agent/tests/test_registry.py
@@ -132,7 +132,7 @@ class TestProtocol:
class TestFallbackChains:
def test_all_expected_markets_present(self) -> None:
- expected = {"a_share", "us_equity", "hk_equity", "india_equity", "kr_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_chains_are_non_empty(self) -> None:
diff --git a/agent/tests/test_stock_news_tool.py b/agent/tests/test_stock_news_tool.py
index 1e8a176b9..a92cebe6c 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.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.
+(: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.
"""
from __future__ import annotations
@@ -69,6 +69,18 @@ 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"
@@ -124,7 +136,9 @@ class TestExecuteSuccess:
def test_a_share_stock_news(self) -> None:
tool = StockNewsTool()
with patch.object(
- eastmoney_client, "throttled_get_json", return_value=_em_news_payload()
+ eastmoney_client,
+ "throttled_get",
+ return_value=_FakeResponse(json.dumps(_em_news_payload())),
) as http:
out = json.loads(tool.execute(code="600519.SH", scope="stock", limit=10))
@@ -145,7 +159,9 @@ class TestExecuteSuccess:
def test_global_scope_needs_no_code(self) -> None:
tool = StockNewsTool()
with patch.object(
- eastmoney_client, "throttled_get_json", return_value=_em_news_payload()
+ eastmoney_client,
+ "throttled_get",
+ return_value=_FakeResponse(json.dumps(_em_news_payload())),
):
out = json.loads(tool.execute(scope="global"))
@@ -225,7 +241,7 @@ class TestExecuteError:
tool = StockNewsTool()
with patch.object(
eastmoney_client,
- "throttled_get_json",
+ "throttled_get",
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.py
index b5e4a1d3f..e789a6fed 100644
--- a/agent/tests/test_swarm_grounding.py
+++ b/agent/tests/test_swarm_grounding.py
@@ -112,6 +112,13 @@ 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.py
index 92bf9a3fc..8682bf5f4 100644
--- a/agent/tests/test_symbol_search_tool.py
+++ b/agent/tests/test_symbol_search_tool.py
@@ -76,6 +76,32 @@ def _yahoo_quotes() -> list:
]
+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."""
diff --git a/agent/tests/test_yahoo_loader.py b/agent/tests/test_yahoo_loader.py
index fc4949acf..e826d4238 100644
--- a/agent/tests/test_yahoo_loader.py
+++ b/agent/tests/test_yahoo_loader.py
@@ -308,7 +308,7 @@ class TestLoaderMetadata:
loader = DataLoader()
assert loader.name == "yahoo"
assert loader.markets == {
- "us_equity", "hk_equity", "india_equity", "kr_equity",
+ "us_equity", "hk_equity", "india_equity", "kr_equity", "ca_equity",
}
assert loader.requires_auth is False
assert loader.is_available() is True