Ai Trading Backtester
/install ai-trading-backtester
\r \r
AI Trading Strategy Backtester\r
\r
Overview\r
\r An AI-powered quantitative trading strategy design and backtesting assistant that helps you transform trading ideas into fully-coded, backtested strategies. It guides you through strategy design (mean reversion, momentum, breakout, pairs trading, ML-based), implements them in Python (backtrader, vectorbt, pandas), evaluates performance across historical data for A-share, HK, and US markets, and produces risk-adjusted performance reports.\r \r
Triggers\r
\r
- "backtest my trading strategy"\r
- "design a momentum strategy for [stock/market]"\r
- "test mean reversion on [symbol]"\r
- "pairs trading strategy example"\r
- "Python backtrader setup guide"\r
- "vectorbt tutorial"\r
- "trading strategy optimization"\r
- "量化回测策略"\r
- "技术指标择时策略"\r
- "A股量化策略设计"\r \r
Workflow\r
\r
Step 1: Define the Strategy Brief\r
\r Collect the trading idea:\r
- Strategy type: Momentum, mean reversion, breakout, pairs trading, ML-based, event-driven\r
- Market: A-share (sh/sz), HK stock (hk), US equity (us)\r
- Timeframe: Intraday (1m/5m/15m), daily, weekly, monthly\r
- Assets: Single stock, ETF, index, portfolio\r
- Entry/Exit signals: Technical indicators, price patterns, fundamental signals, ML predictions\r
- Position sizing: Fixed, Kelly criterion, risk-parity, dynamic\r
- Constraints: Max position size, long-only/short, turnover limit, slippage model\r \r
Step 2: Strategy Design & Code Generation\r
\r Based on the brief, generate production-quality Python code:\r \r
A. Momentum Strategy Template\r
import pandas as pd\r
import numpy as np\r
import backtrader as bt\r
\r
class MomentumStrategy(bt.Strategy):\r
params = (\r
('lookback', 20), # 回望期\r
('hold_period', 5), # 持有期\r
('rank_percentile', 0.2), # 选股分位数\r
)\r
\r
def __init__(self):\r
self.inds = {}\r
for d in self.datas:\r
self.inds[d] = {}\r
self.inds[d]['momentum'] = bt.indicators.RateOfChange(\r
d.close, period=self.params.lookback\r
)\r
\r
def next(self):\r
# 按动量排序,取前20%\r
rankings = sorted(\r
self.datas,\r
key=lambda d: self.inds[d]['momentum'][0],\r
reverse=True\r
)[:int(len(self.datas) * self.params.rank_percentile)]\r
\r
# 平仓不在榜单的持仓\r
for d in self.datas:\r
if d not in rankings and self.getposition(d).size > 0:\r
self.close(d)\r
\r
# 买入榜单中的标的\r
for d in rankings:\r
if self.getposition(d).size == 0:\r
self.order_target_percent(d, 1.0 / len(rankings))\r
```\r
\r
#### B. Mean Reversion Strategy Template\r
```python\r
class MeanReversionStrategy(bt.Strategy):\r
params = (\r
('bb_period', 20),\r
('bb_dev', 2.0),\r
('rsi_period', 14),\r
('rsi_oversold', 30),\r
('rsi_overbought', 70),\r
)\r
\r
def __init__(self):\r
self.bb = bt.indicators.BollingerBands(\r
self.data.close, period=self.params.bb_period,\r
devfactor=self.params.bb_dev\r
)\r
self.rsi = bt.indicators.RSI(\r
self.data.close, period=self.params.rsi_period\r
)\r
\r
def next(self):\r
if self.position.size == 0:\r
# 价格触及下轨且RSI超卖 → 买入\r
if self.data.close \x3C self.bb.lines.bot and \\r
self.rsi \x3C self.params.rsi_oversold:\r
self.order_target_percent(self.data, 1.0)\r
else:\r
# 价格触及上轨或RSI超买 → 卖出\r
if self.data.close > self.bb.lines.top or \\r
self.rsi > self.params.rsi_overbought:\r
self.close()\r
```\r
\r
#### C. Pairs Trading Strategy\r
```python\r
import statsmodels.api as sm\r
\r
def find_cointegrated_pairs(data_dict):\r
"""寻找协整配对"""\r
n = len(data_dict)\r
pairs = []\r
symbols = list(data_dict.keys())\r
\r
for i in range(n):\r
for j in range(i + 1, n):\r
try:\r
x = data_dict[symbols[i]]\r
y = data_dict[symbols[j]]\r
# OLS回归\r
X = sm.add_constant(x)\r
model = sm.OLS(y, X).fit()\r
residuals = model.resid\r
# ADF检验\r
adf_result = sm.tsa.stattools.adfuller(residuals)\r
if adf_result[0] \x3C adf_result[4]['1%']:\r
pairs.append((symbols[i], symbols[j], adf_result[0]))\r
except:\r
continue\r
return sorted(pairs, key=lambda x: x[2])\r
\r
def pairs_trading_signals(spread, z_entry=2.0, z_exit=0.5):\r
"""配对交易信号"""\r
signals = pd.Series(0, index=spread.index)\r
z_score = (spread - spread.mean()) / spread.std()\r
\r
signals[z_score \x3C -z_entry] = 1 # 做多价差\r
signals[z_score > z_entry] = -1 # 做空价差\r
signals[abs(z_score) \x3C z_exit] = 0 # 平仓\r
return signals\r
```\r
\r
### Step 3: Backtest Execution\r
\r
Guide the user through running the backtest:\r
\r
```python\r
import backtrader as bt\r
import pandas as pd\r
\r
# 加载数据\r
data = bt.feeds.GenericCSVData(\r
dataname='historical_data.csv',\r
dtformat='%Y-%m-%d',\r
datetime=0,\r
open=1, high=2, low=3, close=4, volume=5,\r
openinterest=-1\r
)\r
\r
# 运行回测\r
cerebro = bt.Cerebro()\r
cerebro.addstrategy(MomentumStrategy)\r
cerebro.adddata(data)\r
cerebro.broker.setcash(1000000.0) # 100万初始资金\r
cerebro.broker.setcommission(commission=0.001) # 千一手续费\r
cerebro.addsizer(bt.sizers.PercentSizer, percents=95)\r
\r
print(f'初始资金: {cerebro.broker.getvalue():,.2f}')\r
cerebro.run()\r
print(f'最终资金: {cerebro.broker.getvalue():,.2f}')\r
```\r
\r
### Step 4: Performance Analysis\r
\r
Generate comprehensive performance metrics:\r
\r
| Metric | Description | Target |\r
|--------|-------------|--------|\r
| Total Return | Cumulative return | > Benchmark |\r
| Annualized Return | CAGR | > 10% (A-share), > 8% (HK/US) |\r
| Sharpe Ratio | Risk-adjusted return | > 1.5 |\r
| Max Drawdown | Peak-to-trough loss | \x3C 20% |\r
| Win Rate | Percentage of profitable trades | > 50% |\r
| Profit Factor | Gross profit / Gross loss | > 1.5 |\r
| Calmar Ratio | Annual return / Max DD | > 1.0 |\r
| Sortino Ratio | Return / Downside deviation | > 1.0 |\r
\r
### Step 5: Optimization & Stress Testing\r
\r
```\r
A. 参数优化\r
- Grid search over key parameters\r
- Walk-forward analysis (in-sample / out-of-sample)\r
- Avoid overfitting: use Information Coefficient (IC) analysis\r
\r
B. 压力测试\r
- Historical crises: 2008, 2015 A-share crash, COVID-19 (2020)\r
- Monte Carlo simulation of equity curves\r
- Sensitivity analysis: commission, slippage, spread assumptions\r
\r
C. 风险分析\r
- Position-level VaR (Value at Risk)\r
- Factor exposure (momentum, size, volatility)\r
- Tail risk: maximum loss scenarios\r
```\r
\r
## Input/Output Examples\r
\r
### Example 1: Strategy Design Request\r
\r
**Input:**\r
```\r
Design a momentum strategy for A-share market.\r
Criteria:\r
- Daily timeframe\r
- Lookback: 20 days\r
- Hold for 5 days\r
- Long only\r
- Top 20% by momentum score\r
- Max 10 positions\r
- Trade AAPL, TSLA, NVDA, MSFT\r
```\r
\r
**Output:**\r
```\r
Strategy Design Summary:\r
\r
┌─────────────────────────────────────────┐\r
│ Strategy: Top-Momentum Long-Only │\r
│ Market: US Equity (4 stocks) │\r
│ Timeframe: Daily │\r
│ Backtest Period: 2020-01-01 to 2025-12-31 │\r
└─────────────────────────────────────────┘\r
\r
Key Components:\r
1. Momentum ranking: ROC(close, period=20)\r
2. Selection: Top 20% by momentum score (max 10 stocks)\r
3. Position sizing: Equal weight (10% per position)\r
4. Hold period: 5 trading days\r
5. Rebalance: Daily at market open\r
\r
Expected Performance (illustrative):\r
- Annualized Return: 18-25% (historical backtest)\r
- Sharpe Ratio: 0.8-1.2\r
- Max Drawdown: 30-40%\r
- Win Rate: 52-56%\r
\r
Code generated at: strategy_momentum_us.py\r
```\r
\r
### Example 2: Performance Report\r
\r
**Input:**\r
```\r
Compare these two strategies: RSI mean reversion vs momentum breakout on CSI 300 (000300)\r
Period: 2020-2024\r
Initial capital: 1,000,000 CNY\r
```\r
\r
**Output:**\r
```\r
Backtest Results: CSI 300 Strategies (2020-2024)\r
\r
┌──────────────────────┬─────────────────────┬────────────────────┐\r
│ Metric │ RSI Mean Reversion │ Momentum Breakout │\r
├──────────────────────┼─────────────────────┼────────────────────┤\r
│ Total Return │ +68.3% │ +124.7% │\r
│ Annualized Return │ +13.2% │ +17.8% │\r
│ Sharpe Ratio │ 1.12 │ 1.45 │\r
│ Max Drawdown │ -22.1% │ -31.4% │\r
│ Win Rate │ 58.3% │ 49.2% │\r
│ Profit Factor │ 1.82 │ 1.67 │\r
│ Calmar Ratio │ 0.60 │ 0.57 │\r
│ Avg Holding Days │ 8.2 │ 4.6 │\r
│ Total Trades │ 127 │ 284 │\r
└──────────────────────┴─────────────────────┴────────────────────┘\r
Benchmark: CSI 300 Index (+42.1% over same period)\r
\r
Recommendation:\r
- Risk-averse investors: RSI Mean Reversion (lower drawdown, higher win rate)\r
- Return-seeking investors: Momentum Breakout (higher return, more trades)\r
\r
⚠️ Note: Past performance does not guarantee future results.\r
A-share markets are subject to significant regulatory and liquidity risks.\r
```\r
\r
## Strategy Templates Library\r
\r
| Strategy Type | Best For | Timeframe | Markets |\r
|--------------|----------|-----------|---------|\r
| Momentum | Trending markets | Daily/Weekly | All |\r
| Mean Reversion | Range-bound markets | Intraday/Daily | All |\r
| Breakout | Volatile markets | Intraday/Daily | All |\r
| Pairs Trading | Market-neutral | Daily | US/HK |\r
| Machine Learning | Alpha discovery | Daily | All |\r
| Event-Driven | Corporate actions | Daily | A-share/US |\r
\r
## Best Practices\r
\r
1. **Always use out-of-sample testing** — split data 70/30 or use walk-forward\r
2. **Account for transaction costs** — A-share commission + stamp tax ≈ 0.15% per trade\r
3. **Include slippage** — assume 0.05-0.1% for liquid stocks, higher for illiquid\r
4. **Diversify across uncorrelated strategies** — don't rely on one strategy\r
5. **Stress test for A-share specifics** — T+1 trading, limit-up/limit-down, suspension risks\r
6. **Validate with paper trading** — run live for 1-3 months before real capital\r
7. **Beware of overfitting** — fewer parameters = more robust strategy\r
\r
## Risk Disclaimer\r
\r
This skill provides backtesting tools and historical analysis for educational and research purposes only. Backtested results are not indicative of future performance. Real trading involves significant risks including market volatility, liquidity constraints, regulatory changes, and model risk. Always consult with qualified financial advisors before making investment decisions.\r
- Make sure OpenClaw is installed (local or Docker)
- Run the install command in chat:
/install ai-trading-backtester - After installation, invoke the skill by name or use
/ai-trading-backtester - Provide required inputs per the skill's parameter spec and get structured output
What is Ai Trading Backtester?
AI-powered quantitative trading strategy backtesting assistant. Designs, codes, and evaluates trading strategies across historical market data. Supports A-sh... It is an AI Agent Skill for Claude Code / OpenClaw, with 90 downloads so far.
How do I install Ai Trading Backtester?
Run "/install ai-trading-backtester" in the OpenClaw or Claude Code chat to install it in one step — no extra setup required.
Is Ai Trading Backtester free?
Yes, Ai Trading Backtester is completely free, licensed under MIT-0. You can download, install and use it at no cost.
Which platforms does Ai Trading Backtester support?
Ai Trading Backtester is cross-platform and runs anywhere OpenClaw / Claude Code is available (cross-platform).
Who created Ai Trading Backtester?
It is built and maintained by lingfeng-19 (@gechengling); the current version is v1.0.0.