← 返回
未分类 中文

Ai Trading Backtester

AI-powered quantitative trading strategy backtesting assistant. Designs, codes, and evaluates trading strategies across historical market data. Supports A-sh...
AI驱动的量化交易策略回测助手。设计、编写并评估历史市场数据上的交易策略,支持A股。
gechengling
未分类 clawhub v1.0.0 1 版本 99609.4 Key: 无需
★ 0
Stars
📥 255
下载
💾 0
安装
1
版本
#latest

概述

AI Trading Strategy Backtester

Overview

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.

Triggers

  • "backtest my trading strategy"
  • "design a momentum strategy for [stock/market]"
  • "test mean reversion on [symbol]"
  • "pairs trading strategy example"
  • "Python backtrader setup guide"
  • "vectorbt tutorial"
  • "trading strategy optimization"
  • "量化回测策略"
  • "技术指标择时策略"
  • "A股量化策略设计"

Workflow

Step 1: Define the Strategy Brief

Collect the trading idea:

  • Strategy type: Momentum, mean reversion, breakout, pairs trading, ML-based, event-driven
  • Market: A-share (sh/sz), HK stock (hk), US equity (us)
  • Timeframe: Intraday (1m/5m/15m), daily, weekly, monthly
  • Assets: Single stock, ETF, index, portfolio
  • Entry/Exit signals: Technical indicators, price patterns, fundamental signals, ML predictions
  • Position sizing: Fixed, Kelly criterion, risk-parity, dynamic
  • Constraints: Max position size, long-only/short, turnover limit, slippage model

Step 2: Strategy Design & Code Generation

Based on the brief, generate production-quality Python code:

A. Momentum Strategy Template

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))

B. Mean Reversion Strategy Template

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()

C. Pairs Trading Strategy

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

Step 3: Backtest Execution

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}')

Step 4: Performance Analysis

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 |

Step 5: Optimization & Stress Testing

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/Output Examples

Example 1: Strategy Design Request

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

Example 2: Performance Report

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 Templates Library

| 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 |

Best Practices

  1. Always use out-of-sample testing — split data 70/30 or use walk-forward
  2. Account for transaction costs — A-share commission + stamp tax ≈ 0.15% per trade
  3. Include slippage — assume 0.05-0.1% for liquid stocks, higher for illiquid
  4. Diversify across uncorrelated strategies — don't rely on one strategy
  5. Stress test for A-share specifics — T+1 trading, limit-up/limit-down, suspension risks
  6. Validate with paper trading — run live for 1-3 months before real capital
  7. Beware of overfitting — fewer parameters = more robust strategy

Risk Disclaimer

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.

版本历史

共 1 个版本

  • v1.0.0 当前
    2026-05-20 05:39 安全 安全

安全检测

腾讯云安全 (Keen)

安全,无风险
查看报告

腾讯云安全 (Sanbu)

安全,无风险
查看报告

🔗 相关推荐

Tender Bidding Assistant

gechengling
AI-powered enterprise bidding assistant for China government procurement and commercial projects. Full-lifecycle support
★ 1 📥 753

Insurance Claims Intelligence

gechengling
提供多模态医疗票据OCR识别、智能判责、反欺诈检测及全险种保险理赔智能分析与自动化支持。
★ 1 📥 778

Bank Market Research

gechengling
AI驱动的市场研究和竞争情报助手,帮助银行分析行业、竞争对手、市场趋势,并生成结构化市场报告。
★ 1 📥 752