← 返回 Skills 市场
gechengling

Ai Trading Backtester

作者 lingfeng-19 · GitHub ↗ · v1.0.0 · MIT-0
cross-platform ✓ 安全检测通过
90
总下载
0
收藏
0
当前安装
1
版本数
在 OpenClaw 中安装
/install ai-trading-backtester
功能描述
AI-powered quantitative trading strategy backtesting assistant. Designs, codes, and evaluates trading strategies across historical market data. Supports A-sh...
使用说明 (SKILL.md)

\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
安全使用建议
Do not rely on this as a completed security review; rerun the scan when metadata.json and artifact/ can be inspected directly.
能力标签
crypto
能力评估
Purpose & Capability
Artifact coherence could not be assessed because metadata.json and artifact/ were not readable through the available execution tool.
Instruction Scope
Instruction scope could not be reviewed from the artifacts, so no artifact-backed scope concern is reported.
Install Mechanism
Install mechanism could not be reviewed from the artifacts, so no artifact-backed install concern is reported.
Credentials
Environment needs could not be reviewed from the artifacts, so no artifact-backed proportionality concern is reported.
Persistence & Privilege
Persistence and privilege behavior could not be reviewed from the artifacts, so no artifact-backed concern is reported.
如何使用
  1. 确保已安装 OpenClaw(本地或 Docker 部署)
  2. 在对话框中输入安装命令:/install ai-trading-backtester
  3. 安装完成后,直接呼叫该 Skill 的名称或使用 /ai-trading-backtester 触发
  4. 根据 Skill 的参数说明提供必要输入,即可获得结构化输出
版本历史
v1.0.0
Initial release of AI Trading Strategy Backtester. - Enables AI-powered design, coding, and backtesting of quantitative trading strategies. - Supports A-share (China), Hong Kong, and US equity markets. - Provides templates for momentum, mean reversion, breakout, pairs trading, and machine learning-based strategies. - Generates production-quality Python code compatible with backtrader and vectorbt. - Guides users step-by-step through strategy definition, backtest setup, performance analysis, and optimization. - Suitable for both quantitative analysts and retail traders across multiple markets.
元数据
Slug ai-trading-backtester
版本 1.0.0
许可证 MIT-0
累计安装 0
当前安装数 0
历史版本数 1
常见问题

Ai Trading Backtester 是什么?

AI-powered quantitative trading strategy backtesting assistant. Designs, codes, and evaluates trading strategies across historical market data. Supports A-sh... 它是一个面向 Claude Code / OpenClaw 的 AI Agent Skill 插件,目前累计下载 90 次。

如何安装 Ai Trading Backtester?

在 OpenClaw 或 Claude Code 对话框中运行命令「/install ai-trading-backtester」即可一键安装,无需额外配置。

Ai Trading Backtester 是免费的吗?

是的,Ai Trading Backtester 完全免费,采用 MIT-0 许可证,可自由下载、安装和使用。

Ai Trading Backtester 支持哪些平台?

Ai Trading Backtester 跨平台运行,可在任意部署了 OpenClaw / Claude Code 的环境中使用(cross-platform)。

谁开发了 Ai Trading Backtester?

由 lingfeng-19(@gechengling)开发并维护,当前版本 v1.0.0。

💬 留言讨论