Skip to content

"Vibe-Trading: Your Personal Trading Agent"

feat: multi-market backtest engines with per-market rules

warren6188e6963f46205
diff --git a/.gitignore b/.gitignore
index e26333bcc..360ba4577 100644
--- a/.gitignore
+++ b/.gitignore
@@ -27,6 +27,9 @@ data/*.duckdb.wal
data/.duckdb_tmp/
data/parquet/
data/backup/
+
+# Internal docs (plans, specs)
+docs/
data/minutes/
data/overnight*.log
data/*.log
@@ -35,5 +38,6 @@ agent/.pytest_tmp/
agent/tests/e2e_swarm_results.json
agent/vibe_trading.egg-info/
agent/vibe_trading_ai.egg-info/
+agent/tests/
dist/
build/
diff --git a/README.md b/README.md
index 1132b343a..9dba9ced4 100644
--- a/README.md
+++ b/README.md
@@ -44,9 +44,8 @@
## πŸ“° News
-| Date | Update |
-|------|--------|
-| 2026-04-01 | **v0.1.0** β€” Initial release: ReAct agent, 64 skills, 29 swarm presets, cross-market backtest, CLI + Web UI + MCP server. |
+- **2026-04-09** πŸ”§ Multi-market backtest engines β€” per-market rules (A-share T+1, crypto funding/liquidation, US/HK fees) replace the single vectorised engine.
+- **2026-04-01** πŸš€ Released **v0.1.0** β€” Initial release: ReAct agent, 64 skills, 29 swarm presets, cross-market backtest, CLI + Web UI + MCP server.
---
diff --git a/agent/backtest/engines/__init__.py b/agent/backtest/engines/__init__.py
index e69de29bb..da2c0c32c 100644
--- a/agent/backtest/engines/__init__.py
+++ b/agent/backtest/engines/__init__.py
@@ -0,0 +1,8 @@
+"""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)
+"""
diff --git a/agent/backtest/engines/base.py b/agent/backtest/engines/base.py
new file mode 100644
index 000000000..ea37945a4
--- /dev/null
+++ b/agent/backtest/engines/base.py
@@ -0,0 +1,521 @@
+"""Base backtest engine with shared bar-by-bar execution loop.
+
+All market engines inherit from BaseEngine and override market-rule methods.
+The shared run_backtest() handles: data loading β†’ signal generation β†’
+pre-compute target weights (with optimizer) β†’ bar-by-bar execution with
+market rule enforcement β†’ metrics β†’ artifacts.
+"""
+
+from __future__ import annotations
+
+import importlib
+import json
+import sys
+from abc import ABC, abstractmethod
+from pathlib import Path
+from typing import Any, Callable, Dict, List, Optional
+
+import numpy as np
+import pandas as pd
+
+from backtest.metrics import (
+ by_exit_reason_stats,
+ by_symbol_stats,
+ calc_metrics,
+)
+from backtest.models import EquitySnapshot, Position, TradeRecord
+
+
+# ─── Signal alignment (reused from daily_portfolio logic) ───
+
+
+def _align(
+ data_map: Dict[str, pd.DataFrame],
+ signal_map: Dict[str, pd.Series],
+ codes: List[str],
+ optimizer: Optional[Callable] = None,
+) -> tuple:
+ """Build aligned date index, close matrix, target-position matrix, return matrix.
+
+ Signal is shifted by 1 bar (next-bar-open semantics) then normalised so
+ ``sum(abs(weights)) <= 1.0``.
+
+ Args:
+ data_map: code -> OHLCV DataFrame.
+ signal_map: code -> signal Series.
+ codes: Valid instrument codes.
+ optimizer: Optional weight optimiser ``(ret, pos, dates) -> pos``.
+
+ Returns:
+ (dates, close_df, positions_df, returns_df)
+ """
+ all_dates: set = set()
+ for c in codes:
+ all_dates.update(data_map[c].index)
+ dates = pd.DatetimeIndex(sorted(all_dates))
+
+ close = pd.DataFrame(index=dates, columns=codes, dtype=float)
+ for c in codes:
+ close[c] = data_map[c]["close"].reindex(dates)
+ close = close.ffill().bfill()
+
+ pos = pd.DataFrame(0.0, index=dates, columns=codes)
+ for c in codes:
+ raw = signal_map[c].reindex(dates).fillna(0.0).clip(-1.0, 1.0)
+ pos[c] = raw.shift(1).fillna(0.0)
+
+ ret = close.pct_change().fillna(0.0)
+
+ if optimizer is not None:
+ pos = optimizer(ret, pos, dates)
+
+ scale = pos.abs().sum(axis=1).clip(lower=1.0)
+ pos = pos.div(scale, axis=0)
+
+ return dates, close, pos, ret
+
+
+def _load_optimizer(config: Dict[str, Any]) -> Optional[Callable]:
+ """Dynamically load an optimizer function from config.
+
+ Args:
+ config: Backtest configuration.
+
+ Returns:
+ Optimizer callable, or None.
+ """
+ opt_name = config.get("optimizer")
+ if not opt_name:
+ return None
+ opt_params = config.get("optimizer_params") or {}
+ try:
+ mod = importlib.import_module(f"backtest.optimizers.{opt_name}")
+ return lambda ret, pos, dates: mod.optimize(ret, pos, dates, **opt_params)
+ except (ImportError, AttributeError) as e:
+ print(f"[WARN] Failed to load optimizer '{opt_name}': {e}, falling back to equal weight")
+ return None
+
+
+# ─── Base Engine ───
+
+
+class BaseEngine(ABC):
+ """Abstract base for all market engines.
+
+ Subclasses override market-rule methods:
+ - can_execute: whether a trade is allowed by market rules
+ - round_size: lot-size rounding
+ - calc_commission: fee structure
+ - apply_slippage: slippage model
+ - on_bar: per-bar hooks (funding fees, liquidation, etc.)
+ """
+
+ def __init__(self, config: dict):
+ self.config = config
+ self.initial_capital: float = config.get("initial_cash", 1_000_000)
+ self.default_leverage: float = config.get("leverage", 1.0)
+ self.capital: float = self.initial_capital
+ self.positions: Dict[str, Position] = {}
+ self.trades: List[TradeRecord] = []
+ self.equity_snapshots: List[EquitySnapshot] = []
+ self._bar_idx: int = 0
+
+ # ── Market rule interface (subclass must implement) ──
+
+ @abstractmethod
+ def can_execute(self, symbol: str, direction: int, bar: pd.Series) -> bool:
+ """Whether market rules allow this trade.
+
+ Args:
+ symbol: Instrument identifier.
+ direction: 1 (long), -1 (short), 0 (close).
+ bar: Current bar data (OHLCV + extras).
+
+ Returns:
+ True if allowed.
+ """
+
+ @abstractmethod
+ def round_size(self, raw_size: float, price: float) -> float:
+ """Round position size per market lot rules.
+
+ Args:
+ raw_size: Desired size.
+ price: Current price.
+
+ Returns:
+ Rounded size.
+ """
+
+ @abstractmethod
+ def calc_commission(self, size: float, price: float, direction: int, is_open: bool) -> float:
+ """Calculate commission for a trade.
+
+ Args:
+ size: Trade size.
+ price: Execution price.
+ direction: 1 or -1.
+ is_open: True for opening, False for closing.
+
+ Returns:
+ Commission amount.
+ """
+
+ @abstractmethod
+ def apply_slippage(self, price: float, direction: int) -> float:
+ """Apply slippage to execution price.
+
+ Args:
+ price: Raw price.
+ direction: 1 (buying / covering short) or -1 (selling / shorting).
+
+ Returns:
+ Slipped price.
+ """
+
+ def on_bar(self, symbol: str, bar: pd.Series, timestamp: pd.Timestamp) -> None:
+ """Per-bar market-rule hook (funding fees, liquidation, etc.).
+
+ Default: no-op. Override in subclass as needed.
+ """
+
+ # ── Main entry ──
+
+ def run_backtest(
+ self,
+ config: Dict[str, Any],
+ loader: Any,
+ signal_engine: Any,
+ run_dir: Path,
+ bars_per_year: int = 252,
+ ) -> Dict[str, Any]:
+ """Full backtest pipeline.
+
+ Signature matches ``daily_portfolio.run_backtest`` for drop-in replacement.
+
+ Args:
+ config: Backtest configuration dict.
+ loader: DataLoader with ``fetch()`` method.
+ signal_engine: SignalEngine with ``generate()`` method.
+ run_dir: Artifacts output directory.
+ bars_per_year: Annualisation factor.
+
+ Returns:
+ Metrics dictionary.
+ """
+ codes = config.get("codes", [])
+ interval = config.get("interval", "1D")
+ extra_fields = config.get("extra_fields") or None
+
+ # 1. Load data
+ data_map = loader.fetch(
+ codes,
+ config.get("start_date", ""),
+ config.get("end_date", ""),
+ fields=extra_fields,
+ interval=interval,
+ )
+ if not data_map:
+ print(json.dumps({"error": "No data fetched"}))
+ sys.exit(1)
+
+ # 2. Generate signals
+ signal_map = signal_engine.generate(data_map)
+ valid_codes = sorted(c for c in signal_map if c in data_map)
+ if not valid_codes:
+ print(json.dumps({"error": "No valid signals generated"}))
+ sys.exit(1)
+
+ # 3. Pre-compute target weights (with optimizer)
+ opt_fn = _load_optimizer(config)
+ dates, close_df, target_pos, ret_df = _align(
+ data_map, signal_map, valid_codes, optimizer=opt_fn,
+ )
+
+ # 4. Bar-by-bar execution
+ self._execute_bars(dates, data_map, close_df, target_pos, valid_codes)
+
+ # 5. Build output series
+ equity_series = pd.Series(
+ [s.equity for s in self.equity_snapshots],
+ index=[s.timestamp for s in self.equity_snapshots],
+ )
+ bench_ret = ret_df.mean(axis=1) if ret_df.shape[1] > 0 else pd.Series(0.0, index=dates)
+ bench_equity = self.initial_capital * (1 + bench_ret).cumprod()
+
+ # 6. Metrics
+ m = calc_metrics(equity_series, self.trades, self.initial_capital, bars_per_year, bench_ret)
+ m["by_symbol"] = by_symbol_stats(self.trades)
+ m["by_exit_reason"] = by_exit_reason_stats(self.trades)
+
+ # 7. Artifacts
+ self._write_artifacts(
+ run_dir, data_map, dates, equity_series, bench_equity, bench_ret,
+ target_pos, m, valid_codes,
+ )
+
+ # Print scalar metrics (skip nested dicts for JSON compat)
+ print(json.dumps({k: v for k, v in m.items() if not isinstance(v, dict)}, indent=2))
+ return m
+
+ # ── Execution loop ──
+
+ def _execute_bars(
+ self,
+ dates: pd.DatetimeIndex,
+ data_map: Dict[str, pd.DataFrame],
+ close_df: pd.DataFrame,
+ target_pos: pd.DataFrame,
+ codes: List[str],
+ ) -> None:
+ """Bar-by-bar execution with market rule enforcement."""
+ for i, ts in enumerate(dates):
+ self._bar_idx = i
+
+ # a. Per-bar hooks (funding fees, liquidation checks)
+ for c in codes:
+ if ts in data_map[c].index:
+ self.on_bar(c, data_map[c].loc[ts], ts)
+
+ # b. Rebalance each symbol to target weight
+ equity = self._calc_equity(close_df, ts)
+ for c in codes:
+ target_w = float(target_pos.at[ts, c]) if ts in target_pos.index else 0.0
+ self._rebalance(c, target_w, data_map.get(c), ts, equity)
+
+ # c. Record equity snapshot
+ snap_equity = self._calc_equity(close_df, ts)
+ total_unrealized = 0.0
+ for 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)
+ self.equity_snapshots.append(EquitySnapshot(
+ timestamp=ts,
+ capital=self.capital,
+ unrealized=total_unrealized,
+ equity=snap_equity,
+ positions=len(self.positions),
+ ))
+
+ # d. Force close all remaining positions
+ if len(dates) > 0:
+ last_ts = dates[-1]
+ for c in list(self.positions.keys()):
+ price = self._safe_price(close_df, last_ts, c, self.positions[c].entry_price)
+ self._close_position(c, price, last_ts, "end_of_backtest")
+
+ def _calc_equity(self, close_df: pd.DataFrame, ts: pd.Timestamp) -> float:
+ """Total equity = free cash + sum(margin + unrealised) per position."""
+ equity = self.capital
+ for 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)
+ equity += margin + unrealized
+ return equity
+
+ def _rebalance(
+ self,
+ symbol: str,
+ target_weight: float,
+ df: Optional[pd.DataFrame],
+ ts: pd.Timestamp,
+ equity: float,
+ ) -> None:
+ """Adjust position for *symbol* toward *target_weight*."""
+ target_dir = 1 if target_weight > 1e-9 else (-1 if target_weight < -1e-9 else 0)
+ current_pos = self.positions.get(symbol)
+
+ # Nothing to do
+ if current_pos is None and target_dir == 0:
+ return
+ if df is None or ts not in df.index:
+ return
+
+ bar = df.loc[ts]
+
+ # Close if target is flat or direction changed
+ if current_pos is not None:
+ need_close = target_dir == 0 or target_dir != current_pos.direction
+ if need_close:
+ if self.can_execute(symbol, 0, bar):
+ open_price = float(bar.get("open", bar.get("close", 0)))
+ price = self.apply_slippage(open_price, -current_pos.direction)
+ self._close_position(symbol, price, ts, "signal")
+ else:
+ return # blocked (e.g. limit-down can't sell)
+
+ # Open new if target non-zero and no remaining position
+ if target_dir != 0 and symbol not in self.positions:
+ if not self.can_execute(symbol, target_dir, bar):
+ return # blocked (e.g. A-share no-short)
+
+ open_price = float(bar.get("open", bar.get("close", 0)))
+ if open_price <= 0:
+ return
+
+ slipped = self.apply_slippage(open_price, target_dir)
+ leverage = self.default_leverage
+ target_notional = abs(target_weight) * equity * leverage
+ raw_size = target_notional / slipped
+ size = self.round_size(raw_size, slipped)
+ if size <= 0:
+ return
+
+ margin = size * slipped / leverage
+ comm = self.calc_commission(size, slipped, target_dir, is_open=True)
+
+ # Capital check β€” reduce if insufficient
+ if margin + comm > self.capital:
+ available = self.capital - comm
+ if available <= 0:
+ return
+ size = self.round_size(available * leverage / slipped, slipped)
+ if size <= 0:
+ return
+ margin = size * slipped / leverage
+ comm = self.calc_commission(size, slipped, target_dir, is_open=True)
+
+ self.capital -= (margin + comm)
+ self.positions[symbol] = Position(
+ symbol=symbol,
+ direction=target_dir,
+ entry_price=slipped,
+ entry_time=ts,
+ size=size,
+ leverage=leverage,
+ entry_bar_idx=self._bar_idx,
+ entry_commission=comm,
+ )
+
+ def _close_position(
+ self,
+ symbol: str,
+ exit_price: float,
+ exit_time: pd.Timestamp,
+ reason: str,
+ ) -> None:
+ """Close position, record trade, return capital."""
+ pos = 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_pct = pnl / margin * 100 if margin > 1e-9 else 0.0
+ exit_comm = self.calc_commission(pos.size, exit_price, pos.direction, is_open=False)
+
+ self.capital += margin + pnl - exit_comm
+
+ holding_bars = max(self._bar_idx - pos.entry_bar_idx, 0)
+
+ self.trades.append(TradeRecord(
+ symbol=symbol,
+ direction=pos.direction,
+ entry_price=pos.entry_price,
+ exit_price=exit_price,
+ entry_time=pos.entry_time,
+ exit_time=exit_time,
+ size=pos.size,
+ leverage=pos.leverage,
+ pnl=pnl,
+ pnl_pct=pnl_pct,
+ exit_reason=reason,
+ holding_bars=holding_bars,
+ commission=pos.entry_commission + exit_comm,
+ ))
+
+ # ── Artifacts ──
+
+ def _write_artifacts(
+ self,
+ run_dir: Path,
+ data_map: Dict[str, pd.DataFrame],
+ dates: pd.DatetimeIndex,
+ equity_series: pd.Series,
+ bench_equity: pd.Series,
+ bench_ret: pd.Series,
+ target_pos: pd.DataFrame,
+ metrics: dict,
+ codes: List[str],
+ ) -> None:
+ """Write CSV artifacts compatible with daily_portfolio format."""
+ out = run_dir / "artifacts"
+ out.mkdir(parents=True, exist_ok=True)
+
+ # OHLCV per symbol
+ for code, df in data_map.items():
+ df.to_csv(out / f"ohlcv_{code}.csv")
+
+ # Equity curve
+ port_ret = equity_series.pct_change().fillna(0.0)
+ peak = equity_series.cummax()
+ dd = (equity_series - peak) / peak.replace(0, 1)
+ eq_df = pd.DataFrame({
+ "ret": port_ret,
+ "equity": equity_series,
+ "drawdown": dd,
+ "benchmark_equity": bench_equity.reindex(dates),
+ "active_ret": port_ret - bench_ret.reindex(dates).fillna(0.0),
+ }, index=dates)
+ eq_df.index.name = "timestamp"
+ eq_df.to_csv(out / "equity.csv")
+
+ # Position weights (target, for compatibility)
+ target_pos.index.name = "timestamp"
+ target_pos.to_csv(out / "positions.csv")
+
+ # Trades (compatible format)
+ trade_rows = []
+ for t in self.trades:
+ # Entry event
+ trade_rows.append({
+ "timestamp": str(t.entry_time.date()) if hasattr(t.entry_time, "date") else str(t.entry_time),
+ "code": t.symbol,
+ "side": "buy" if t.direction == 1 else "sell",
+ "price": round(t.entry_price, 4),
+ "qty": round(t.size, 6),
+ "reason": "signal",
+ "pnl": 0.0,
+ "holding_days": 0,
+ "return_pct": 0.0,
+ })
+ # Exit event
+ try:
+ hold_days = (t.exit_time - t.entry_time).days
+ except Exception:
+ hold_days = 0
+ trade_rows.append({
+ "timestamp": str(t.exit_time.date()) if hasattr(t.exit_time, "date") else str(t.exit_time),
+ "code": t.symbol,
+ "side": "sell" if t.direction == 1 else "buy",
+ "price": round(t.exit_price, 4),
+ "qty": round(t.size, 6),
+ "reason": t.exit_reason,
+ "pnl": round(t.pnl, 4),
+ "holding_days": hold_days,
+ "return_pct": round(t.pnl_pct, 2),
+ })
+
+ trade_cols = ["timestamp", "code", "side", "price", "qty", "reason", "pnl", "holding_days", "return_pct"]
+ pd.DataFrame(trade_rows or [], columns=trade_cols).to_csv(out / "trades.csv", index=False)
+
+ # Metrics
+ flat_metrics = {k: v for k, v in metrics.items() if not isinstance(v, dict)}
+ pd.DataFrame([flat_metrics]).to_csv(out / "metrics.csv", index=False)
+
+ # ── Helpers ──
+
+ @staticmethod
+ def _safe_price(
+ close_df: pd.DataFrame,
+ ts: pd.Timestamp,
+ symbol: str,
+ fallback: float,
+ ) -> float:
+ """Get close price with fallback."""
+ if ts in close_df.index and symbol in close_df.columns:
+ val = close_df.at[ts, symbol]
+ if pd.notna(val):
+ return float(val)
+ return fallback
diff --git a/agent/backtest/engines/china_a.py b/agent/backtest/engines/china_a.py
new file mode 100644
index 000000000..a08c212a4
--- /dev/null
+++ b/agent/backtest/engines/china_a.py
@@ -0,0 +1,148 @@
+"""A-share (China mainland) backtest engine.
+
+Market rules:
+ - T+1: cannot sell shares bought today
+ - No short selling for retail investors
+ - Price limits: Β±10% main board, Β±20% ChiNext/STAR, Β±5% ST
+ - Minimum lot: 100 shares (odd lots can only be sold, not bought)
+ - Commission: Β₯5 minimum, 0.025% bilateral
+ - Stamp tax: 0.05% sell-side only
+ - Transfer fee: 0.001% bilateral
+"""
+
+from __future__ import annotations
+
+import pandas as pd
+
+from backtest.engines.base import BaseEngine
+
+
+class ChinaAEngine(BaseEngine):
+ """A-share market engine.
+
+ Config keys:
+ - commission_rate: default 0.00025 (δΈ‡2.5)
+ - commission_min: default 5.0 (RMB)
+ - stamp_tax: default 0.0005 (δΈ‡5, sell-only)
+ - transfer_fee: default 0.00001 (δΈ‡0.1)
+ - slippage: default 0.001
+ """
+
+ def __init__(self, config: dict):
+ config = {**config, "leverage": 1.0} # A-shares: no leverage
+ super().__init__(config)
+ self.commission_rate: float = config.get("commission_rate", 0.00025)
+ self.commission_min: float = config.get("commission_min", 5.0)
+ self.stamp_tax: float = config.get("stamp_tax", 0.0005)
+ self.transfer_fee: float = config.get("transfer_fee", 0.00001)
+ self.slippage_rate: float = config.get("slippage", 0.001)
+
+ def can_execute(self, symbol: str, direction: int, bar: pd.Series) -> bool:
+ """A-share execution rules.
+
+ Args:
+ symbol: Stock code (e.g. 000001.SZ).
+ direction: 1 (buy), -1 (short β€” always blocked), 0 (sell/close).
+ bar: Current bar (needs 'close', 'pre_close' or 'pct_chg').
+
+ Returns:
+ True if the trade is allowed.
+ """
+ # 1. No short selling
+ if direction == -1:
+ return False
+
+ # 2. T+1: can't sell shares bought today
+ if direction == 0:
+ pos = self.positions.get(symbol)
+ if pos is not None:
+ bar_date = _bar_date(bar)
+ entry_date = pos.entry_time.date() if hasattr(pos.entry_time, "date") else None
+ if bar_date is not None and entry_date is not None and bar_date == entry_date:
+ return False
+
+ # 3. Price limits
+ pct_chg = _calc_pct_change(bar)
+ if pct_chg is not None:
+ limit = _price_limit(symbol)
+ if direction == 1 and pct_chg >= limit - 0.001:
+ return False # limit-up: can't buy
+ if direction == 0 and pct_chg <= -limit + 0.001:
+ return False # limit-down: can't sell
+
+ return True
+
+ def round_size(self, raw_size: float, price: float) -> float:
+ """Round down to 100-share lots."""
+ return max(int(raw_size / 100) * 100, 0)
+
+ def calc_commission(self, size: float, price: float, direction: int, is_open: bool) -> float:
+ """A-share fee structure: commission + stamp tax (sell) + transfer fee."""
+ notional = size * price
+ # Commission: δΈ‡2.5, min Β₯5
+ comm = max(notional * self.commission_rate, self.commission_min)
+ # Transfer fee: δΈ‡0.1 bilateral
+ comm += notional * self.transfer_fee
+ # Stamp tax: δΈ‡5 sell-only
+ if not is_open:
+ comm += notional * self.stamp_tax
+ return comm
+
+ def apply_slippage(self, price: float, direction: int) -> float:
+ """A-share slippage (relatively small due to tick size)."""
+ return price * (1 + direction * self.slippage_rate)
+
+
+# ── Helpers ──
+
+
+def _bar_date(bar: pd.Series):
+ """Extract date from bar, handling various column names."""
+ for col in ("trade_date", "date"):
+ if col in bar.index:
+ val = bar[col]
+ if hasattr(val, "date"):
+ return val.date()
+ try:
+ return pd.Timestamp(val).date()
+ except Exception:
+ pass
+ # Fall back to bar name (index timestamp)
+ if hasattr(bar, "name") and hasattr(bar.name, "date"):
+ return bar.name.date()
+ return None
+
+
+def _calc_pct_change(bar: pd.Series):
+ """Calculate price change percentage from bar data."""
+ if "pct_chg" in bar.index:
+ val = bar["pct_chg"]
+ if pd.notna(val):
+ return float(val) / 100.0 # tushare pct_chg is in percentage points
+
+ 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)
+ return None
+
+
+def _price_limit(symbol: str) -> float:
+ """Determine price limit based on board.
+
+ Args:
+ symbol: Stock code (e.g. 300001.SZ, 688001.SH, 000001.SZ).
+
+ Returns:
+ Limit as fraction (0.10, 0.20, or 0.05).
+ """
+ code = symbol.split(".")[0] if "." in symbol else symbol
+ # ChiNext (300xxx) / STAR (688xxx): Β±20%
+ if code.startswith("300") or code.startswith("688"):
+ return 0.20
+ # ST stocks: Β±5% (heuristic: can't fully detect from code alone)
+ # Beijing exchange (8xxxxx): Β±30% β€” simplified to 0.30
+ if code.startswith("8") and len(code) == 6:
+ return 0.30
+ # Main board: Β±10%
+ return 0.10
diff --git a/agent/backtest/engines/crypto.py b/agent/backtest/engines/crypto.py
new file mode 100644
index 000000000..f3c87bd1d
--- /dev/null
+++ b/agent/backtest/engines/crypto.py
@@ -0,0 +1,135 @@
+"""Crypto perpetual-contract backtest engine.
+
+Market rules:
+ - 24/7 trading, no restrictions on direction
+ - Maker/Taker fee separation
+ - Funding fee settlement every 8 hours (00:00/08:00/16:00 UTC)
+ - Forced liquidation when maintenance margin ratio <= 100%
+ - Fractional position sizes allowed
+"""
+
+from __future__ import annotations
+
+import pandas as pd
+
+from backtest.engines.base import BaseEngine
+
+
+# OKX tiered maintenance margin table (simplified)
+# (max_notional_usd, maintenance_margin_rate)
+_TIER_TABLE = [
+ (100_000, 0.004),
+ (500_000, 0.006),
+ (1_000_000, 0.01),
+ (5_000_000, 0.02),
+ (10_000_000, 0.05),
+ (float("inf"), 0.10),
+]
+
+# Funding fee settlement hours (UTC)
+_FUNDING_HOURS = {0, 8, 16}
+
+
+class CryptoEngine(BaseEngine):
+ """Crypto perpetual contract engine.
+
+ Config keys:
+ - leverage: default 1.0
+ - maker_rate: default 0.0002
+ - taker_rate: default 0.0005
+ - slippage: default 0.0005
+ - margin_mode: "isolated" (default) or "cross"
+ - funding_rate: fixed rate per settlement, default 0.0001
+ """
+
+ def __init__(self, config: dict):
+ super().__init__(config)
+ self.maker_rate: float = config.get("maker_rate", 0.0002)
+ 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
+
+ def can_execute(self, symbol: str, direction: int, bar: pd.Series) -> bool:
+ """Crypto: 24/7, long/short/close all allowed."""
+ return True
+
+ def round_size(self, raw_size: float, price: float) -> float:
+ """Crypto supports fractional sizes, round to 6 decimals."""
+ return round(max(raw_size, 0.0), 6)
+
+ def calc_commission(self, size: float, price: float, direction: int, is_open: bool) -> float:
+ """Maker/Taker separated. Opens typically hit taker, closes hit maker."""
+ rate = self.taker_rate if is_open else self.maker_rate
+ return size * price * rate
+
+ def apply_slippage(self, price: float, direction: int) -> float:
+ """Slippage: unfavourable direction."""
+ return price * (1 + direction * self.slippage_rate)
+
+ def on_bar(self, symbol: str, bar: pd.Series, timestamp: pd.Timestamp) -> None:
+ """Crypto per-bar hooks: funding fee + liquidation check."""
+ self._apply_funding_fee(symbol, bar, timestamp)
+ self._check_liquidation(symbol, bar, timestamp)
+
+ # ── Funding fee (exchange-enforced, every 8h) ──
+
+ def _apply_funding_fee(
+ self, symbol: str, bar: pd.Series, timestamp: pd.Timestamp,
+ ) -> None:
+ """Deduct/credit funding fee at settlement hours.
+
+ Positive rate: longs pay shorts. Negative rate: shorts pay longs.
+ """
+ if not hasattr(timestamp, "hour"):
+ return
+ hour = timestamp.hour
+ if hour not in _FUNDING_HOURS:
+ return
+ # Avoid double-settlement on same hour
+ if hour == self._last_funding_hour:
+ return
+ self._last_funding_hour = hour
+
+ pos = self.positions.get(symbol)
+ if pos is None:
+ return
+
+ 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
+ self.capital -= fee
+
+ # ── Liquidation (exchange-enforced) ──
+
+ def _check_liquidation(
+ self, symbol: str, bar: pd.Series, timestamp: pd.Timestamp,
+ ) -> None:
+ """Force-close when maintenance margin ratio drops to / below 100%."""
+ pos = self.positions.get(symbol)
+ if pos is None or pos.leverage <= 1.0:
+ return # spot has no liquidation
+
+ mark_price = float(bar.get("close", pos.entry_price))
+ margin = pos.size * pos.entry_price / pos.leverage
+ unrealized = pos.direction * pos.size * (mark_price - pos.entry_price)
+
+ # Maintenance margin rate (tiered)
+ notional = pos.size * mark_price
+ maint_rate = self._maintenance_rate(notional)
+ maint_margin = notional * maint_rate
+
+ # Margin ratio = (margin + unrealized) / maint_margin
+ equity_in_pos = margin + unrealized
+ if equity_in_pos <= maint_margin:
+ # Liquidation: close at mark price with taker fee
+ liq_price = self.apply_slippage(mark_price, -pos.direction)
+ self._close_position(symbol, liq_price, timestamp, "liquidation")
+
+ @staticmethod
+ def _maintenance_rate(notional_usd: float) -> float:
+ """Look up tiered maintenance margin rate."""
+ for tier_max, rate in _TIER_TABLE:
+ if notional_usd <= tier_max:
+ return rate
+ return _TIER_TABLE[-1][1]
diff --git a/agent/backtest/engines/daily_portfolio.py b/agent/backtest/engines/daily_portfolio.py
deleted file mode 100644
index 82174446f..000000000
--- a/agent/backtest/engines/daily_portfolio.py
+++ /dev/null
@@ -1,461 +0,0 @@
-"""Portfolio-level vectorised backtest engine.
-
-Supports arbitrary bar intervals (1m/5m/15m/30m/1H/4H/1D).
-Signal lag: bar-T signal executes at bar T+1 (close-to-close return approx).
-Position normalisation: sum(abs(weights)) <= 1.0, no leverage ever.
-Commission: deducted as percentage of turnover.
-Artifacts: equity.csv, metrics.csv, trades.csv, positions.csv, ohlcv_{code}.csv.
-"""
-
-from pathlib import Path
-from typing import Any, Callable, Dict, List, Optional
-
-import numpy as np
-import pandas as pd
-
-
-# ─── Annualisation factor mapping (auto-inferred from source and interval) ───
-
-_TRADING_DAYS = {"tushare": 252, "yfinance": 252, "okx": 365}
-_BARS_PER_DAY = {
- "1m": {"tushare": 240, "okx": 1440, "yfinance": 390},
- "5m": {"tushare": 48, "okx": 288, "yfinance": 78},
- "15m": {"tushare": 16, "okx": 96, "yfinance": 26},
- "30m": {"tushare": 8, "okx": 48, "yfinance": 13},
- "1H": {"tushare": 4, "okx": 24, "yfinance": 7},
- "4H": {"tushare": 1, "okx": 6, "yfinance": 2},
- "1D": {"tushare": 1, "okx": 1, "yfinance": 1},
-}
-
-
-def _calc_bars_per_year(interval: str = "1D", source: str = "tushare") -> int:
- """Calculate the number of bars per year for annualisation.
-
- Args:
- interval: Bar interval (e.g. 1m, 1H, 1D).
- source: Data source (determines trading days and bars per day).
-
- Returns:
- Number of bars per year, used for annualised return and Sharpe ratio.
- """
- trading_days = _TRADING_DAYS.get(source, 252)
- bars_per_day = _BARS_PER_DAY.get(interval, {}).get(source, 1)
- return trading_days * bars_per_day
-
-
-def _align(
- data_map: Dict[str, pd.DataFrame],
- signal_map: Dict[str, pd.Series],
- codes: List[str],
- optimizer: Optional[Callable] = None,
-) -> tuple:
- """Build aligned date index, close matrix, position matrix, and return matrix.
-
- For multi-market mixes, takes the union of all trading dates and forward-fills gaps.
- Applies signal shift(1), optional optimizer weighting, and normalisation (sum|w|<=1).
-
- Args:
- data_map: code -> OHLCV DataFrame.
- signal_map: code -> signal Series.
- codes: List of valid instrument codes.
- optimizer: Optional weight optimisation function (ret_df, pos_df, date_idx) -> pos_df.
-
- Returns:
- (dates, close_df, positions_df, returns_df)
- """
- all_dates = set()
- for c in codes:
- all_dates.update(data_map[c].index)
- dates = pd.DatetimeIndex(sorted(all_dates))
-
- close = pd.DataFrame(index=dates, columns=codes, dtype=float)
- for c in codes:
- close[c] = data_map[c]["close"].reindex(dates)
- close = close.ffill().bfill()
-
- pos = pd.DataFrame(0.0, index=dates, columns=codes)
- for c in codes:
- raw = signal_map[c].reindex(dates).fillna(0.0).clip(-1.0, 1.0)
- pos[c] = raw.shift(1).fillna(0.0)
-
- ret = close.pct_change().fillna(0.0)
-
- # optimizer weighting (before normalisation)
- if optimizer is not None:
- pos = optimizer(ret, pos, dates)
-
- scale = pos.abs().sum(axis=1).clip(lower=1.0)
- pos = pos.div(scale, axis=0)
-
- return dates, close, pos, ret
-
-
-def _benchmark_equity(
- ret: pd.DataFrame,
- cash: float,
-) -> tuple:
- """Calculate equal-weight buy-and-hold benchmark.
-
- Args:
- ret: Return matrix.
- cash: Initial capital.
-
- Returns:
- (bench_ret Series, bench_equity Series)
- """
- n_assets = ret.shape[1]
- bench_ret = ret.mean(axis=1) if n_assets > 0 else pd.Series(0.0, index=ret.index)
- bench_equity = cash * (1 + bench_ret).cumprod()
- return bench_ret, bench_equity
-
-
-def _portfolio_equity(
- pos: pd.DataFrame,
- ret: pd.DataFrame,
- commission: float,
- cash: float,
-) -> tuple:
- """Portfolio returns -> equity curve -> drawdown.
-
- Args:
- pos: Position matrix.
- ret: Return matrix.
- commission: Commission rate.
- cash: Initial capital.
-
- Returns:
- (port_ret Series, equity Series, drawdown Series)
- """
- port_ret = (pos * ret).sum(axis=1)
- turnover = pos.diff().abs().sum(axis=1).fillna(0.0)
- port_ret = port_ret - turnover * commission
- equity = cash * (1 + port_ret).cumprod()
- peak = equity.cummax()
- dd = (equity - peak) / peak.replace(0, 1)
- return port_ret, equity, dd
-
-
-def _log_trades(
- pos: pd.DataFrame,
- close: pd.DataFrame,
- codes: List[str],
-) -> List[Dict[str, Any]]:
- """Generate per-trade records from position diffs, including per-trade P&L.
-
- Args:
- pos: Position matrix.
- close: Close price matrix.
- codes: List of instrument codes.
-
- Returns:
- Trade list sorted by timestamp.
- """
- diff = pos.diff()
- diff.iloc[0] = pos.iloc[0]
-
- # Track entry cost and entry date per instrument
- cost: Dict[str, float] = {}
- hold: Dict[str, float] = {}
- entry_date: Dict[str, str] = {}
-
- trades: List[Dict[str, Any]] = []
- # Collect all trade events then sort by timestamp
- raw_events = []
- for c in codes:
- delta = diff[c]
- for ts in delta.index[delta.abs() > 1e-9]:
- d = float(delta.loc[ts])
- p = float(close.at[ts, c]) if pd.notna(close.at[ts, c]) else 0.0
- raw_events.append((str(ts.date()) if hasattr(ts, "date") else str(ts), c, d, p))
- raw_events.sort(key=lambda x: x[0])
-
- for ts_str, c, d, p in raw_events:
- side = "buy" if d > 0 else "sell"
- qty = abs(d)
- pnl = 0.0
- holding_days = 0
- return_pct = 0.0
-
- prev = hold.get(c, 0.0)
- if prev * d >= 0:
- # Same-direction add: update average cost
- old = cost.get(c, p)
- total = abs(prev) + qty
- cost[c] = (old * abs(prev) + p * qty) / total if total > 1e-9 else p
- hold[c] = prev + d
- if c not in entry_date:
- entry_date[c] = ts_str
- else:
- # Opposite direction: realise P&L
- close_qty = min(qty, abs(prev))
- entry = cost.get(c, p)
- pnl = (p - entry) * close_qty if prev > 0 else (entry - p) * close_qty
- return_pct = (p / entry - 1) * 100 if entry > 1e-9 and prev > 0 else (entry / p - 1) * 100 if p > 1e-9 else 0.0
-
- ed = entry_date.get(c, ts_str)
- try:
- holding_days = (pd.Timestamp(ts_str) - pd.Timestamp(ed)).days
- except Exception:
- holding_days = 0
-
- remain = prev + d
- if abs(remain) < 1e-9:
- hold.pop(c, None)
- cost.pop(c, None)
- entry_date.pop(c, None)
- else:
- hold[c] = remain
- if remain * prev <= 0:
- cost[c] = p
- entry_date[c] = ts_str
-
- trades.append({
- "timestamp": ts_str,
- "code": c,
- "side": side,
- "price": round(p, 4),
- "qty": round(qty, 6),
- "reason": "signal",
- "pnl": round(pnl, 4),
- "holding_days": holding_days,
- "return_pct": round(return_pct, 2),
- })
-
- return trades
-
-
-def _win_rate_and_stats(trades: List[Dict[str, Any]]) -> Dict[str, float]:
- """Calculate win rate and P&L statistics from trade records.
-
- Args:
- trades: List of trade records.
-
- Returns:
- Dict containing win_rate, profit_loss_ratio, max_consecutive_loss, avg_holding_days.
- """
- closed = [t for t in trades if t.get("pnl", 0) != 0]
- if not closed:
- return {"win_rate": 0.0, "profit_loss_ratio": 0.0, "max_consecutive_loss": 0, "avg_holding_days": 0.0}
-
- wins = [t["pnl"] for t in closed if t["pnl"] > 0]
- losses = [t["pnl"] for t in closed if t["pnl"] < 0]
- win_rate = len(wins) / len(closed) if closed else 0.0
-
- avg_win = np.mean(wins) if wins else 0.0
- avg_loss = abs(np.mean(losses)) if losses else 1e-10
- profit_loss_ratio = avg_win / avg_loss if avg_loss > 1e-10 else 0.0
-
- # Max consecutive losses
- max_consec = 0
- cur_consec = 0
- for t in closed:
- if t["pnl"] < 0:
- cur_consec += 1
- max_consec = max(max_consec, cur_consec)
- else:
- cur_consec = 0
-
- # Average holding days
- hold_days = [t["holding_days"] for t in closed if t["holding_days"] > 0]
- avg_holding = np.mean(hold_days) if hold_days else 0.0
-
- return {
- "win_rate": win_rate,
- "profit_loss_ratio": round(profit_loss_ratio, 4),
- "max_consecutive_loss": max_consec,
- "avg_holding_days": round(avg_holding, 1),
- }
-
-
-def _metrics(
- port_ret: pd.Series,
- equity: pd.Series,
- dd: pd.Series,
- cash: float,
- trades: List[Dict[str, Any]],
- bench_ret: Optional[pd.Series] = None,
- bars_per_year: int = 252,
-) -> Dict[str, Any]:
- """Calculate the full set of performance metrics.
-
- Args:
- port_ret: Portfolio bar return series.
- equity: Equity curve.
- dd: Drawdown series.
- cash: Initial capital.
- trades: Trade records.
- bench_ret: Benchmark return series (optional).
- bars_per_year: Bars per year (252 for daily, 8760 for 1H OKX, etc.).
-
- Returns:
- Metrics dictionary.
- """
- n = len(port_ret)
- if n == 0:
- return dict(
- final_value=cash, total_return=0, annual_return=0,
- max_drawdown=0, sharpe=0, calmar=0, sortino=0,
- win_rate=0, profit_loss_ratio=0, max_consecutive_loss=0,
- avg_holding_days=0, trade_count=0,
- benchmark_return=0, excess_return=0, information_ratio=0,
- )
-
- bpy = bars_per_year
-
- total_ret = float(equity.iloc[-1] / cash - 1)
- ann_ret = float((1 + total_ret) ** (bpy / max(n, 1)) - 1)
- vol = float(port_ret.std())
- sharpe = float(port_ret.mean() / (vol + 1e-10) * np.sqrt(bpy))
-
- # Calmar = annualised return / |max drawdown|
- max_dd = float(dd.min())
- calmar = ann_ret / abs(max_dd) if abs(max_dd) > 1e-10 else 0.0
-
- # Sortino = mean(ret) / downside_std * sqrt(bars_per_year) (unchanged)
- downside = port_ret[port_ret < 0]
- downside_std = float(downside.std()) if len(downside) > 1 else 1e-10
- sortino = float(port_ret.mean() / (downside_std + 1e-10) * np.sqrt(bpy))
-
- # Trade statistics
- trade_stats = _win_rate_and_stats(trades)
-
- # Benchmark comparison
- bench_return = 0.0
- excess = 0.0
- ir = 0.0
- if bench_ret is not None and len(bench_ret) > 0:
- bench_return = float((1 + bench_ret).prod() - 1)
- excess = total_ret - bench_return
- active_ret = port_ret - bench_ret
- active_std = float(active_ret.std())
- ir = float(active_ret.mean() / (active_std + 1e-10) * np.sqrt(bpy))
-
- return {
- "final_value": float(equity.iloc[-1]),
- "total_return": total_ret,
- "annual_return": ann_ret,
- "max_drawdown": max_dd,
- "sharpe": sharpe,
- "calmar": round(calmar, 4),
- "sortino": round(sortino, 4),
- "win_rate": trade_stats["win_rate"],
- "profit_loss_ratio": trade_stats["profit_loss_ratio"],
- "max_consecutive_loss": trade_stats["max_consecutive_loss"],
- "avg_holding_days": trade_stats["avg_holding_days"],
- "trade_count": len(trades),
- "benchmark_return": round(bench_return, 6),
- "excess_return": round(excess, 6),
- "information_ratio": round(ir, 4),
- }
-
-
-def run_backtest(
- config: Dict[str, Any],
- loader: Any,
- engine: Any,
- run_dir: Path,
- bars_per_year: int = 252,
-) -> Dict[str, Any]:
- """Main entry point: load data -> generate signals -> vectorised backtest -> write artifacts.
-
- Args:
- config: Backtest configuration (codes, start_date, end_date, initial_cash, commission,
- extra_fields, optimizer, interval, source).
- loader: DataLoader instance (must have a fetch method).
- engine: SignalEngine instance (must have a generate method).
- run_dir: Run directory path.
- bars_per_year: Bars per year, computed by runner from interval+source.
-
- Returns:
- Metrics dictionary.
-
- Raises:
- SystemExit: When no data is fetched or no valid signals are generated.
- """
- import json
- import sys
-
- codes = config.get("codes", [])
- start_date = config.get("start_date", "")
- end_date = config.get("end_date", "")
- initial_cash = config.get("initial_cash", 1_000_000)
- commission = config.get("commission", 0.001)
- extra_fields = config.get("extra_fields") or None
-
- interval = config.get("interval", "1D")
- data_map = loader.fetch(codes, start_date, end_date, fields=extra_fields, interval=interval)
- if not data_map:
- print(json.dumps({"error": "No data fetched"}))
- sys.exit(1)
-
- signal_map = engine.generate(data_map)
- valid_codes = sorted(c for c in signal_map if c in data_map)
- if not valid_codes:
- print(json.dumps({"error": "No valid signals generated"}))
- sys.exit(1)
-
- # Load optimizer if configured
- opt_fn = _load_optimizer(config)
-
- dates, close, pos, ret = _align(data_map, signal_map, valid_codes, optimizer=opt_fn)
- port_ret, equity, dd = _portfolio_equity(pos, ret, commission, initial_cash)
- bench_ret, bench_equity = _benchmark_equity(ret, initial_cash)
- trades = _log_trades(pos, close, valid_codes)
- m = _metrics(port_ret, equity, dd, initial_cash, trades, bench_ret, bars_per_year)
-
- out = run_dir / "artifacts"
- out.mkdir(parents=True, exist_ok=True)
-
- for code, df in data_map.items():
- df.to_csv(out / f"ohlcv_{code}.csv")
-
- eq = pd.DataFrame({
- "ret": port_ret,
- "equity": equity,
- "drawdown": dd,
- "benchmark_equity": bench_equity,
- "active_ret": port_ret - bench_ret,
- }, index=dates)
- eq.index.name = "timestamp"
- eq.to_csv(out / "equity.csv")
-
- pos.index.name = "timestamp"
- pos.to_csv(out / "positions.csv")
-
- trade_cols = ["timestamp", "code", "side", "price", "qty", "reason", "pnl", "holding_days", "return_pct"]
- pd.DataFrame(
- trades or [],
- columns=trade_cols,
- ).to_csv(out / "trades.csv", index=False)
-
- pd.DataFrame([m]).to_csv(out / "metrics.csv", index=False)
- print(json.dumps(m, indent=2))
- return m
-
-
-def _load_optimizer(config: Dict[str, Any]) -> Optional[Callable]:
- """Dynamically load an optimizer function from config.
-
- Supports any module under backtest/optimizers/ that exposes an
- `optimize(ret, pos, dates, **params)` function.
-
- Args:
- config: Backtest configuration.
-
- Returns:
- Optimizer callable, or None.
- """
- import importlib
-
- opt_name = config.get("optimizer")
- if not opt_name:
- return None
-
- opt_params = config.get("optimizer_params") or {}
-
- try:
- mod = importlib.import_module(f"backtest.optimizers.{opt_name}")
- return lambda ret, pos, dates: mod.optimize(ret, pos, dates, **opt_params)
- except (ImportError, AttributeError) as e:
- print(f"[WARN] Failed to load optimizer '{opt_name}': {e}, falling back to equal weight")
- return None
diff --git a/agent/backtest/engines/global_equity.py b/agent/backtest/engines/global_equity.py
new file mode 100644
index 000000000..a80e0288f
--- /dev/null
+++ b/agent/backtest/engines/global_equity.py
@@ -0,0 +1,74 @@
+"""Global equity (US / HK) backtest engine.
+
+Market rules:
+ US:
+ - T+0, long/short allowed
+ - Zero commission (retail brokers)
+ - Fractional shares supported (round to 0.01)
+ - Low slippage (high liquidity)
+ HK:
+ - T+0, long/short allowed
+ - Stamp tax 0.1% bilateral + levies
+ - Lot-size rounding (simplified to 100 shares)
+ - Higher slippage than US
+"""
+
+from __future__ import annotations
+
+import pandas as pd
+
+from backtest.engines.base import BaseEngine
+
+
+class GlobalEquityEngine(BaseEngine):
+ """US / HK equity engine, selected by *market* parameter.
+
+ Config keys:
+ - slippage_us: default 0.0005
+ - slippage_hk: default 0.001
+ - hk_stamp_tax: default 0.001 (0.1% bilateral)
+ - hk_commission: default 0.00015 (δΈ‡1.5)
+ - hk_levy: default 0.0000565 (SFC + FRC)
+ - hk_settlement: default 0.00002 (CCASS)
+ """
+
+ def __init__(self, config: dict, market: str = "us"):
+ config = {**config, "leverage": config.get("leverage", 1.0)}
+ super().__init__(config)
+ self.market = market
+
+ # US defaults
+ self.slippage_us: float = config.get("slippage_us", 0.0005)
+ # HK defaults
+ self.slippage_hk: float = config.get("slippage_hk", 0.001)
+ self.hk_stamp_tax: float = config.get("hk_stamp_tax", 0.001)
+ self.hk_commission: float = config.get("hk_commission", 0.00015)
+ self.hk_levy: float = config.get("hk_levy", 0.0000565)
+ self.hk_settlement: float = config.get("hk_settlement", 0.00002)
+
+ def can_execute(self, symbol: str, direction: int, bar: pd.Series) -> bool:
+ """US/HK: T+0, both directions allowed."""
+ return True
+
+ def round_size(self, raw_size: float, price: float) -> float:
+ """US: fractional shares (0.01). HK: 100-share lots."""
+ if self.market == "hk":
+ return max(int(raw_size / 100) * 100, 0)
+ return round(max(raw_size, 0.0), 2)
+
+ def calc_commission(self, size: float, price: float, direction: int, is_open: bool) -> float:
+ """US: zero commission. HK: stamp tax + levies."""
+ if self.market == "hk":
+ notional = size * price
+ comm = notional * self.hk_commission # broker commission
+ comm += notional * self.hk_stamp_tax # stamp tax bilateral
+ comm += notional * self.hk_levy # SFC + FRC levies
+ comm += notional * self.hk_settlement # CCASS settlement
+ return comm
+ # US: zero commission (SEC fee negligible)
+ return 0.0
+
+ def apply_slippage(self, price: float, direction: int) -> float:
+ """US: low slippage. HK: moderate slippage."""
+ rate = self.slippage_hk if self.market == "hk" else self.slippage_us
+ return price * (1 + direction * rate)
diff --git a/agent/backtest/metrics.py b/agent/backtest/metrics.py
new file mode 100644
index 000000000..744f6bf5b
--- /dev/null
+++ b/agent/backtest/metrics.py
@@ -0,0 +1,232 @@
+"""Shared backtest metrics, extracted from daily_portfolio.py for reuse.
+
+Provides annualisation helpers, trade statistics, and full metric calculation.
+"""
+
+from __future__ import annotations
+
+from typing import Any, Dict, List, Optional
+
+import numpy as np
+import pandas as pd
+
+from backtest.models import TradeRecord
+
+# ─── Annualisation factor mapping ───
+
+_TRADING_DAYS = {"tushare": 252, "yfinance": 252, "okx": 365}
+_BARS_PER_DAY = {
+ "1m": {"tushare": 240, "okx": 1440, "yfinance": 390},
+ "5m": {"tushare": 48, "okx": 288, "yfinance": 78},
+ "15m": {"tushare": 16, "okx": 96, "yfinance": 26},
+ "30m": {"tushare": 8, "okx": 48, "yfinance": 13},
+ "1H": {"tushare": 4, "okx": 24, "yfinance": 7},
+ "4H": {"tushare": 1, "okx": 6, "yfinance": 2},
+ "1D": {"tushare": 1, "okx": 1, "yfinance": 1},
+}
+
+
+def calc_bars_per_year(interval: str = "1D", source: str = "tushare") -> int:
+ """Number of bars per year for annualisation.
+
+ Args:
+ interval: Bar size (1m / 5m / 15m / 30m / 1H / 4H / 1D).
+ source: Data source (tushare / yfinance / okx).
+
+ Returns:
+ Bars per year.
+ """
+ trading_days = _TRADING_DAYS.get(source, 252)
+ bars_per_day = _BARS_PER_DAY.get(interval, {}).get(source, 1)
+ return trading_days * bars_per_day
+
+
+def win_rate_and_stats(trades: List[TradeRecord]) -> Dict[str, float]:
+ """Win rate and P&L statistics from completed trades.
+
+ Args:
+ trades: Completed round-trip trades.
+
+ Returns:
+ Dict with win_rate, profit_loss_ratio, max_consecutive_loss,
+ avg_holding_bars, profit_factor.
+ """
+ if not trades:
+ return {
+ "win_rate": 0.0,
+ "profit_loss_ratio": 0.0,
+ "max_consecutive_loss": 0,
+ "avg_holding_bars": 0.0,
+ "profit_factor": 0.0,
+ }
+
+ wins = [t.pnl for t in trades if t.pnl > 0]
+ losses = [t.pnl for t in trades if t.pnl < 0]
+
+ win_rate = len(wins) / len(trades)
+
+ avg_win = float(np.mean(wins)) if wins else 0.0
+ avg_loss = abs(float(np.mean(losses))) if losses else 1e-10
+ profit_loss_ratio = avg_win / avg_loss if avg_loss > 1e-10 else 0.0
+
+ gross_profit = sum(wins) if wins else 0.0
+ gross_loss = abs(sum(losses)) if losses else 1e-10
+ profit_factor = gross_profit / gross_loss if gross_loss > 1e-10 else 0.0
+
+ max_consec = 0
+ cur_consec = 0
+ for t in trades:
+ if t.pnl < 0:
+ cur_consec += 1
+ max_consec = max(max_consec, cur_consec)
+ else:
+ cur_consec = 0
+
+ hold_bars = [t.holding_bars for t in trades if t.holding_bars > 0]
+ avg_holding = float(np.mean(hold_bars)) if hold_bars else 0.0
+
+ return {
+ "win_rate": win_rate,
+ "profit_loss_ratio": round(profit_loss_ratio, 4),
+ "max_consecutive_loss": max_consec,
+ "avg_holding_bars": round(avg_holding, 1),
+ "profit_factor": round(profit_factor, 4),
+ }
+
+
+def by_symbol_stats(trades: List[TradeRecord]) -> Dict[str, Dict[str, Any]]:
+ """Per-symbol trade statistics.
+
+ Args:
+ trades: Completed round-trip trades.
+
+ Returns:
+ {symbol: {count, win_rate, total_pnl, avg_pnl}}.
+ """
+ groups: Dict[str, list] = {}
+ for t in trades:
+ groups.setdefault(t.symbol, []).append(t)
+
+ result = {}
+ for sym, sym_trades in groups.items():
+ pnls = [t.pnl for t in sym_trades]
+ wins = [p for p in pnls if p > 0]
+ result[sym] = {
+ "count": len(sym_trades),
+ "win_rate": round(len(wins) / len(sym_trades), 4) if sym_trades else 0.0,
+ "total_pnl": round(sum(pnls), 2),
+ "avg_pnl": round(float(np.mean(pnls)), 2) if pnls else 0.0,
+ }
+ return result
+
+
+def by_exit_reason_stats(trades: List[TradeRecord]) -> Dict[str, Dict[str, Any]]:
+ """Per-exit-reason trade statistics.
+
+ Args:
+ trades: Completed round-trip trades.
+
+ Returns:
+ {reason: {count, total_pnl}}.
+ """
+ groups: Dict[str, list] = {}
+ for t in trades:
+ groups.setdefault(t.exit_reason, []).append(t)
+
+ result = {}
+ for reason, reason_trades in groups.items():
+ pnls = [t.pnl for t in reason_trades]
+ result[reason] = {
+ "count": len(reason_trades),
+ "total_pnl": round(sum(pnls), 2),
+ }
+ return result
+
+
+def calc_metrics(
+ equity_curve: pd.Series,
+ trades: List[TradeRecord],
+ initial_cash: float,
+ bars_per_year: int = 252,
+ bench_ret: Optional[pd.Series] = None,
+) -> Dict[str, Any]:
+ """Full set of performance metrics.
+
+ Args:
+ equity_curve: Equity time series (index=timestamp, values=equity).
+ trades: Completed round-trip trades.
+ initial_cash: Starting capital.
+ bars_per_year: Bars per year for annualisation.
+ bench_ret: Benchmark per-bar return series (optional).
+
+ Returns:
+ Metrics dictionary (compatible with daily_portfolio format).
+ """
+ if len(equity_curve) == 0:
+ return _empty_metrics(initial_cash)
+
+ n = len(equity_curve)
+ bpy = bars_per_year
+
+ port_ret = equity_curve.pct_change().fillna(0.0)
+
+ total_ret = float(equity_curve.iloc[-1] / initial_cash - 1)
+ ann_ret = float((1 + total_ret) ** (bpy / max(n, 1)) - 1)
+ vol = float(port_ret.std())
+ sharpe = float(port_ret.mean() / (vol + 1e-10) * np.sqrt(bpy))
+
+ # Drawdown
+ peak = equity_curve.cummax()
+ dd = (equity_curve - peak) / peak.replace(0, 1)
+ max_dd = float(dd.min())
+
+ calmar = ann_ret / abs(max_dd) if abs(max_dd) > 1e-10 else 0.0
+
+ # Sortino
+ downside = port_ret[port_ret < 0]
+ downside_std = float(downside.std()) if len(downside) > 1 else 1e-10
+ sortino = float(port_ret.mean() / (downside_std + 1e-10) * np.sqrt(bpy))
+
+ trade_stats = win_rate_and_stats(trades)
+
+ # Benchmark comparison
+ bench_return = 0.0
+ excess = 0.0
+ ir = 0.0
+ if bench_ret is not None and len(bench_ret) > 0:
+ bench_return = float((1 + bench_ret).prod() - 1)
+ excess = total_ret - bench_return
+ active_ret = port_ret - bench_ret.reindex(port_ret.index).fillna(0.0)
+ active_std = float(active_ret.std())
+ ir = float(active_ret.mean() / (active_std + 1e-10) * np.sqrt(bpy))
+
+ return {
+ "final_value": float(equity_curve.iloc[-1]),
+ "total_return": total_ret,
+ "annual_return": ann_ret,
+ "max_drawdown": max_dd,
+ "sharpe": sharpe,
+ "calmar": round(calmar, 4),
+ "sortino": round(sortino, 4),
+ "win_rate": trade_stats["win_rate"],
+ "profit_loss_ratio": trade_stats["profit_loss_ratio"],
+ "profit_factor": trade_stats["profit_factor"],
+ "max_consecutive_loss": trade_stats["max_consecutive_loss"],
+ "avg_holding_days": trade_stats["avg_holding_bars"],
+ "trade_count": len(trades),
+ "benchmark_return": round(bench_return, 6),
+ "excess_return": round(excess, 6),
+ "information_ratio": round(ir, 4),
+ }
+
+
+def _empty_metrics(initial_cash: float) -> Dict[str, Any]:
+ """Return zero-valued metrics when no data is available."""
+ return {
+ "final_value": initial_cash,
+ "total_return": 0, "annual_return": 0, "max_drawdown": 0,
+ "sharpe": 0, "calmar": 0, "sortino": 0,
+ "win_rate": 0, "profit_loss_ratio": 0, "profit_factor": 0,
+ "max_consecutive_loss": 0, "avg_holding_days": 0, "trade_count": 0,
+ "benchmark_return": 0, "excess_return": 0, "information_ratio": 0,
+ }
diff --git a/agent/backtest/models.py b/agent/backtest/models.py
new file mode 100644
index 000000000..9ff03e584
--- /dev/null
+++ b/agent/backtest/models.py
@@ -0,0 +1,89 @@
+"""Shared data models for backtest engines.
+
+Immutable dataclasses for positions, trades, and equity snapshots.
+"""
+
+from __future__ import annotations
+
+from dataclasses import dataclass
+
+import pandas as pd
+
+
+@dataclass(frozen=True)
+class Position:
+ """An open position in a single instrument.
+
+ Args:
+ symbol: Instrument identifier.
+ direction: 1 for long, -1 for short.
+ entry_price: Execution price at entry.
+ entry_time: Timestamp when position was opened.
+ size: Number of shares / coins.
+ leverage: Effective leverage (1 for spot/stocks).
+ entry_bar_idx: Index in the dates array at entry (for holding_bars).
+ entry_commission: Commission paid at entry.
+ """
+
+ symbol: str
+ direction: int
+ entry_price: float
+ entry_time: pd.Timestamp
+ size: float
+ leverage: float = 1.0
+ entry_bar_idx: int = 0
+ entry_commission: float = 0.0
+
+
+@dataclass(frozen=True)
+class TradeRecord:
+ """A completed round-trip trade.
+
+ Args:
+ symbol: Instrument identifier.
+ direction: 1 for long, -1 for short.
+ entry_price: Entry execution price.
+ exit_price: Exit execution price.
+ entry_time: Entry timestamp.
+ exit_time: Exit timestamp.
+ size: Number of shares / coins traded.
+ leverage: Effective leverage.
+ pnl: Realised profit/loss in cash terms.
+ pnl_pct: Realised P&L as percentage of margin.
+ exit_reason: Why closed (signal / liquidation / end_of_backtest).
+ holding_bars: Number of bars held.
+ commission: Total commission (entry + exit).
+ """
+
+ symbol: str
+ direction: int
+ entry_price: float
+ exit_price: float
+ entry_time: pd.Timestamp
+ exit_time: pd.Timestamp
+ size: float
+ leverage: float
+ pnl: float
+ pnl_pct: float
+ exit_reason: str
+ holding_bars: int
+ commission: float
+
+
+@dataclass(frozen=True)
+class EquitySnapshot:
+ """Portfolio state at a single point in time.
+
+ Args:
+ timestamp: Bar timestamp.
+ capital: Free cash.
+ unrealized: Total unrealised P&L across all positions.
+ equity: capital + margin_in_use + unrealized.
+ positions: Number of open positions.
+ """
+
+ timestamp: pd.Timestamp
+ capital: float
+ unrealized: float
+ equity: float
+ positions: int
diff --git a/agent/backtest/runner.py b/agent/backtest/runner.py
index 7e254d959..244f02327 100644
--- a/agent/backtest/runner.py
+++ b/agent/backtest/runner.py
@@ -162,38 +162,65 @@ def main(run_dir: Path) -> None:
# Engine
engine_type = config.get("engine", "daily")
- run_backtest_fn = _get_engine(engine_type)
-
- engine = engine_cls()
+ signal_engine = engine_cls()
# Annualization bars
effective_source = _detect_primary_source(codes, source)
- from backtest.engines.daily_portfolio import _calc_bars_per_year
- bars_per_year = _calc_bars_per_year(interval, effective_source)
+ from backtest.metrics import calc_bars_per_year
+ bars_per_year = calc_bars_per_year(interval, effective_source)
# Auto mode: wrap preloaded data in a dummy loader
if source == "auto":
loader = _AutoLoader(data_map)
- run_backtest_fn(config, loader, engine, run_dir, bars_per_year=bars_per_year)
+
+ if engine_type == "options":
+ from backtest.engines.options_portfolio import run_options_backtest
+ run_options_backtest(config, loader, signal_engine, run_dir, bars_per_year=bars_per_year)
else:
- run_backtest_fn(config, loader, engine, run_dir, bars_per_year=bars_per_year)
+ market_engine = _create_market_engine(effective_source, config, codes)
+ market_engine.run_backtest(config, loader, signal_engine, run_dir, bars_per_year=bars_per_year)
-def _get_engine(engine_type: str):
- """Resolve ``run_backtest`` / ``run_options_backtest`` by engine name.
+def _create_market_engine(source: str, config: dict, codes: List[str]):
+ """Create the appropriate market engine based on data source.
Args:
- engine_type: ``daily`` or ``options``.
+ source: Data source (okx / tushare / yfinance).
+ config: Backtest configuration.
+ codes: Instrument codes.
Returns:
- Callable backtest entry.
+ BaseEngine subclass instance.
"""
- if engine_type == "options":
- from backtest.engines.options_portfolio import run_options_backtest
- return run_options_backtest
+ if source == "okx":
+ from backtest.engines.crypto import CryptoEngine
+ return CryptoEngine(config)
+ elif source == "tushare":
+ from backtest.engines.china_a import ChinaAEngine
+ return ChinaAEngine(config)
+ elif source == "yfinance":
+ from backtest.engines.global_equity import GlobalEquityEngine
+ market = _detect_submarket(codes)
+ return GlobalEquityEngine(config, market=market)
else:
- from backtest.engines.daily_portfolio import run_backtest
- return run_backtest
+ # Default: crypto (most permissive rules)
+ from backtest.engines.crypto import CryptoEngine
+ return CryptoEngine(config)
+
+
+def _detect_submarket(codes: List[str]) -> str:
+ """Detect US vs HK from symbol suffixes.
+
+ Args:
+ codes: Instrument codes.
+
+ Returns:
+ "hk" if any code ends with .HK, else "us".
+ """
+ for code in codes:
+ if code.upper().endswith(".HK"):
+ return "hk"
+ return "us"
def _detect_primary_source(codes: List[str], source: str) -> str: