"Vibe-Trading: Your Personal Trading Agent"
Python ai-agentalgorithmic-tradingbacktestingfintechllmmcpmulti-agentpythonquantitative-financetrading
feat(backtest): serve Vietnam HOSE equities from the Yahoo loaders
Pham Van Ngoanf79b56195396
diff --git a/agent/backtest/loaders/registry.py b/agent/backtest/loaders/registry.pyindex 1bdcf284e..90a8cd654 100644--- a/agent/backtest/loaders/registry.py+++ b/agent/backtest/loaders/registry.py@@ -147,6 +147,9 @@ FALLBACK_CHAINS: dict[str, list[str]] = {"kr_equity": ["pykrx", "yahoo", "yfinance", "local"],# TSX (.TO) / TSX Venture (.V): direct Yahoo first, SDK fallback second."ca_equity": ["yahoo", "yfinance", "local"],+ # Vietnam (.VN): Yahoo lists HOSE only — HNX and UPCOM are unsupported,+ # so those two are reachable only through the user's local files.+ "vietnam_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.pyindex 5a3bc3586..bfbc96d20 100644--- a/agent/backtest/loaders/yahoo_client.py+++ b/agent/backtest/loaders/yahoo_client.py@@ -18,6 +18,8 @@ Symbol convention (Vibe-Trading -> Yahoo):``.NS``/``.BO`` suffix verbatim)* Canada ``TD.TO`` / ``PNG.V`` -> unchanged (Yahoo carries the``.TO``/``.V`` suffix verbatim)+ * Vietnam ``VIC.VN`` -> unchanged (Yahoo carries the ``.VN`` suffix+ verbatim; HOSE listings only)* Anything else is passed through unchanged (e.g. ``BTC-USD``, ``^GSPC``).This module is provider-specific glue only; it returns plain Pythondiff --git a/agent/backtest/loaders/yahoo_loader.py b/agent/backtest/loaders/yahoo_loader.pyindex a9c54ac17..eeae1b0ab 100644--- a/agent/backtest/loaders/yahoo_loader.py+++ b/agent/backtest/loaders/yahoo_loader.py@@ -4,8 +4,11 @@ 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 Canadian equities (``TD.TO`` / ``PNG.V``); the client maps-each project symbol to Yahoo's ticker form.+(``00700.HK``), Canadian equities (``TD.TO`` / ``PNG.V``), and Vietnamese+equities (``VIC.VN``); the client maps each project symbol to Yahoo's ticker+form.++Yahoo officially lists HOSE under ``.VN``; HNX and UPCOM are not supported.The chart endpoint returns each bar's ``trade_date`` as an epoch-secondtimestamp; this loader converts those to a tz-naive ``DatetimeIndex`` and clips@@ -44,14 +47,14 @@ _INTERVAL_MAP = {def _is_supported(code: str) -> bool:"""Return whether *code* is a symbol this loader handles.- Covers US/HK/India/Korea/Canada equities plus Yahoo's own futures+ Covers US/HK/India/Korea/Canada/Vietnam equities plus Yahoo's own futures(``GC=F``) and forex (``EURUSD=X``) suffix conventions, which the publicchart 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", ".TO", ".V", "=F", "=X")+ (".US", ".HK", ".NS", ".BO", ".KS", ".KQ", ".TO", ".V", ".VN", "=F", "=X"))@@ -177,6 +180,7 @@ class DataLoader:name = "yahoo"markets = {"us_equity", "hk_equity", "india_equity", "kr_equity", "ca_equity",+ "vietnam_equity",}# Yahoo chart volume is single shares for US/HK equities# (HKUDS/Vibe-Trading#1062; HK verified 2026-08-11, 00700.HK ratio 1.00@@ -204,8 +208,8 @@ class DataLoader:"""Fetch OHLCV history keyed by the original project symbols.Args:- codes: Project symbols such as ``AAPL.US``, ``00700.HK``, and- ``TD.TO``.+ codes: Project symbols such as ``AAPL.US``, ``00700.HK``,+ ``TD.TO``, and ``VIC.VN``.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 7dd0dcb59..7fe97b42a 100644--- a/agent/backtest/loaders/yfinance_loader.py+++ b/agent/backtest/loaders/yfinance_loader.py@@ -71,8 +71,8 @@ def _to_yfinance_symbol(code: str) -> str:if upper.endswith("-USDC"):return upper[:-5] + "-USD"# 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.+ # 247540.KQ), Canada TSX/TSXV (TD.TO, PNG.V), and Vietnam HOSE (VIC.VN):+ # yfinance carries these suffixes as-is.return upper@@ -232,7 +232,8 @@ class DataLoader:name = "yfinance"markets = {- "us_equity", "hk_equity", "india_equity", "kr_equity", "ca_equity", "crypto",+ "us_equity", "hk_equity", "india_equity", "kr_equity", "ca_equity",+ "vietnam_equity", "crypto",}# yfinance volume is single shares for US/HK equities# (HKUDS/Vibe-Trading#1062; HK verified 2026-08-11, 00700.HK ratio 1.00diff --git a/agent/backtest/runner.py b/agent/backtest/runner.pyindex d3687bf99..f0e8b965c 100644--- a/agent/backtest/runner.py+++ b/agent/backtest/runner.py@@ -800,6 +800,7 @@ _MARKET_TO_SOURCE = {"india_equity": "yahoo","kr_equity": "pykrx","ca_equity": "yahoo",+ "vietnam_equity": "yahoo","crypto": "okx","futures": "tushare","fund": "tushare",diff --git a/agent/tests/test_registry.py b/agent/tests/test_registry.pyindex 6ae7ca855..a6f119bb5 100644--- a/agent/tests/test_registry.py+++ b/agent/tests/test_registry.py@@ -134,13 +134,17 @@ 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",+ "ca_equity", "vietnam_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_vietnam_chain_uses_only_compatible_sources(self) -> None:+ assert FALLBACK_CHAINS["vietnam_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_vietnam_equity.py b/agent/tests/test_vietnam_equity.pynew file mode 100644index 000000000..22684154e--- /dev/null+++ b/agent/tests/test_vietnam_equity.py@@ -0,0 +1,107 @@+"""Tests for Vietnam (HOSE) equity data routing via Yahoo.++All network access is mocked at the loader's ``yahoo_client.get_chart`` import+site; nothing here reaches Yahoo.+"""++from __future__ import annotations++from unittest.mock import patch++import pandas as pd++from backtest.engines._market_hooks import _detect_market+from backtest.loaders.registry import FALLBACK_CHAINS+from backtest.loaders.yahoo_client import map_symbol+from backtest.loaders.yahoo_loader import DataLoader, _is_supported+from backtest.loaders.yfinance_loader import _to_yfinance_symbol+++class TestSymbolGating:+ """``.VN`` is accepted alongside the other equity suffixes."""++ def test_vn_suffix_supported(self) -> None:+ assert _is_supported("VIC.VN") is True+ assert _is_supported("vic.vn") is True++ def test_vn_does_not_collide_with_tsx_venture(self) -> None:+ # ``.V`` (TSXV) and ``.VN`` (HOSE) are distinct suffixes; neither may+ # swallow the other.+ assert _is_supported("PNG.V") is True+ assert _detect_market("PNG.V") == "ca_equity"+ assert _detect_market("VIC.VN") != "ca_equity"+++class TestSymbolMapping:+ """Both Yahoo paths carry ``.VN`` verbatim — no conversion."""++ def test_yahoo_client_passes_vn_through(self) -> None:+ assert map_symbol("VIC.VN") == "VIC.VN"++ def test_yfinance_passes_vn_through(self) -> None:+ assert _to_yfinance_symbol("VIC.VN") == "VIC.VN"+++class TestFallbackChain:+ def test_vietnam_chain(self) -> None:+ assert FALLBACK_CHAINS["vietnam_equity"] == ["yahoo", "yfinance", "local"]++ def test_yahoo_declares_vietnam_market(self) -> None:+ assert "vietnam_equity" in DataLoader.markets+++class TestSymbolsAreNotAutoRouted:+ """``.VN`` deliberately does not auto-detect yet.++ Classifying ``.VN`` as ``vietnam_equity`` without an execution engine to+ match would route a HOSE backtest through engine selection that has no+ Vietnam branch. Detection lands with the engine, not with the data.+ """++ def test_vn_is_not_yet_classified_as_vietnam_equity(self) -> None:+ assert _detect_market("VIC.VN") != "vietnam_equity"+++class TestFetch:+ """The loader returns a normalized frame for a HOSE symbol."""++ def _chart_rows(self) -> list[dict]:+ # 2024-01-02 .. 2024-01-04 UTC midnights, VND prices.+ return [+ {"trade_date": 1704153600, "open": 42.0, "high": 43.0,+ "low": 41.5, "close": 42.5, "volume": 1_000_000},+ {"trade_date": 1704240000, "open": 42.5, "high": 44.0,+ "low": 42.0, "close": 43.8, "volume": 1_200_000},+ {"trade_date": 1704326400, "open": 43.8, "high": 44.5,+ "low": 43.0, "close": 44.2, "volume": 900_000},+ ]++ def test_fetch_returns_ohlcv_frame(self) -> None:+ with patch(+ "backtest.loaders.yahoo_loader.yahoo_client.get_chart",+ return_value=self._chart_rows(),+ ) as chart:+ result = DataLoader().fetch(+ ["VIC.VN"], "2024-01-01", "2024-01-31", interval="1D"+ )++ assert "VIC.VN" in result+ frame = result["VIC.VN"]+ assert list(frame.columns) == ["open", "high", "low", "close", "volume"]+ assert len(frame) == 3+ assert isinstance(frame.index, pd.DatetimeIndex)+ assert frame["close"].iloc[-1] == 44.2+ # The symbol reaches the client unchanged.+ assert chart.call_args.args[0] == "VIC.VN"++ def test_unlisted_symbol_is_omitted_not_raised(self) -> None:+ # HNX/UPCOM are unsupported on Yahoo: no rows, no exception.+ with patch(+ "backtest.loaders.yahoo_loader.yahoo_client.get_chart",+ return_value=[],+ ):+ result = DataLoader().fetch(+ ["PVS.VN"], "2024-01-01", "2024-01-31", interval="1D"+ )++ assert result == {} or result.get("PVS.VN", pd.DataFrame()).emptydiff --git a/agent/tests/test_yahoo_loader.py b/agent/tests/test_yahoo_loader.pyindex 991a6edc1..862ecc932 100644--- a/agent/tests/test_yahoo_loader.py+++ b/agent/tests/test_yahoo_loader.py@@ -314,6 +314,7 @@ class TestLoaderMetadata:assert loader.name == "yahoo"assert loader.markets == {"us_equity", "hk_equity", "india_equity", "kr_equity", "ca_equity",+ "vietnam_equity",}assert loader.requires_auth is Falseassert loader.is_available() is True