"Vibe-Trading: Your Personal Trading Agent"
Python ai-agentalgorithmic-tradingbacktestingfintechllmmcpmulti-agentpythonquantitative-financetrading
fix(shadow): run multi-market backtests per settlement currency (#997)
shadowinlife5848544e994a
diff --git a/agent/mcp_server.py b/agent/mcp_server.pyindex 13aed5fcc..05c3046a8 100644--- a/agent/mcp_server.py+++ b/agent/mcp_server.py@@ -2469,6 +2469,10 @@ def run_shadow_backtest("""Run a multi-market backtest (A股/港股/美股/crypto) on a Shadow Accountprofile and compute delta-PnL attribution vs the user's realized trades.+ Markets are backtested per settlement currency (CNY / HKD / USD pools;+ us + crypto share the USD pool); the headline PnL uses the profile's+ source-market currency.+Requires `extract_shadow_strategy` to have run first.Args:diff --git a/agent/src/shadow_account/backtester.py b/agent/src/shadow_account/backtester.pyindex 66db6c189..82d0e6e24 100644--- a/agent/src/shadow_account/backtester.py+++ b/agent/src/shadow_account/backtester.py@@ -3,8 +3,9 @@Responsibilities:1. Pick representative symbols per market based on the user's preferredmarkets (with a liquid-basket fallback).- 2. Render a run_dir (via ``codegen.write_run_dir``) and call- ``src.tools.backtest_tool.run_backtest``.+ 2. Group the selection by settlement currency, render one run_dir per+ currency pool (via ``codegen.write_run_dir``) and call+ ``src.tools.backtest_tool.run_backtest`` once per pool.3. Parse the emitted artifacts (metrics JSON / equity CSV) back into a``ShadowBacktestResult``.4. Compute attribution: noise trades, missed signals, early/late exits,@@ -23,6 +24,7 @@ from typing import Anyimport pandas as pd+from backtest.engines._market_hooks import code_currencyfrom src.shadow_account.codegen import write_run_dirfrom src.shadow_account.models import (AttributionBreakdown,@@ -90,6 +92,72 @@ def flatten_codes(selection: dict[str, list[str]]) -> list[str]:return out+def _group_selection_by_currency(+ selection: dict[str, list[str]],+) -> dict[str, dict[str, list[str]]]:+ """Group a per-market selection by settlement currency.++ The composite backtest engine refuses a code set that spans currencies+ (its shared capital pool has no FX translation), so multi-market shadow+ runs are split into one backtest per currency pool. Markets that settle+ in the same currency (us + crypto → USD) share one pool.++ Args:+ selection: Dict market → list of codes.++ Returns:+ ``{currency: {market: [codes]}}`` preserving market insertion order+ within each group and first-seen currency order across groups.+ Codes are grouped per-code, so a market whose codes span currencies+ is split across groups. Empty code lists produce no entries.+ """+ groups: dict[str, dict[str, list[str]]] = {}+ for market, codes in selection.items():+ for code in codes:+ currency = code_currency(code)+ groups.setdefault(currency, {}).setdefault(market, []).append(code)+ return groups+++def _usable_metrics(combined: dict[str, Any]) -> bool:+ """True when a combined metrics dict carries real numbers (not an error)."""+ return bool(combined) and "error" not in combined+++def _headline_index(+ group_results: list[tuple[str, dict[str, float]]],+ selection: dict[str, list[str]],+ source_market: str,+) -> int:+ """Pick the headline currency group for combined metrics + attribution.++ Preference order:+ 1. The group holding the profile's source-market codes, when it has+ usable metrics — the journal's realized PnL is denominated in that+ market's currency, so only this pool makes delta-PnL meaningful.+ 2. The first group with usable metrics (deterministic fallback).+ 3. Index 0 (all groups failed — keeps the error-reporting path).++ Args:+ group_results: ``(currency, combined)`` pairs in run order.+ selection: Original per-market selection.+ source_market: Profile's dominant journal market.++ Returns:+ Index into ``group_results``.+ """+ source_codes = selection.get(source_market) or []+ if source_codes:+ source_currency = code_currency(source_codes[0])+ for i, (currency, combined) in enumerate(group_results):+ if currency == source_currency and _usable_metrics(combined):+ return i+ for i, (_, combined) in enumerate(group_results):+ if _usable_metrics(combined):+ return i+ return 0++# ---------------- Backtest execution ----------------def run_shadow_backtest(@@ -106,13 +174,20 @@ def run_shadow_backtest() -> ShadowBacktestResult:"""Drive a multi-market backtest from a ShadowProfile.+ Markets are backtested per settlement currency: the composite engine+ refuses a mixed-currency code set (its shared capital pool has no FX+ translation), so the selection is split into one run per currency pool —+ e.g. the default four markets produce three runs: CNY (china_a),+ HKD (hk) and USD (us + crypto sharing one pool). Each pool starts with+ the full ``initial_capital``; there is no cross-currency aggregation.+Args:profile: ShadowProfile to replay.window_start / window_end: ISO dates.markets: Target market buckets.per_market_count: Codes per market.source: Loader source (``auto`` routes by suffix).- initial_capital: Starting cash.+ initial_capital: Starting cash per currency pool.journal_path: Original journal path (used to compute attributionagainst the user's realized trades). Attribution is skipped ifNone or the file is missing.@@ -122,33 +197,74 @@ def run_shadow_backtest(entrypoint.Returns:- ShadowBacktestResult with per-market + combined metrics, equity- curves (when emitted), and attribution (zeros when unavailable).+ ShadowBacktestResult with per-market metrics from each market's own+ currency pool, combined metrics from the headline pool (the profile's+ source-market currency when available — the only pool whose PnL is+ comparable with the journal), one equity curve per pool plus a+ ``combined`` alias of the headline curve, and attribution (zeros when+ unavailable)."""selection = select_multi_market_codes(profile, per_market_count=per_market_count, markets=markets,)- codes = flatten_codes(selection)- if not codes:+ groups = _group_selection_by_currency(selection)+ if not groups:raise ValueError("No codes available for requested markets.")- run_dir = runs_dir(profile.shadow_id)- write_run_dir(- profile,- run_dir,- codes=codes,- start_date=window_start,- end_date=window_end,- source=source,- initial_capital=initial_capital,- )-+ base_dir = runs_dir(profile.shadow_id)backtest_fn = run_backtest_fn or _default_run_backtest_fn()- payload = json.loads(backtest_fn(str(run_dir)))- per_market, combined, equity_curves = _summarize_artifacts(- payload=payload, run_dir=run_dir, selection=selection,+ # One backtest per currency pool; a failing pool degrades to an error+ # row without aborting the others.+ group_results: list[+ tuple[str, dict[str, dict[str, float]], dict[str, float], list[tuple[str, float]]]+ ] = []+ for currency, sub_selection in groups.items():+ codes = flatten_codes(sub_selection)+ group_run_dir = base_dir / currency+ write_run_dir(+ profile,+ group_run_dir,+ codes=codes,+ start_date=window_start,+ end_date=window_end,+ source=source,+ initial_capital=initial_capital,+ )+ payload = json.loads(backtest_fn(str(group_run_dir)))+ per_market, combined, curves = _summarize_artifacts(+ payload=payload, run_dir=group_run_dir, selection=sub_selection,+ )+ group_results.append(+ (currency, per_market, combined, curves.get("combined") or []),+ )++ headline = _headline_index(+ [(currency, combined) for currency, _, combined, _ in group_results],+ selection,+ profile.source_market,)+ headline_currency, _, headline_combined, headline_points = group_results[headline]++ per_market: dict[str, dict[str, float]] = {}+ for _, group_per_market, _, _ in group_results:+ per_market.update(group_per_market)++ combined = dict(headline_combined)+ if len(group_results) > 1 and _usable_metrics(combined):+ combined["_currency_note"] = (+ f"headline metrics are the {headline_currency} currency pool; "+ f"{len(group_results)} currency pools ran — other pools are "+ "reported in per_market rows (no FX conversion)"+ )++ equity_curves: dict[str, list[tuple[str, float]]] = {+ currency: points+ for currency, _, _, points in group_results+ if points+ }+ if headline_points:+ equity_curves["combined"] = headline_pointsattribution, shadow_pnl, real_pnl = _attribution_or_zero(profile=profile,@@ -166,7 +282,7 @@ def run_shadow_backtest(real_total_pnl=real_pnl,delta_pnl=round(shadow_pnl - real_pnl, 2),)- _cache_result(run_dir, result)+ _cache_result(base_dir, result)return result@@ -337,14 +453,13 @@ def _per_market_breakdown(combined: dict[str, float],selection: dict[str, list[str]],) -> dict[str, dict[str, float]]:- """Project the combined metrics into each requested market.+ """Project one currency pool's combined metrics into its markets.- v1 limitation: the runner emits a single combined metrics file regardless- of cross-market composition, so per-market rows reuse the combined- metrics. This is faithful (same backtest) but intentionally lossy; a- follow-up can split equity by market attribution.+ Markets within a pool genuinely shared the capital pool, so they share+ its metrics; each market's row is completed from its own pool's run.+ Error payloads yield empty rows rather than propagating the error dict."""- if not combined:+ if not _usable_metrics(combined):return {market: {} for market in selection}return {market: dict(combined) for market in selection}diff --git a/agent/src/tools/shadow_account_tool.py b/agent/src/tools/shadow_account_tool.pyindex 921d6e8db..cb817e1b6 100644--- a/agent/src/tools/shadow_account_tool.py+++ b/agent/src/tools/shadow_account_tool.py@@ -165,6 +165,9 @@ class RunShadowBacktestTool(BaseTool):description = ("Run a multi-market backtest (A股/港股/美股/crypto) on a Shadow Account ""profile and compute delta-PnL attribution vs the user's realized trades. "+ "Markets are backtested per settlement currency (CNY / HKD / USD pools; "+ "us + crypto share the USD pool); the headline PnL uses the profile's "+ "source-market currency. ""Requires `extract_shadow_strategy` to have been run first.")parameters = {diff --git a/agent/tests/test_shadow_account.py b/agent/tests/test_shadow_account.pyindex 28093253c..1c05fc231 100644--- a/agent/tests/test_shadow_account.py+++ b/agent/tests/test_shadow_account.py@@ -13,10 +13,6 @@ from pathlib import Pathimport pandas as pdimport pytest-pytestmark = pytest.mark.filterwarnings(- "ignore:Number of distinct clusters.*:UserWarning",-)-from src.shadow_account import (AttributionBreakdown,ShadowBacktestResult,@@ -34,9 +30,12 @@ from src.shadow_account import (validate_generated,write_run_dir,)-from src.shadow_account.models import AttributionBreakdown as _AttrClsfrom src.shadow_account.extractor import MIN_PROFITABLE_ROUNDTRIPS+pytestmark = pytest.mark.filterwarnings(+ "ignore:Number of distinct clusters.*:UserWarning",+)+# ---------------- Helpers ----------------@@ -269,7 +268,6 @@ def test_generated_engine_runs_on_mock_data_map(profitable_journal: Path) -> Nonprofile = extract_shadow_profile(profitable_journal)source = render_signal_engine(profile)- module_path = Path("./_shadow_test_engine.py").resolve()# Use tmp via test's temp dir proxy — write + exec.import tempfile@@ -420,6 +418,241 @@ def test_run_shadow_backtest_handles_runner_failure(assert result.equity_curves == {}+# ---------------- M3b: per-currency multi-market runs ----------------++from backtest.engines._market_hooks import code_currency # noqa: E402+from src.shadow_account.backtester import ( # noqa: E402+ _group_selection_by_currency,+ _LIQUID_BASKETS,+)+from src.shadow_account.storage import runs_dir # noqa: E402+++def _recording_stub(+ metrics_by_pool: dict[str, dict[str, float]],+ calls: list[dict[str, object]],+ *,+ fail_pools: frozenset[str] = frozenset(),+ with_equity: bool = False,+):+ """Build a run_backtest_fn stub keyed by the run_dir's pool name."""++ def stub(run_dir_str: str) -> str:+ run_path = Path(run_dir_str)+ pool = run_path.name+ cfg = json.loads((run_path / "config.json").read_text(encoding="utf-8"))+ calls.append({"pool": pool, "codes": cfg.get("codes") or []})+ if pool in fail_pools:+ return json.dumps({+ "status": "error",+ "exit_code": 1,+ "stderr": f"{pool} fetch failed",+ "artifacts": {},+ })+ artifacts_dir = run_path / "artifacts"+ artifacts_dir.mkdir(parents=True, exist_ok=True)+ metrics_path = artifacts_dir / "metrics.json"+ metrics_path.write_text(+ json.dumps(metrics_by_pool[pool]), encoding="utf-8",+ )+ artifacts = {"metrics.json": str(metrics_path)}+ if with_equity:+ equity_path = artifacts_dir / "equity.csv"+ equity_path.write_text(+ "date,equity\n2026-01-02,1000000\n2026-06-30,1000000\n",+ encoding="utf-8",+ )+ artifacts["equity.csv"] = str(equity_path)+ return json.dumps({+ "status": "ok", "exit_code": 0, "artifacts": artifacts,+ })++ return stub+++def test_group_selection_by_currency_default_markets(+ profitable_journal: Path,+) -> None:+ profile = extract_shadow_profile(profitable_journal)+ selection = select_multi_market_codes(profile, per_market_count=3)+ groups = _group_selection_by_currency(selection)+ assert set(groups.keys()) == {"CNY", "HKD", "USD"}+ assert set(groups["CNY"].keys()) == {"china_a"}+ assert set(groups["HKD"].keys()) == {"hk"}+ assert set(groups["USD"].keys()) == {"us", "crypto"}+++def test_group_selection_by_currency_us_crypto_single_group() -> None:+ groups = _group_selection_by_currency({+ "us": _LIQUID_BASKETS["us"][:2],+ "crypto": _LIQUID_BASKETS["crypto"][:2],+ })+ assert set(groups.keys()) == {"USD"}+ assert set(groups["USD"].keys()) == {"us", "crypto"}+++def test_run_shadow_backtest_runs_once_per_currency(+ profitable_journal: Path, tmp_path: Path, monkeypatch: pytest.MonkeyPatch,+) -> None:+ monkeypatch.setenv("HOME", str(tmp_path))+ monkeypatch.setenv("USERPROFILE", str(tmp_path))+ profile = extract_shadow_profile(profitable_journal)++ calls: list[dict[str, object]] = []+ metrics = {+ "CNY": {"total_return_abs": 100.0, "sharpe": 1.0},+ "HKD": {"total_return_abs": 200.0, "sharpe": 2.0},+ "USD": {"total_return_abs": 300.0, "sharpe": 3.0},+ }+ result = run_shadow_backtest(+ profile,+ window_start="2026-01-01",+ window_end="2026-06-30",+ run_backtest_fn=_recording_stub(metrics, calls),+ )+ assert len(calls) == 3+ assert {c["pool"] for c in calls} == {"CNY", "HKD", "USD"}+ for call in calls:+ currencies = {code_currency(c) for c in call["codes"]} # type: ignore[union-attr]+ assert len(currencies) == 1+ assert (runs_dir(profile.shadow_id) / "shadow_result.json").exists()+ assert set(result.per_market.keys()) == {"china_a", "hk", "us", "crypto"}+++def test_per_market_rows_come_from_own_currency_group(+ profitable_journal: Path, tmp_path: Path, monkeypatch: pytest.MonkeyPatch,+) -> None:+ monkeypatch.setenv("HOME", str(tmp_path))+ monkeypatch.setenv("USERPROFILE", str(tmp_path))+ profile = extract_shadow_profile(profitable_journal)++ calls: list[dict[str, object]] = []+ metrics = {+ "CNY": {"total_return_abs": 100.0, "sharpe": 1.0},+ "HKD": {"total_return_abs": 200.0, "sharpe": 2.0},+ "USD": {"total_return_abs": 300.0, "sharpe": 3.0},+ }+ result = run_shadow_backtest(+ profile,+ window_start="2026-01-01",+ window_end="2026-06-30",+ run_backtest_fn=_recording_stub(metrics, calls),+ )+ assert result.per_market["china_a"]["sharpe"] == 1.0+ assert result.per_market["hk"]["sharpe"] == 2.0+ assert result.per_market["us"]["sharpe"] == 3.0+ assert result.per_market["crypto"]["sharpe"] == 3.0+++def test_headline_pnl_uses_source_market_currency(+ profitable_journal: Path, tmp_path: Path, monkeypatch: pytest.MonkeyPatch,+) -> None:+ monkeypatch.setenv("HOME", str(tmp_path))+ monkeypatch.setenv("USERPROFILE", str(tmp_path))+ profile = extract_shadow_profile(profitable_journal)+ assert profile.source_market == "china_a"++ calls: list[dict[str, object]] = []+ metrics = {+ "CNY": {"total_return_abs": 100.0, "sharpe": 1.0},+ "HKD": {"total_return_abs": 200.0, "sharpe": 2.0},+ "USD": {"total_return_abs": 300.0, "sharpe": 3.0},+ }+ result = run_shadow_backtest(+ profile,+ window_start="2026-01-01",+ window_end="2026-06-30",+ run_backtest_fn=_recording_stub(metrics, calls),+ )+ assert result.combined["total_return_abs"] == 100.0+ assert result.shadow_total_pnl == 100.0+ assert "_currency_note" in result.combined+++def test_single_currency_group_keeps_single_run(+ profitable_journal: Path, tmp_path: Path, monkeypatch: pytest.MonkeyPatch,+) -> None:+ monkeypatch.setenv("HOME", str(tmp_path))+ monkeypatch.setenv("USERPROFILE", str(tmp_path))+ profile = extract_shadow_profile(profitable_journal)++ calls: list[dict[str, object]] = []+ metrics = {"USD": {"total_return_abs": 300.0, "sharpe": 3.0}}+ result = run_shadow_backtest(+ profile,+ window_start="2026-01-01",+ window_end="2026-06-30",+ markets=("us", "crypto"),+ run_backtest_fn=_recording_stub(metrics, calls, with_equity=True),+ )+ assert len(calls) == 1+ assert calls[0]["pool"] == "USD"+ assert result.combined["total_return_abs"] == 300.0+ assert "_currency_note" not in result.combined+ assert set(result.equity_curves.keys()) == {"USD", "combined"}+ assert result.equity_curves["combined"] == result.equity_curves["USD"]+++def test_currency_group_failure_is_isolated(+ profitable_journal: Path, tmp_path: Path, monkeypatch: pytest.MonkeyPatch,+) -> None:+ monkeypatch.setenv("HOME", str(tmp_path))+ monkeypatch.setenv("USERPROFILE", str(tmp_path))+ profile = extract_shadow_profile(profitable_journal)++ calls: list[dict[str, object]] = []+ metrics = {+ "HKD": {"total_return_abs": 200.0, "sharpe": 2.0},+ "USD": {"total_return_abs": 300.0, "sharpe": 3.0},+ }+ result = run_shadow_backtest(+ profile,+ window_start="2026-01-01",+ window_end="2026-06-30",+ run_backtest_fn=_recording_stub(+ metrics, calls, fail_pools=frozenset({"CNY"}),+ ),+ )+ assert len(calls) == 3+ assert result.per_market["china_a"] == {}+ assert result.per_market["hk"]["sharpe"] == 2.0+ assert result.per_market["us"]["sharpe"] == 3.0+ assert "error" not in result.combined+ assert result.combined["total_return_abs"] == 200.0+ assert result.shadow_total_pnl == 200.0+++def test_all_currency_groups_failure(+ profitable_journal: Path, tmp_path: Path, monkeypatch: pytest.MonkeyPatch,+) -> None:+ monkeypatch.setenv("HOME", str(tmp_path))+ monkeypatch.setenv("USERPROFILE", str(tmp_path))+ profile = extract_shadow_profile(profitable_journal)++ calls: list[dict[str, object]] = []+ result = run_shadow_backtest(+ profile,+ window_start="2026-01-01",+ window_end="2026-06-30",+ run_backtest_fn=_recording_stub(+ {}, calls, fail_pools=frozenset({"CNY", "HKD", "USD"}),+ ),+ )+ assert len(calls) == 3+ assert result.combined.get("error")+ assert result.shadow_total_pnl == 0.0+ assert result.equity_curves == {}+ assert all(row == {} for row in result.per_market.values())++# ---------------- M4: Reporter ----------------def _stub_backtest_result(profile: ShadowProfile) -> ShadowBacktestResult: