Backtesting Trading Strategies
Overview
Validate trading strategies against historical data before risking real capital. This skill provides a complete backtesting framework with 8 built-in strategies, comprehensive performance metrics, and parameter optimization.
Key Features:
- - 8 pre-built trading strategies (SMA, EMA, RSI, MACD, Bollinger, Breakout, Mean Reversion, Momentum)
- Full performance metrics (Sharpe, Sortino, Calmar, VaR, max drawdown)
- Parameter grid search optimization
- Equity curve visualization
- Trade-by-trade analysis
Prerequisites
Install required dependencies:
CODEBLOCK0
Optional for advanced features:
CODEBLOCK1
Instructions
Step 1: Fetch Historical Data
CODEBLOCK2
Data is cached to {baseDir}/data/{symbol}_{interval}.csv for reuse.
Step 2: Run Backtest
Basic backtest with default parameters:
CODEBLOCK3
Advanced backtest with custom parameters:
CODEBLOCK4
Step 3: Analyze Results
Results are saved to {baseDir}/reports/ including:
- -
*_summary.txt - Performance metrics - INLINECODE3 - Trade log
- INLINECODE4 - Equity curve data
- INLINECODE5 - Visual equity curve
Step 4: Optimize Parameters
Find optimal parameters via grid search:
CODEBLOCK5
Output
Performance Metrics
| Metric | Description |
|---|
| Total Return | Overall percentage gain/loss |
| CAGR |
Compound annual growth rate |
| Sharpe Ratio | Risk-adjusted return (target: >1.5) |
| Sortino Ratio | Downside risk-adjusted return |
| Calmar Ratio | Return divided by max drawdown |
Risk Metrics
| Metric | Description |
|---|
| Max Drawdown | Largest peak-to-trough decline |
| VaR (95%) |
Value at Risk at 95% confidence |
| CVaR (95%) | Expected loss beyond VaR |
| Volatility | Annualized standard deviation |
Trade Statistics
| Metric | Description |
|---|
| Total Trades | Number of round-trip trades |
| Win Rate |
Percentage of profitable trades |
| Profit Factor | Gross profit divided by gross loss |
| Expectancy | Expected value per trade |
Example Output
CODEBLOCK6
Supported Strategies
| Strategy | Description | Key Parameters |
|---|
| INLINECODE6 | Simple moving average crossover | INLINECODE7 , INLINECODE8 |
| INLINECODE9 |
Exponential MA crossover |
fast_period,
slow_period |
|
rsi_reversal | RSI overbought/oversold |
period,
overbought,
oversold |
|
macd | MACD signal line crossover |
fast,
slow,
signal |
|
bollinger_bands | Mean reversion on bands |
period,
std_dev |
|
breakout | Price breakout from range |
lookback,
threshold |
|
mean_reversion | Return to moving average |
period,
z_threshold |
|
momentum | Rate of change momentum |
period,
threshold |
Configuration
Create {baseDir}/config/settings.yaml:
CODEBLOCK7
Error Handling
See {baseDir}/references/errors.md for common issues and solutions.
Examples
See {baseDir}/references/examples.md for detailed usage examples including:
- - Multi-asset comparison
- Walk-forward analysis
- Parameter optimization workflows
Files
| File | Purpose |
|---|
| INLINECODE35 | Main backtesting engine |
| INLINECODE36 |
Historical data fetcher |
|
scripts/strategies.py | Strategy definitions |
|
scripts/metrics.py | Performance calculations |
|
scripts/optimize.py | Parameter optimization |
Resources
交易策略回测
概述
在实际投入资金前,使用历史数据验证交易策略。该技能提供完整的回测框架,包含8个内置策略、全面的绩效指标和参数优化功能。
主要特性:
- - 8个预置交易策略(SMA、EMA、RSI、MACD、布林带、突破、均值回归、动量)
- 完整绩效指标(夏普比率、索提诺比率、卡尔玛比率、VaR、最大回撤)
- 参数网格搜索优化
- 权益曲线可视化
- 逐笔交易分析
前置条件
安装所需依赖:
bash
pip install pandas numpy yfinance matplotlib
高级功能可选安装:
bash
pip install ta-lib scipy scikit-learn
操作说明
步骤1:获取历史数据
bash
python {baseDir}/scripts/fetch_data.py --symbol BTC-USD --period 2y --interval 1d
数据缓存至 {baseDir}/data/{symbol}_{interval}.csv 以便重复使用。
步骤2:运行回测
使用默认参数进行基础回测:
bash
python {baseDir}/scripts/backtest.py --strategy sma_crossover --symbol BTC-USD --period 1y
使用自定义参数进行高级回测:
bash
示例:指定日期范围回测
python {baseDir}/scripts/backtest.py \
--strategy rsi_reversal \
--symbol ETH-USD \
--period 1y \
--capital 10000 \
--params {period: 14, overbought: 70, oversold: 30}
步骤3:分析结果
结果保存至 {baseDir}/reports/,包含:
- - summary.txt - 绩效指标
- trades.csv - 交易日志
- equity.csv - 权益曲线数据
- chart.png - 权益曲线可视化图
步骤4:参数优化
通过网格搜索寻找最优参数:
bash
python {baseDir}/scripts/optimize.py \
--strategy sma_crossover \
--symbol BTC-USD \
--period 1y \
--param-grid {fastperiod: [10, 20, 30], slowperiod: [50, 100, 200]}
输出结果
绩效指标
年化复合增长率 |
| 夏普比率 | 风险调整后收益(目标:>1.5) |
| 索提诺比率 | 下行风险调整后收益 |
| 卡尔玛比率 | 收益率除以最大回撤 |
风险指标
| 指标 | 说明 |
|---|
| 最大回撤 | 最大峰值到谷值跌幅 |
| VaR(95%) |
95%置信水平下的风险价值 |
| CVaR(95%) | 超出VaR的预期损失 |
| 波动率 | 年化标准差 |
交易统计
盈利交易占比 |
| 盈亏比 | 总盈利除以总亏损 |
| 期望值 | 每笔交易预期价值 |
示例输出
================================================================================
回测结果:SMA交叉策略
BTC-USD | [开始日期] 至 [结束日期]
================================================================================
绩效指标 | 风险指标
总收益率: +47.32% | 最大回撤: -18.45%
年化复合增长率: +47.32% | VaR(95%): -2.34%
夏普比率: 1.87 | 波动率: 42.1%
索提诺比率: 2.41 | 溃疡指数: 8.2
交易统计
总交易次数: 24 | 盈亏比: 2.34
胜率: 58.3% | 期望值: $197.17
平均盈利: $892.45 | 最大连续亏损: 3
================================================================================
支持的策略
| 策略 | 说明 | 关键参数 |
|---|
| smacrossover | 简单移动平均线交叉 | fastperiod, slowperiod |
| emacrossover |
指数移动平均线交叉 | fast
period, slowperiod |
| rsi_reversal | RSI超买超卖 | period, overbought, oversold |
| macd | MACD信号线交叉 | fast, slow, signal |
| bollinger
bands | 布林带均值回归 | period, stddev |
| breakout | 价格突破区间 | lookback, threshold |
| mean
reversion | 回归移动平均线 | period, zthreshold |
| momentum | 变化率动量 | period, threshold |
配置
创建 {baseDir}/config/settings.yaml:
yaml
data:
provider: yfinance
cache_dir: ./data
backtest:
default_capital: 10000
commission: 0.001 # 每笔交易0.1%手续费
slippage: 0.0005 # 0.05%滑点
risk:
maxpositionsize: 0.95
stop_loss: null # 可选固定止损
take_profit: null # 可选固定止盈
错误处理
常见问题及解决方案请参见 {baseDir}/references/errors.md。
示例
详细使用示例请参见 {baseDir}/references/examples.md,包括:
文件
| 文件 | 用途 |
|---|
| scripts/backtest.py | 主回测引擎 |
| scripts/fetch_data.py |
历史数据获取器 |
| scripts/strategies.py | 策略定义 |
| scripts/metrics.py | 绩效计算 |
| scripts/optimize.py | 参数优化 |
资源