"Vibe-Trading: Your Personal Trading Agent"
Python ai-agentalgorithmic-tradingbacktestingfintechllmmcpmulti-agentpythonquantitative-financetrading
feat: backtest Wave 2 (multi-asset engines) + Wave 3 (statistical validation)
warren6181e3db39722f8
diff --git a/README.md b/README.mdindex ee0e17e8f..90e3f0c2d 100644--- a/README.md+++ b/README.md@@ -46,8 +46,8 @@## π° News- **2026-04-10** π§ **Performance & multi-provider**: LLM timeout 2400sβ120s, all tuning params configurable via `.env`. Added 11 LLM providers (DeepSeek, Groq, Gemini, Ollama, etc.). Hardened `ml-strategy` skill template with input validation and inf/NaN sanitization.-- **2026-04-09** π§ **Data source expansion**: 5 sources with auto-fallback, `web_search` tool, skill categorization (7 categories).-- **2026-04-08** π§ **Multi-market backtest** with per-market rules; **Pine Script v6 export** for TradingView.+- **2026-04-09** π **Backtest Wave 2 β multi-asset engines**: added ChinaFutures (CFFEX/SHFE/DCE/ZCE, 50+ contracts), GlobalFutures (CME/ICE/Eurex, 30+ contracts), Forex (24 pairs, spread + swap), Options v2 (American exercise, IV smile). Statistical validation: Monte Carlo permutation test, Bootstrap Sharpe CI, Walk-Forward analysis.+- **2026-04-08** π§ **Multi-market backtest** with per-market rules; **Pine Script v6 export** for TradingView. **Data source expansion**: 5 sources with auto-fallback, `web_search` tool, skill categorization (7 categories).- **2026-04-01** π **v0.1.0** β Initial release: ReAct agent, 64 skills, 29 swarm presets, cross-market backtest, CLI + Web UI + MCP server.---@@ -98,8 +98,8 @@ Vibe-Trading is an AI-powered multi-agent finance workspace that turns natural l<img src="https://img.shields.io/badge/5_Data_Sources-FFD93D?style=for-the-badge&logo=bitcoin&logoColor=black" alt="Backtest" /><br><br><div align="left">β’ A-shares, HK/US equities, crypto, futures & forex<br>- β’ Auto-fallback: always finds a working source<br>- β’ Daily & options portfolio engines<br>+ β’ 7 market engines: A-share, US/HK equity, crypto, China futures, global futures, forex<br>+ β’ Statistical validation: Monte Carlo, Bootstrap CI, Walk-Forward<br>β’ 15+ performance metrics & 4 optimizers</div></td>diff --git a/agent/api_server.py b/agent/api_server.pyindex cbe1504a4..c5f612d5f 100644--- a/agent/api_server.py+++ b/agent/api_server.py@@ -111,6 +111,7 @@ class RunResponse(BaseModel):artifacts_equity_csv: Optional[List[Dict[str, Any]]] = Field(None, description="Full equity rows")artifacts_metrics_csv: Optional[List[Dict[str, Any]]] = Field(None, description="Full metrics rows")artifacts_trades_csv: Optional[List[Dict[str, Any]]] = Field(None, description="Full trade rows")+ validation: Optional[Dict[str, Any]] = Field(None, description="Statistical validation results")run_directory: str = Field(..., description="Run directory path")run_stage: Optional[str] = Field(None, description="UI-facing run stage")@@ -342,6 +343,13 @@ def _build_response_from_run_dir(run_dir: Path, elapsed: float, *, include_analyif trades_path.exists():response.artifacts_trades_csv = _load_csv_to_dict(trades_path)+ validation_path = run_dir / "artifacts" / "validation.json"+ if validation_path.exists():+ try:+ response.validation = json.loads(validation_path.read_text(encoding="utf-8"))+ except (json.JSONDecodeError, OSError):+ pass+if response.artifacts_equity_csv:filtered_equity = []for row in response.artifacts_equity_csv[:1000]:diff --git a/agent/backtest/engines/__init__.py b/agent/backtest/engines/__init__.pyindex da2c0c32c..1ed9bad77 100644--- a/agent/backtest/engines/__init__.py+++ b/agent/backtest/engines/__init__.py@@ -1,8 +1,25 @@"""Backtest engines.-- BaseEngine: ABC for bar-by-bar execution with market rules-- ChinaAEngine: A-share (T+1, no short, price limits)-- GlobalEquityEngine: US / HK equities-- CryptoEngine: Crypto perpetuals (funding fees, liquidation)-- options_portfolio: European options (Black-Scholes)+Wave 1 (v1):+ - BaseEngine: ABC for bar-by-bar execution with market rules+ - ChinaAEngine: A-share (T+1, no short, price limits)+ - GlobalEquityEngine: US / HK equities+ - CryptoEngine: Crypto perpetuals (funding fees, liquidation)+ - options_portfolio: European/American options (Black-Scholes, v2 with IV smile)++Wave 2:+ - FuturesBaseEngine: intermediate layer adding contract-multiplier logic+ - ChinaFuturesEngine: China commodity/financial futures (CFFEX/SHFE/DCE/ZCE/INE)+ - GlobalFuturesEngine: International futures (CME/ICE/Eurex)+ - ForexEngine: FX spot/CFD (spread, swap, high leverage)++Inheritance:+ BaseEngine+ βββ ChinaAEngine+ βββ GlobalEquityEngine+ βββ CryptoEngine+ βββ ForexEngine+ βββ FuturesBaseEngine+ βββ ChinaFuturesEngine+ βββ GlobalFuturesEngine"""diff --git a/agent/backtest/engines/base.py b/agent/backtest/engines/base.pyindex ea37945a4..92127d75d 100644--- a/agent/backtest/engines/base.py+++ b/agent/backtest/engines/base.py@@ -119,6 +119,7 @@ class BaseEngine(ABC):self.trades: List[TradeRecord] = []self.equity_snapshots: List[EquitySnapshot] = []self._bar_idx: int = 0+ self._active_symbol: str = "" # set by _rebalance/_close_position for subclass use# ββ Market rule interface (subclass must implement) ββ@@ -179,6 +180,28 @@ class BaseEngine(ABC):Default: no-op. Override in subclass as needed."""+ # ββ PnL / margin calculation hooks ββ+ # Override in FuturesBaseEngine to inject contract multiplier.++ def _calc_pnl(+ self, symbol: str, direction: int, size: float,+ entry_price: float, exit_price: float,+ ) -> float:+ """Realised PnL for a closed position."""+ return direction * size * (exit_price - entry_price)++ def _calc_margin(+ self, symbol: str, size: float, price: float, leverage: float,+ ) -> float:+ """Margin (collateral) required for a position."""+ return size * price / leverage++ def _calc_raw_size(+ self, symbol: str, target_notional: float, price: float,+ ) -> float:+ """Convert target notional exposure to number of units/contracts."""+ return target_notional / price+# ββ Main entry ββdef run_backtest(@@ -248,7 +271,18 @@ class BaseEngine(ABC):m["by_symbol"] = by_symbol_stats(self.trades)m["by_exit_reason"] = by_exit_reason_stats(self.trades)- # 7. Artifacts+ # 7. Validation (optional β triggered by config["validation"])+ if config.get("validation"):+ from backtest.validation import run_validation+ v_results = run_validation(+ config, equity_series, self.trades, self.initial_capital, bars_per_year,+ )+ m["validation"] = v_results+ # Write validation.json artifact+ v_path = run_dir / "artifacts" / "validation.json"+ v_path.write_text(json.dumps(v_results, indent=2, ensure_ascii=False), encoding="utf-8")++ # 8. Artifactsself._write_artifacts(run_dir, data_map, dates, equity_series, bench_equity, bench_ret,target_pos, m, valid_codes,@@ -288,7 +322,7 @@ class BaseEngine(ABC):total_unrealized = 0.0for p in self.positions.values():cp = self._safe_price(close_df, ts, p.symbol, p.entry_price)- total_unrealized += p.direction * p.size * (cp - p.entry_price)+ total_unrealized += self._calc_pnl(p.symbol, p.direction, p.size, p.entry_price, cp)self.equity_snapshots.append(EquitySnapshot(timestamp=ts,capital=self.capital,@@ -309,8 +343,8 @@ class BaseEngine(ABC):equity = self.capitalfor sym, pos in self.positions.items():cp = self._safe_price(close_df, ts, sym, pos.entry_price)- margin = pos.size * pos.entry_price / pos.leverage- unrealized = pos.direction * pos.size * (cp - pos.entry_price)+ margin = self._calc_margin(sym, pos.size, pos.entry_price, pos.leverage)+ unrealized = self._calc_pnl(sym, pos.direction, pos.size, pos.entry_price, cp)equity += margin + unrealizedreturn equity@@ -323,6 +357,7 @@ class BaseEngine(ABC):equity: float,) -> None:"""Adjust position for *symbol* toward *target_weight*."""+ self._active_symbol = symboltarget_dir = 1 if target_weight > 1e-9 else (-1 if target_weight < -1e-9 else 0)current_pos = self.positions.get(symbol)@@ -357,12 +392,12 @@ class BaseEngine(ABC):slipped = self.apply_slippage(open_price, target_dir)leverage = self.default_leveragetarget_notional = abs(target_weight) * equity * leverage- raw_size = target_notional / slipped+ raw_size = self._calc_raw_size(symbol, target_notional, slipped)size = self.round_size(raw_size, slipped)if size <= 0:return- margin = size * slipped / leverage+ margin = self._calc_margin(symbol, size, slipped, leverage)comm = self.calc_commission(size, slipped, target_dir, is_open=True)# Capital check β reduce if insufficient@@ -370,10 +405,12 @@ class BaseEngine(ABC):available = self.capital - commif available <= 0:return- size = self.round_size(available * leverage / slipped, slipped)+ size = self.round_size(+ self._calc_raw_size(symbol, available * leverage, slipped), slipped,+ )if size <= 0:return- margin = size * slipped / leverage+ margin = self._calc_margin(symbol, size, slipped, leverage)comm = self.calc_commission(size, slipped, target_dir, is_open=True)self.capital -= (margin + comm)@@ -396,12 +433,13 @@ class BaseEngine(ABC):reason: str,) -> None:"""Close position, record trade, return capital."""+ self._active_symbol = symbolpos = self.positions.pop(symbol, None)if pos is None:return- pnl = pos.direction * pos.size * (exit_price - pos.entry_price)- margin = pos.size * pos.entry_price / pos.leverage+ pnl = self._calc_pnl(symbol, pos.direction, pos.size, pos.entry_price, exit_price)+ margin = self._calc_margin(symbol, pos.size, pos.entry_price, pos.leverage)pnl_pct = pnl / margin * 100 if margin > 1e-9 else 0.0exit_comm = self.calc_commission(pos.size, exit_price, pos.direction, is_open=False)diff --git a/agent/backtest/engines/china_futures.py b/agent/backtest/engines/china_futures.pynew file mode 100644index 000000000..43b300246--- /dev/null+++ b/agent/backtest/engines/china_futures.py@@ -0,0 +1,269 @@+"""China futures backtest engine.++Market rules (exchange-level, CFFEX / SHFE / DCE / ZCE / INE / GFEX):+ - T+0: can open and close same day (intraday trading allowed)+ - Margin trading: 5%~15% by product (exchange-set minimum)+ - Price limits: stock-index +-10%, bonds +-2%, commodities +-3%~8%+ - Commission: per-lot fixed or per-notional rate (varies by product)+ - Contract multiplier: product-specific (IF=300, rb=10, au=1000, ...)+ - Minimum trading unit: 1 contract+ - Night session: 21:00-02:30 (varies by product, not enforced in bar-level sim)+"""++from __future__ import annotations++import re++import pandas as pd++from backtest.engines.futures_base import FuturesBaseEngine+++# ββ Contract multiplier lookup ββ++_MULTIPLIER: dict[str, int] = {+ # Stock index futures (CFFEX)+ "IF": 300, "IC": 200, "IH": 300, "IM": 200,+ # Treasury bond futures (CFFEX)+ "T": 10000, "TF": 10000, "TS": 20000, "TL": 10000,+ # Metals (SHFE)+ "au": 1000, "ag": 15, "cu": 5, "al": 5, "zn": 5,+ "pb": 5, "ni": 1, "sn": 1, "ss": 5,+ # Ferrous (SHFE / DCE)+ "rb": 10, "hc": 10, "i": 100, "j": 100, "jm": 60,+ # Energy (SHFE / INE)+ "sc": 1000, "fu": 10, "lu": 10, "bu": 10, "nr": 10,+ # Agriculture (DCE)+ "c": 10, "cs": 10, "m": 10, "y": 10, "a": 10,+ "p": 10, "jd": 10, "lh": 16, "rr": 10, "pg": 20,+ # Agriculture (ZCE)+ "CF": 5, "SR": 10, "TA": 5, "MA": 10, "AP": 10,+ "RM": 10, "OI": 10, "CJ": 5, "PK": 5, "CY": 5,+ # Chemical (DCE / ZCE)+ "pp": 5, "l": 5, "v": 5, "eg": 10, "eb": 5,+ "PF": 5, "SA": 20, "FG": 20, "UR": 20,+ # GFEX+ "si": 5, "lc": 1,+}++# ββ Margin rate (exchange minimum) ββ++_MARGIN_RATE: dict[str, float] = {+ # CFFEX stock index+ "IF": 0.12, "IC": 0.12, "IH": 0.12, "IM": 0.12,+ # CFFEX bonds+ "T": 0.03, "TF": 0.02, "TS": 0.015, "TL": 0.035,+ # SHFE metals+ "au": 0.08, "ag": 0.09, "cu": 0.08, "al": 0.07,+ "zn": 0.08, "pb": 0.08, "ni": 0.12, "sn": 0.10, "ss": 0.08,+ # Ferrous+ "rb": 0.10, "hc": 0.10, "i": 0.12, "j": 0.12, "jm": 0.12,+ # Energy+ "sc": 0.10, "fu": 0.10, "lu": 0.10, "bu": 0.10,+ # Agriculture+ "c": 0.07, "cs": 0.07, "m": 0.08, "y": 0.08, "a": 0.08,+ "p": 0.08, "jd": 0.08, "lh": 0.12,+ # Textiles / chemical+ "CF": 0.07, "SR": 0.07, "TA": 0.07, "MA": 0.07,+ "pp": 0.07, "l": 0.07, "v": 0.07, "eg": 0.08,+ "SA": 0.08, "FG": 0.08, "UR": 0.08,+}++# ββ Price limit (fraction, Β± from settlement) ββ++_PRICE_LIMIT: dict[str, float] = {+ # CFFEX stock index Β±10%+ "IF": 0.10, "IC": 0.10, "IH": 0.10, "IM": 0.10,+ # CFFEX bonds Β±2% (simplified)+ "T": 0.02, "TF": 0.012, "TS": 0.005, "TL": 0.035,+}+_DEFAULT_PRICE_LIMIT = 0.05 # most commodities Β±4%~7%, use 5% as default++# ββ Commission structure ββ+# ("rate", pct) = per-notional | ("fixed", amount_per_lot) = per-contract++_COMMISSION: dict[str, tuple[str, float]] = {+ # CFFEX stock index: ~0.0023% of notional+ "IF": ("rate", 0.000023), "IC": ("rate", 0.000023),+ "IH": ("rate", 0.000023), "IM": ("rate", 0.000023),+ # CFFEX bonds+ "T": ("fixed", 3.0), "TF": ("fixed", 3.0), "TS": ("fixed", 3.0),+ # Metals+ "au": ("fixed", 10.0), "ag": ("fixed", 3.0), "cu": ("fixed", 5.0),+ "al": ("fixed", 3.0), "zn": ("fixed", 3.0), "ni": ("fixed", 3.0),+ # Ferrous+ "rb": ("rate", 0.0001), "hc": ("rate", 0.0001), "i": ("rate", 0.0001),+ "j": ("rate", 0.0001), "jm": ("rate", 0.0001),+ # Energy+ "sc": ("fixed", 20.0), "fu": ("rate", 0.00005),+ # Agriculture+ "c": ("fixed", 1.2), "cs": ("fixed", 1.5), "m": ("fixed", 1.5),+ "y": ("fixed", 2.5), "a": ("fixed", 2.0), "p": ("fixed", 2.5),+ "jd": ("rate", 0.00015), "lh": ("rate", 0.0002),+ # Textiles / chemical+ "CF": ("fixed", 4.3), "SR": ("fixed", 3.0), "TA": ("fixed", 3.0),+ "MA": ("fixed", 2.0), "pp": ("fixed", 1.0), "l": ("fixed", 1.0),+ "v": ("fixed", 1.0), "SA": ("fixed", 3.5), "FG": ("fixed", 3.0),+}+_DEFAULT_COMMISSION: tuple[str, float] = ("fixed", 5.0)+++def _extract_product(symbol: str) -> str:+ """Extract product code from futures symbol.++ Examples:+ 'IF2406.CFFEX' -> 'IF'+ 'rb2410.SHFE' -> 'rb'+ 'au2412' -> 'au'++ Args:+ symbol: Futures symbol string.++ Returns:+ Product code (e.g. 'IF', 'rb', 'au').+ """+ code = symbol.split(".")[0]+ m = re.match(r"([A-Za-z]+)", code)+ return m.group(1) if m else code+++class ChinaFuturesEngine(FuturesBaseEngine):+ """China futures engine covering CFFEX / SHFE / DCE / ZCE / INE / GFEX.++ Config keys:+ - slippage: default 0.0005+ - margin_rate_override: override margin rate for all products+ - commission_override: override commission for all products+ """++ def __init__(self, config: dict):+ # Derive leverage from margin rate of first code, or use config override+ margin_override = config.get("margin_rate_override")+ if margin_override:+ leverage = 1.0 / margin_override+ else:+ codes = config.get("codes", [])+ if codes:+ product = _extract_product(codes[0])+ mr = _MARGIN_RATE.get(product, 0.10)+ leverage = 1.0 / mr+ else:+ leverage = 10.0 # ~10% margin default+ config = {**config, "leverage": leverage}+ super().__init__(config)+ self.slippage_rate: float = config.get("slippage", 0.0005)+ self._commission_override = config.get("commission_override")++ def can_execute(self, symbol: str, direction: int, bar: pd.Series) -> bool:+ """China futures: T+0, both directions, price-limit enforced.++ Args:+ symbol: Futures code.+ direction: 1 (long), -1 (short), 0 (close).+ bar: Current bar data.++ Returns:+ True if allowed.+ """+ # T+0: no same-day sell restriction+ # Both long and short allowed++ # Price limit check+ pct_chg = _calc_pct_change(bar)+ if pct_chg is not None:+ product = _extract_product(symbol)+ limit = _PRICE_LIMIT.get(product, _DEFAULT_PRICE_LIMIT)+ if direction == 1 and pct_chg >= limit - 0.001:+ return False # limit-up: can't open long / can't buy+ if direction == -1 and pct_chg <= -limit + 0.001:+ return False # limit-down: can't open short+ if direction == 0:+ pos = self.positions.get(symbol)+ if pos is not None:+ # Can't close long at limit-down, can't close short at limit-up+ if pos.direction == 1 and pct_chg <= -limit + 0.001:+ return False+ if pos.direction == -1 and pct_chg >= limit - 0.001:+ return False+ return True++ def round_size(self, raw_size: float, price: float) -> float:+ """Minimum 1 contract, integer lots only."""+ return max(int(raw_size), 0)++ def calc_commission(self, size: float, price: float, direction: int, is_open: bool) -> float:+ """Commission varies by product: fixed per-lot or percentage of notional."""+ if self._commission_override is not None:+ return size * price * self._commission_override+ return self.calc_commission_for_symbol(self._active_symbol, size, price, is_open)++ def calc_commission_for_symbol(+ self, symbol: str, size: float, price: float, is_open: bool,+ ) -> float:+ """Symbol-aware commission calculation.++ Args:+ symbol: Futures code.+ size: Number of contracts.+ price: Execution price.+ is_open: True for opening trade.++ Returns:+ Commission in RMB.+ """+ product = _extract_product(symbol)+ mode, value = _COMMISSION.get(product, _DEFAULT_COMMISSION)+ cm = _MULTIPLIER.get(product, 10)+ if mode == "rate":+ return size * price * cm * value+ return size * value++ def apply_slippage(self, price: float, direction: int) -> float:+ """Futures slippage."""+ return price * (1 + direction * self.slippage_rate)++ def get_contract_multiplier(self, symbol: str) -> float:+ """Look up contract multiplier from product code."""+ product = _extract_product(symbol)+ return float(_MULTIPLIER.get(product, 10))++ def get_margin_rate(self, symbol: str) -> float:+ """Look up exchange margin rate for a product.++ Args:+ symbol: Futures symbol.++ Returns:+ Margin rate (e.g. 0.10 for 10%).+ """+ product = _extract_product(symbol)+ return _MARGIN_RATE.get(product, 0.10)+++# ββ Helpers ββ+++def _calc_pct_change(bar: pd.Series):+ """Calculate bar price change percentage.++ Priority: settle/pre_settle (futures native) > close/pre_close > pct_chg.+ pct_chg from tushare is always in percentage points (0.5 = 0.5%).+ """+ # Prefer settlement prices (unambiguous for futures)+ settle = bar.get("settle")+ pre_settle = bar.get("pre_settle")+ if settle is not None and pre_settle is not None and pre_settle > 0:+ return (float(settle) - float(pre_settle)) / float(pre_settle)++ close = bar.get("close")+ pre_close = bar.get("pre_close")+ if close is not None and pre_close is not None and pre_close > 0:+ return (float(close) - float(pre_close)) / float(pre_close)++ # tushare pct_chg is in percentage points (e.g. 0.5 = 0.5%)+ if "pct_chg" in bar.index:+ val = bar["pct_chg"]+ if pd.notna(val):+ return float(val) / 100.0++ return Nonediff --git a/agent/backtest/engines/crypto.py b/agent/backtest/engines/crypto.pyindex f3c87bd1d..b2c4cb0bc 100644--- a/agent/backtest/engines/crypto.py+++ b/agent/backtest/engines/crypto.py@@ -48,7 +48,8 @@ class CryptoEngine(BaseEngine):self.taker_rate: float = config.get("taker_rate", 0.0005)self.slippage_rate: float = config.get("slippage", 0.0005)self.funding_rate: float = config.get("funding_rate", 0.0001)- self._last_funding_hour: int = -1+ self._funding_applied: set = set() # (symbol, date, hour) β per-slot dedup+ self._funding_daily_done: set = set() # (symbol, date) β daily fallback dedupdef can_execute(self, symbol: str, direction: int, bar: pd.Series) -> bool:"""Crypto: 24/7, long/short/close all allowed."""@@ -80,16 +81,29 @@ class CryptoEngine(BaseEngine):"""Deduct/credit funding fee at settlement hours.Positive rate: longs pay shorts. Negative rate: shorts pay longs.++ For intraday bars: applies at each 8h settlement (0/8/16 UTC).+ For daily bars: applies once per calendar day regardless of hour.+ Dedup is per-(symbol, date, hour) so multi-symbol portfolios work."""- if not hasattr(timestamp, "hour"):- return- hour = timestamp.hour- if hour not in _FUNDING_HOURS:+ if not hasattr(timestamp, "date"):return- # Avoid double-settlement on same hour- if hour == self._last_funding_hour:- return- self._last_funding_hour = hour++ current_date = timestamp.date()+ hour = timestamp.hour if hasattr(timestamp, "hour") else 0++ if hour in _FUNDING_HOURS:+ key = (symbol, current_date, hour)+ if key in self._funding_applied:+ return+ self._funding_applied.add(key)+ else:+ # Non-settlement hour (e.g. daily bar at 12:00 UTC)+ # Apply once per day as approximation+ day_key = (symbol, current_date)+ if day_key in self._funding_daily_done:+ return+ self._funding_daily_done.add(day_key)pos = self.positions.get(symbol)if pos is None:@@ -97,7 +111,7 @@ class CryptoEngine(BaseEngine):mark_price = float(bar.get("close", pos.entry_price))notional = pos.size * mark_price- fee = notional * self.funding_rate * pos.direction # long pays when rate > 0+ fee = notional * self.funding_rate * pos.directionself.capital -= fee# ββ Liquidation (exchange-enforced) ββdiff --git a/agent/backtest/engines/forex.py b/agent/backtest/engines/forex.pynew file mode 100644index 000000000..0e9bd7ff3--- /dev/null+++ b/agent/backtest/engines/forex.py@@ -0,0 +1,189 @@+"""Forex (FX spot / CFD) backtest engine.++Market rules:+ - 24x5 (Mon Sydney open to Fri NYC close)+ - Spread replaces explicit commission (bid-ask)+ - Leverage: 50:1 to 500:1 (configurable)+ - Standard lot = 100,000 units of base currency+ - Swap (overnight rollover interest) at daily close+ - No price limits, no restrictions on direction+ - PnL in quote currency (converted via exit price for cross pairs)+"""++from __future__ import annotations++import pandas as pd++from backtest.engines.base import BaseEngine+++# ββ Typical spreads in pips (1 pip = 0.0001 for most pairs, 0.01 for JPY) ββ++_SPREAD_PIPS: dict[str, float] = {+ # Majors+ "EUR/USD": 1.0, "GBP/USD": 1.2, "USD/JPY": 1.0, "USD/CHF": 1.3,+ "AUD/USD": 1.2, "USD/CAD": 1.5, "NZD/USD": 1.5,+ # Crosses+ "EUR/GBP": 1.5, "EUR/JPY": 1.5, "GBP/JPY": 2.5, "EUR/CHF": 1.8,+ "AUD/JPY": 2.0, "CHF/JPY": 2.5, "EUR/AUD": 2.0, "GBP/AUD": 3.0,+ "EUR/CAD": 2.5, "GBP/CAD": 3.5, "AUD/CAD": 2.5, "NZD/JPY": 2.5,+ # Exotics (wider spreads)+ "USD/TRY": 15.0, "USD/ZAR": 10.0, "USD/MXN": 8.0,+ "USD/SGD": 3.0, "USD/HKD": 3.0, "USD/CNH": 5.0,+}+_DEFAULT_SPREAD_PIPS = 2.0++# ββ Daily swap points (per standard lot, in account currency) ββ+# Positive = receive, negative = pay. Varies by broker/rates; simplified table.++_SWAP_LONG: dict[str, float] = {+ "EUR/USD": -6.5, "GBP/USD": -3.0, "USD/JPY": 8.0, "USD/CHF": 4.0,+ "AUD/USD": -2.0, "USD/CAD": 2.0, "NZD/USD": -1.5,+}+_SWAP_SHORT: dict[str, float] = {+ "EUR/USD": 3.5, "GBP/USD": -1.0, "USD/JPY": -12.0, "USD/CHF": -8.0,+ "AUD/USD": -1.0, "USD/CAD": -5.0, "NZD/USD": -2.0,+}++# Standard lot size+STANDARD_LOT = 100_000+++def _pip_value(symbol: str) -> float:+ """Size of 1 pip for the pair.++ Args:+ symbol: Forex pair (e.g. 'EUR/USD', 'USD/JPY').++ Returns:+ 1 pip in price terms (0.0001 or 0.01 for JPY pairs).+ """+ quote = symbol.split("/")[1] if "/" in symbol else symbol[3:6]+ return 0.01 if quote.upper() == "JPY" else 0.0001+++def _normalize_symbol(symbol: str) -> str:+ """Normalize forex symbol to 'XXX/YYY' format.++ Args:+ symbol: Raw symbol (e.g. 'EURUSD.FX', 'EUR/USD', 'EURUSD').++ Returns:+ Normalized pair (e.g. 'EUR/USD').+ """+ s = symbol.replace(".FX", "").replace(".", "").strip()+ if "/" in s:+ return s.upper()+ if len(s) == 6:+ return f"{s[:3]}/{s[3:]}".upper()+ return s.upper()+++class ForexEngine(BaseEngine):+ """Forex engine for spot / CFD pairs.++ Config keys:+ - leverage: default 100.0 (100:1)+ - spread_pips_override: override spread for all pairs+ - lot_size: default 100000 (standard lot)+ - swap_enabled: default True+ - slippage_pips: additional slippage beyond spread, default 0.3+ """++ def __init__(self, config: dict):+ config = {**config, "leverage": config.get("leverage", 100.0)}+ super().__init__(config)+ self.spread_override = config.get("spread_pips_override")+ self.lot_size: float = config.get("lot_size", STANDARD_LOT)+ self.swap_enabled: bool = config.get("swap_enabled", True)+ self.slippage_pips: float = config.get("slippage_pips", 0.3)+ self._last_swap_dates: dict = {} # per-symbol swap tracking++ def can_execute(self, symbol: str, direction: int, bar: pd.Series) -> bool:+ """Forex: 24x5, no restrictions."""+ return True++ def round_size(self, raw_size: float, price: float) -> float:+ """Round to micro-lot granularity (0.01 lots = 1000 units).++ Position size is in currency units (not lots) for PnL compatibility.+ Round to nearest 1000 units (micro lot).+ """+ return max(int(raw_size / 1000) * 1000, 0)++ def calc_commission(self, size: float, price: float, direction: int, is_open: bool) -> float:+ """Forex: spread is the cost, embedded in slippage. No explicit commission.++ Some ECN brokers charge per-lot commission; for simplicity, zero here.+ The cost is captured via apply_slippage (half-spread applied to execution).+ """+ return 0.0++ def apply_slippage(self, price: float, direction: int) -> float:+ """Apply half-spread + slippage using _active_symbol for correct pip/spread."""+ return self.apply_slippage_for_symbol(self._active_symbol, price, direction)++ def apply_slippage_for_symbol(self, symbol: str, price: float, direction: int) -> float:+ """Symbol-aware slippage with correct spread.++ Args:+ symbol: Forex pair.+ price: Mid price.+ direction: 1 (buy) or -1 (sell).++ Returns:+ Slipped price.+ """+ pair = _normalize_symbol(symbol)+ pip = _pip_value(pair)++ if self.spread_override is not None:+ spread_pips = self.spread_override+ else:+ spread_pips = _SPREAD_PIPS.get(pair, _DEFAULT_SPREAD_PIPS)++ total_pips = (spread_pips / 2) + self.slippage_pips+ return price + direction * total_pips * pip++ def on_bar(self, symbol: str, bar: pd.Series, timestamp: pd.Timestamp) -> None:+ """Apply daily swap/rollover at end of trading day."""+ if not self.swap_enabled:+ return+ self._apply_swap(symbol, timestamp)++ def get_contract_multiplier(self, symbol: str) -> float:+ """Forex: multiplier is 1.0 (size is in currency units)."""+ return 1.0++ # ββ Swap (overnight rollover) ββ++ def _apply_swap(self, symbol: str, timestamp: pd.Timestamp) -> None:+ """Deduct/credit swap at daily rollover (once per calendar day).++ Triple swap on Wednesday (covers weekend).+ """+ if not hasattr(timestamp, "date"):+ return++ current_date = timestamp.date()+ if self._last_swap_dates.get(symbol) == current_date:+ return+ self._last_swap_dates[symbol] = current_date++ pos = self.positions.get(symbol)+ if pos is None:+ return++ pair = _normalize_symbol(symbol)+ lots = pos.size / self.lot_size++ if pos.direction == 1:+ swap_per_lot = _SWAP_LONG.get(pair, -1.0)+ else:+ swap_per_lot = _SWAP_SHORT.get(pair, -1.0)++ # Wednesday = triple swap (covers Sat+Sun)+ multiplier = 3.0 if timestamp.weekday() == 2 else 1.0+ swap = lots * swap_per_lot * multiplier++ self.capital += swapdiff --git a/agent/backtest/engines/futures_base.py b/agent/backtest/engines/futures_base.pynew file mode 100644index 000000000..8370653dd--- /dev/null+++ b/agent/backtest/engines/futures_base.py@@ -0,0 +1,56 @@+"""Base class for all futures engines.++Adds contract-multiplier awareness on top of BaseEngine.+Only futures engines inherit from this; stocks/crypto/forex use BaseEngine directly.++The multiplier affects:+ - PnL: direction * size * multiplier * (exit - entry)+ - Margin: size * price * multiplier / leverage+ - Position sizing: target_notional / (price * multiplier)+"""++from __future__ import annotations++from abc import abstractmethod++from backtest.engines.base import BaseEngine+++class FuturesBaseEngine(BaseEngine):+ """BaseEngine with contract-multiplier support.++ Subclasses must implement ``get_contract_multiplier(symbol)``+ in addition to the standard market-rule methods.+ """++ @abstractmethod+ def get_contract_multiplier(self, symbol: str) -> float:+ """Contract multiplier for the instrument.++ Args:+ symbol: Futures symbol (e.g. 'IF2406.CFFEX', 'ESZ4').++ Returns:+ Points-to-currency multiplier (e.g. IF=300, ES=50).+ """++ # ββ Override PnL / margin / sizing to include multiplier ββ++ def _calc_pnl(+ self, symbol: str, direction: int, size: float,+ entry_price: float, exit_price: float,+ ) -> float:+ cm = self.get_contract_multiplier(symbol)+ return direction * size * cm * (exit_price - entry_price)++ def _calc_margin(+ self, symbol: str, size: float, price: float, leverage: float,+ ) -> float:+ cm = self.get_contract_multiplier(symbol)+ return size * price * cm / leverage++ def _calc_raw_size(+ self, symbol: str, target_notional: float, price: float,+ ) -> float:+ cm = self.get_contract_multiplier(symbol)+ return target_notional / (price * cm)diff --git a/agent/backtest/engines/global_futures.py b/agent/backtest/engines/global_futures.pynew file mode 100644index 000000000..059a66f07--- /dev/null+++ b/agent/backtest/engines/global_futures.py@@ -0,0 +1,241 @@+"""Global futures backtest engine (CME / ICE / Eurex).++Market rules:+ - Nearly 24x5 (CME Globex: Sun 17:00 - Fri 16:00 CT, daily pause 16:00-17:00)+ - Margin: initial + maintenance (exchange-set per contract)+ - Limit up/down: dynamic for equity index, fixed for commodities+ - Contract multiplier: per-product (ES=$50/pt, CL=$1000/bbl, GC=$100/oz)+ - Commission: per-contract ($1-3 per side typical)+ - Minimum unit: 1 contract+ - Roll/expiry: not modeled (assumes continuous front-month data)+"""++from __future__ import annotations++import re++import pandas as pd++from backtest.engines.futures_base import FuturesBaseEngine+++# ββ Contract multiplier (USD per point / per unit) ββ++_MULTIPLIER: dict[str, float] = {+ # Equity index (CME)+ "ES": 50, "NQ": 20, "YM": 5, "RTY": 50,+ # Micro equity index+ "MES": 5, "MNQ": 2, "MYM": 0.5, "M2K": 5,+ # Energy (NYMEX)+ "CL": 1000, "NG": 10000, "RB": 42000, "HO": 42000,+ # Metals (COMEX)+ "GC": 100, "SI": 5000, "HG": 25000, "PL": 50, "PA": 100,+ # Micro metals+ "MGC": 10, "SIL": 1000,+ # Grains (CBOT)+ "ZC": 50, "ZS": 50, "ZW": 50, "ZM": 100, "ZL": 600,+ # Bonds (CBOT)+ "ZB": 1000, "ZN": 1000, "ZF": 1000, "ZT": 2000,+ # Currencies (CME)+ "6E": 125000, "6J": 12500000, "6B": 62500, "6A": 100000, "6C": 100000,+ # Softs (ICE)+ "KC": 37500, "SB": 112000, "CC": 10, "CT": 50000,+ # Livestock (CME)+ "LE": 400, "HE": 400, "GF": 500,+ # Eurex+ "FESX": 10, "FDAX": 25, "FGBL": 1000,+}++# ββ Margin per contract (approximate USD, initial margin) ββ++_MARGIN_PER_CONTRACT: dict[str, float] = {+ # Equity index+ "ES": 12650, "NQ": 17600, "YM": 8800, "RTY": 6600,+ "MES": 1265, "MNQ": 1760,+ # Energy+ "CL": 6270, "NG": 3300,+ # Metals+ "GC": 9950, "SI": 11000, "HG": 4400, "PL": 3300,+ "MGC": 995,+ # Grains+ "ZC": 1650, "ZS": 2200, "ZW": 1925,+ # Bonds+ "ZB": 4400, "ZN": 2200, "ZF": 1375,+ # Currencies+ "6E": 2475, "6J": 3300, "6B": 2750,+}++# ββ Price limit (fraction of prev settlement) ββ++_PRICE_LIMIT: dict[str, float] = {+ # Equity index: 7% (Level 1), simplified to single level+ "ES": 0.07, "NQ": 0.07, "YM": 0.07, "RTY": 0.07,+ "MES": 0.07, "MNQ": 0.07,+ # Energy: varies, typically ~$10-15 for CL+ # Not easily expressed as %, skip for most commodities+}++# ββ Per-contract commission (USD, one side) ββ++_COMMISSION_PER_CONTRACT: dict[str, float] = {+ "ES": 2.25, "NQ": 2.25, "YM": 2.25, "RTY": 2.25,+ "MES": 0.62, "MNQ": 0.62,+ "CL": 2.25, "NG": 2.25,+ "GC": 2.25, "SI": 2.25, "HG": 2.25,+ "MGC": 0.62,+ "ZC": 2.25, "ZS": 2.25, "ZW": 2.25,+ "ZB": 1.52, "ZN": 1.52, "ZF": 1.02,+ "6E": 2.25, "6J": 2.25, "6B": 2.25,+}+_DEFAULT_COMMISSION = 2.50+++_MONTH_CODES = set("FGHJKMNQUVXZ")+++def _extract_product(symbol: str) -> str:+ """Extract product code from futures symbol.++ Handles CME conventions:+ - Product + month-code + year: ESZ4, CLF25, GCM2025+ - Product + YYMM: CL2412, NQ2503+ - Product.exchange: ES.CME+ - Bare product: ES++ Args:+ symbol: Futures symbol string.++ Returns:+ Product code (e.g. 'ES', 'CL', 'GC').+ """+ code = symbol.split(".")[0].upper()++ # Pattern 1: product + month-code + year (ESZ4, CLF25, GCM2025)+ m = re.match(r"([A-Z]{2,4})([FGHJKMNQUVXZ])(\d{1,4})$", code)+ if m:+ return m.group(1)++ # Pattern 2: product + YYMM (NQ2503, CL2412)+ m = re.match(r"([A-Z]+)(\d{4})$", code)+ if m:+ return m.group(1)++ # Pattern 3: bare product or fallback+ m = re.match(r"([A-Z]+)", code)+ return m.group(1) if m else code+++class GlobalFuturesEngine(FuturesBaseEngine):+ """International futures engine (CME/CBOT/NYMEX/COMEX/ICE/Eurex).++ Config keys:+ - slippage: default 0.0003+ - commission_per_contract: override, default varies by product+ """++ def __init__(self, config: dict):+ # Leverage: most futures have 5-15% margin β 7-20x leverage.+ # Price is unknown at init, so use a reasonable fixed default.+ # User can override via config["leverage"].+ leverage = config.get("leverage", 10.0)+ config = {**config, "leverage": leverage}+ super().__init__(config)+ self.slippage_rate: float = config.get("slippage", 0.0003)+ self._comm_override = config.get("commission_per_contract")++ def can_execute(self, symbol: str, direction: int, bar: pd.Series) -> bool:+ """Global futures: T+0, both directions, limit checks for equity index.++ Args:+ symbol: Futures symbol.+ direction: 1 (long), -1 (short), 0 (close).+ bar: Current bar data.++ Returns:+ True if allowed.+ """+ product = _extract_product(symbol)+ limit = _PRICE_LIMIT.get(product)+ if limit is None:+ return True # no price limit for most commodities++ pct_chg = _calc_pct_change(bar)+ if pct_chg is not None:+ if direction == 1 and pct_chg >= limit - 0.001:+ return False # limit-up+ if direction == -1 and pct_chg <= -limit + 0.001:+ return False # limit-down+ if direction == 0:+ pos = self.positions.get(symbol)+ if pos is not None:+ if pos.direction == 1 and pct_chg <= -limit + 0.001:+ return False+ if pos.direction == -1 and pct_chg >= limit - 0.001:+ return False+ return True++ def round_size(self, raw_size: float, price: float) -> float:+ """Integer contracts, minimum 1."""+ return max(int(raw_size), 0)++ def calc_commission(self, size: float, price: float, direction: int, is_open: bool) -> float:+ """Per-contract fixed commission (uses _active_symbol for product lookup)."""+ if self._comm_override is not None:+ return size * self._comm_override+ return self.calc_commission_for_symbol(self._active_symbol, size, price, is_open)++ def calc_commission_for_symbol(+ self, symbol: str, size: float, price: float, is_open: bool,+ ) -> float:+ """Symbol-aware commission.++ Args:+ symbol: Futures code.+ size: Number of contracts.+ price: Execution price (unused β fixed per-lot).+ is_open: Opening or closing.++ Returns:+ Commission in USD.+ """+ product = _extract_product(symbol)+ rate = _COMMISSION_PER_CONTRACT.get(product, _DEFAULT_COMMISSION)+ return size * rate++ def apply_slippage(self, price: float, direction: int) -> float:+ """Slippage model for liquid global futures."""+ return price * (1 + direction * self.slippage_rate)++ def get_contract_multiplier(self, symbol: str) -> float:+ """Product-specific contract multiplier."""+ product = _extract_product(symbol)+ return float(_MULTIPLIER.get(product, 50))+++# ββ Helpers ββ+++def _calc_pct_change(bar: pd.Series):+ """Calculate bar price change percentage.++ Priority: close/pre_close > settle/pre_settle > pct_chg.+ Falls back to pct_chg only when price fields are absent.+ """+ close = bar.get("close")+ pre_close = bar.get("pre_close")+ if close is not None and pre_close is not None and pre_close > 0:+ return (float(close) - float(pre_close)) / float(pre_close)++ settle = bar.get("settle")+ pre_settle = bar.get("pre_settle")+ if settle is not None and pre_settle is not None and pre_settle > 0:+ return (float(settle) - float(pre_settle)) / float(pre_settle)++ if "pct_chg" in bar.index:+ val = bar["pct_chg"]+ if pd.notna(val):+ raw = float(val)+ # Heuristic: values > 1 are likely percentage points+ return raw / 100.0 if abs(raw) > 1.0 else raw++ return Nonediff --git a/agent/backtest/engines/options_portfolio.py b/agent/backtest/engines/options_portfolio.pyindex 0aadaee52..dc928d9ec 100644--- a/agent/backtest/engines/options_portfolio.py+++ b/agent/backtest/engines/options_portfolio.py@@ -1,7 +1,14 @@-"""Options portfolio backtest engine.+"""Options portfolio backtest engine (v2).-European options backtest engine based on Black-Scholes model.-Synthesises theoretical option prices from underlying prices; supports multi-leg strategies.+Supports European and American options via Black-Scholes model with+IV smile approximation. Synthesises theoretical option prices from+underlying prices; supports multi-leg strategies.++v2 enhancements over v1:+ - American option support (early exercise heuristic for calls on dividends,+ always-exercise check for deep ITM puts)+ - IV smile model: skew adjustment based on moneyness (log(K/S))+ - Portfolio-level Greeks aggregationSignal interface: OptionsSignalEngine.generate(data_map) returns a list of trade instructions.Artifacts: equity.csv, metrics.csv, trades.csv, greeks.csv.@@ -123,6 +130,62 @@ def historical_volatility(close: pd.Series, window: int = 30) -> pd.Series:return hv.fillna(hv.dropna().iloc[0] if len(hv.dropna()) > 0 else 0.3)+# --- IV Smile model (v2) ---+++def iv_smile_adjustment(S: float, K: float, base_iv: float,+ skew: float = -0.15, curvature: float = 0.05) -> float:+ """Adjust IV for moneyness using a quadratic smile model.++ IV(K) = base_iv + skew * log(K/S) + curvature * log(K/S)^2++ Args:+ S: Spot price.+ K: Strike price.+ base_iv: At-the-money implied volatility.+ skew: Slope of the smile (negative = put skew). Default -0.15.+ curvature: Curvature of the smile (always positive). Default 0.05.++ Returns:+ Adjusted implied volatility, floored at 0.01.+ """+ if S <= 0 or K <= 0:+ return max(base_iv, 0.01)+ log_moneyness = np.log(K / S)+ adj = base_iv + skew * log_moneyness + curvature * log_moneyness ** 2+ return max(adj, 0.01)+++# --- American option early exercise heuristic (v2) ---+++def american_exercise_value(+ S: float, K: float, T: float, r: float, sigma: float,+ option_type: str = "put",+) -> float:+ """Check whether early exercise is optimal for American options.++ For American puts: exercise if intrinsic > BS continuation value.+ For American calls on non-dividend stocks: never exercise early.+ For American calls with dividends: simplified β exercise if deep ITM+ and time value < dividend capture.++ Args:+ S: Spot price.+ K: Strike price.+ T: Time to expiry in years.+ r: Risk-free rate.+ sigma: Volatility.+ option_type: "call" or "put".++ Returns:+ Max of (intrinsic, BS continuation value).+ """+ intrinsic = max(K - S, 0.0) if option_type == "put" else max(S - K, 0.0)+ continuation = bs_price(S, K, T, r, sigma, option_type)+ return max(intrinsic, continuation)++# --- Option positions ---@@ -229,6 +292,9 @@ def run_options_backtest(risk_free_rate = options_cfg.get("risk_free_rate", 0.05)iv_source = options_cfg.get("iv_source", "historical")contract_multiplier = options_cfg.get("contract_multiplier", 1.0)+ exercise_style = options_cfg.get("exercise_style", "european") # v2: "european" or "american"+ iv_skew = options_cfg.get("iv_skew", 0.0) # v2: smile skew param (0 = flat)+ iv_curvature = options_cfg.get("iv_curvature", 0.0) # v2: smile curvature# Load underlying datadata_map = loader.fetch(codes, start_date, end_date)@@ -282,7 +348,38 @@ def run_options_backtest(spot_prices[code] = float(df.at[last, "close"])ivs[code] = float(iv_map[code].at[last]) if last in iv_map[code].index else 0.3- # 2. Handle expiry+ # 2a. American early exercise (v2): exercise if intrinsic > continuation+ if exercise_style == "american":+ for pos in list(positions):+ if pos.is_expired(ts):+ continue # handled below+ spot = spot_prices.get(pos.underlying_code, 0.0)+ iv_val_ex = ivs.get(pos.underlying_code, 0.3)+ T_ex = pos.time_to_expiry(ts)+ if T_ex <= 0:+ continue+ intrinsic = pos.intrinsic_value(spot)+ continuation = bs_price(spot, pos.strike, T_ex, risk_free_rate, iv_val_ex, pos.option_type)+ if intrinsic > 0 and intrinsic > continuation * 1.02:+ # Early exercise is optimal+ settlement = intrinsic * pos.qty * contract_multiplier+ cash += settlement+ pnl = (intrinsic - pos.entry_price) * pos.qty * contract_multiplier+ trade_records.append({+ "timestamp": date_str,+ "code": pos.underlying_code,+ "option_type": pos.option_type,+ "strike": pos.strike,+ "expiry": str(pos.expiry.date()),+ "side": "early_exercise",+ "price": round(intrinsic, 4),+ "qty": pos.qty,+ "pnl": round(pnl, 4),+ "entry_date": pos.entry_date,+ })+ positions.remove(pos)++ # 2b. Handle expiryexpired = [p for p in positions if p.is_expired(ts)]for pos in expired:spot = spot_prices.get(pos.underlying_code, 0.0)@@ -327,8 +424,13 @@ def run_options_backtest(expiry_ts = pd.Timestamp(expiry)T = max((expiry_ts - ts).days / 365.0, 0.001)- # Black-Scholes price- opt_price = bs_price(spot, strike, T, risk_free_rate, iv_val, leg_type)+ # Apply IV smile adjustment (v2) if configured+ adj_iv = iv_val+ if iv_skew != 0 or iv_curvature != 0:+ adj_iv = iv_smile_adjustment(spot, strike, iv_val, iv_skew, iv_curvature)++ # Black-Scholes price (with smile-adjusted IV if enabled)+ opt_price = bs_price(spot, strike, T, risk_free_rate, adj_iv, leg_type)if action == "open":# Open: long pays premium, short receives premiumdiff --git a/agent/backtest/runner.py b/agent/backtest/runner.pyindex 1658e0d9e..7f3a045c6 100644--- a/agent/backtest/runner.py+++ b/agent/backtest/runner.py@@ -57,7 +57,15 @@ _MARKET_PATTERNS = [(re.compile(r"^\d{3,5}\.HK$", re.I), "hk_equity"),(re.compile(r"^[A-Z]+-USDT$", re.I), "crypto"),(re.compile(r"^[A-Z]+/USDT$", re.I), "crypto"),- (re.compile(r"^[A-Z]{1,2}\d{3,4}\.(ZCE|DCE|SHFE|INE|CFFEX|GFEX)$", re.I), "futures"),+ # China futures: product+delivery.exchange (e.g. IF2406.CFFEX, rb2410.SHFE)+ (re.compile(r"^[A-Za-z]{1,2}\d{3,4}\.(ZCE|DCE|SHFE|INE|CFFEX|GFEX)$", re.I), "futures"),+ # Global futures: product+month-code (e.g. ESZ4, CLF25, GCM2025)+ (re.compile(r"^[A-Z]{2,4}[FGHJKMNQUVXZ]\d{1,2}$", re.I), "futures"),+ # Global futures: product+YYMM (e.g. CL2412, ES2503)+ (re.compile(r"^[A-Z]{2,4}\d{4}$", re.I), "futures"),+ # Global futures: bare product code with exchange (e.g. ES.CME)+ (re.compile(r"^[A-Z]{2,4}\.(CME|CBOT|NYMEX|COMEX|ICE|EUREX)$", re.I), "futures"),+ # 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"),]@@ -243,7 +251,11 @@ def main(run_dir: Path) -> None:def _create_market_engine(source: str, config: dict, codes: List[str]):- """Create the appropriate market engine based on data source.+ """Create the appropriate market engine based on data source and market type.++ Routing priority:+ 1. Detect market type from symbol patterns (futures, forex, etc.)+ 2. Fall back to source-based routing (okx->crypto, tushare->china_a, etc.)Args:source: Data source (okx/ccxt/tushare/akshare/yfinance).@@ -253,12 +265,28 @@ def _create_market_engine(source: str, config: dict, codes: List[str]):Returns:BaseEngine subclass instance."""+ # Detect dominant market type from codes+ markets = {_detect_market(c) for c in codes} if codes else set()++ # Futures routing (Wave 2)+ if "futures" in markets:+ # Distinguish China vs global futures by exchange suffix+ if any(_is_china_futures(c) for c in codes):+ from backtest.engines.china_futures import ChinaFuturesEngine+ return ChinaFuturesEngine(config)+ from backtest.engines.global_futures import GlobalFuturesEngine+ return GlobalFuturesEngine(config)++ # Forex routing (Wave 2)+ if "forex" in markets:+ from backtest.engines.forex import ForexEngine+ return ForexEngine(config)++ # Original routing (Wave 1)if source in ("okx", "ccxt"):from backtest.engines.crypto import CryptoEnginereturn CryptoEngine(config)elif source in ("tushare", "akshare"):- # Determine if codes look like A-shares or global equities- markets = {_detect_market(c) for c in codes}if markets & {"us_equity", "hk_equity"}:from backtest.engines.global_equity import GlobalEquityEnginemarket = _detect_submarket(codes)@@ -274,6 +302,39 @@ def _create_market_engine(source: str, config: dict, codes: List[str]):return CryptoEngine(config)+def _is_china_futures(code: str) -> bool:+ """Check if a futures code belongs to a Chinese exchange.++ Args:+ code: Symbol string (e.g. 'IF2406.CFFEX', 'rb2410.SHFE').++ Returns:+ True if it matches a Chinese futures exchange suffix.+ """+ china_exchanges = {"CFFEX", "SHFE", "DCE", "ZCE", "INE", "GFEX"}+ parts = code.upper().split(".")+ if len(parts) == 2 and parts[1] in china_exchanges:+ return True+ # Heuristic: Chinese futures product codes+ m = re.match(r"([A-Za-z]+)\d+", parts[0])+ if m:+ product = m.group(1)+ # Known Chinese futures products (partial list)+ cn_products = {+ "IF", "IC", "IH", "IM", "T", "TF", "TS", "TL",+ "au", "ag", "cu", "al", "zn", "pb", "ni", "sn", "ss",+ "rb", "hc", "i", "j", "jm",+ "sc", "fu", "lu", "bu", "nr",+ "c", "cs", "m", "y", "a", "p", "jd", "lh",+ "CF", "SR", "TA", "MA", "AP", "RM", "OI",+ "pp", "l", "v", "eg", "eb", "PF", "SA", "FG", "UR",+ "si", "lc",+ }+ if product in cn_products:+ return True+ return False++def _detect_submarket(codes: List[str]) -> str:"""Detect US vs HK from symbol suffixes.diff --git a/agent/backtest/validation.py b/agent/backtest/validation.pynew file mode 100644index 000000000..42da7ea81--- /dev/null+++ b/agent/backtest/validation.py@@ -0,0 +1,378 @@+"""Statistical validation for backtest results.++Three independent tools:+ - Monte Carlo permutation test: is the strategy significantly better than random?+ - Bootstrap Sharpe CI: how stable is the risk-adjusted return?+ - Walk-Forward analysis: is performance consistent across time windows?++Usage: called automatically by BaseEngine.run_backtest when config["validation"]+is present, or invoked directly on backtest outputs.+"""++from __future__ import annotations++from pathlib import Path+from typing import Any, Dict, List++import numpy as np+import pandas as pd++from backtest.models import TradeRecord+++# βββ Monte Carlo Permutation Test βββ+++def monte_carlo_test(+ trades: List[TradeRecord],+ initial_capital: float,+ n_simulations: int = 1000,+ seed: int = 42,+) -> Dict[str, Any]:+ """Shuffle trade PnL order to test path significance.++ Null hypothesis: the observed Sharpe / max-drawdown is no better than+ a random ordering of the same trades.++ Args:+ trades: Completed round-trip trades from backtest.+ initial_capital: Starting capital.+ n_simulations: Number of random permutations.+ seed: Random seed for reproducibility.++ Returns:+ Dict with actual_sharpe, p_value_sharpe, actual_max_dd,+ p_value_max_dd, simulated_sharpes (percentiles).+ """+ if len(trades) < 3:+ return {"error": "need at least 3 trades", "p_value_sharpe": 1.0}++ pnls = np.array([t.pnl for t in trades])+ actual = _path_metrics(pnls, initial_capital)++ rng = np.random.default_rng(seed)+ sharpe_count = 0+ dd_count = 0+ sim_sharpes = []++ for _ in range(n_simulations):+ shuffled = rng.permutation(pnls)+ sim = _path_metrics(shuffled, initial_capital)+ sim_sharpes.append(sim["sharpe"])+ if sim["sharpe"] >= actual["sharpe"]:+ sharpe_count += 1+ if sim["max_dd"] >= actual["max_dd"]: # less negative = "better"+ dd_count += 1++ sim_arr = np.array(sim_sharpes)+ return {+ "actual_sharpe": round(actual["sharpe"], 4),+ "actual_max_dd": round(actual["max_dd"], 4),+ "p_value_sharpe": round(sharpe_count / n_simulations, 4),+ "p_value_max_dd": round(dd_count / n_simulations, 4),+ "simulated_sharpe_mean": round(float(sim_arr.mean()), 4),+ "simulated_sharpe_std": round(float(sim_arr.std()), 4),+ "simulated_sharpe_p5": round(float(np.percentile(sim_arr, 5)), 4),+ "simulated_sharpe_p95": round(float(np.percentile(sim_arr, 95)), 4),+ "n_simulations": n_simulations,+ "n_trades": len(trades),+ }+++def _path_metrics(pnls: np.ndarray, initial_capital: float) -> Dict[str, float]:+ """Compute Sharpe and max drawdown from a PnL sequence."""+ equity = initial_capital + np.cumsum(pnls)+ returns = np.diff(equity) / equity[:-1] if len(equity) > 1 else np.array([0.0])+ std = returns.std()+ sharpe = float(returns.mean() / (std + 1e-10) * np.sqrt(252))+ peak = np.maximum.accumulate(equity)+ dd = (equity - peak) / np.where(peak > 0, peak, 1.0)+ max_dd = float(dd.min())+ return {"sharpe": sharpe, "max_dd": max_dd}+++# βββ Bootstrap Sharpe CI βββ+++def bootstrap_sharpe_ci(+ equity_curve: pd.Series,+ n_bootstrap: int = 1000,+ confidence: float = 0.95,+ bars_per_year: int = 252,+ seed: int = 42,+) -> Dict[str, Any]:+ """Resample daily returns to estimate Sharpe confidence interval.++ Args:+ equity_curve: Equity time series.+ n_bootstrap: Number of bootstrap samples.+ confidence: Confidence level (e.g. 0.95 for 95% CI).+ bars_per_year: Annualisation factor.+ seed: Random seed.++ Returns:+ Dict with observed_sharpe, ci_lower, ci_upper, median_sharpe,+ prob_positive (fraction of samples with Sharpe > 0).+ """+ returns = equity_curve.pct_change().dropna().values+ if len(returns) < 5:+ return {"error": "need at least 5 return observations"}++ observed = _sharpe(returns, bars_per_year)++ rng = np.random.default_rng(seed)+ boot_sharpes = []+ for _ in range(n_bootstrap):+ sample = rng.choice(returns, size=len(returns), replace=True)+ boot_sharpes.append(_sharpe(sample, bars_per_year))++ arr = np.array(boot_sharpes)+ alpha = (1 - confidence) / 2+ lower = float(np.percentile(arr, alpha * 100))+ upper = float(np.percentile(arr, (1 - alpha) * 100))+ prob_pos = float(np.mean(arr > 0))++ return {+ "observed_sharpe": round(observed, 4),+ "ci_lower": round(lower, 4),+ "ci_upper": round(upper, 4),+ "median_sharpe": round(float(np.median(arr)), 4),+ "prob_positive": round(prob_pos, 4),+ "confidence": confidence,+ "n_bootstrap": n_bootstrap,+ }+++def _sharpe(returns: np.ndarray, bars_per_year: int = 252) -> float:+ std = returns.std()+ return float(returns.mean() / (std + 1e-10) * np.sqrt(bars_per_year))+++# βββ Walk-Forward Analysis βββ+++def walk_forward_analysis(+ equity_curve: pd.Series,+ trades: List[TradeRecord],+ n_windows: int = 5,+ bars_per_year: int = 252,+) -> Dict[str, Any]:+ """Split backtest into sequential windows, check consistency.++ Each window is evaluated independently (returns normalised to window start).++ Args:+ equity_curve: Equity time series.+ trades: Completed trades.+ n_windows: Number of non-overlapping windows.+ bars_per_year: Annualisation factor.++ Returns:+ Dict with per_window stats, consistency metrics.+ """+ if len(equity_curve) < n_windows * 2:+ return {"error": f"need at least {n_windows * 2} bars for {n_windows} windows"}++ indices = equity_curve.index+ window_size = len(indices) // n_windows+ windows = []++ for i in range(n_windows):+ start_idx = i * window_size+ end_idx = (i + 1) * window_size if i < n_windows - 1 else len(indices)+ win_eq = equity_curve.iloc[start_idx:end_idx]+ win_start = indices[start_idx]+ win_end = indices[end_idx - 1]++ # Per-window trades+ win_trades = [+ t for t in trades+ if win_start <= t.entry_time <= win_end+ ]++ # Per-window metrics+ ret = float(win_eq.iloc[-1] / win_eq.iloc[0] - 1) if win_eq.iloc[0] > 0 else 0.0+ win_returns = win_eq.pct_change().dropna().values+ sharpe = _sharpe(win_returns, bars_per_year) if len(win_returns) > 1 else 0.0++ peak = win_eq.cummax()+ dd = (win_eq - peak) / peak.replace(0, 1)+ max_dd = float(dd.min())++ win_pnls = [t.pnl for t in win_trades]+ win_rate = (+ len([p for p in win_pnls if p > 0]) / len(win_pnls)+ if win_pnls else 0.0+ )++ windows.append({+ "window": i + 1,+ "start": str(win_start.date()) if hasattr(win_start, "date") else str(win_start),+ "end": str(win_end.date()) if hasattr(win_end, "date") else str(win_end),+ "return": round(ret, 6),+ "sharpe": round(sharpe, 4),+ "max_dd": round(max_dd, 6),+ "trades": len(win_trades),+ "win_rate": round(win_rate, 4),+ })++ # Consistency metrics+ returns_list = [w["return"] for w in windows]+ sharpes_list = [w["sharpe"] for w in windows]+ profitable_windows = sum(1 for r in returns_list if r > 0)++ return {+ "n_windows": n_windows,+ "windows": windows,+ "profitable_windows": profitable_windows,+ "consistency_rate": round(profitable_windows / n_windows, 4),+ "return_mean": round(float(np.mean(returns_list)), 6),+ "return_std": round(float(np.std(returns_list)), 6),+ "sharpe_mean": round(float(np.mean(sharpes_list)), 4),+ "sharpe_std": round(float(np.std(sharpes_list)), 4),+ }+++# βββ Runner integration βββ+++def run_validation(+ config: Dict[str, Any],+ equity_curve: pd.Series,+ trades: List[TradeRecord],+ initial_capital: float,+ bars_per_year: int = 252,+) -> Dict[str, Any]:+ """Run configured validation checks.++ Reads from config["validation"]:+ - monte_carlo: {n_simulations, seed}+ - bootstrap: {n_bootstrap, confidence, seed}+ - walk_forward: {n_windows}++ Args:+ config: Backtest config (must contain "validation" key).+ equity_curve: Equity time series.+ trades: Completed trades.+ initial_capital: Starting capital.+ bars_per_year: Annualisation factor.++ Returns:+ Dict keyed by validation type with results.+ """+ v_cfg = config.get("validation", {})+ results: Dict[str, Any] = {}++ if "monte_carlo" in v_cfg:+ mc_cfg = v_cfg["monte_carlo"] if isinstance(v_cfg["monte_carlo"], dict) else {}+ results["monte_carlo"] = monte_carlo_test(+ trades, initial_capital,+ n_simulations=mc_cfg.get("n_simulations", 1000),+ seed=mc_cfg.get("seed", 42),+ )++ if "bootstrap" in v_cfg:+ bs_cfg = v_cfg["bootstrap"] if isinstance(v_cfg["bootstrap"], dict) else {}+ results["bootstrap"] = bootstrap_sharpe_ci(+ equity_curve, bars_per_year=bars_per_year,+ n_bootstrap=bs_cfg.get("n_bootstrap", 1000),+ confidence=bs_cfg.get("confidence", 0.95),+ seed=bs_cfg.get("seed", 42),+ )++ if "walk_forward" in v_cfg:+ wf_cfg = v_cfg["walk_forward"] if isinstance(v_cfg["walk_forward"], dict) else {}+ results["walk_forward"] = walk_forward_analysis(+ equity_curve, trades,+ n_windows=wf_cfg.get("n_windows", 5),+ bars_per_year=bars_per_year,+ )++ return results+++# βββ Standalone CLI βββ+++def _load_equity(run_dir: Path) -> pd.Series:+ """Load equity curve from artifacts/equity.csv."""+ path = run_dir / "artifacts" / "equity.csv"+ df = pd.read_csv(path, index_col=0, parse_dates=True)+ return df["equity"]+++def _load_trades(run_dir: Path) -> List[TradeRecord]:+ """Load trades from artifacts/trades.csv and convert to TradeRecord list."""+ path = run_dir / "artifacts" / "trades.csv"+ df = pd.read_csv(path)+ if df.empty:+ return []++ # trades.csv has entry+exit row pairs; extract exit rows (they have pnl != 0)+ trades = []+ exit_rows = df[df["pnl"] != 0].reset_index(drop=True)+ for _, row in exit_rows.iterrows():+ trades.append(TradeRecord(+ symbol=str(row.get("code", "")),+ direction=1 if row.get("side") == "sell" else -1,+ entry_price=0.0,+ exit_price=float(row.get("price", 0)),+ entry_time=pd.Timestamp(row.get("timestamp", "2000-01-01")),+ exit_time=pd.Timestamp(row.get("timestamp", "2000-01-01")),+ size=float(row.get("qty", 0)),+ leverage=1.0,+ pnl=float(row.get("pnl", 0)),+ pnl_pct=float(row.get("return_pct", 0)),+ exit_reason=str(row.get("reason", "signal")),+ holding_bars=int(row.get("holding_days", 0)),+ commission=0.0,+ ))+ return trades+++def main(run_dir: Path) -> Dict[str, Any]:+ """Run all three validations on existing backtest artifacts.++ Reads equity.csv, trades.csv, and config.json from run_dir.++ Args:+ run_dir: Directory with artifacts/ subdirectory.++ Returns:+ Validation results dict.+ """+ import json++ # Load config for initial_cash+ config_path = run_dir / "config.json"+ if config_path.exists():+ config = json.loads(config_path.read_text(encoding="utf-8"))+ else:+ config = {}+ initial_capital = config.get("initial_cash", 1_000_000)++ equity = _load_equity(run_dir)+ trades = _load_trades(run_dir)++ results = {+ "monte_carlo": monte_carlo_test(trades, initial_capital),+ "bootstrap": bootstrap_sharpe_ci(equity),+ "walk_forward": walk_forward_analysis(equity, trades),+ }++ # Write results+ out = run_dir / "artifacts" / "validation.json"+ out.write_text(json.dumps(results, indent=2, ensure_ascii=False), encoding="utf-8")++ print(json.dumps(results, indent=2))+ return results+++if __name__ == "__main__":+ import sys+ from pathlib import Path++ if len(sys.argv) < 2:+ print("Usage: python -m backtest.validation <run_dir>")+ sys.exit(1)+ main(Path(sys.argv[1]))diff --git a/agent/src/skills/strategy-generate/SKILL.md b/agent/src/skills/strategy-generate/SKILL.mdindex 97dfd0c59..d6a130567 100644--- a/agent/src/skills/strategy-generate/SKILL.md+++ b/agent/src/skills/strategy-generate/SKILL.md@@ -118,12 +118,14 @@ Self-check after writing `signal_engine.py`:"extra_fields": null,"optimizer": null,"optimizer_params": {},- "engine": "daily"+ "engine": "daily",+ "validation": null}```-- `source`: `"auto"` (recommended, auto-select by code format) / `"tushare"` / `"yfinance"` / `"okx"`+- `source`: `"auto"` (recommended, auto-select by code format) / `"tushare"` / `"yfinance"` / `"okx"` / `"akshare"` / `"ccxt"`- `"auto"` supports mixed instruments. For example, `["000001.SZ", "BTC-USDT"]` will be automatically routed to `tushare` and `okx`+ - Futures codes (e.g. `"IF2406.CFFEX"`, `"ESZ4"`) and forex pairs (e.g. `"EUR/USD"`) are also auto-routed- `interval`: candlestick interval, default `"1D"`. Supported values: `"1m"` / `"5m"` / `"15m"` / `"30m"` / `"1H"` / `"4H"` / `"1D"`- The annualization factor for minute backtests is inferred automatically from `source` (252 trading days for China A-shares, 365 calendar days for crypto)- Minute backtests can be very data-heavy. Recommended limits are no more than 30 days for `1m`, or 1 year for `1H`@@ -133,6 +135,19 @@ Self-check after writing `signal_engine.py`:- `engine`: backtest engine, default `"daily"`. For options strategies, set `"options"` (requires `OptionsSignalEngine`)- `initial_cash`: default 1,000,000- `commission`: default 0.1%+- `validation`: optional statistical validation after backtest completes. Omit to skip. Example:+ ```json+ "validation": {+ "monte_carlo": {"n_simulations": 1000},+ "bootstrap": {"n_bootstrap": 1000, "confidence": 0.95},+ "walk_forward": {"n_windows": 5}+ }+ ```+ - `monte_carlo`: permutation test β shuffles trade order to compute p-value (is Sharpe significantly better than random?)+ - `bootstrap`: resamples daily returns to compute Sharpe 95% confidence interval+ - `walk_forward`: splits equity curve into N windows, checks performance consistency+ - Each key is optional β include only the validations you want+ - Can also run standalone on past results: `python -m backtest.validation <run_dir>`## Review Criteriadiff --git a/agent/src/tools/backtest_tool.py b/agent/src/tools/backtest_tool.pyindex a0d864711..5f6071a60 100644--- a/agent/src/tools/backtest_tool.py+++ b/agent/src/tools/backtest_tool.py@@ -32,7 +32,7 @@ def run_backtest(run_dir: str) -> str:if "source" not in config:return json.dumps({"status": "error", "error": "config.json missing 'source' field (tushare/okx/yfinance)"}, ensure_ascii=False)- valid_sources = {"tushare", "okx", "yfinance", "auto"}+ valid_sources = {"tushare", "okx", "yfinance", "akshare", "ccxt", "auto"}if config["source"] not in valid_sources:return json.dumps({"status": "error", "error": f"source must be one of {valid_sources}, got: {config['source']}"}, ensure_ascii=False)diff --git a/agent/tests/test_china_futures_engine.py b/agent/tests/test_china_futures_engine.pynew file mode 100644index 000000000..b7f7d5009--- /dev/null+++ b/agent/tests/test_china_futures_engine.py@@ -0,0 +1,285 @@+"""Tests for ChinaFuturesEngine market rules.++Validates:+ - T+0: can close same-day positions (unlike A-shares)+ - Both long and short allowed+ - Price limit enforcement (varies by product)+ - Integer contract rounding+ - Commission (fixed per-lot and per-notional)+ - Contract multiplier lookup+ - Margin rate lookup+ - Product code extraction+"""++from __future__ import annotations++import pandas as pd+import pytest++from backtest.engines.china_futures import (+ ChinaFuturesEngine,+ _extract_product,+ _MULTIPLIER,+ _MARGIN_RATE,+ _COMMISSION,+ _PRICE_LIMIT,+ _DEFAULT_PRICE_LIMIT,+)+from backtest.models import Position+++# ---------------------------------------------------------------------------+# Helpers+# ---------------------------------------------------------------------------+++def _make_bar(+ close: float = 5000.0,+ pre_close: float | None = None,+ pct_chg: float | None = None,+ settle: float | None = None,+ pre_settle: float | None = None,+ open_: float | None = None,+) -> pd.Series:+ d: dict = {"close": close, "open": open_ or close}+ if pre_close is not None:+ d["pre_close"] = pre_close+ if pct_chg is not None:+ d["pct_chg"] = pct_chg+ if settle is not None:+ d["settle"] = settle+ if pre_settle is not None:+ d["pre_settle"] = pre_settle+ return pd.Series(d)+++def _make_engine(**overrides) -> ChinaFuturesEngine:+ config = {"initial_cash": 1_000_000, "codes": ["IF2406.CFFEX"]}+ config.update(overrides)+ return ChinaFuturesEngine(config)+++# ---------------------------------------------------------------------------+# Product extraction+# ---------------------------------------------------------------------------+++class TestExtractProduct:+ @pytest.mark.parametrize(+ "symbol, expected",+ [+ ("IF2406.CFFEX", "IF"),+ ("rb2410.SHFE", "rb"),+ ("au2412", "au"),+ ("CF501.ZCE", "CF"),+ ("sc2503.INE", "sc"),+ ("si2406.GFEX", "si"),+ ],+ )+ def test_extract(self, symbol: str, expected: str) -> None:+ assert _extract_product(symbol) == expected+++# ---------------------------------------------------------------------------+# can_execute: T+0 (both directions allowed)+# ---------------------------------------------------------------------------+++class TestDirectionAndT0:+ def test_long_allowed(self) -> None:+ engine = _make_engine()+ bar = _make_bar()+ assert engine.can_execute("IF2406.CFFEX", 1, bar) is True++ def test_short_allowed(self) -> None:+ """China futures allow short selling (unlike A-shares)."""+ engine = _make_engine()+ bar = _make_bar()+ assert engine.can_execute("IF2406.CFFEX", -1, bar) is True++ def test_close_same_day_allowed(self) -> None:+ """T+0: can close positions opened today."""+ engine = _make_engine()+ engine.positions["IF2406.CFFEX"] = Position(+ symbol="IF2406.CFFEX",+ direction=1,+ entry_price=5000.0,+ entry_time=pd.Timestamp("2025-06-10"),+ size=2.0,+ leverage=1 / 0.12,+ )+ bar = _make_bar()+ assert engine.can_execute("IF2406.CFFEX", 0, bar) is True+++# ---------------------------------------------------------------------------+# can_execute: price limits+# ---------------------------------------------------------------------------+++class TestPriceLimits:+ def test_stock_index_limit_up_blocks_long(self) -> None:+ """IF has Β±10% limit; at limit-up, can't open long."""+ engine = _make_engine()+ bar = _make_bar(close=5500.0, pre_close=5000.0) # +10%+ assert engine.can_execute("IF2406.CFFEX", 1, bar) is False++ def test_stock_index_limit_down_blocks_short(self) -> None:+ engine = _make_engine()+ bar = _make_bar(close=4500.0, pre_close=5000.0) # -10%+ assert engine.can_execute("IF2406.CFFEX", -1, bar) is False++ def test_stock_index_within_limit(self) -> None:+ engine = _make_engine()+ bar = _make_bar(close=5200.0, pre_close=5000.0) # +4%+ assert engine.can_execute("IF2406.CFFEX", 1, bar) is True++ def test_commodity_default_5pct(self) -> None:+ """Commodity like rb uses default Β±5% limit."""+ engine = _make_engine(codes=["rb2410.SHFE"])+ bar = _make_bar(close=4250.0, pre_close=4000.0) # +6.25% > 5%+ assert engine.can_execute("rb2410.SHFE", 1, bar) is False++ def test_commodity_within_limit(self) -> None:+ engine = _make_engine(codes=["rb2410.SHFE"])+ bar = _make_bar(close=4100.0, pre_close=4000.0) # +2.5%+ assert engine.can_execute("rb2410.SHFE", 1, bar) is True++ def test_limit_down_blocks_long_close(self) -> None:+ """At limit-down, can't sell (close long position)."""+ engine = _make_engine()+ engine.positions["IF2406.CFFEX"] = Position(+ "IF2406.CFFEX", 1, 5000.0, pd.Timestamp("2025-06-09"), 2.0,+ )+ bar = _make_bar(close=4500.0, pre_close=5000.0) # -10%+ assert engine.can_execute("IF2406.CFFEX", 0, bar) is False+++# ---------------------------------------------------------------------------+# round_size+# ---------------------------------------------------------------------------+++class TestRoundSize:+ def test_rounds_down_to_integer(self) -> None:+ engine = _make_engine()+ assert engine.round_size(2.7, 5000.0) == 2++ def test_exact_integer(self) -> None:+ engine = _make_engine()+ assert engine.round_size(5.0, 5000.0) == 5++ def test_less_than_one_becomes_zero(self) -> None:+ engine = _make_engine()+ assert engine.round_size(0.9, 5000.0) == 0++ def test_negative_clamps_to_zero(self) -> None:+ engine = _make_engine()+ assert engine.round_size(-2.0, 5000.0) == 0+++# ---------------------------------------------------------------------------+# calc_commission+# ---------------------------------------------------------------------------+++class TestCommission:+ def test_rate_commission_via_active_symbol(self) -> None:+ """calc_commission uses _active_symbol for product-specific rate."""+ engine = _make_engine()+ engine._active_symbol = "IF2406.CFFEX"+ comm = engine.calc_commission(2, 5000.0, 1, is_open=True)+ # 2 contracts Γ 5000 Γ 300 (multiplier) Γ 0.000023 = 69+ expected = 2 * 5000 * 300 * 0.000023+ assert comm == pytest.approx(expected, rel=0.01)++ def test_fixed_commission_via_active_symbol(self) -> None:+ """au uses fixed per-lot commission."""+ engine = _make_engine()+ engine._active_symbol = "au2412.SHFE"+ comm = engine.calc_commission(3, 500.0, 1, is_open=True)+ expected = 3 * 10.0 # 10 RMB per lot+ assert comm == pytest.approx(expected)++ def test_symbol_aware_rate_commission(self) -> None:+ engine = _make_engine()+ comm = engine.calc_commission_for_symbol("IF2406.CFFEX", 2, 5000.0, is_open=True)+ expected = 2 * 5000 * 300 * 0.000023+ assert comm == pytest.approx(expected, rel=0.01)++ def test_commission_override(self) -> None:+ engine = _make_engine(commission_override=0.001)+ comm = engine.calc_commission(5, 4000.0, 1, is_open=True)+ assert comm == pytest.approx(5 * 4000.0 * 0.001)+++# ---------------------------------------------------------------------------+# Contract multiplier and margin rate+# ---------------------------------------------------------------------------+++class TestContractMultiplier:+ @pytest.mark.parametrize(+ "symbol, expected",+ [+ ("IF2406.CFFEX", 300),+ ("IC2406.CFFEX", 200),+ ("rb2410.SHFE", 10),+ ("au2412.SHFE", 1000),+ ("sc2503.INE", 1000),+ ("c2501.DCE", 10),+ ("CF501.ZCE", 5),+ ],+ )+ def test_multipliers(self, symbol: str, expected: int) -> None:+ engine = _make_engine()+ assert engine.get_contract_multiplier(symbol) == expected+++class TestMarginRate:+ def test_stock_index_12pct(self) -> None:+ engine = _make_engine()+ assert engine.get_margin_rate("IF2406.CFFEX") == 0.12++ def test_copper_8pct(self) -> None:+ engine = _make_engine()+ assert engine.get_margin_rate("cu2410.SHFE") == 0.08++ def test_unknown_product_default_10pct(self) -> None:+ engine = _make_engine()+ assert engine.get_margin_rate("XX9999.SHFE") == 0.10+++# ---------------------------------------------------------------------------+# Slippage+# ---------------------------------------------------------------------------+++class TestSlippage:+ def test_buy_slippage_increases_price(self) -> None:+ engine = _make_engine()+ assert engine.apply_slippage(5000.0, 1) > 5000.0++ def test_sell_slippage_decreases_price(self) -> None:+ engine = _make_engine()+ assert engine.apply_slippage(5000.0, -1) < 5000.0++ def test_custom_slippage(self) -> None:+ engine = _make_engine(slippage=0.002)+ assert engine.apply_slippage(5000.0, 1) == pytest.approx(5010.0)+++# ---------------------------------------------------------------------------+# Leverage derived from margin+# ---------------------------------------------------------------------------+++class TestLeverageFromMargin:+ def test_if_leverage(self) -> None:+ """IF margin=12% β leverageβ8.33."""+ engine = _make_engine(codes=["IF2406.CFFEX"])+ assert engine.default_leverage == pytest.approx(1 / 0.12, rel=0.01)++ def test_override_margin_rate(self) -> None:+ engine = _make_engine(margin_rate_override=0.20)+ assert engine.default_leverage == pytest.approx(5.0)diff --git a/agent/tests/test_crypto_engine.py b/agent/tests/test_crypto_engine.pyindex c8d9f178f..837ccbf83 100644--- a/agent/tests/test_crypto_engine.py+++ b/agent/tests/test_crypto_engine.py@@ -135,7 +135,8 @@ class TestFundingFee:# Long pays: 1.0 Γ 60000 Γ 0.0001 Γ 1(long) = $6assert engine.capital == pytest.approx(initial_capital - 6.0)- def test_no_funding_at_non_settlement_hour(self) -> None:+ def test_non_settlement_hour_applies_daily_fallback(self) -> None:+ """Non-settlement hour still applies funding once per day (daily bar support)."""engine = _make_engine(funding_rate=0.0001)engine.positions["BTC-USDT"] = Position("BTC-USDT", 1, 60000.0, pd.Timestamp("2025-01-01"), 1.0, leverage=10.0,@@ -144,7 +145,8 @@ class TestFundingFee:bar = _make_bar(close=60000.0)ts = pd.Timestamp("2025-01-01 05:00:00") # not settlement hourengine._apply_funding_fee("BTC-USDT", bar, ts)- assert engine.capital == initial_capital+ # Daily fallback: applies once even at non-settlement hour+ assert engine.capital == pytest.approx(initial_capital - 6.0)def test_short_receives_funding(self) -> None:engine = _make_engine(funding_rate=0.0001)@@ -179,6 +181,57 @@ class TestFundingFee:engine._apply_funding_fee("BTC-USDT", bar, ts)assert engine.capital == initial_capital+ def test_daily_bars_apply_each_day(self) -> None:+ """Regression: daily bars (all hour=0) must apply funding every day, not just day 1."""+ engine = _make_engine(funding_rate=0.0001)+ engine.positions["BTC-USDT"] = Position(+ "BTC-USDT", 1, 60000.0, pd.Timestamp("2025-01-01"), 1.0, leverage=10.0,+ )+ bar = _make_bar(close=60000.0)+ initial = engine.capital++ # Day 1+ engine._apply_funding_fee("BTC-USDT", bar, pd.Timestamp("2025-01-01"))+ after_day1 = engine.capital+ assert after_day1 < initial # fee deducted++ # Day 2 (same hour=0, different date)+ engine._apply_funding_fee("BTC-USDT", bar, pd.Timestamp("2025-01-02"))+ after_day2 = engine.capital+ assert after_day2 < after_day1 # fee deducted again++ # Day 3+ engine._apply_funding_fee("BTC-USDT", bar, pd.Timestamp("2025-01-03"))+ after_day3 = engine.capital+ assert after_day3 < after_day2 # fee deducted again++ # Each day: 1 Γ 60000 Γ 0.0001 = $6+ assert initial - after_day3 == pytest.approx(18.0)++ def test_multi_symbol_funding(self) -> None:+ """Each symbol gets independent funding settlement."""+ engine = _make_engine(funding_rate=0.0001)+ engine.positions["BTC-USDT"] = Position(+ "BTC-USDT", 1, 60000.0, pd.Timestamp("2025-01-01"), 1.0, leverage=10.0,+ )+ engine.positions["ETH-USDT"] = Position(+ "ETH-USDT", 1, 3000.0, pd.Timestamp("2025-01-01"), 10.0, leverage=10.0,+ )+ initial = engine.capital+ bar_btc = _make_bar(close=60000.0)+ bar_eth = _make_bar(close=3000.0)+ ts = pd.Timestamp("2025-01-01 08:00:00")++ engine._apply_funding_fee("BTC-USDT", bar_btc, ts)+ after_btc = engine.capital+ engine._apply_funding_fee("ETH-USDT", bar_eth, ts)+ after_both = engine.capital++ # BTC: 1 Γ 60000 Γ 0.0001 = $6+ # ETH: 10 Γ 3000 Γ 0.0001 = $3+ assert initial - after_btc == pytest.approx(6.0)+ assert initial - after_both == pytest.approx(9.0)+def test_funding_hours_correct(self) -> None:assert _FUNDING_HOURS == {0, 8, 16}diff --git a/agent/tests/test_forex_engine.py b/agent/tests/test_forex_engine.pynew file mode 100644index 000000000..838024f9d--- /dev/null+++ b/agent/tests/test_forex_engine.py@@ -0,0 +1,280 @@+"""Tests for ForexEngine market rules.++Validates:+ - 24x5: no restrictions on direction or timing+ - Zero explicit commission (cost via spread)+ - Spread-based slippage+ - Micro-lot rounding (1000 units)+ - Swap (overnight rollover)+ - Symbol normalization+ - Pip value detection+"""++from __future__ import annotations++import pandas as pd+import pytest++from backtest.engines.forex import (+ ForexEngine,+ _normalize_symbol,+ _pip_value,+ _SPREAD_PIPS,+ _SWAP_LONG,+ STANDARD_LOT,+)+from backtest.models import Position+++# ---------------------------------------------------------------------------+# Helpers+# ---------------------------------------------------------------------------+++def _make_bar(close: float = 1.1050, open_: float | None = None) -> pd.Series:+ return pd.Series({"close": close, "open": open_ or close})+++def _make_engine(**overrides) -> ForexEngine:+ config = {"initial_cash": 100_000}+ config.update(overrides)+ return ForexEngine(config)+++# ---------------------------------------------------------------------------+# Symbol normalization+# ---------------------------------------------------------------------------+++class TestNormalize:+ @pytest.mark.parametrize(+ "raw, expected",+ [+ ("EUR/USD", "EUR/USD"),+ ("EURUSD", "EUR/USD"),+ ("EURUSD.FX", "EUR/USD"),+ ("gbpjpy", "GBP/JPY"),+ ("usd/jpy", "USD/JPY"),+ ],+ )+ def test_normalize(self, raw: str, expected: str) -> None:+ assert _normalize_symbol(raw) == expected+++# ---------------------------------------------------------------------------+# Pip values+# ---------------------------------------------------------------------------+++class TestPipValue:+ def test_eurusd(self) -> None:+ assert _pip_value("EUR/USD") == 0.0001++ def test_usdjpy(self) -> None:+ assert _pip_value("USD/JPY") == 0.01++ def test_gbpjpy(self) -> None:+ assert _pip_value("GBP/JPY") == 0.01++ def test_audusd(self) -> None:+ assert _pip_value("AUD/USD") == 0.0001+++# ---------------------------------------------------------------------------+# can_execute: always allowed+# ---------------------------------------------------------------------------+++class TestCanExecute:+ def test_long_allowed(self) -> None:+ engine = _make_engine()+ assert engine.can_execute("EUR/USD", 1, _make_bar()) is True++ def test_short_allowed(self) -> None:+ engine = _make_engine()+ assert engine.can_execute("EUR/USD", -1, _make_bar()) is True++ def test_close_allowed(self) -> None:+ engine = _make_engine()+ assert engine.can_execute("EUR/USD", 0, _make_bar()) is True+++# ---------------------------------------------------------------------------+# round_size: micro-lot (1000 units)+# ---------------------------------------------------------------------------+++class TestRoundSize:+ def test_rounds_to_micro_lot(self) -> None:+ engine = _make_engine()+ assert engine.round_size(15500.0, 1.1) == 15000++ def test_exact_lot(self) -> None:+ engine = _make_engine()+ assert engine.round_size(100000.0, 1.1) == 100000++ def test_less_than_micro_is_zero(self) -> None:+ engine = _make_engine()+ assert engine.round_size(999.0, 1.1) == 0++ def test_negative_clamps(self) -> None:+ engine = _make_engine()+ assert engine.round_size(-5000.0, 1.1) == 0+++# ---------------------------------------------------------------------------+# Commission: zero (cost in spread)+# ---------------------------------------------------------------------------+++class TestCommission:+ def test_zero_commission(self) -> None:+ engine = _make_engine()+ assert engine.calc_commission(100000, 1.1, 1, is_open=True) == 0.0++ def test_zero_on_close(self) -> None:+ engine = _make_engine()+ assert engine.calc_commission(100000, 1.1, -1, is_open=False) == 0.0+++# ---------------------------------------------------------------------------+# Slippage: half-spread + extra+# ---------------------------------------------------------------------------+++class TestSlippage:+ def test_buy_increases_price(self) -> None:+ engine = _make_engine()+ engine._active_symbol = "EUR/USD"+ assert engine.apply_slippage(1.1050, 1) > 1.1050++ def test_sell_decreases_price(self) -> None:+ engine = _make_engine()+ engine._active_symbol = "EUR/USD"+ assert engine.apply_slippage(1.1050, -1) < 1.1050++ def test_symbol_aware_spread(self) -> None:+ """EUR/USD has 1.0 pip spread; half = 0.5 pip + 0.3 slippage."""+ engine = _make_engine(slippage_pips=0.0) # no extra slippage+ slipped = engine.apply_slippage_for_symbol("EUR/USD", 1.1050, 1)+ pip = 0.0001+ expected = 1.1050 + 0.5 * pip # half spread+ assert slipped == pytest.approx(expected)++ def test_jpy_pair_pip(self) -> None:+ """JPY pairs have pip = 0.01."""+ engine = _make_engine(slippage_pips=0.0)+ slipped = engine.apply_slippage_for_symbol("USD/JPY", 150.00, 1)+ pip = 0.01+ expected = 150.00 + 0.5 * pip # half of 1.0 pip spread+ assert slipped == pytest.approx(expected)+++# ---------------------------------------------------------------------------+# Swap (overnight rollover)+# ---------------------------------------------------------------------------+++class TestSwap:+ def test_swap_applied_once_per_day(self) -> None:+ engine = _make_engine()+ engine.positions["EUR/USD"] = Position(+ symbol="EUR/USD", direction=1, entry_price=1.1050,+ entry_time=pd.Timestamp("2025-06-10"), size=100000,+ )+ initial_capital = engine.capital+ ts = pd.Timestamp("2025-06-10 17:00")+ engine.on_bar("EUR/USD", _make_bar(), ts)+ # Long EUR/USD swap is negative β capital decreases+ swap = _SWAP_LONG.get("EUR/USD", 0)+ expected = initial_capital + 1.0 * swap # 1 standard lot+ assert engine.capital == pytest.approx(expected, abs=0.1)++ def test_swap_not_applied_twice_same_day(self) -> None:+ engine = _make_engine()+ engine.positions["EUR/USD"] = Position(+ symbol="EUR/USD", direction=1, entry_price=1.1050,+ entry_time=pd.Timestamp("2025-06-10"), size=100000,+ )+ ts = pd.Timestamp("2025-06-10 17:00")+ engine.on_bar("EUR/USD", _make_bar(), ts)+ capital_after_first = engine.capital+ engine.on_bar("EUR/USD", _make_bar(), ts)+ assert engine.capital == capital_after_first++ def test_swap_multi_symbol(self) -> None:+ """Each symbol gets its own daily swap (not shared)."""+ engine = _make_engine()+ engine.positions["EUR/USD"] = Position(+ symbol="EUR/USD", direction=1, entry_price=1.1050,+ entry_time=pd.Timestamp("2025-06-10"), size=100000,+ )+ engine.positions["USD/JPY"] = Position(+ symbol="USD/JPY", direction=1, entry_price=150.00,+ entry_time=pd.Timestamp("2025-06-10"), size=100000,+ )+ initial = engine.capital+ ts = pd.Timestamp("2025-06-10 17:00")+ engine.on_bar("EUR/USD", _make_bar(), ts)+ after_eur = engine.capital+ engine.on_bar("USD/JPY", _make_bar(close=150.0), ts)+ after_both = engine.capital+ # Both symbols should have gotten swap, not just the first+ assert after_both != after_eur++ def test_triple_swap_wednesday(self) -> None:+ """Wednesday gets 3x swap (covers weekend)."""+ engine = _make_engine()+ engine.positions["EUR/USD"] = Position(+ symbol="EUR/USD", direction=1, entry_price=1.1050,+ entry_time=pd.Timestamp("2025-06-10"), size=100000,+ )+ initial = engine.capital+ # 2025-06-11 is a Wednesday+ ts = pd.Timestamp("2025-06-11 17:00")+ engine.on_bar("EUR/USD", _make_bar(), ts)+ swap = _SWAP_LONG.get("EUR/USD", 0)+ expected = initial + 1.0 * swap * 3.0+ assert engine.capital == pytest.approx(expected, abs=0.1)++ def test_swap_disabled(self) -> None:+ engine = _make_engine(swap_enabled=False)+ engine.positions["EUR/USD"] = Position(+ symbol="EUR/USD", direction=1, entry_price=1.1050,+ entry_time=pd.Timestamp("2025-06-10"), size=100000,+ )+ initial = engine.capital+ engine.on_bar("EUR/USD", _make_bar(), pd.Timestamp("2025-06-10 17:00"))+ assert engine.capital == initial++ def test_no_position_no_swap(self) -> None:+ engine = _make_engine()+ initial = engine.capital+ engine.on_bar("EUR/USD", _make_bar(), pd.Timestamp("2025-06-10 17:00"))+ assert engine.capital == initial+++# ---------------------------------------------------------------------------+# Leverage default+# ---------------------------------------------------------------------------+++class TestLeverage:+ def test_default_100x(self) -> None:+ engine = _make_engine()+ assert engine.default_leverage == 100.0++ def test_custom_leverage(self) -> None:+ engine = _make_engine(leverage=50.0)+ assert engine.default_leverage == 50.0+++# ---------------------------------------------------------------------------+# Contract multiplier+# ---------------------------------------------------------------------------+++class TestContractMultiplier:+ def test_forex_multiplier_is_one(self) -> None:+ engine = _make_engine()+ assert engine.get_contract_multiplier("EUR/USD") == 1.0diff --git a/agent/tests/test_global_futures_engine.py b/agent/tests/test_global_futures_engine.pynew file mode 100644index 000000000..f0fea8c9a--- /dev/null+++ b/agent/tests/test_global_futures_engine.py@@ -0,0 +1,224 @@+"""Tests for GlobalFuturesEngine market rules.++Validates:+ - T+0, both long and short allowed+ - Equity index price-limit enforcement (7% simplified)+ - Commodity futures: no price limit+ - Integer contract rounding+ - Per-contract commission+ - Contract multiplier lookup+ - Product code extraction+"""++from __future__ import annotations++import pandas as pd+import pytest++from backtest.engines.global_futures import (+ GlobalFuturesEngine,+ _extract_product,+ _MULTIPLIER,+ _MARGIN_PER_CONTRACT,+ _COMMISSION_PER_CONTRACT,+)+from backtest.models import Position+++# ---------------------------------------------------------------------------+# Helpers+# ---------------------------------------------------------------------------+++def _make_bar(+ close: float = 5000.0,+ pre_close: float | None = None,+ pct_chg: float | None = None,+ open_: float | None = None,+) -> pd.Series:+ d: dict = {"close": close, "open": open_ or close}+ if pre_close is not None:+ d["pre_close"] = pre_close+ if pct_chg is not None:+ d["pct_chg"] = pct_chg+ return pd.Series(d)+++def _make_engine(**overrides) -> GlobalFuturesEngine:+ config = {"initial_cash": 1_000_000, "codes": ["ESZ4"]}+ config.update(overrides)+ return GlobalFuturesEngine(config)+++# ---------------------------------------------------------------------------+# Product extraction+# ---------------------------------------------------------------------------+++class TestExtractProduct:+ @pytest.mark.parametrize(+ "symbol, expected",+ [+ ("ESZ4", "ES"),+ ("CLF25", "CL"),+ ("GCM2025", "GC"),+ ("NQ2503", "NQ"),+ ("ES.CME", "ES"),+ ("ZCH4", "ZC"),+ ],+ )+ def test_extract(self, symbol: str, expected: str) -> None:+ assert _extract_product(symbol) == expected+++# ---------------------------------------------------------------------------+# can_execute: T+0, both directions+# ---------------------------------------------------------------------------+++class TestDirections:+ def test_long_allowed(self) -> None:+ engine = _make_engine()+ bar = _make_bar()+ assert engine.can_execute("ESZ4", 1, bar) is True++ def test_short_allowed(self) -> None:+ engine = _make_engine()+ bar = _make_bar()+ assert engine.can_execute("ESZ4", -1, bar) is True++ def test_close_allowed(self) -> None:+ engine = _make_engine()+ bar = _make_bar()+ assert engine.can_execute("ESZ4", 0, bar) is True+++# ---------------------------------------------------------------------------+# can_execute: price limits (equity index only)+# ---------------------------------------------------------------------------+++class TestPriceLimits:+ def test_es_limit_up_blocks_long(self) -> None:+ """ES has 7% limit; at limit-up, can't open long."""+ engine = _make_engine()+ bar = _make_bar(close=5400.0, pre_close=5000.0) # +8% > 7%+ assert engine.can_execute("ESZ4", 1, bar) is False++ def test_es_limit_down_blocks_short(self) -> None:+ engine = _make_engine()+ bar = _make_bar(close=4600.0, pre_close=5000.0) # -8% > 7%+ assert engine.can_execute("ESZ4", -1, bar) is False++ def test_es_within_limit(self) -> None:+ engine = _make_engine()+ bar = _make_bar(close=5200.0, pre_close=5000.0) # +4%+ assert engine.can_execute("ESZ4", 1, bar) is True++ def test_commodity_no_limit(self) -> None:+ """CL has no configured price limit; always allowed."""+ engine = _make_engine(codes=["CLF25"])+ bar = _make_bar(close=100.0, pre_close=70.0) # +43%+ assert engine.can_execute("CLF25", 1, bar) is True+ assert engine.can_execute("CLF25", -1, bar) is True++ def test_gc_no_limit(self) -> None:+ engine = _make_engine(codes=["GCM25"])+ bar = _make_bar(close=2500.0, pre_close=2000.0) # +25%+ assert engine.can_execute("GCM25", 1, bar) is True+++# ---------------------------------------------------------------------------+# round_size+# ---------------------------------------------------------------------------+++class TestRoundSize:+ def test_integer_rounding(self) -> None:+ engine = _make_engine()+ assert engine.round_size(3.7, 5000.0) == 3++ def test_exact_integer(self) -> None:+ engine = _make_engine()+ assert engine.round_size(5.0, 5000.0) == 5++ def test_zero(self) -> None:+ engine = _make_engine()+ assert engine.round_size(0.5, 5000.0) == 0++ def test_negative_to_zero(self) -> None:+ engine = _make_engine()+ assert engine.round_size(-1.0, 5000.0) == 0+++# ---------------------------------------------------------------------------+# calc_commission+# ---------------------------------------------------------------------------+++class TestCommission:+ def test_es_commission_via_active_symbol(self) -> None:+ """calc_commission uses _active_symbol for product lookup."""+ engine = _make_engine()+ engine._active_symbol = "ESZ4"+ comm = engine.calc_commission(2, 5000.0, 1, is_open=True)+ assert comm == pytest.approx(2 * 2.25)++ def test_micro_commission_via_active_symbol(self) -> None:+ engine = _make_engine()+ engine._active_symbol = "MESZ4"+ comm = engine.calc_commission(10, 5000.0, 1, is_open=True)+ assert comm == pytest.approx(10 * 0.62)++ def test_symbol_aware_direct(self) -> None:+ engine = _make_engine()+ comm = engine.calc_commission_for_symbol("ESZ4", 2, 5000.0, is_open=True)+ assert comm == pytest.approx(2 * 2.25)++ def test_commission_override(self) -> None:+ engine = _make_engine(commission_per_contract=1.0)+ comm = engine.calc_commission(5, 5000.0, 1, is_open=True)+ assert comm == pytest.approx(5.0)+++# ---------------------------------------------------------------------------+# Contract multiplier+# ---------------------------------------------------------------------------+++class TestContractMultiplier:+ @pytest.mark.parametrize(+ "symbol, expected",+ [+ ("ESZ4", 50),+ ("NQH5", 20),+ ("CLF25", 1000),+ ("GCM25", 100),+ ("SIH25", 5000),+ ("ZCH4", 50),+ ("ZBM5", 1000),+ ("MESZ4", 5),+ ],+ )+ def test_multipliers(self, symbol: str, expected: float) -> None:+ engine = _make_engine()+ assert engine.get_contract_multiplier(symbol) == expected+++# ---------------------------------------------------------------------------+# Slippage+# ---------------------------------------------------------------------------+++class TestSlippage:+ def test_buy_increases_price(self) -> None:+ engine = _make_engine()+ assert engine.apply_slippage(5000.0, 1) > 5000.0++ def test_sell_decreases_price(self) -> None:+ engine = _make_engine()+ assert engine.apply_slippage(5000.0, -1) < 5000.0++ def test_custom_slippage(self) -> None:+ engine = _make_engine(slippage=0.001)+ assert engine.apply_slippage(5000.0, 1) == pytest.approx(5005.0)diff --git a/agent/tests/test_validation.py b/agent/tests/test_validation.pynew file mode 100644index 000000000..7fad148a0--- /dev/null+++ b/agent/tests/test_validation.py@@ -0,0 +1,240 @@+"""Tests for backtest validation module.++Validates:+ - Monte Carlo permutation test: p-value, output structure+ - Bootstrap Sharpe CI: confidence interval bounds, prob_positive+ - Walk-Forward analysis: window splitting, consistency metrics+ - run_validation dispatcher+"""++from __future__ import annotations++import numpy as np+import pandas as pd+import pytest++from backtest.models import TradeRecord+from backtest.validation import (+ bootstrap_sharpe_ci,+ monte_carlo_test,+ run_validation,+ walk_forward_analysis,+)+++# ---------------------------------------------------------------------------+# Fixtures+# ---------------------------------------------------------------------------+++def _make_trades(pnls: list[float], start: str = "2025-01-01") -> list[TradeRecord]:+ """Create TradeRecord list from PnL values."""+ trades = []+ base = pd.Timestamp(start)+ for i, pnl in enumerate(pnls):+ entry = base + pd.Timedelta(days=i * 2)+ exit_ = entry + pd.Timedelta(days=1)+ trades.append(TradeRecord(+ symbol="TEST",+ direction=1,+ entry_price=100.0,+ exit_price=100.0 + pnl / 10,+ entry_time=entry,+ exit_time=exit_,+ size=10.0,+ leverage=1.0,+ pnl=pnl,+ pnl_pct=pnl / 1000 * 100,+ exit_reason="signal",+ holding_bars=1,+ commission=0.0,+ ))+ return trades+++def _make_equity(n: int = 100, drift: float = 0.001, seed: int = 42) -> pd.Series:+ """Create a synthetic equity curve."""+ rng = np.random.default_rng(seed)+ returns = rng.normal(drift, 0.02, n)+ prices = 1_000_000 * np.cumprod(1 + returns)+ dates = pd.bdate_range("2025-01-01", periods=n)+ return pd.Series(prices, index=dates)+++# ---------------------------------------------------------------------------+# Monte Carlo Permutation Test+# ---------------------------------------------------------------------------+++class TestMonteCarlo:+ def test_output_structure(self) -> None:+ trades = _make_trades([100, -50, 200, -30, 150, -80, 120, -40, 90, -20])+ result = monte_carlo_test(trades, 1_000_000, n_simulations=100)+ assert "actual_sharpe" in result+ assert "p_value_sharpe" in result+ assert "p_value_max_dd" in result+ assert "n_simulations" in result+ assert result["n_simulations"] == 100+ assert result["n_trades"] == 10++ def test_p_value_range(self) -> None:+ trades = _make_trades([100, -50, 200, -30, 150])+ result = monte_carlo_test(trades, 1_000_000, n_simulations=200)+ assert 0.0 <= result["p_value_sharpe"] <= 1.0+ assert 0.0 <= result["p_value_max_dd"] <= 1.0++ def test_strong_strategy_low_p_value(self) -> None:+ """A consistently profitable strategy should have low p-value."""+ trades = _make_trades([100, 200, 150, 180, 120, 90, 110, 130, 160, 140])+ result = monte_carlo_test(trades, 1_000_000, n_simulations=500, seed=42)+ # All trades profitable β hard to beat by shuffling (already optimal)+ # p-value should be moderate (shuffling can't make it worse when all positive)+ assert result["actual_sharpe"] > 0++ def test_too_few_trades(self) -> None:+ trades = _make_trades([100, -50])+ result = monte_carlo_test(trades, 1_000_000)+ assert "error" in result++ def test_reproducibility(self) -> None:+ trades = _make_trades([100, -50, 200, -30, 150, -80])+ r1 = monte_carlo_test(trades, 1_000_000, n_simulations=100, seed=42)+ r2 = monte_carlo_test(trades, 1_000_000, n_simulations=100, seed=42)+ assert r1["p_value_sharpe"] == r2["p_value_sharpe"]+++# ---------------------------------------------------------------------------+# Bootstrap Sharpe CI+# ---------------------------------------------------------------------------+++class TestBootstrapSharpe:+ def test_output_structure(self) -> None:+ eq = _make_equity(100)+ result = bootstrap_sharpe_ci(eq, n_bootstrap=100)+ assert "observed_sharpe" in result+ assert "ci_lower" in result+ assert "ci_upper" in result+ assert "prob_positive" in result+ assert "confidence" in result+ assert result["confidence"] == 0.95++ def test_ci_contains_observed(self) -> None:+ """The observed Sharpe should usually fall within the CI."""+ eq = _make_equity(200, drift=0.001)+ result = bootstrap_sharpe_ci(eq, n_bootstrap=500)+ # Not guaranteed, but very likely for 95% CI+ assert result["ci_lower"] <= result["ci_upper"]++ def test_positive_drift_mostly_positive(self) -> None:+ """Equity with positive drift should have high prob_positive."""+ eq = _make_equity(200, drift=0.003, seed=123)+ result = bootstrap_sharpe_ci(eq, n_bootstrap=500)+ assert result["prob_positive"] > 0.5++ def test_too_few_observations(self) -> None:+ eq = pd.Series([100, 101, 102], index=pd.bdate_range("2025-01-01", periods=3))+ result = bootstrap_sharpe_ci(eq, n_bootstrap=100)+ assert "error" in result++ def test_reproducibility(self) -> None:+ eq = _make_equity(50)+ r1 = bootstrap_sharpe_ci(eq, n_bootstrap=100, seed=42)+ r2 = bootstrap_sharpe_ci(eq, n_bootstrap=100, seed=42)+ assert r1["ci_lower"] == r2["ci_lower"]++ def test_custom_confidence(self) -> None:+ eq = _make_equity(100)+ r90 = bootstrap_sharpe_ci(eq, confidence=0.90, n_bootstrap=200)+ r99 = bootstrap_sharpe_ci(eq, confidence=0.99, n_bootstrap=200)+ # 99% CI should be wider than 90% CI+ width_90 = r90["ci_upper"] - r90["ci_lower"]+ width_99 = r99["ci_upper"] - r99["ci_lower"]+ assert width_99 >= width_90+++# ---------------------------------------------------------------------------+# Walk-Forward Analysis+# ---------------------------------------------------------------------------+++class TestWalkForward:+ def test_output_structure(self) -> None:+ eq = _make_equity(100)+ trades = _make_trades([100, -50] * 10)+ result = walk_forward_analysis(eq, trades, n_windows=4)+ assert result["n_windows"] == 4+ assert len(result["windows"]) == 4+ assert "consistency_rate" in result+ assert "return_mean" in result+ assert "sharpe_mean" in result++ def test_window_fields(self) -> None:+ eq = _make_equity(100)+ trades = _make_trades([100, -50] * 10)+ result = walk_forward_analysis(eq, trades, n_windows=5)+ w = result["windows"][0]+ assert "window" in w+ assert "start" in w+ assert "end" in w+ assert "return" in w+ assert "sharpe" in w+ assert "max_dd" in w+ assert "trades" in w+ assert "win_rate" in w++ def test_consistency_rate(self) -> None:+ """Equity with positive drift should have high consistency."""+ eq = _make_equity(200, drift=0.003)+ trades = _make_trades([100] * 50)+ result = walk_forward_analysis(eq, trades, n_windows=5)+ assert result["consistency_rate"] > 0.5++ def test_windows_cover_full_range(self) -> None:+ eq = _make_equity(100)+ trades = _make_trades([100] * 10)+ result = walk_forward_analysis(eq, trades, n_windows=5)+ first_start = result["windows"][0]["start"]+ last_end = result["windows"][-1]["end"]+ assert first_start == str(eq.index[0].date())+ assert last_end == str(eq.index[-1].date())++ def test_too_few_bars(self) -> None:+ eq = pd.Series([100, 101], index=pd.bdate_range("2025-01-01", periods=2))+ result = walk_forward_analysis(eq, [], n_windows=5)+ assert "error" in result+++# ---------------------------------------------------------------------------+# run_validation dispatcher+# ---------------------------------------------------------------------------+++class TestRunValidation:+ def test_empty_config_returns_empty(self) -> None:+ eq = _make_equity(50)+ result = run_validation({}, eq, [], 1_000_000)+ assert result == {}++ def test_all_three(self) -> None:+ eq = _make_equity(100)+ trades = _make_trades([100, -50, 200, -30, 150])+ config = {+ "validation": {+ "monte_carlo": {"n_simulations": 50},+ "bootstrap": {"n_bootstrap": 50},+ "walk_forward": {"n_windows": 3},+ }+ }+ result = run_validation(config, eq, trades, 1_000_000)+ assert "monte_carlo" in result+ assert "bootstrap" in result+ assert "walk_forward" in result++ def test_single_tool(self) -> None:+ eq = _make_equity(100)+ trades = _make_trades([100, -50, 200])+ config = {"validation": {"bootstrap": {"n_bootstrap": 50}}}+ result = run_validation(config, eq, trades, 1_000_000)+ assert "bootstrap" in result+ assert "monte_carlo" not in resultdiff --git a/frontend/src/components/charts/ValidationPanel.tsx b/frontend/src/components/charts/ValidationPanel.tsxnew file mode 100644index 000000000..d99fbaa96--- /dev/null+++ b/frontend/src/components/charts/ValidationPanel.tsx@@ -0,0 +1,183 @@+import { cn } from "@/lib/utils";+import type { ValidationData } from "@/lib/api";++interface Props {+ data: ValidationData;+}++function Badge({ value, good }: { value: string; good: boolean | null }) {+ return (+ <span+ className={cn(+ "inline-block px-2 py-0.5 rounded-full text-xs font-semibold",+ good === true && "bg-emerald-500/15 text-emerald-600 dark:text-emerald-400",+ good === false && "bg-red-500/15 text-red-600 dark:text-red-400",+ good === null && "bg-zinc-500/10 text-zinc-500",+ )}+ >+ {value}+ </span>+ );+}++function Stat({ label, value, sub }: { label: string; value: string; sub?: string }) {+ return (+ <div className="text-center py-2">+ <p className="text-[10px] text-muted-foreground uppercase tracking-wide">{label}</p>+ <p className="text-sm font-bold font-mono tabular-nums">{value}</p>+ {sub && <p className="text-[10px] text-muted-foreground">{sub}</p>}+ </div>+ );+}++function pctFmt(v: number): string {+ return (v * 100).toFixed(2) + "%";+}++function MonteCarloSection({ mc }: { mc: NonNullable<ValidationData["monte_carlo"]> }) {+ if (mc.error) return <p className="text-sm text-muted-foreground">{mc.error}</p>;+ const sig = mc.p_value_sharpe < 0.05;+ return (+ <div className="space-y-3">+ <div className="flex items-center gap-2">+ <h4 className="text-sm font-semibold">Monte Carlo Permutation Test</h4>+ <Badge value={sig ? "Significant" : "Not Significant"} good={sig} />+ </div>+ <p className="text-xs text-muted-foreground">+ Shuffled trade order {mc.n_simulations.toLocaleString()} times to test if Sharpe is better than random.+ </p>+ <div className="grid grid-cols-2 sm:grid-cols-4 gap-1 rounded-xl border border-border/60 bg-muted/20 p-3">+ <Stat label="Actual Sharpe" value={mc.actual_sharpe.toFixed(2)} />+ <Stat label="p-value (Sharpe)" value={mc.p_value_sharpe.toFixed(4)} sub={sig ? "< 0.05" : ">= 0.05"} />+ <Stat label="Simulated Mean" value={mc.simulated_sharpe_mean.toFixed(2)} sub={`std ${mc.simulated_sharpe_std.toFixed(2)}`} />+ <Stat label="Simulated 90% Range" value={`[${mc.simulated_sharpe_p5.toFixed(2)}, ${mc.simulated_sharpe_p95.toFixed(2)}]`} />+ </div>+ {/* Visual: where actual falls in distribution */}+ <div className="space-y-1">+ <div className="flex justify-between text-[10px] text-muted-foreground font-mono">+ <span>P5: {mc.simulated_sharpe_p5.toFixed(2)}</span>+ <span>Actual: {mc.actual_sharpe.toFixed(2)}</span>+ <span>P95: {mc.simulated_sharpe_p95.toFixed(2)}</span>+ </div>+ <div className="relative h-3 rounded-full bg-muted overflow-hidden">+ <div className="absolute inset-y-0 bg-zinc-300 dark:bg-zinc-600 rounded-full" style={barStyle(mc.simulated_sharpe_p5, mc.simulated_sharpe_p95, mc.simulated_sharpe_p5, mc.simulated_sharpe_p95)} />+ <div className="absolute top-0 bottom-0 w-0.5 bg-emerald-500" style={markerStyle(mc.actual_sharpe, mc.simulated_sharpe_p5, mc.simulated_sharpe_p95)} />+ </div>+ </div>+ </div>+ );+}++function BootstrapSection({ bs }: { bs: NonNullable<ValidationData["bootstrap"]> }) {+ if (bs.error) return <p className="text-sm text-muted-foreground">{bs.error}</p>;+ const reliable = bs.ci_lower > 0;+ return (+ <div className="space-y-3">+ <div className="flex items-center gap-2">+ <h4 className="text-sm font-semibold">Bootstrap Sharpe CI</h4>+ <Badge value={reliable ? "CI > 0" : "CI includes 0"} good={reliable} />+ </div>+ <p className="text-xs text-muted-foreground">+ Resampled daily returns {bs.n_bootstrap.toLocaleString()} times to estimate {(bs.confidence * 100).toFixed(0)}% confidence interval.+ </p>+ <div className="grid grid-cols-2 sm:grid-cols-4 gap-1 rounded-xl border border-border/60 bg-muted/20 p-3">+ <Stat label="Observed Sharpe" value={bs.observed_sharpe.toFixed(2)} />+ <Stat label={`${(bs.confidence * 100).toFixed(0)}% CI`} value={`[${bs.ci_lower.toFixed(2)}, ${bs.ci_upper.toFixed(2)}]`} />+ <Stat label="Median Sharpe" value={bs.median_sharpe.toFixed(2)} />+ <Stat label="P(Sharpe > 0)" value={pctFmt(bs.prob_positive)} />+ </div>+ {/* CI bar */}+ <div className="space-y-1">+ <div className="flex justify-between text-[10px] text-muted-foreground font-mono">+ <span>{bs.ci_lower.toFixed(2)}</span>+ <span>{bs.ci_upper.toFixed(2)}</span>+ </div>+ <div className="relative h-3 rounded-full bg-muted overflow-hidden">+ <div className={cn("absolute inset-y-0 rounded-full", reliable ? "bg-emerald-500/30" : "bg-amber-500/30")} style={barStyle(bs.ci_lower, bs.ci_upper, Math.min(bs.ci_lower, 0), Math.max(bs.ci_upper, 1))} />+ <div className="absolute top-0 bottom-0 w-0.5 bg-foreground" style={markerStyle(bs.observed_sharpe, Math.min(bs.ci_lower, 0), Math.max(bs.ci_upper, 1))} />+ </div>+ </div>+ </div>+ );+}++function WalkForwardSection({ wf }: { wf: NonNullable<ValidationData["walk_forward"]> }) {+ if (wf.error) return <p className="text-sm text-muted-foreground">{wf.error}</p>;+ const consistent = wf.consistency_rate >= 0.8;+ return (+ <div className="space-y-3">+ <div className="flex items-center gap-2">+ <h4 className="text-sm font-semibold">Walk-Forward Analysis</h4>+ <Badge value={`${wf.profitable_windows}/${wf.n_windows} profitable`} good={consistent ? true : wf.consistency_rate >= 0.5 ? null : false} />+ </div>+ <p className="text-xs text-muted-foreground">+ Split into {wf.n_windows} sequential windows to check performance consistency.+ </p>+ <div className="grid grid-cols-2 sm:grid-cols-4 gap-1 rounded-xl border border-border/60 bg-muted/20 p-3">+ <Stat label="Consistency" value={pctFmt(wf.consistency_rate)} />+ <Stat label="Avg Return" value={pctFmt(wf.return_mean)} sub={`std ${pctFmt(wf.return_std)}`} />+ <Stat label="Avg Sharpe" value={wf.sharpe_mean.toFixed(2)} sub={`std ${wf.sharpe_std.toFixed(2)}`} />+ <Stat label="Windows" value={String(wf.n_windows)} />+ </div>+ {/* Per-window table */}+ <table className="w-full text-xs">+ <thead>+ <tr className="border-b text-left text-muted-foreground">+ <th className="py-1.5 pr-3">#</th>+ <th className="py-1.5 pr-3">Period</th>+ <th className="py-1.5 pr-3 text-right">Return</th>+ <th className="py-1.5 pr-3 text-right">Sharpe</th>+ <th className="py-1.5 pr-3 text-right">Max DD</th>+ <th className="py-1.5 pr-3 text-right">Trades</th>+ <th className="py-1.5 text-right">Win Rate</th>+ </tr>+ </thead>+ <tbody>+ {wf.windows.map((w) => (+ <tr key={w.window} className="border-b last:border-0">+ <td className="py-1.5 pr-3 font-mono">{w.window}</td>+ <td className="py-1.5 pr-3 font-mono text-muted-foreground">{w.start} ~ {w.end}</td>+ <td className={cn("py-1.5 pr-3 text-right font-mono tabular-nums", w.return > 0 ? "text-emerald-600 dark:text-emerald-400" : "text-red-600 dark:text-red-400")}>{pctFmt(w.return)}</td>+ <td className="py-1.5 pr-3 text-right font-mono tabular-nums">{w.sharpe.toFixed(2)}</td>+ <td className="py-1.5 pr-3 text-right font-mono tabular-nums">{pctFmt(w.max_dd)}</td>+ <td className="py-1.5 pr-3 text-right font-mono tabular-nums">{w.trades}</td>+ <td className="py-1.5 text-right font-mono tabular-nums">{pctFmt(w.win_rate)}</td>+ </tr>+ ))}+ </tbody>+ </table>+ </div>+ );+}++/* Position helpers for the mini bar visualizations */+function barStyle(start: number, end: number, min: number, max: number) {+ const range = max - min || 1;+ const left = ((start - min) / range) * 100;+ const width = ((end - start) / range) * 100;+ return { left: `${Math.max(left, 0)}%`, width: `${Math.min(width, 100)}%` };+}++function markerStyle(value: number, min: number, max: number) {+ const range = max - min || 1;+ const left = ((value - min) / range) * 100;+ return { left: `${Math.max(0, Math.min(100, left))}%` };+}++export function ValidationPanel({ data }: Props) {+ const hasMC = !!data.monte_carlo;+ const hasBS = !!data.bootstrap;+ const hasWF = !!data.walk_forward;++ if (!hasMC && !hasBS && !hasWF) {+ return <p className="p-8 text-sm text-muted-foreground">No validation data available.</p>;+ }++ return (+ <div className="p-4 space-y-6">+ {hasMC && <MonteCarloSection mc={data.monte_carlo!} />}+ {hasBS && <BootstrapSection bs={data.bootstrap!} />}+ {hasWF && <WalkForwardSection wf={data.walk_forward!} />}+ </div>+ );+}diff --git a/frontend/src/lib/api.ts b/frontend/src/lib/api.tsindex 5bcd919c2..178bbeb47 100644--- a/frontend/src/lib/api.ts+++ b/frontend/src/lib/api.ts@@ -127,6 +127,52 @@ export interface EquityPoint {drawdown: string | number;}+export interface ValidationData {+ monte_carlo?: {+ actual_sharpe: number;+ actual_max_dd: number;+ p_value_sharpe: number;+ p_value_max_dd: number;+ simulated_sharpe_mean: number;+ simulated_sharpe_std: number;+ simulated_sharpe_p5: number;+ simulated_sharpe_p95: number;+ n_simulations: number;+ n_trades: number;+ error?: string;+ };+ bootstrap?: {+ observed_sharpe: number;+ ci_lower: number;+ ci_upper: number;+ median_sharpe: number;+ prob_positive: number;+ confidence: number;+ n_bootstrap: number;+ error?: string;+ };+ walk_forward?: {+ n_windows: number;+ windows: Array<{+ window: number;+ start: string;+ end: string;+ return: number;+ sharpe: number;+ max_dd: number;+ trades: number;+ win_rate: number;+ }>;+ profitable_windows: number;+ consistency_rate: number;+ return_mean: number;+ return_std: number;+ sharpe_mean: number;+ sharpe_std: number;+ error?: string;+ };+}+export interface RunData {status: string;run_id: string;@@ -138,6 +184,7 @@ export interface RunData {metrics?: BacktestMetrics;artifacts?: ArtifactInfo[];+ validation?: ValidationData;price_series?: Record<string, PriceBar[]>;indicator_series?: Record<string, Record<string, IndicatorPoint[]>>;diff --git a/frontend/src/lib/i18n.tsx b/frontend/src/lib/i18n.tsxindex d1d243742..af29c0818 100644--- a/frontend/src/lib/i18n.tsx+++ b/frontend/src/lib/i18n.tsx@@ -75,6 +75,7 @@ const messages = {metricBenchmarkReturn: "Benchmark",metricExcessReturn: "Excess Return",metricIR: "IR",+ validation: "Validation",overlayMA: "Moving Avg",overlayChannel: "Channel",overlayIndicators: "Indicators",diff --git a/frontend/src/pages/RunDetail.tsx b/frontend/src/pages/RunDetail.tsxindex dca6d0d2e..1cc6ba115 100644--- a/frontend/src/pages/RunDetail.tsx+++ b/frontend/src/pages/RunDetail.tsx@@ -1,6 +1,6 @@import { useEffect, useState } from "react";import { useParams, Link, useNavigate } from "react-router-dom";-import { CheckCircle2, XCircle, BarChart3, List, Code2, ArrowLeft, Download } from "lucide-react";+import { CheckCircle2, XCircle, BarChart3, List, Code2, ArrowLeft, Download, ShieldCheck } from "lucide-react";import { cn } from "@/lib/utils";import { useI18n } from "@/lib/i18n";import { api, type RunData, type BacktestMetrics } from "@/lib/api";@@ -9,12 +9,13 @@ import rehypeHighlight from "rehype-highlight";import { CandlestickChart } from "@/components/charts/CandlestickChart";import { EquityChart } from "@/components/charts/EquityChart";import { MetricsCard } from "@/components/chat/MetricsCard";+import { ValidationPanel } from "@/components/charts/ValidationPanel";import { Skeleton, SkeletonMetrics, SkeletonChart } from "@/components/common/Skeleton";import { ErrorBoundary } from "@/components/common/ErrorBoundary";const rehypePlugins = [rehypeHighlight];-type Tab = "chart" | "trades" | "code";+type Tab = "chart" | "trades" | "code" | "validation";function downloadCsv(filename: string, csvContent: string) {const blob = new Blob(["\uFEFF" + csvContent], { type: "text/csv;charset=utf-8;" });@@ -57,9 +58,11 @@ export function RunDetail() {const [tab, setTab] = useState<Tab>("chart");const [loading, setLoading] = useState(true);- const TABS: { id: Tab; label: string; icon: typeof BarChart3 }[] = [+ const hasValidation = !!run?.validation;+ const TABS: { id: Tab; label: string; icon: typeof BarChart3; hidden?: boolean }[] = [{ id: "chart", label: t.chart, icon: BarChart3 },{ id: "trades", label: t.trades, icon: List },+ { id: "validation", label: t.validation, icon: ShieldCheck, hidden: !hasValidation },{ id: "code", label: t.code, icon: Code2 },];@@ -104,7 +107,7 @@ export function RunDetail() {{run.metrics && <MetricsCard metrics={run.metrics as Record<string, number>} />}<div className="flex items-center gap-1">- {TABS.map(({ id, label, icon: Icon }) => (+ {TABS.filter(t => !t.hidden).map(({ id, label, icon: Icon }) => (<buttonkey={id}onClick={() => setTab(id)}@@ -144,6 +147,7 @@ export function RunDetail() {<ErrorBoundary>{tab === "chart" && <ChartTab run={run} />}{tab === "trades" && <TradesTab run={run} />}+ {tab === "validation" && run.validation && <ValidationPanel data={run.validation} />}{tab === "code" && <CodeTab code={code} />}</ErrorBoundary></div>