zhengxinjipai

Backtesting Trading Strategies

專業領域v2.0.0
作者:zhengxinjipai更新於 2026-05-11backtesting-trading-strategies
#Trading Strategy

據 AlphaMoat 統計,截至 2026-09,Backtesting Trading Strategies 累計下載 3,865 次、獲 0 個星標,在全部 5,078 個 AI 技能中排名第 2,696 位,在「專業領域」分類(465 個)中排名第 224 位。

累計安裝
105
累計下載
3865
星標
-
全站排名
#2,696
全站前 54% · 「專業領域」前 49%
平台累計安裝累計下載星標評論
ClawHub ↗1053865--

各平台的計數口徑不同,統計時間不一致。

這個技能是做什麼的

回測依賴資料來源、交易成本、滑點和模型假設;歷史表現不能保證未來結果,也不應直接作為交易指令。

資料釋出於 2026-10-29

可以用來做什麼

  • 比較不同策略在歷史資料上的表現。
  • 檢查風險指標、權益曲線和逐筆交易結果。
  • 規劃引數搜尋與結果複核。

什麼時候用

  • 需要在實盤決策前檢驗交易策略假設時。
  • 需要檢視歷史收益、回撤和風險表現時。
  • 需要評估資料、手續費及滑點假設對回測結果的影響時。

示例提示詞

以下是根據技能文件生成的示例,不代表實際執行結果。

概述該回測工作流能生成的分析輸出及其限制。
列出判斷歷史回測是否適用於實際決策時要檢查的假設。

月度資料趨勢

累計下載3865
1207263540622026-03 · 累計下載 14042026-05 · 累計下載 30132026-06 · 累計下載 29002026-07 · 累計下載 33112026-08 · 累計下載 36482026-09 · 累計下載 386526-0326-09
星標-
0112026-03 · 星標 -2026-05 · 星標 -2026-06 · 星標 -2026-07 · 星標 -2026-08 · 星標 -2026-09 · 星標 -26-0326-09

2026-09 起統計方法調整:同名技能按作者分別統計,並覆蓋全部技能。圖中虛線為調整前的月份,與之後的資料不直接比較,也不計算跨越調整的增長。

月份累計下載環比星標
2026-093865—-
2026-083648+10.2%-
2026-073311+14.2%-
2026-062900-3.8%-
2026-053013—-
2026-031404—-

SKILL.md 原文

以下是作者釋出的原始檔案,按純文字顯示,本站未做修改或稽核;其中的連結不可點選,命令請核實後再執行。抓取於 2026-10-23。

6.2 KB · ClawHub v2.0.0
---
name: backtesting-trading-strategies
description: |
  Backtest crypto and traditional trading strategies against historical data.
  Calculates performance metrics (Sharpe, Sortino, max drawdown), generates equity curves,
  and optimizes strategy parameters. Use when user wants to test a trading strategy,
  validate signals, or compare approaches.
  Trigger with phrases like "backtest strategy", "test trading strategy", "historical performance",
  "simulate trades", "optimize parameters", or "validate signals".
allowed-tools: Read, Write, Edit, Grep, Glob, Bash(python:*)
展開全部(共 201 行)
version: 2.0.0
author: Jeremy Longshore <[email protected]>
license: MIT
---

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

```bash
pip install pandas numpy yfinance matplotlib
```

Optional for advanced features:
```bash
pip install ta-lib scipy scikit-learn
```

## Instructions

### Step 1: Fetch Historical Data

```bash
python {baseDir}/scripts/fetch_data.py --symbol BTC-USD --period 2y --interval 1d
```

Data is cached to `{baseDir}/data/{symbol}_{interval}.csv` for reuse.

### Step 2: Run Backtest

Basic backtest with default parameters:

```bash
python {baseDir}/scripts/backtest.py --strategy sma_crossover --symbol BTC-USD --period 1y
```

Advanced backtest with custom parameters:

```bash
# Example: 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}'
```

### Step 3: Analyze Results

Results are saved to `{baseDir}/reports/` including:
- `*_summary.txt` - Performance metrics
- `*_trades.csv` - Trade log
- `*_equity.csv` - Equity curve data
- `*_chart.png` - Visual equity curve

### Step 4: Optimize Parameters

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]}'
```

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

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

## Supported Strategies

| Strategy | Description | Key Parameters |
|----------|-------------|----------------|
| `sma_crossover` | Simple moving average crossover | `fast_period`, `slow_period` |
| `ema_crossover` | 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`:

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

## 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 |
|------|---------|
| `scripts/backtest.py` | Main backtesting engine |
| `scripts/fetch_data.py` | Historical data fetcher |
| `scripts/strategies.py` | Strategy definitions |
| `scripts/metrics.py` | Performance calculations |
| `scripts/optimize.py` | Parameter optimization |

## Resources

- [yfinance](https://github.com/ranaroussi/yfinance) - Yahoo Finance data
- [TA-Lib](https://ta-lib.org/) - Technical analysis library
- [QuantStats](https://github.com/ranaroussi/quantstats) - Portfolio analytics

「專業領域」分類下的熱門技能

zhengxinjipai 的其他技能

資料月份:2026-09 · 下載/星標/安裝數聚合自公開技能註冊庫(ClawHub、SkillHub),按月更新。口徑說明見資料方法。