Skip to content

"Vibe-Trading: Your Personal Trading Agent"

fix(shadow): scope attribution to the pool currency and make buckets exclusive

Yufeng He53a57bc3e74a
diff --git a/agent/src/shadow_account/backtester.py b/agent/src/shadow_account/backtester.py
index 769f1bc77..a48a41c4e 100644
--- a/agent/src/shadow_account/backtester.py
+++ b/agent/src/shadow_account/backtester.py
@@ -271,6 +271,7 @@ def run_shadow_backtest(
journal_path=journal_path,
combined=combined,
initial_capital=initial_capital,
+ pool_currency=headline_currency,
)
result = ShadowBacktestResult(
@@ -494,6 +495,7 @@ def _attribution_or_zero(
journal_path: str | Path | None,
combined: dict[str, float],
initial_capital: float,
+ pool_currency: str | None = None,
) -> tuple[AttributionBreakdown, float | None, float]:
"""Compute attribution if the journal is available, else return zeros."""
shadow_pnl = _shadow_pnl_from_metrics(combined, initial_capital)
@@ -516,7 +518,12 @@ def _attribution_or_zero(
if not roundtrips:
return _zero_attribution(), shadow_pnl, 0.0
- return _compute_attribution(profile=profile, roundtrips=roundtrips, shadow_pnl=shadow_pnl)
+ return _compute_attribution(
+ profile=profile,
+ roundtrips=roundtrips,
+ shadow_pnl=shadow_pnl,
+ pool_currency=pool_currency,
+ )
def _zero_attribution() -> AttributionBreakdown:
@@ -535,6 +542,7 @@ def _compute_attribution(
profile: ShadowProfile,
roundtrips: list[dict[str, Any]],
shadow_pnl: float,
+ pool_currency: str | None = None,
) -> tuple[AttributionBreakdown, float, float]:
"""Attribute the delta between user's real PnL and shadow PnL.
@@ -553,35 +561,58 @@ def _compute_attribution(
``counterfactual_trades`` lists the top-5 |impact| roundtrips for
Section 6 of the report.
+
+ ``pool_currency`` restricts the comparison to the shadow pool's currency:
+ the pool is single-currency, so roundtrips settling in other currencies
+ are excluded from ``real_pnl`` and counted in
+ ``AttributionBreakdown.excluded_currencies`` instead of being summed
+ against it (#14).
"""
rule_hold_lo, rule_hold_hi = _aggregate_holding_range(profile)
noise = 0.0
early = 0.0
late = 0.0
+ excluded_currencies: dict[str, int] = {}
+ pool_roundtrips = [
+ rt
+ for rt in roundtrips
+ if pool_currency is None or code_currency(rt["symbol"]) == pool_currency
+ ]
+ if pool_currency is not None:
+ for rt in roundtrips:
+ currency = code_currency(rt["symbol"])
+ if currency != pool_currency:
+ excluded_currencies[currency] = excluded_currencies.get(currency, 0) + 1
real_pnl = 0.0
counterfactuals: list[dict[str, Any]] = []
- for rt in roundtrips:
+ for rt in pool_roundtrips:
pnl = float(rt["pnl"])
real_pnl += pnl
hold = float(rt["hold_days"])
within_rule = rule_hold_lo <= hold <= rule_hold_hi
impact = 0.0
reason = ""
+ # Buckets are mutually exclusive (#17): a too-short winner belongs to
+ # early-exit and a too-long loser to late-exit; only the remaining
+ # out-of-range trades count as rule-violation noise. Without the
+ # split, those trades landed in both noise and early/late and
+ # `explained` summed them twice.
if not within_rule:
- noise += -pnl
- impact += -pnl
- reason = "rule_violation"
- if pnl > 0 and hold < rule_hold_lo:
- shortfall = pnl * max(0.0, (rule_hold_lo - hold) / max(rule_hold_lo, 1))
- early += shortfall
- impact += shortfall
- reason = reason or "early_exit"
- if pnl < 0 and hold > rule_hold_hi:
- excess = -pnl * max(0.0, (hold - rule_hold_hi) / max(rule_hold_hi, 1))
- late += excess
- impact += excess
- reason = reason or "late_exit"
+ if pnl > 0 and hold < rule_hold_lo:
+ shortfall = pnl * max(0.0, (rule_hold_lo - hold) / max(rule_hold_lo, 1))
+ early += shortfall
+ impact += shortfall
+ reason = "early_exit"
+ elif pnl < 0 and hold > rule_hold_hi:
+ excess = -pnl * max(0.0, (hold - rule_hold_hi) / max(rule_hold_hi, 1))
+ late += excess
+ impact += excess
+ reason = "late_exit"
+ else:
+ noise += -pnl
+ impact += -pnl
+ reason = "rule_violation"
if impact != 0.0:
counterfactuals.append({
"symbol": rt["symbol"],
@@ -593,7 +624,7 @@ def _compute_attribution(
"reason": reason,
})
- overtrading = _overtrading_pnl(profile=profile, roundtrips=roundtrips)
+ overtrading = _overtrading_pnl(profile=profile, roundtrips=pool_roundtrips)
explained = noise + early + late + overtrading
missed = round(shadow_pnl - real_pnl - explained, 2)
@@ -608,6 +639,7 @@ def _compute_attribution(
late_exit_pnl=round(late, 2),
overtrading_pnl=round(overtrading, 2),
counterfactual_trades=top5,
+ excluded_currencies=excluded_currencies,
),
round(shadow_pnl, 2),
round(real_pnl, 2),
diff --git a/agent/src/shadow_account/models.py b/agent/src/shadow_account/models.py
index 0017c3bfe..5c26f40cd 100644
--- a/agent/src/shadow_account/models.py
+++ b/agent/src/shadow_account/models.py
@@ -94,6 +94,9 @@ class AttributionBreakdown:
late_exit_pnl: float
overtrading_pnl: float
counterfactual_trades: tuple[dict[str, Any], ...] = field(default_factory=tuple)
+ # Roundtrips settled in other currencies than the shadow pool's, kept out
+ # of the comparison (currency -> count). Empty for single-currency journals.
+ excluded_currencies: dict[str, int] = field(default_factory=dict)
@dataclass(frozen=True)
diff --git a/agent/tests/test_shadow_attribution.py b/agent/tests/test_shadow_attribution.py
new file mode 100644
index 000000000..a556dbac8
--- /dev/null
+++ b/agent/tests/test_shadow_attribution.py
@@ -0,0 +1,105 @@
+"""Attribution currency scoping (#14) and mutually exclusive buckets (#17).
+
+A mixed HK+US journal used to have every roundtrip summed into real_pnl and
+compared against a single-currency shadow pool, so HKD amounts leaked into a
+USD delta. And the early/late conditions were subsets of not-within-rule, so
+one trade landed in both noise and early/late and `explained` summed it
+twice.
+"""
+
+from __future__ import annotations
+
+import pandas as pd
+import pytest
+
+from src.shadow_account.backtester import _compute_attribution
+from src.shadow_account.models import ShadowProfile, ShadowRule
+
+
+def _profile() -> ShadowProfile:
+ rule = ShadowRule(
+ rule_id="R1",
+ human_text="hold ~3d",
+ entry_condition={"market": "us"},
+ exit_condition={"holding_days": {"min": 2, "max": 5}},
+ holding_days_range=(3, 3),
+ support_count=10,
+ coverage_rate=0.5,
+ sample_trades=("AAPL@2026-01-10",),
+ )
+ return ShadowProfile(
+ shadow_id="shadow_test",
+ created_at="2026-01-01T00:00:00",
+ journal_hash="test",
+ source_market="us",
+ profitable_roundtrips=10,
+ total_roundtrips=20,
+ date_range=("2025-01-01", "2026-01-01"),
+ profile_text="test",
+ rules=(rule,),
+ preferred_markets=("us",),
+ typical_holding_days=(3.0, 3.0),
+ )
+
+
+def _rt(symbol: str, pnl: float, hold_days: float) -> dict:
+ return {
+ "symbol": symbol,
+ "buy_dt": pd.Timestamp("2026-01-01"),
+ "sell_dt": pd.Timestamp("2026-01-01") + pd.Timedelta(days=hold_days),
+ "qty": 10.0,
+ "buy_price": 100.0,
+ "sell_price": 100.0 + pnl / 10.0,
+ "hold_days": hold_days,
+ "pnl": pnl,
+ "pnl_pct": pnl / 1000.0,
+ }
+
+
+def test_mixed_journal_excludes_other_currencies_from_real_pnl() -> None:
+ roundtrips = [
+ _rt("AAPL.US", 100.0, 3.0),
+ _rt("0700.HK", 50.0, 3.0),
+ _rt("9988.HK", -20.0, 3.0),
+ ]
+ breakdown, _, real_pnl = _compute_attribution(
+ profile=_profile(), roundtrips=roundtrips, shadow_pnl=200.0, pool_currency="USD",
+ )
+ assert real_pnl == 100.0
+ assert breakdown.excluded_currencies == {"HKD": 2}
+
+
+def test_no_pool_currency_keeps_legacy_sum() -> None:
+ roundtrips = [_rt("AAPL.US", 100.0, 3.0), _rt("0700.HK", 50.0, 3.0)]
+ _, _, real_pnl = _compute_attribution(
+ profile=_profile(), roundtrips=roundtrips, shadow_pnl=200.0,
+ )
+ assert real_pnl == 150.0
+
+
+def test_short_winner_counts_once_in_early_not_noise() -> None:
+ # hold 1d under the 3d rule with a win: early-exit only.
+ breakdown, _, _ = _compute_attribution(
+ profile=_profile(), roundtrips=[_rt("AAPL.US", 30.0, 1.0)], shadow_pnl=0.0,
+ )
+ assert breakdown.early_exit_pnl == pytest.approx(30.0 * (3 - 1) / 3)
+ assert breakdown.noise_trades_pnl == 0.0
+
+
+def test_long_loser_counts_once_in_late_not_noise() -> None:
+ # hold 5d past the 3d rule with a loss: late-exit only.
+ breakdown, _, _ = _compute_attribution(
+ profile=_profile(), roundtrips=[_rt("AAPL.US", -30.0, 5.0)], shadow_pnl=0.0,
+ )
+ assert breakdown.late_exit_pnl == pytest.approx(30.0 * (5 - 3) / 3)
+ assert breakdown.noise_trades_pnl == 0.0
+
+
+def test_short_loser_is_noise_only() -> None:
+ # hold 1d with a loss: not an early winner, so the whole -pnl is noise.
+ breakdown, _, _ = _compute_attribution(
+ profile=_profile(), roundtrips=[_rt("AAPL.US", -30.0, 1.0)], shadow_pnl=0.0,
+ )
+ assert breakdown.noise_trades_pnl == pytest.approx(30.0)
+ assert breakdown.early_exit_pnl == 0.0
+ assert breakdown.late_exit_pnl == 0.0