Skip to content

"Vibe-Trading: Your Personal Trading Agent"

fix(backtest): route bare US tickers to us_equity in market detection (#994)

shadowinlifea4ef999989ea
diff --git a/agent/backtest/engines/_market_hooks.py b/agent/backtest/engines/_market_hooks.py
index 62598bca6..6fcf12c8b 100644
--- a/agent/backtest/engines/_market_hooks.py
+++ b/agent/backtest/engines/_market_hooks.py
@@ -48,6 +48,12 @@ _MARKET_PATTERNS = [
# Forex pairs: XXX/YYY or XXXXXX.FX
(re.compile(r"^[A-Z]{3}/[A-Z]{3}$"), "forex"),
(re.compile(r"^[A-Z]{6}\.FX$"), "forex"),
+ # Bare US tickers (AAPL, MSFT, SPY, T, ...). Must stay LAST so every
+ # suffixed equity / futures / crypto / forex form above wins first.
+ # ``{1,5}`` covers every standard US ticker length while 6-char bare
+ # forex (EURUSD) and longer crypto codes (BTCUSDT) fall through to the
+ # a_share default.
+ (re.compile(r"^[A-Z]{1,5}$", re.I), "us_equity"),
]
_CHINA_EXCHANGES = {"CFFEX", "SHFE", "DCE", "ZCE", "INE", "GFEX"}
@@ -129,8 +135,9 @@ def _detect_market(code: str) -> str:
code: Ticker / symbol string.
Returns:
- Market type (a_share/us_equity/hk_equity/crypto/futures/forex);
- unknown defaults to ``a_share``.
+ Market type (a_share/us_equity/hk_equity/crypto/futures/forex).
+ Bare 1-5 letter alphabetic tickers resolve to ``us_equity``;
+ any other unknown format defaults to ``a_share``.
"""
for pattern, market in _MARKET_PATTERNS:
if pattern.match(code):
diff --git a/agent/src/shadow_account/backtester.py b/agent/src/shadow_account/backtester.py
index 2efa8ecb8..66db6c189 100644
--- a/agent/src/shadow_account/backtester.py
+++ b/agent/src/shadow_account/backtester.py
@@ -40,7 +40,7 @@ SUPPORTED_MARKETS: tuple[str, ...] = ("china_a", "hk", "us", "crypto")
_LIQUID_BASKETS: dict[str, list[str]] = {
"china_a": ["600519.SH", "000858.SZ", "300750.SZ", "600036.SH", "000001.SZ"],
"hk": ["00700.HK", "09988.HK", "03690.HK", "00388.HK", "01810.HK"],
- "us": ["AAPL", "MSFT", "NVDA", "AMZN", "GOOGL"],
+ "us": ["AAPL.US", "MSFT.US", "NVDA.US", "AMZN.US", "GOOGL.US"],
"crypto": ["BTC-USDT", "ETH-USDT", "SOL-USDT", "BNB-USDT", "XRP-USDT"],
}
diff --git a/agent/tests/test_market_detection.py b/agent/tests/test_market_detection.py
index 6e80311d7..1c22341b7 100644
--- a/agent/tests/test_market_detection.py
+++ b/agent/tests/test_market_detection.py
@@ -11,7 +11,7 @@ from __future__ import annotations
import pytest
-from backtest.engines._market_hooks import _is_china_futures
+from backtest.engines._market_hooks import _is_china_futures, code_currency
from backtest.runner import (
_detect_market,
_detect_source,
@@ -46,6 +46,15 @@ class TestDetectMarket:
("AAPL.US", "us_equity"),
("TSLA.US", "us_equity"),
("NVDA.US", "us_equity"),
+ # US equity — bare tickers without the .US suffix (issue #986)
+ ("AAPL", "us_equity"),
+ ("MSFT", "us_equity"),
+ ("NVDA", "us_equity"),
+ ("AMZN", "us_equity"),
+ ("GOOGL", "us_equity"),
+ ("SPY", "us_equity"),
+ ("T", "us_equity"),
+ ("V", "us_equity"),
# HK equity
("0700.HK", "hk_equity"),
("9988.HK", "hk_equity"),
@@ -81,11 +90,68 @@ class TestDetectMarket:
def test_case_insensitive(self) -> None:
assert _detect_market("000001.sz") == "a_share"
assert _detect_market("aapl.us") == "us_equity"
+ assert _detect_market("aapl") == "us_equity"
assert _detect_market("btc-usdt") == "crypto"
def test_unknown_defaults_to_a_share(self) -> None:
assert _detect_market("UNKNOWN") == "a_share"
assert _detect_market("random-string") == "a_share"
+ # Bare codes outside the 1-5 letter US shape keep the old default.
+ assert _detect_market("EURUSD") == "a_share"
+ assert _detect_market("BTCUSDT") == "a_share"
+
+
+# ---------------------------------------------------------------------------
+# Issue #986 — bare US tickers must route to the us_equity chain
+# ---------------------------------------------------------------------------
+
+
+class TestBareUsTickerRouting:
+ """Regression suite for issue #986.
+
+ Bare US tickers (the Shadow Account US basket, agent-generated configs)
+ previously fell through to the a_share default, walked the A-share
+ loader chain, and died with NoAvailableSourceError. The catch-all
+ ``^[A-Z]{1,5}$`` pattern must stay the lowest-priority entry so every
+ suffixed / futures / crypto / forex form keeps winning first.
+ """
+
+ def test_shadow_us_basket_groups_into_us_equity(self) -> None:
+ basket = ["AAPL", "MSFT", "NVDA", "AMZN", "GOOGL"]
+ groups = _group_codes_by_market(basket)
+ assert groups == {"us_equity": basket}
+
+ def test_bare_ticker_source_and_currency(self) -> None:
+ assert _detect_source("AAPL") == "yfinance"
+ assert code_currency("AAPL") == "USD"
+ assert code_currency("AAPL.US") == "USD"
+
+ def test_catch_all_is_lowest_priority(self) -> None:
+ assert _detect_market("600519.SH") == "a_share"
+ assert _detect_market("00700.HK") == "hk_equity"
+ assert _detect_market("BTC-USDT") == "crypto"
+ assert _detect_market("RELIANCE.NS") == "india_equity"
+ assert _detect_market("005930.KS") == "kr_equity"
+ assert _detect_market("RB2410") == "futures"
+ assert _detect_market("ES2503") == "futures"
+ assert _detect_market("CLZ4") == "futures"
+ assert _detect_market("EUR/USD") == "forex"
+
+ def test_shadow_liquid_baskets_route_to_their_own_market(self) -> None:
+ from src.shadow_account.backtester import _LIQUID_BASKETS
+
+ expected = {
+ "china_a": "a_share",
+ "hk": "hk_equity",
+ "us": "us_equity",
+ "crypto": "crypto",
+ }
+ for market, codes in _LIQUID_BASKETS.items():
+ for code in codes:
+ assert _detect_market(code) == expected[market], (
+ f"{market} basket code {code!r} detected as "
+ f"{_detect_market(code)!r}, expected {expected[market]!r}"
+ )
# ---------------------------------------------------------------------------
diff --git a/agent/tests/test_shadow_scanner.py b/agent/tests/test_shadow_scanner.py
index 5bcb8be9a..1dda7a556 100644
--- a/agent/tests/test_shadow_scanner.py
+++ b/agent/tests/test_shadow_scanner.py
@@ -56,7 +56,7 @@ def _bars(closes: list[float], volumes: list[float] | None = None) -> pd.DataFra
def test_scan_today_signals_matches_price_features() -> None:
profile = _profile()
frames = {
- "AAPL": _bars(
+ "AAPL.US": _bars(
[10, 10.2, 10.4, 10.5, 10.7, 11.4],
[100, 100, 100, 100, 100, 180],
),
@@ -66,7 +66,7 @@ def test_scan_today_signals_matches_price_features() -> None:
assert matches == [
{
- "symbol": "AAPL",
+ "symbol": "AAPL.US",
"market": "us",
"rule_id": "R1",
"reason": "R1 price features matched (hold 3-7d)",
@@ -78,7 +78,7 @@ def test_scan_today_signals_matches_price_features() -> None:
def test_scan_today_signals_returns_no_match_when_features_fail() -> None:
profile = _profile()
frames = {
- "AAPL": _bars(
+ "AAPL.US": _bars(
[11.5, 11.2, 11.0, 10.9, 10.7, 10.5],
[180, 160, 150, 140, 130, 100],
),
@@ -90,7 +90,7 @@ def test_scan_today_signals_returns_no_match_when_features_fail() -> None:
@pytest.mark.unit
def test_scan_today_signals_skips_missing_and_empty_data() -> None:
profile = _profile()
- frames = {"AAPL": pd.DataFrame(), "MSFT": pd.DataFrame({"open": [1, 2]})}
+ frames = {"AAPL.US": pd.DataFrame(), "MSFT.US": pd.DataFrame({"open": [1, 2]})}
assert scan_today_signals(profile, target_date="2026-04-06", price_frames=frames) == []
@@ -109,7 +109,10 @@ def test_scan_today_signals_respects_per_market_cap() -> None:
[10, 10.2, 10.4, 10.5, 10.7, 11.4],
[100, 100, 100, 100, 100, 180],
)
- frames = {symbol: frame for symbol in ["AAPL", "MSFT", "NVDA", "AMZN", "GOOGL"]}
+ frames = {
+ symbol: frame
+ for symbol in ["AAPL.US", "MSFT.US", "NVDA.US", "AMZN.US", "GOOGL.US"]
+ }
matches = scan_today_signals(
profile,
@@ -118,7 +121,7 @@ def test_scan_today_signals_respects_per_market_cap() -> None:
price_frames=frames,
)
- assert [match["symbol"] for match in matches] == ["AAPL", "MSFT"]
+ assert [match["symbol"] for match in matches] == ["AAPL.US", "MSFT.US"]
def _ramp(n: int, start: float, step: float) -> list[float]:
@@ -137,11 +140,11 @@ def test_scan_today_signals_matches_rsi_range_condition() -> None:
profile = _profile({"market": "us", "entry_rsi14": {"min": 50.0, "max": 100.0}})
closes = _ramp(20, 10.0, 0.2) # >= 14 bars so RSI is defined
target = pd.Timestamp("2026-04-01") + pd.Timedelta(days=len(closes) - 1)
- frames = {"AAPL": _bars(closes)}
+ frames = {"AAPL.US": _bars(closes)}
matches = scan_today_signals(profile, target_date=target.date(), price_frames=frames)
- assert [m["symbol"] for m in matches] == ["AAPL"]
+ assert [m["symbol"] for m in matches] == ["AAPL.US"]
@pytest.mark.unit
@@ -150,7 +153,7 @@ def test_scan_today_signals_rejects_out_of_band_rsi() -> None:
profile = _profile({"market": "us", "entry_rsi14": {"min": 0.0, "max": 30.0}})
closes = _ramp(20, 10.0, 0.2)
target = pd.Timestamp("2026-04-01") + pd.Timedelta(days=len(closes) - 1)
- frames = {"AAPL": _bars(closes)}
+ frames = {"AAPL.US": _bars(closes)}
assert scan_today_signals(profile, target_date=target.date(), price_frames=frames) == []
@@ -164,11 +167,11 @@ def test_scan_today_signals_honors_prior_return_dict_band() -> None:
band; a too-high floor must reject it.
"""
closes = [10, 10.2, 10.4, 10.5, 10.7, 11.4]
- frames = {"AAPL": _bars(closes)}
+ frames = {"AAPL.US": _bars(closes)}
inside = _profile({"market": "us", "prior_5d_return": {"min": 0.10, "max": 0.20}})
assert [m["symbol"] for m in scan_today_signals(
- inside, target_date="2026-04-06", price_frames=frames)] == ["AAPL"]
+ inside, target_date="2026-04-06", price_frames=frames)] == ["AAPL.US"]
outside = _profile({"market": "us", "prior_5d_return": {"min": 0.50, "max": 1.0}})
assert scan_today_signals(outside, target_date="2026-04-06", price_frames=frames) == []
@@ -178,7 +181,7 @@ def test_scan_today_signals_honors_prior_return_dict_band() -> None:
def test_scan_today_signals_no_match_when_rsi_history_insufficient() -> None:
"""Too few bars to compute RSI → the RSI-bearing rule cannot match."""
profile = _profile({"market": "us", "entry_rsi14": {"min": 0.0, "max": 100.0}})
- frames = {"AAPL": _bars(_ramp(6, 10.0, 0.2))} # < 14 bars, RSI undefined
+ frames = {"AAPL.US": _bars(_ramp(6, 10.0, 0.2))} # < 14 bars, RSI undefined
assert scan_today_signals(profile, target_date="2026-04-06", price_frames=frames) == []