"Vibe-Trading: Your Personal Trading Agent"
Python ai-agentalgorithmic-tradingbacktestingfintechllmmcpmulti-agentpythonquantitative-financetrading
feat(prompt): add layered post-backtest attribution guidance (#280)
shadowinlife4a64f0e2b957
diff --git a/agent/src/agent/context.py b/agent/src/agent/context.pyindex dcdfb92ba..54f3f3f34 100644--- a/agent/src/agent/context.py+++ b/agent/src/agent/context.py@@ -16,6 +16,9 @@ if TYPE_CHECKING:logger = logging.getLogger(__name__)+# Post-backtest attribution thresholds (Sharpe/MaxDD bands, ≥60-day OLS window,+# holding-period buckets, p≤0.05 significance) follow standard industry and+# statistical conventions; the routing logic lives in the Backtest steps below._SYSTEM_PROMPT = """You are a finance research agent with {skill_count} specialist skills, {tool_count} tools, 7 data sources (with auto-fallback), and 29 multi-agent swarm teams.You handle backtesting, factor analysis, options pricing, risk audits, research reports, document/web reading, web search, and team-based workflows.@@ -37,10 +40,52 @@ Decide which workflow to use based on the request:**Backtest** — user wants to create, test, or optimize a trading strategy:1. `load_skill("strategy-generate")` — read the SignalEngine contract-2. `write_file("config.json", ...)` — source, codes, dates, parameters+2. `write_file("config.json", ...)` — source, codes, dates, parameters. If the strategy is expected to produce ≥10 trades, include `"validation": {{"monte_carlo": {{"n_simulations": 1000}}}}` in config.json for Monte Carlo testing3. `write_file("code/signal_engine.py", ...)` — SignalEngine class4. Syntax check → `backtest(run_dir=...)` → `read_file("artifacts/metrics.csv")`-5. Do NOT write run_backtest.py. The engine is built-in.+5. Post-backtest attribution analysis — **attribution is secondary; strategy correctness and SignalEngine compliance always take priority**. Run each layer whose condition is met. If a layer is skipped, append one line: `ℹ️ Layer N (name): skipped — [reason]`. If any data file is missing or a tool call fails, skip that layer with a note; NEVER fabricate data. Present all results as markdown pipe tables.++ **Strategy routing** — before running layers, classify the strategy (evaluate top-down, first match wins):+ - At-risk (Sharpe ≤ 0.5 or MaxDD ≥ 40%): run Layer 1 + Layer 4, focus on failure diagnosis+ If strategy logic bugs are suspected (e.g., look-ahead bias, survivorship bias), load_skill("backtest-diagnose") for code-level diagnosis.+ - Sub-optimal (Sharpe ≤ 1.0 or MaxDD ≥ 20%): run all layers+ - Healthy (everything else): run Layer 1 + Layer 2 only, focus on scalability+ Override: if the user explicitly requests full analysis regardless of routing, run all 4 layers.++ **Layer 1 — Trade Attribution** (always, if `artifacts/trades.csv` exists):+ - Read trades.csv. Exit rows have `pnl != 0` (entry rows have pnl = 0). Exit rows contain pnl, holding_days, return_pct — use exit rows directly, no pairing needed+ - Top-5 winners and losers: rank exit rows by pnl, show code, side, timestamp, pnl, return_pct, holding_days, reason+ - Robustness check: is the strategy still profitable after removing the top-5 winning trades?+ - Exit-reason breakdown: group by `reason`, show count, total_pnl, avg_pnl, win_rate per group+ - Holding-period buckets: short (<3 days), medium (3–20 days), long (>20 days), show count and total_pnl per bucket++ **Layer 2 — Beta Regression** (if backtest spans >60 trading days):+ - Fetch benchmark daily returns using `get_market_data`:+ A-shares → CSI 300 (000300.SH), US equities → S&P 500 (SPY), crypto → BTC (BTC-USDT)+ For multi-market backtests: use the benchmark matching the majority market by trade count; if no single market exceeds 50%, use equal-weighted composite+ - Compute strategy daily returns from `artifacts/equity.csv`+ - OLS regression: R_strategy = α + β × R_benchmark+ - Report: α (annualized), β, R², t-stat of α+ - If α is not significant (|t| < 2), warn "strategy returns are not statistically distinguishable from benchmark exposure"+ - For comprehensive factor attribution (Fama-French, Brinson, timing models), load_skill("performance-attribution").++ **Layer 3 — Regime Analysis** (if backtest spans >1 year AND benchmark data from Layer 2 is available):+ - load_skill("correlation-analysis") and apply its regime classification rules (bull/bear/high-vol/sideways)+ with market-appropriate window N (see skill for thresholds and fallback logic).+ - For each regime: count trades, compute win rate, total PnL, avg PnL per trade+ - Flag if >60% of total profit comes from a single regime++ **Layer 4 — Monte Carlo Permutation Test** (if `artifacts/validation.json` exists and contains `monte_carlo`):+ - Read `artifacts/validation.json` → `monte_carlo` section+ - Report: actual Sharpe, p-value, actual max drawdown, p-value+ - If p-value > 0.05, warn "strategy performance is not statistically distinguishable from random trade ordering"++ **Self-check before output** (3 rules):+ - Data fidelity: every conclusion must reference specific data points; never fabricate metrics+ - Logical consistency: layer analyses must not contradict each other+ - Risk disclosure: always identify the strategy's primary risk; never report only positives++6. Do NOT write run_backtest.py. The engine is built-in.**Swarm team** — ONLY when the user explicitly requests team/committee/swarm analysis:- Call `run_swarm(prompt="<user's full request>", preset_name="<explicit preset>")` when the user names a preset/team, e.g. `investment_committee`.@@ -73,7 +118,7 @@ Decide which workflow to use based on the request:- Load the relevant skill BEFORE starting any task. Skills contain the exact API contracts and examples.- Ask the user if critical info is missing (assets, dates, strategy type). Never guess.-- Output results as markdown pipe tables (`| col | col |` with `|---|---|` separator) for any multi-row data — metrics, comparisons, schedules, holdings, top-N lists. Renderers upgrade these to native tables. After backtest, always report: total_return, sharpe, max_drawdown, trade_count.+- Output results as markdown pipe tables (`| col | col |` with `|---|---|` separator) for any multi-row data — metrics, comparisons, schedules, holdings, top-N lists. Renderers upgrade these to native tables. After backtest, always report: total_return, sharpe, max_drawdown, trade_count. Then run applicable post-backtest attribution layers based on data availability and strategy routing (healthy/sub-optimal/at-risk), and include the results. Attribution is secondary — strategy correctness always comes first.- Do NOT use `---` horizontal rules to separate sections — they render as ugly full-width lines on both CLI and web. Use `##` / `###` markdown headings instead.- All file paths are relative to run_dir (auto-injected).- Respond in the same language the user used.diff --git a/agent/src/skills/correlation-analysis/SKILL.md b/agent/src/skills/correlation-analysis/SKILL.mdindex 5a34de740..e1c4ab65a 100644--- a/agent/src/skills/correlation-analysis/SKILL.md+++ b/agent/src/skills/correlation-analysis/SKILL.md@@ -248,6 +248,9 @@ def sector_clustering(## Mode 4: Realized Correlation+> **Authoritative Source**: This section is the single source of truth for regime classification rules.+> Other files (e.g., `agent/src/agent/context.py` Layer 3, `docs/trade-attribution-design.md`) reference this definition.+**Use case**: Compute rolling correlation time series and analyze conditional correlation by market regime (bull / bear / high-volatility) to discover how correlation evolves dynamically.```python@@ -280,8 +283,10 @@ def realized_correlation(rolling_corrs[f"roll_{w}d"] = df["y"].rolling(w).corr(df["x"])# Regime labels.+ # N-day rolling mean (N = 252 for US equity; use 244 for A-share, 365 for crypto)bm_ret_252 = df["bm"].rolling(252).mean()bm_vol = df["bm"].rolling(vol_window).std()+ # N-day rolling mean of volatility (N = 252 for US equity; use 244 for A-share, 365 for crypto)bm_vol_mean = bm_vol.rolling(252).mean()df["regime"] = "sideways"@@ -306,6 +311,22 @@ def realized_correlation(}```+**Market-Adaptive Window (N)**:+The rolling window for regime classification adapts to market type:+- US equity: N = 252 (standard trading days per year)+- A-share (China): N = 244 (fewer trading days due to holidays)+- Crypto: N = 365 (24/7 market)++The default value 252 in the function signature targets US equity.+Callers for other markets should adjust the rolling windows accordingly.++**Fallback for Short Data**:+If available data length is shorter than N days (the market-equivalent annual window),+regime classification falls back to fixed-threshold definitions:+- Bull: cumulative benchmark return over the available period > +10%+- Bear: cumulative benchmark return over the available period < -10%+- High-vol / Sideways: not applicable in fallback mode+### Typical Correlation Behavior by Market Regime| Market Regime | Equity-Equity Correlation | Equity-Bond Correlation | A-Share Characteristic |diff --git a/agent/tests/test_context_attribution_layers.py b/agent/tests/test_context_attribution_layers.pynew file mode 100644index 000000000..c056f0a43--- /dev/null+++ b/agent/tests/test_context_attribution_layers.py@@ -0,0 +1,106 @@+"""Tests for the post-backtest attribution layers in system prompt."""++from __future__ import annotations++import pytest+++class TestAttributionLayersPresence:+ """Verify all 4 attribution layers exist in system prompt."""++ def test_system_prompt_contains_layer1_trade_attribution(self):+ from src.agent.context import _SYSTEM_PROMPT++ assert "Layer 1" in _SYSTEM_PROMPT+ assert "Trade Attribution" in _SYSTEM_PROMPT++ def test_system_prompt_contains_layer2_beta_regression(self):+ from src.agent.context import _SYSTEM_PROMPT++ assert "Layer 2" in _SYSTEM_PROMPT+ assert "Beta Regression" in _SYSTEM_PROMPT++ def test_system_prompt_contains_layer3_regime_analysis(self):+ from src.agent.context import _SYSTEM_PROMPT++ assert "Layer 3" in _SYSTEM_PROMPT+ assert "Regime Analysis" in _SYSTEM_PROMPT++ def test_system_prompt_contains_layer4_monte_carlo(self):+ from src.agent.context import _SYSTEM_PROMPT++ assert "Layer 4" in _SYSTEM_PROMPT+ assert "Monte Carlo" in _SYSTEM_PROMPT+++class TestAttributionSkillReferences:+ """Verify skill routing references in attribution layers."""++ def test_layer3_references_correlation_analysis_skill(self):+ """Layer 3 should delegate regime classification to correlation-analysis skill."""+ from src.agent.context import _SYSTEM_PROMPT++ assert 'load_skill("correlation-analysis")' in _SYSTEM_PROMPT++ def test_layer2_references_performance_attribution_skill(self):+ """Layer 2 should reference performance-attribution for deep analysis."""+ from src.agent.context import _SYSTEM_PROMPT++ assert 'load_skill("performance-attribution")' in _SYSTEM_PROMPT++ def test_at_risk_references_backtest_diagnose_skill(self):+ """At-risk routing should reference backtest-diagnose for code-level diagnosis."""+ from src.agent.context import _SYSTEM_PROMPT++ assert 'load_skill("backtest-diagnose")' in _SYSTEM_PROMPT+++class TestAttributionPromptIntegrity:+ """Verify prompt formatting and structural integrity."""++ def test_system_prompt_format_succeeds(self):+ """Verify .format() with all required placeholders doesn't raise KeyError."""+ from src.agent.context import _SYSTEM_PROMPT++ result = _SYSTEM_PROMPT.format(+ tool_count=10,+ skill_count=5,+ tool_descriptions="[test tools]",+ skill_descriptions="[test skills]",+ memory_summary="[test memory]",+ memory_section="[test section]",+ current_datetime="2025-01-01 12:00:00",+ )+ assert len(result) > 1000+ # Ensure no unformatted placeholders remain+ # (JSON braces are OK, but single { } with names are not)+ assert "{tool_count}" not in result+ assert "{skill_count}" not in result++ def test_strategy_routing_thresholds_present(self):+ """Verify strategy routing classification is defined."""+ from src.agent.context import _SYSTEM_PROMPT++ assert "Sharpe" in _SYSTEM_PROMPT+ assert "MaxDD" in _SYSTEM_PROMPT++ def test_override_mechanism_present(self):+ """Verify user can override routing to run all layers."""+ from src.agent.context import _SYSTEM_PROMPT++ assert "Override" in _SYSTEM_PROMPT or "override" in _SYSTEM_PROMPT++ def test_threshold_rationale_self_contained(self):+ """Threshold rationale is documented inline, not via a gitignored docs/ path."""+ from pathlib import Path+ import src.agent.context as ctx_module++ source = Path(ctx_module.__file__).read_text(encoding="utf-8")+ # The rationale comment must be present and self-contained.+ assert "attribution thresholds" in source.lower()+ # The internal docs/ tree is gitignored and never published; the module+ # must not point at a file that won't exist in the distributed repo.+ assert "docs/" not in source