backtesting-trading-strategies
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseBacktesting 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
在投入真实资金前,基于历史数据验证交易策略。本Skill提供完整的回测框架,包含8种内置策略、全面的绩效指标以及参数优化功能。
核心特性:
- 8种预构建交易策略(SMA、EMA、RSI、MACD、布林带、突破、均值回归、动量)
- 完整绩效指标(Sharpe比率、Sortino比率、Calmar比率、VaR、最大回撤)
- 参数网格搜索优化
- 权益曲线可视化
- 逐笔交易分析
Prerequisites
前置条件
Install required dependencies:
bash
pip install pandas numpy yfinance matplotlibOptional for advanced features:
bash
pip install ta-lib scipy scikit-learn安装所需依赖:
bash
pip install pandas numpy yfinance matplotlib高级功能可选依赖:
bash
pip install ta-lib scipy scikit-learnInstructions
操作步骤
Step 1: Fetch Historical Data
步骤1:获取历史数据
bash
python {baseDir}/scripts/fetch_data.py --symbol BTC-USD --period 2y --interval 1dData is cached to for reuse.
{baseDir}/data/{symbol}_{interval}.csvbash
python {baseDir}/scripts/fetch_data.py --symbol BTC-USD --period 2y --interval 1d数据会缓存到以便重复使用。
{baseDir}/data/{symbol}_{interval}.csvStep 2: Run Backtest
步骤2:运行回测
Basic backtest with default parameters:
bash
python {baseDir}/scripts/backtest.py --strategy sma_crossover --symbol BTC-USD --period 1yAdvanced backtest with custom parameters:
bash
undefined使用默认参数进行基础回测:
bash
python {baseDir}/scripts/backtest.py --strategy sma_crossover --symbol BTC-USD --period 1y使用自定义参数进行高级回测:
bash
undefinedExample: backtest with specific date range
示例:针对特定日期范围进行回测
python {baseDir}/scripts/backtest.py
--strategy rsi_reversal
--symbol ETH-USD
--period 1y
--capital 10000
--params '{"period": 14, "overbought": 70, "oversold": 30}'
--strategy rsi_reversal
--symbol ETH-USD
--period 1y
--capital 10000
--params '{"period": 14, "overbought": 70, "oversold": 30}'
undefinedpython {baseDir}/scripts/backtest.py
--strategy rsi_reversal
--symbol ETH-USD
--period 1y
--capital 10000
--params '{"period": 14, "overbought": 70, "oversold": 30}'
--strategy rsi_reversal
--symbol ETH-USD
--period 1y
--capital 10000
--params '{"period": 14, "overbought": 70, "oversold": 30}'
undefinedStep 3: Analyze Results
步骤3:分析结果
Results are saved to including:
{baseDir}/reports/- - Performance metrics
*_summary.txt - - Trade log
*_trades.csv - - Equity curve data
*_equity.csv - - Visual equity curve
*_chart.png
结果会保存到目录,包含:
{baseDir}/reports/- - 绩效指标汇总
*_summary.txt - - 交易日志
*_trades.csv - - 权益曲线数据
*_equity.csv - - 可视化权益曲线
*_chart.png
Step 4: Optimize Parameters
步骤4:优化参数
Find optimal parameters via grid search:
bash
python {baseDir}/scripts/optimize.py \
--strategy sma_crossover \
--symbol BTC-USD \
--period 1y \
--param-grid '{"fast_period": [10, 20, 30], "slow_period": [50, 100, 200]}'通过网格搜索寻找最优参数:
bash
python {baseDir}/scripts/optimize.py \
--strategy sma_crossover \
--symbol BTC-USD \
--period 1y \
--param-grid '{"fast_period": [10, 20, 30], "slow_period": [50, 100, 200]}'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 |
| 指标 | 描述 |
|---|---|
| 总回报率 | 整体盈利/亏损百分比 |
| CAGR | 复合年增长率 |
| Sharpe比率 | 风险调整后回报率(目标:>1.5) |
| Sortino比率 | 下行风险调整后回报率 |
| Calmar比率 | 回报率除以最大回撤 |
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 |
| 指标 | 描述 |
|---|---|
| 最大回撤 | 最大的峰谷跌幅 |
| VaR (95%) | 95%置信水平下的风险价值 |
| CVaR (95%) | VaR之外的预期损失 |
| 波动率 | 年化标准差 |
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
示例输出
================================================================================
BACKTEST RESULTS: SMA CROSSOVER
BTC-USD | [start_date] to [end_date]
================================================================================
PERFORMANCE | RISK
Total Return: +47.32% | Max Drawdown: -18.45%
CAGR: +47.32% | VaR (95%): -2.34%
Sharpe Ratio: 1.87 | Volatility: 42.1%
Sortino Ratio: 2.41 | Ulcer Index: 8.2
--------------------------------------------------------------------------------
TRADE STATISTICS
Total Trades: 24 | Profit Factor: 2.34
Win Rate: 58.3% | Expectancy: $197.17
Avg Win: $892.45 | Max Consec. Losses: 3
================================================================================================================================================================
回测结果:SMA交叉策略
BTC-USD | [开始日期] 至 [结束日期]
================================================================================
绩效 | 风险
总回报率: +47.32% | 最大回撤: -18.45%
CAGR: +47.32% | VaR (95%): -2.34%
Sharpe比率: 1.87 | 波动率: 42.1%
Sortino比率: 2.41 | 溃疡指数: 8.2
--------------------------------------------------------------------------------
交易统计
总交易次数: 24 | 利润因子: 2.34
胜率: 58.3% | 预期收益: $197.17
平均盈利: $892.45 | 连续最大亏损次数: 3
================================================================================Supported Strategies
支持的策略
| Strategy | Description | Key Parameters |
|---|---|---|
| Simple moving average crossover | |
| Exponential MA crossover | |
| RSI overbought/oversold | |
| MACD signal line crossover | |
| Mean reversion on bands | |
| Price breakout from range | |
| Return to moving average | |
| Rate of change momentum | |
| 策略 | 描述 | 核心参数 |
|---|---|---|
| 简单移动平均交叉 | |
| 指数移动平均交叉 | |
| RSI超买/超卖 | |
| MACD信号线交叉 | |
| 基于布林带的均值回归 | |
| 价格突破区间 | |
| 回归至移动平均 | |
| 变动率动量 | |
Configuration
配置
Create :
{baseDir}/config/settings.yamlyaml
data:
provider: yfinance
cache_dir: ./data
backtest:
default_capital: 10000
commission: 0.001 # 0.1% per trade
slippage: 0.0005 # 0.05% slippage
risk:
max_position_size: 0.95
stop_loss: null # Optional fixed stop loss
take_profit: null # Optional fixed take profit创建文件:
{baseDir}/config/settings.yamlyaml
data:
provider: yfinance
cache_dir: ./data
backtest:
default_capital: 10000
commission: 0.001 # 每笔交易0.1%
slippage: 0.0005 # 0.05%滑点
risk:
max_position_size: 0.95
stop_loss: null # 可选固定止损
take_profit: null # 可选固定止盈Error Handling
错误处理
See for common issues and solutions.
{baseDir}/references/errors.md请查看获取常见问题及解决方案。
{baseDir}/references/errors.mdExamples
示例
See for detailed usage examples including:
{baseDir}/references/examples.md- Multi-asset comparison
- Walk-forward analysis
- Parameter optimization workflows
请查看获取详细使用示例,包括:
{baseDir}/references/examples.md- 多资产比较
- 滚动窗口分析
- 参数优化工作流
Files
文件说明
| File | Purpose |
|---|---|
| Main backtesting engine |
| Historical data fetcher |
| Strategy definitions |
| Performance calculations |
| Parameter optimization |
| 文件 | 用途 |
|---|---|
| 主回测引擎 |
| 历史数据获取工具 |
| 策略定义文件 |
| 绩效计算模块 |
| 参数优化工具 |
Resources
参考资源
- yfinance - Yahoo Finance data
- TA-Lib - Technical analysis library
- QuantStats - Portfolio analytics
- yfinance - Yahoo Finance数据接口
- TA-Lib - 技术分析库
- QuantStats - 投资组合分析工具