Install
openclaw skills install ai-trading-backtesterAI-powered quantitative trading strategy backtesting assistant. Designs, codes, and evaluates trading strategies across historical market data. Supports A-share (China), Hong Kong, US equity markets. Covers mean reversion, momentum, breakout, pairs trading, and machine learning-based strategies. Built for quantitative analysts and retail traders. Keywords: trading backtest, quantitative strategy, algorithmic trading, Python backtesting, backtrader, vectorbt, trading strategy, momentum, mean reversion, pairs trading, A-share strategy, financial data, technical indicators.
openclaw skills install ai-trading-backtesterAn 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.
Collect the trading idea:
Based on the brief, generate production-quality Python code:
import pandas as pd
import numpy as np
import backtrader as bt
class MomentumStrategy(bt.Strategy):
params = (
('lookback', 20), # 回望期
('hold_period', 5), # 持有期
('rank_percentile', 0.2), # 选股分位数
)
def __init__(self):
self.inds = {}
for d in self.datas:
self.inds[d] = {}
self.inds[d]['momentum'] = bt.indicators.RateOfChange(
d.close, period=self.params.lookback
)
def next(self):
# 按动量排序,取前20%
rankings = sorted(
self.datas,
key=lambda d: self.inds[d]['momentum'][0],
reverse=True
)[:int(len(self.datas) * self.params.rank_percentile)]
# 平仓不在榜单的持仓
for d in self.datas:
if d not in rankings and self.getposition(d).size > 0:
self.close(d)
# 买入榜单中的标的
for d in rankings:
if self.getposition(d).size == 0:
self.order_target_percent(d, 1.0 / len(rankings))
class MeanReversionStrategy(bt.Strategy):
params = (
('bb_period', 20),
('bb_dev', 2.0),
('rsi_period', 14),
('rsi_oversold', 30),
('rsi_overbought', 70),
)
def __init__(self):
self.bb = bt.indicators.BollingerBands(
self.data.close, period=self.params.bb_period,
devfactor=self.params.bb_dev
)
self.rsi = bt.indicators.RSI(
self.data.close, period=self.params.rsi_period
)
def next(self):
if self.position.size == 0:
# 价格触及下轨且RSI超卖 → 买入
if self.data.close < self.bb.lines.bot and \
self.rsi < self.params.rsi_oversold:
self.order_target_percent(self.data, 1.0)
else:
# 价格触及上轨或RSI超买 → 卖出
if self.data.close > self.bb.lines.top or \
self.rsi > self.params.rsi_overbought:
self.close()
import statsmodels.api as sm
def find_cointegrated_pairs(data_dict):
"""寻找协整配对"""
n = len(data_dict)
pairs = []
symbols = list(data_dict.keys())
for i in range(n):
for j in range(i + 1, n):
try:
x = data_dict[symbols[i]]
y = data_dict[symbols[j]]
# OLS回归
X = sm.add_constant(x)
model = sm.OLS(y, X).fit()
residuals = model.resid
# ADF检验
adf_result = sm.tsa.stattools.adfuller(residuals)
if adf_result[0] < adf_result[4]['1%']:
pairs.append((symbols[i], symbols[j], adf_result[0]))
except:
continue
return sorted(pairs, key=lambda x: x[2])
def pairs_trading_signals(spread, z_entry=2.0, z_exit=0.5):
"""配对交易信号"""
signals = pd.Series(0, index=spread.index)
z_score = (spread - spread.mean()) / spread.std()
signals[z_score < -z_entry] = 1 # 做多价差
signals[z_score > z_entry] = -1 # 做空价差
signals[abs(z_score) < z_exit] = 0 # 平仓
return signals
Guide the user through running the backtest:
import backtrader as bt
import pandas as pd
# 加载数据
data = bt.feeds.GenericCSVData(
dataname='historical_data.csv',
dtformat='%Y-%m-%d',
datetime=0,
open=1, high=2, low=3, close=4, volume=5,
openinterest=-1
)
# 运行回测
cerebro = bt.Cerebro()
cerebro.addstrategy(MomentumStrategy)
cerebro.adddata(data)
cerebro.broker.setcash(1000000.0) # 100万初始资金
cerebro.broker.setcommission(commission=0.001) # 千一手续费
cerebro.addsizer(bt.sizers.PercentSizer, percents=95)
print(f'初始资金: {cerebro.broker.getvalue():,.2f}')
cerebro.run()
print(f'最终资金: {cerebro.broker.getvalue():,.2f}')
Generate comprehensive performance metrics:
| Metric | Description | Target |
|---|---|---|
| Total Return | Cumulative return | > Benchmark |
| Annualized Return | CAGR | > 10% (A-share), > 8% (HK/US) |
| Sharpe Ratio | Risk-adjusted return | > 1.5 |
| Max Drawdown | Peak-to-trough loss | < 20% |
| Win Rate | Percentage of profitable trades | > 50% |
| Profit Factor | Gross profit / Gross loss | > 1.5 |
| Calmar Ratio | Annual return / Max DD | > 1.0 |
| Sortino Ratio | Return / Downside deviation | > 1.0 |
A. 参数优化
- Grid search over key parameters
- Walk-forward analysis (in-sample / out-of-sample)
- Avoid overfitting: use Information Coefficient (IC) analysis
B. 压力测试
- Historical crises: 2008, 2015 A-share crash, COVID-19 (2020)
- Monte Carlo simulation of equity curves
- Sensitivity analysis: commission, slippage, spread assumptions
C. 风险分析
- Position-level VaR (Value at Risk)
- Factor exposure (momentum, size, volatility)
- Tail risk: maximum loss scenarios
Input:
Design a momentum strategy for A-share market.
Criteria:
- Daily timeframe
- Lookback: 20 days
- Hold for 5 days
- Long only
- Top 20% by momentum score
- Max 10 positions
- Trade AAPL, TSLA, NVDA, MSFT
Output:
Strategy Design Summary:
┌─────────────────────────────────────────┐
│ Strategy: Top-Momentum Long-Only │
│ Market: US Equity (4 stocks) │
│ Timeframe: Daily │
│ Backtest Period: 2020-01-01 to 2025-12-31 │
└─────────────────────────────────────────┘
Key Components:
1. Momentum ranking: ROC(close, period=20)
2. Selection: Top 20% by momentum score (max 10 stocks)
3. Position sizing: Equal weight (10% per position)
4. Hold period: 5 trading days
5. Rebalance: Daily at market open
Expected Performance (illustrative):
- Annualized Return: 18-25% (historical backtest)
- Sharpe Ratio: 0.8-1.2
- Max Drawdown: 30-40%
- Win Rate: 52-56%
Code generated at: strategy_momentum_us.py
Input:
Compare these two strategies: RSI mean reversion vs momentum breakout on CSI 300 (000300)
Period: 2020-2024
Initial capital: 1,000,000 CNY
Output:
Backtest Results: CSI 300 Strategies (2020-2024)
┌──────────────────────┬─────────────────────┬────────────────────┐
│ Metric │ RSI Mean Reversion │ Momentum Breakout │
├──────────────────────┼─────────────────────┼────────────────────┤
│ Total Return │ +68.3% │ +124.7% │
│ Annualized Return │ +13.2% │ +17.8% │
│ Sharpe Ratio │ 1.12 │ 1.45 │
│ Max Drawdown │ -22.1% │ -31.4% │
│ Win Rate │ 58.3% │ 49.2% │
│ Profit Factor │ 1.82 │ 1.67 │
│ Calmar Ratio │ 0.60 │ 0.57 │
│ Avg Holding Days │ 8.2 │ 4.6 │
│ Total Trades │ 127 │ 284 │
└──────────────────────┴─────────────────────┴────────────────────┘
Benchmark: CSI 300 Index (+42.1% over same period)
Recommendation:
- Risk-averse investors: RSI Mean Reversion (lower drawdown, higher win rate)
- Return-seeking investors: Momentum Breakout (higher return, more trades)
⚠️ Note: Past performance does not guarantee future results.
A-share markets are subject to significant regulatory and liquidity risks.
| Strategy Type | Best For | Timeframe | Markets |
|---|---|---|---|
| Momentum | Trending markets | Daily/Weekly | All |
| Mean Reversion | Range-bound markets | Intraday/Daily | All |
| Breakout | Volatile markets | Intraday/Daily | All |
| Pairs Trading | Market-neutral | Daily | US/HK |
| Machine Learning | Alpha discovery | Daily | All |
| Event-Driven | Corporate actions | Daily | A-share/US |
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.