Files

993 lines
40 KiB
Markdown
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# RaptorBT
[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://uppercase.org/licenses/MIT)
[![Python 3.10+](https://img.shields.io/badge/python-3.10+-blue.svg)](https://www.python.org/downloads/)
[![Rust](https://img.shields.io/badge/rust-1.70+-red.svg)](https://www.rust-lang.org/)
**高性能 Rust 回测引擎 + 策略自动化框架,亚毫秒级回测,80+ 技术指标,位级确定性执行。**
RaptorBT 是一个用 Rust 编写的高性能回测引擎,通过 PyO3 提供 Python 绑定。支持单标的、篮子、配对、期权、价差、多策略、Tick 级回测,在亚毫秒级时间内返回完整的 33 项绩效指标报告。项目还内置完整的策略自动化框架(参数优化 / Walk-Forward 验证 / 验收检查 / 交付包导出),支持 AI agent 自主开发与交付策略。
<p align="center">
<strong>亚毫秒级回测</strong> · <strong>编译后 < 1 MB</strong> · <strong>80+ 技术指标</strong> · <strong>位级确定性</strong> · <strong>原生并行</strong> · <strong>策略自动化框架</strong>
</p>
---
## 快速开始
### 安装
```bash
pip install raptorbt
```
### 30 秒示例
```python
import numpy as np
import raptorbt
# 配置回测
config = raptorbt.PyBacktestConfig(initial_capital=100000, fees=0.001)
# 运行回测
result = raptorbt.run_single_backtest(
timestamps=timestamps,
open=open, high=high, low=low, close=close, volume=volume,
entries=entries, exits=exits,
direction=1, weight=1.0, symbol="AAPL",
config=config,
)
# 查看结果
print(f"收益率: {result.metrics.total_return_pct:.2f}%")
print(f"夏普比率: {result.metrics.sharpe_ratio:.2f}")
print(f"最大回撤: {result.metrics.max_drawdown_pct:.2f}%")
```
---
## 目录
- [概述](#概述)
- [策略自动化框架](#策略自动化框架) ★
- [项目结构](#项目结构) ★
- [性能](#性能)
- [策略类型](#策略类型)
- [技术指标](#技术指标)
- [止损与止盈](#止损与止盈)
- [蒙特卡洛组合模拟](#蒙特卡洛组合模拟)
- [回测结果与指标](#回测结果与指标)
- [API 参考](#api-参考)
- [从源码构建](#从源码构建)
- [版本历史](#版本历史)
---
## 概述
RaptorBT 编译为单一原生扩展,完全在 Rust 中运行。在典型 K 线数量下,完整的回测加上所有 33 项绩效指标的执行时间不足 1 毫秒。在 Apple M4 上测量的基准数据(raptorbt 0.4.1):
| 指标 | RaptorBT |
|------|----------|
| **编译引擎大小** | < 1 MB |
| **回测速度 (1K 根 K 线)** | ~0.03 ms |
| **回测速度 (10K 根 K 线)** | ~0.25 ms |
| **回测速度 (50K 根 K 线)** | ~1.4 ms |
| **内存使用** | 低(原生内存管理) |
### 核心特性
- **7 种策略类型**:单标的、篮子/集体、配对交易、期权、价差、多策略、Tick 级
- **资产与券商无关**:从任何数据源传入 NumPy OHLCV 或 Tick 数组——股票、期货、外汇、加密货币、期权,RaptorBT 从不假设市场或数据供应商
- **80+ 技术指标**:集成 ferro-ta 指标库,覆盖趋势、动量、波动率、强度、成交量、价格变换、统计、周期变换、市场状态检测、投资组合工具
- **Tick 级模拟**:全 Tick 分辨率,支持日内期权动量、剥头皮和微观结构策略
- **批量价差回测**:通过 Rayon 并行运行多个价差回测,释放 GIL
- **蒙特卡洛模拟**:基于 GBM + Cholesky 分解的相关多资产前向投影
- **33 项绩效指标**:夏普、索提诺、卡玛、Omega、SQN、盈亏比、恢复因子等
- **止损/止盈管理**:固定、ATR 基于和追踪止损,风险回报目标
- **位级确定性**:相同输入产生 bit-for-bit 相同结果——无 JIT 编译偏差
- **原生并行**Rayon 并行处理 + SIMD 优化
---
## 策略自动化框架
RaptorBT 内置完整的策略自动化框架,覆盖从策略开发到交付的完整流程:
```
scaffold 生成模板 → 编写信号逻辑 → check 前视检测 → optimize 参数优化
→ walkforward 验证 → acceptance 验收 → deliver 生成交付包
```
### 数据源
框架支持两种数据源,默认用 CSV 离线数据:
- **CSV(默认)**:把 MT5 History Center / quant data manager 导出的 M1 CSV 放到 `data/` 目录,加载器自动识别品种、时区、重采样、spread→slippage 转换。适合策略研究。
- **Mt5Bridge**:用 `--source mt5` 切换,从远程 MT5 拉取实时数据。适合最终策略验证。
### CLI 入口
所有命令通过 `python -m app.main` 调用:
```bash
# 列出所有已注册策略 (同时列出 data/ 下可用 CSV 品种)
python -m app.main list
# 运行单个策略回测 (默认 CSV 离线数据)
python -m app.main run --strategy sma_cross --symbol XAUUSD --bars 500
# 对比所有策略表现
python -m app.main compare --symbol XAUUSD
# 参数网格搜索优化
python -m app.main optimize --strategy sma_cross \
--param fast=5,10,15 --param slow=20,30 --metric sharpe_ratio --export
# Walk-Forward 验证 (滚动 IS/OOS + 过拟合检测)
python -m app.main walkforward --strategy sma_cross \
--param fast=5,10 --param slow=20,30 --bars 1000 --train-size 300 --test-size 100
# 列出所有可用策略 / 可用指标 (80 个)
python -m app.main list
python -m app.main list --indicators --json # AI agent 开发前先查询指标目录
# 策略验收检查 (盈利优先三层标准 + 前视偏差强制检测)
python -m app.main validate --strategy sma_cross \
--param fast=5,10 --param slow=20,30
# 前视偏差检测 (静态 AST 扫描 + 动态扰动验证)
python -m app.main check --strategy sma_cross --dynamic --bars 500
python -m app.main check --strategy all # 扫描所有策略
# 生成策略模板文件 (自带前视警告头部)
python -m app.main scaffold --name my_rsi --template mean_reversion
# 生成完整交付包 (强制前视检测, 未通过则拒绝生成)
python -m app.main deliver --strategy sma_cross \
--param fast=5,10 --param slow=20,30
# 所有命令支持 --json 输出 (供 AI agent 解析, 含失败诊断建议)
python -m app.main validate --strategy sma_cross \
--param fast=5,10 --param slow=20,30 --json
```
### 9 个自动化模块
| 模块 | 作用 | 关键能力 |
|------|------|----------|
| [app/main.py](app/main.py) | CLI 入口 | 9 个子命令 (list/run/compare/optimize/walkforward/validate/check/scaffold/deliver),全部支持 `--json` 结构化输出 |
| [app/data_loader.py](app/data_loader.py) | CSV 数据加载 | MT5 格式 M1 CSV,17 品种识别,13 周期重采样,spread→slippage |
| [app/lookahead_check.py](app/lookahead_check.py) | 前视偏差防护 | 静态 AST 扫描 (11 规则) + 动态扰动验证,强制集成到 validate/deliver |
| [app/indicator_catalog.py](app/indicator_catalog.py) | 指标目录 | 80 个原生指标的可查询目录,含签名/输入/默认值/返回值,`list --indicators` 输出 |
| [app/optimizer.py](app/optimizer.py) | 参数网格搜索 | 遍历参数组合,按指标排序,导出完整响应面 |
| [app/walk_forward.py](app/walk_forward.py) | Walk-Forward 验证 | 滚动 IS/OOS 窗口,衰减比,参数稳定性分析,过拟合检测 |
| [app/acceptance.py](app/acceptance.py) | 验收检查 | 盈利优先三层标准 (L1 盈利性必须 / L2 风险可控 / L3 健壮性) + 失败诊断建议 (按层分级) |
| [app/scaffold.py](app/scaffold.py) | 策略模板生成器 | 5 种模板 (crossover/mean_reversion/trend_following/breakout/custom),自带前视警告 |
| [app/exporter.py](app/exporter.py) | 交付包打包导出 | 策略源码 + 8 章节 Markdown 报告 + 3 个 CSV |
### 前视偏差防护链
防止 AI agent 自动开发策略时引入前视偏差(使用未来 bar 数据导致回测虚高)。完整防护链:
```
scaffold (头部警告) → check (静态+动态检测) → validate (强制前置) → deliver (强制前置, 拒绝生成)
```
| 防护点 | 行为 |
|------|------|
| scaffold 模板 | 生成的策略文件头部自带 ⚠️ 前视警告,列出禁用模式 |
| `check` 命令 | 单独运行静态 AST 扫描 + 动态扰动验证 |
| `validate` 命令 | 前置前视检测,未通过则**终止验收** |
| `deliver` 命令 | 前置前视检测,未通过则**拒绝生成交付包** |
| 引擎层 | `upon_bar_close=True`(默认)确保信号在 bar 收盘后生成 |
检测的常见前视模式:`.shift(-N)``close[-1]` 负索引、`df.iloc[i+N:]` 切片未来、`np.roll` 循环移位、`future`/`lookahead` 关键词等 11 条规则。
### JSON 输出 + 失败驱动迭代 ★
所有 CLI 命令支持 `--json` 标志,输出结构化 JSON(自动清理 NaN/Inf,不转义中文),AI agent 可直接解析无需正则匹配表格:
```bash
python -m app.main validate --strategy sma_cross \
--param fast=5,10 --param slow=20,30 --json
```
**失败驱动的自动迭代**:当 `validate` 未通过时,JSON 中 `acceptance.criteria` 数组的每条失败标准都带 `suggestions` 字段(5 条具体可执行建议,按 L1/L2/L3 分级)。AI agent 按**优先级决策**
- `l1_passed=false` → 策略不赚钱,**不要在参数优化上浪费时间**,按 L1 建议换策略逻辑/品种/周期
- `l1_passed=true && (l2|l3)=false` → 按 L2/L3 建议调整风控或统计性问题
- 全过 → `deliver --json` 生成交付包
| 失败标准 | 层 | 建议方向 |
|---------|----|---------|
| OOS 盈利因子 < 1.3 | **L1** | 重审信号逻辑、切换策略类型、切换品种/周期、检查止损、反向信号 |
| OOS 净收益 ≤ 0 | **L1** | 检查 IS 是否也亏、评估成本侵蚀、减少频率、切换顺势品种、反向信号 |
| OOS 每笔期望 ≤ 0 | **L1** | 检查胜率×盈亏比、放大止盈/追踪止损、加过滤提高胜率、放宽止损 |
| OOS 最大回撤 > 20% | L2 | 收紧止损、ATR 动态止损、追踪止损、降仓位、加趋势过滤 |
| OOS 夏普 < 0.7 | L3 | 放宽止损、加趋势过滤、切大周期、加成交量过滤(已降为参考) |
| OOS 交易数 < 30 | L3 | 缩短指标周期、降低入场阈值、切更小周期、放宽过滤、检查 warmup |
| 衰减比 < 0.5 | L3 | 缩小参数空间、增加 WF 窗口数、简化策略、用中位数参数、检查前视 |
### 验收标准 (盈利优先三层)
> ⚠️ **设计原则**:策略的最终目的是赚钱,不是为了优化指标而优化指标。盈利性(PF/收益/期望)是 L1 必须层,先确认真赚钱再看风险/健壮性。避免"Sharpe=1.06 但年化 2.5%"这种假阳性,也避免"IS/OOS 都亏但衰减比 3.0"这种误导性通过。
| 层级 | 标准 | 阈值 | 性质 |
|------|------|------|------|
| **L1 盈利性** | OOS 盈利因子 | ≥ 1.3 | 必须(任一失败即拒收) |
| | OOS 净收益率 | > 0% | 必须 |
| | OOS 每笔期望 | > 0 | 必须 |
| **L2 风险可控** | OOS 最大回撤 | ≤ 20% | 应该 |
| **L3 健壮性** | OOS 夏普比率 | ≥ 0.7 | 建议(参考性,已放宽原 1.0) |
| | OOS 总交易数 | ≥ 30 | 建议 |
| | IS/OOS 衰减比 | ≥ 0.5 | 建议(注:IS 也亏时高衰减比无意义) |
> 💡 详见 [docs/策略自动化框架.md](docs/策略自动化框架.md) 的"验收检查"章节。
### 策略框架 (strategies/)
所有策略继承 `Strategy` 基类,实现 3 个方法即可自动注册:
```python
from .base import Strategy, SignalResult
import raptorbt, numpy as np
class MyStrategy(Strategy):
name = "my_strategy"
def __init__(self, period: int = 14):
self.period = period
def warmup_bars(self) -> int:
return self.period + 1
def generate_signals(self, df) -> SignalResult:
close = df["close"].values.astype(np.float64)
rsi = raptorbt.rsi(close, period=self.period)
entries = (rsi < 30).astype(bool)
exits = (rsi > 70).astype(bool)
entries, exits = self.apply_warmup(entries, exits)
return SignalResult(entries=entries, exits=exits, direction=1)
def build_config(self) -> raptorbt.PyBacktestConfig:
config = raptorbt.PyBacktestConfig(initial_capital=100000.0, fees=0.001)
config.set_fixed_stop(0.02)
return config
def description(self) -> str:
return f"RSI({self.period}) 均值回归"
STRATEGY_CLASS = MyStrategy # 暴露此常量即可自动注册
```
> 详细文档见 [docs/策略自动化框架.md](docs/策略自动化框架.md)
---
## 项目结构
```
my-python-backteat/
├── app/ # 应用层 (Python)
│ ├── __init__.py # 包入口 + 版本号
│ ├── main.py # CLI 入口 (9 个子命令)
│ ├── data_loader.py # CSV 数据加载器 (M1→多周期重采样)
│ ├── indicators.py # 自定义指标库 (转发 ferro-ta 原生)
│ ├── lookahead_check.py # 前视偏差检测器 (静态 AST + 动态扰动)
│ ├── optimizer.py # 参数网格搜索优化器
│ ├── walk_forward.py # Walk-Forward 验证 + 过拟合检测
│ ├── acceptance.py # 策略验收标准
│ ├── scaffold.py # 策略模板生成器 (自带前视警告)
│ └── exporter.py # 交付包打包导出
├── strategies/ # 策略框架 (用户扩展区)
│ ├── __init__.py # 自动发现注册表
│ ├── base.py # Strategy 基类 + SignalResult
│ ├── sma_cross.py # 示例: SMA 交叉
│ ├── rsi_mean_reversion.py # 示例: RSI 均值回归
│ ├── sar_adx_cci.py # 示例: SAR+ADX+CCI
│ └── atr_stop_rr.py # 示例: ATR 止损 + 风险回报
├── data/ # CSV 数据目录 (用户放置, gitignore)
├── docs/ # 文档
│ ├── RaptorBT使用手册.md
│ ├── Mt5Bridge使用指南.md
│ └── 策略自动化框架.md
├── src/ # RaptorBT 引擎 (Rust)
├── python/raptorbt/ # PyO3 Python 绑定
├── benches/ # Rust 基准测试
├── tests/ # Rust 单元测试
├── vendor/ # 第三方源码依赖 ★必须随项目提交 (保证可移植)
│ ├── README.md # 依赖管理说明
│ └── ferro-ta-main/ # ferro-ta v1.2.0 — 80+ 指标的 Rust 原生实现
├── backtest_output/ # 运行时输出 (gitignore)
├── deliverables/ # 交付包 (运行时创建, gitignore)
├── Cargo.toml # Rust 依赖 (通过 path 引用 vendor/ferro-ta-main/)
├── pyproject.toml # Python 项目配置
├── requirements.txt # Python 依赖
└── README.md
```
**分层职责**
- **引擎层** (`src/`, `python/raptorbt/`)Rust 高性能回测核心 + Python 绑定
- **应用层** (`app/`):CLI、优化器、验证器、导出器、数据加载器、前视检测器
- **策略层** (`strategies/`):策略定义与自动注册
- **文档层** (`docs/`):使用手册与指南
- **依赖层** (`vendor/`):第三方源码依赖(ferro-ta-main),随项目提交以保证换电脑即可编译
> ⚠️ **可移植性**`vendor/ferro-ta-main/` 是 `ferro_ta_core` 的源码依赖(在 [Cargo.toml](Cargo.toml) 中通过 `path = "vendor/ferro-ta-main/crates/ferro_ta_core"` 引用),**必须随项目提交**。换电脑后无需联网拉取外部 crate,直接 clone 即可编译。详见 [vendor/README.md](vendor/README.md)。
---
## 技术指标
RaptorBT 提供 **80+ 个技术指标**,其中 12 个为原版指标,其余 68 个来自 ferro-ta 指标库。所有指标均以原生 Rust 实现,接受 NumPy `float64` 数组并返回 NumPy 数组。预热期返回 NaN。
### 原版指标 (12 个)
| 类别 | 指标 |
|------|------|
| **趋势** | SMA、EMA、Supertrend |
| **动量** | RSI、MACD、Stochastic |
| **波动率** | ATR、Bollinger Bands |
| **强度** | ADX |
| **成交量** | VWAP |
| **滚动** | Rolling Min、Rolling Max |
### ferro-ta 扩展指标 (68 个)
#### 趋势类 (15 个)
| 函数 | 签名 | 返回 | 说明 |
|------|------|------|------|
| `wma` | `wma(data, period)` | `ndarray` | 加权移动平均 |
| `dema` | `dema(data, period)` | `ndarray` | 双重指数移动平均 |
| `tema` | `tema(data, period)` | `ndarray` | 三重指数移动平均 |
| `kama` | `kama(data, period)` | `ndarray` | Kaufman 自适应移动平均 |
| `t3` | `t3(data, period=5, vfactor=0.7)` | `ndarray` | Tillson T3 移动平均 |
| `trima` | `trima(data, period)` | `ndarray` | 三角移动平均 |
| `midpoint` | `midpoint(data, period)` | `ndarray` | 周期内中点值 |
| `midprice` | `midprice(high, low, period)` | `ndarray` | 周期内最高/最低均价 |
| `sar` | `sar(high, low, acceleration=0.02, maximum=0.2)` | `ndarray` | 抛物线 SAR |
| `hull_ma` | `hull_ma(data, period)` | `ndarray` | Hull 移动平均 |
| `donchian` | `donchian(high, low, period)` | `(upper, middle, lower)` | 唐奇安通道 |
| `choppiness_index` | `choppiness_index(high, low, close, period=14)` | `ndarray` | 混沌指标 (0=趋势, 100=震荡) |
| `chandelier_exit` | `chandelier_exit(high, low, close, period=22, multiplier=3.0)` | `(long_exit, short_exit)` | 吊灯止损 (ATR 追踪) |
| `ichimoku` | `ichimoku(high, low, close, tenkan=9, kijun=26, senkou_b=52, displacement=26)` | `(tenkan, kijun, senkou_a, senkou_b, chikou)` | 一目均衡表 |
| `pivot_points` | `pivot_points(high, low, close, method="classic")` | `(pivot, r1, s1, r2, s2)` | 枢轴点 (classic/fibonacci/camarilla) |
#### 动量类 (14 个)
| 函数 | 签名 | 返回 | 说明 |
|------|------|------|------|
| `cci` | `cci(high, low, close, period)` | `ndarray` | 商品通道指数 |
| `willr` | `willr(high, low, close, period)` | `ndarray` | 威廉指标 (-100~0) |
| `roc` | `roc(data, period)` | `ndarray` | 变化率 |
| `mom` | `mom(data, period)` | `ndarray` | 动量 |
| `cmo` | `cmo(data, period)` | `ndarray` | 钱德动量振荡器 |
| `trix` | `trix(data, period)` | `ndarray` | 三重指数平滑变化率 |
| `stochrsi` | `stochrsi(data, timeperiod=14, fastk_period=5, fastd_period=3)` | `(fastk, fastd)` | 随机 RSI (0~100) |
| `aroon` | `aroon(high, low, period)` | `(up, down)` | Aroon 上升/下降 (0~100) |
| `aroonosc` | `aroonosc(high, low, period)` | `ndarray` | Aroon 振荡器 (-100~100) |
| `bop` | `bop(open, high, low, close)` | `ndarray` | 力量平衡 (-1~1) |
| `ultosc` | `ultosc(high, low, close, period1=7, period2=14, period3=28)` | `ndarray` | 终极振荡器 (0~100) |
| `ppo` | `ppo(data, fastperiod=12, slowperiod=26, signalperiod=9)` | `(line, signal, hist)` | 百分比价格振荡器 |
| `apo` | `apo(data, fastperiod=12, slowperiod=26)` | `ndarray` | 绝对价格振荡器 |
| `adx_all` | `adx_all(high, low, close, period)` | `(adx, +di, -di)` | ADX + DI+ + DI- |
#### 波动率类 (5 个)
| 函数 | 签名 | 返回 | 说明 |
|------|------|------|------|
| `natr` | `natr(high, low, close, period)` | `ndarray` | 归一化 ATR (%) |
| `trange` | `trange(high, low, close)` | `ndarray` | 真实波幅 |
| `stddev` | `stddev(data, period, nbdev=1.0)` | `ndarray` | 标准差 |
| `var` | `var(data, period, nbdev=1.0)` | `ndarray` | 方差 |
| `atr` | `atr(high, low, close, period)` | `ndarray` | 平均真实波幅 (原版) |
#### 强度类 (3 个)
| 函数 | 签名 | 返回 | 说明 |
|------|------|------|------|
| `adx` | `adx(high, low, close, period)` | `ndarray` | ADX (0~100) (原版) |
| `plus_di` | `plus_di(high, low, close, period)` | `ndarray` | +DI 方向指标 |
| `minus_di` | `minus_di(high, low, close, period)` | `ndarray` | -DI 方向指标 |
| `adxr` | `adxr(high, low, close, period)` | `ndarray` | ADX 评级 |
#### 成交量类 (5 个)
| 函数 | 签名 | 返回 | 说明 |
|------|------|------|------|
| `ad` | `ad(high, low, close, volume)` | `ndarray` | 累积/派发线 |
| `adosc` | `adosc(high, low, close, volume, fastperiod=3, slowperiod=10)` | `ndarray` | 累积/派发振荡器 |
| `obv` | `obv(close, volume)` | `ndarray` | 能量潮 |
| `mfi` | `mfi(high, low, close, volume, period)` | `ndarray` | 资金流量指数 (0~100) |
| `vwma` | `vwma(data, volume, period=20)` | `ndarray` | 成交量加权移动平均 |
#### 价格变换类 (4 个)
| 函数 | 签名 | 返回 | 说明 |
|------|------|------|------|
| `typprice` | `typprice(high, low, close)` | `ndarray` | 典型价格 (H+L+C)/3 |
| `medprice` | `medprice(high, low)` | `ndarray` | 中间价格 (H+L)/2 |
| `avgprice` | `avgprice(open, high, low, close)` | `ndarray` | 平均价格 (O+H+L+C)/4 |
| `wclprice` | `wclprice(high, low, close)` | `ndarray` | 加权收盘价 (H+L+C*2)/4 |
#### 统计类 (7 个)
| 函数 | 签名 | 返回 | 说明 |
|------|------|------|------|
| `linearreg` | `linearreg(data, period)` | `ndarray` | 线性回归 |
| `linearreg_slope` | `linearreg_slope(data, period)` | `ndarray` | 线性回归斜率 |
| `linearreg_angle` | `linearreg_angle(data, period)` | `ndarray` | 线性回归角度 |
| `linearreg_intercept` | `linearreg_intercept(data, period)` | `ndarray` | 线性回归截距 |
| `tsf` | `tsf(data, period)` | `ndarray` | 时间序列预测 |
| `beta` | `beta(data0, data1, period)` | `ndarray` | Beta 系数 |
| `correl` | `correl(data0, data1, period)` | `ndarray` | 相关系数 |
#### Hilbert 变换 (6 个)
基于希尔伯特变换的周期分析工具(需要至少 32 根 K 线):
| 函数 | 签名 | 返回 | 说明 |
|------|------|------|------|
| `ht_trendline` | `ht_trendline(data)` | `ndarray` | 希尔伯特瞬时趋势线 |
| `ht_dcperiod` | `ht_dcperiod(data)` | `ndarray` | 主导周期周期 |
| `ht_dcphase` | `ht_dcphase(data)` | `ndarray` | 主导周期相位(度) |
| `ht_phasor` | `ht_phasor(data)` | `(in_phase, quadrature)` | 相量分量 |
| `ht_sine` | `ht_sine(data)` | `(sine, lead_sine)` | 正弦波(含超前信号) |
| `ht_trendmode` | `ht_trendmode(data)` | `ndarray[i32]` | 趋势/周期模式 (1=趋势, 0=周期) |
#### 市场状态检测 (4 个)
用于判断当前市场处于趋势或震荡状态,以及检测结构性突变:
| 函数 | 签名 | 返回 | 说明 |
|------|------|------|------|
| `regime_adx` | `regime_adx(adx, threshold=25.0)` | `ndarray[i8]` | 基于 ADX 的趋势/震荡标签 (1=趋势, 0=震荡, -1=预热) |
| `regime_combined` | `regime_combined(adx, atr, close, adx_threshold=25.0, atr_pct_threshold=2.0)` | `ndarray[i8]` | ADX+ATR 组合判断 |
| `detect_breaks_cusum` | `detect_breaks_cusum(data, window, threshold, slack)` | `ndarray[i8]` | CUSUM 结构性突变检测 (1=突变点) |
| `rolling_variance_break` | `rolling_variance_break(data, short_window, long_window, threshold)` | `ndarray[i8]` | 滚动方差比突变检测 (1=突变点) |
#### 投资组合工具 (6 个)
跨序列分析工具,用于配对交易、风险管理、相对强度计算:
| 函数 | 签名 | 返回 | 说明 |
|------|------|------|------|
| `rolling_beta` | `rolling_beta(asset, benchmark, window)` | `ndarray` | 滚动 Beta 系数 |
| `drawdown_series` | `drawdown_series(equity)` | `(dd_series, max_dd)` | 回撤序列 + 最大回撤 |
| `zscore_series` | `zscore_series(data, window)` | `ndarray` | 滚动 Z-Score |
| `relative_strength` | `relative_strength(asset_returns, benchmark_returns)` | `ndarray` | 相对强度 (excess return 风格) |
| `spread` | `spread(a, b, hedge)` | `ndarray` | 价差序列 (a - hedge*b) |
| `ratio` | `ratio(a, b)` | `ndarray` | 比率序列 (a/b) |
#### Tick 微结构函数 (8 个)
| 函数 | 签名 | 返回 | 说明 |
|------|------|------|------|
| `tick_spread_pct` | `tick_spread_pct(bid, ask)` | `ndarray` | 每 Tick 买卖价差百分比 |
| `buy_sell_imbalance_delta` | `buy_sell_imbalance_delta(buy_cum, sell_cum)` | `ndarray` | 每 Tick 买卖失衡 |
| `return_window` | `return_window(timestamps_ns, ltp, window_seconds=60.0)` | `ndarray` | 时间窗口回看收益率 |
| `realized_vol_rolling` | `realized_vol_rolling(timestamps_ns, ltp, window_seconds=300.0)` | `ndarray` | 滚动已实现波动率 |
| `oi_position_pct` | `oi_position_pct(oi, oi_day_high, oi_day_low)` | `ndarray` | OI 位置百分比 [0, 100] |
| `tick_velocity` | `tick_velocity(timestamps_ns, window_seconds=60.0)` | `ndarray` | Tick 速度 (ticks/min) |
| `compute_tick_entry_signals` | `compute_tick_entry_signals(spread_pct, bsi_delta, return_1m, ...)` | `ndarray[bool]` | Tick 入场信号 |
| `compute_tick_exit_signals` | `compute_tick_exit_signals(timestamps_ns, eod_exit_time_ns=0)` | `ndarray[bool]` | Tick 出场信号 |
### 用法示例
```python
import raptorbt
import numpy as np
close = np.array([...], dtype=np.float64)
high = np.array([...], dtype=np.float64)
low = np.array([...], dtype=np.float64)
open_ = np.array([...], dtype=np.float64)
volume = np.array([...], dtype=np.float64)
# 趋势
sma20 = raptorbt.sma(close, 20)
hull_ma = raptorbt.hull_ma(close, 14)
donchian_upper, donchian_middle, donchian_lower = raptorbt.donchian(high, low, 20)
ichimoku = raptorbt.ichimoku(high, low, close)
# 动量
rsi14 = raptorbt.rsi(close, 14)
macd_line, macd_signal, macd_hist = raptorbt.macd(close, 12, 26, 9)
cci20 = raptorbt.cci(high, low, close, 20)
ppo_line, ppo_signal, ppo_hist = raptorbt.ppo(close)
# 波动率
atr14 = raptorbt.atr(high, low, close, 14)
natr14 = raptorbt.natr(high, low, close, 14)
bb_upper, bb_middle, bb_lower = raptorbt.bollinger_bands(close, 20, 2.0)
# 成交量
ad_line = raptorbt.ad(high, low, close, volume)
mfi14 = raptorbt.mfi(high, low, close, volume, 14)
# Hilbert
ht_trendline = raptorbt.ht_trendline(close)
sine, lead_sine = raptorbt.ht_sine(close)
# 市场状态
adx_vals = raptorbt.adx(high, low, close, 14)
regime = raptorbt.regime_adx(adx_vals, threshold=25.0)
# 投资组合
rolling_beta = raptorbt.rolling_beta(close, benchmark, 20)
dd_series, max_dd = raptorbt.drawdown_series(equity_curve)
```
---
## 策略类型
### 1. 单标的回测
```python
config = raptorbt.PyBacktestConfig(initial_capital=100000, fees=0.001, slippage=0.0005)
config.set_fixed_stop(0.02) # 2% 止损
config.set_fixed_target(0.04) # 4% 止盈
result = raptorbt.run_single_backtest(
timestamps=timestamps, open=open, high=high, low=low, close=close, volume=volume,
entries=entries, exits=exits, direction=1, weight=1.0, symbol="AAPL", config=config,
instrument_config=raptorbt.PyInstrumentConfig(lot_size=1.0), # 可选
)
```
### 2. 篮子回测
多标的同步信号交易:
```python
instruments = [
(ts, o1, h1, l1, c1, v1, ent1, ext1, 1, 0.33, "AAPL"),
(ts, o2, h2, l2, c2, v2, ent2, ext2, 1, 0.33, "GOOGL"),
(ts, o3, h3, l3, c3, v3, ent3, ext3, 1, 0.34, "MSFT"),
]
result = raptorbt.run_basket_backtest(
instruments=instruments,
config=config,
sync_mode="all", # "all" | "any" | "majority" | "master"
)
```
### 3. 配对交易
做多一个标的,做空另一个:
```python
result = raptorbt.run_pairs_backtest(
leg1_timestamps=ts, leg1_open=o1, leg1_high=h1, leg1_low=l1, leg1_close=c1, leg1_volume=v1,
leg2_timestamps=ts, leg2_open=o2, leg2_high=h2, leg2_low=l2, leg2_close=c2, leg2_volume=v2,
entries=entries, exits=exits, direction=1, symbol="PAIR", config=config,
hedge_ratio=1.5, # 空头 1.5 倍
dynamic_hedge=False,
)
```
### 4. 期权回测
```python
result = raptorbt.run_options_backtest(
timestamps=ts, open=o, high=h, low=l, close=c, volume=v,
option_prices=option_premiums, entries=entries, exits=exits,
direction=1, symbol="NIFTY_CE", config=config,
option_type="call", # "call" | "put"
strike_selection="atm", # "atm" | "otm1" | "otm2" | "itm1" | "itm2"
size_type="percent", # "percent" | "contracts" | "notional" | "risk"
size_value=0.1,
lot_size=50,
)
```
### 5. 多策略回测
同一标的上组合多个策略:
```python
strategies = [
(entries_sma, exits_sma, 1, 0.4, "SMA_Cross"),
(entries_rsi, exits_rsi, 1, 0.35, "RSI_MeanRev"),
(entries_bb, exits_bb, 1, 0.25, "BB_Break"),
]
result = raptorbt.run_multi_backtest(
timestamps=ts, open=o, high=h, low=l, close=c, volume=v,
strategies=strategies,
config=config,
combine_mode="any", # "any" | "all" | "majority" | "weighted" | "independent"
)
```
### 6. 批量价差回测
Rayon 并行执行多个价差回测,GIL 释放:
```python
items = [
raptorbt.PyBatchSpreadItem(
strategy_id="straddle_24000",
legs_premiums=[call_premiums, put_premiums],
leg_configs=[("CE", 24000.0, -1, 50), ("PE", 24000.0, -1, 50)],
entries=entries, exits=exits,
spread_type="straddle",
max_loss=5000.0, target_profit=3000.0,
),
]
results = raptorbt.batch_spread_backtest(
timestamps=ts, underlying_close=close,
items=items, config=config,
)
for sid, result in results:
print(f"{sid}: {result.metrics.total_return_pct:.2f}%")
```
### 7. Tick 级回测
全 Tick 分辨率模拟,无 K 线重采样:
```python
result = raptorbt.run_tick_backtest(
timestamps=timestamps_ns, # int64 纳秒
ltp=ltp_arr, bid=bid_arr, ask=ask_arr,
buy_qty_delta=buy_delta, sell_qty_delta=sell_delta,
oi=oi_arr,
entries=entry_signals, exits=exit_signals,
symbol="TICK",
initial_capital=100000.0, fees=0.001, slippage=0.0005,
stop_loss_pct=5.0, take_profit_pct=10.0,
max_hold_seconds=1800, entry_cooldown_ticks=10, max_trades=50,
)
```
> **Zerodha 数据注意**`total_buy_qty` / `total_sell_qty` 是累计值,需先转换:
> `buy_delta = np.diff(buy_cum, prepend=0).clip(min=0)`
---
## 止损与止盈
### 固定百分比
```python
config = raptorbt.PyBacktestConfig(initial_capital=100000, fees=0.001)
config.set_fixed_stop(0.02) # 2% 止损
config.set_fixed_target(0.04) # 4% 止盈
```
### ATR 动态止损
```python
config.set_atr_stop(multiplier=2.0, period=14) # 2倍 ATR 止损
config.set_atr_target(multiplier=3.0, period=14) # 3倍 ATR 止盈
```
### 追踪止损
```python
config.set_trailing_stop(0.02) # 2% 追踪止损
```
### 风险回报比止盈
```python
config.set_risk_reward_target(ratio=2.0) # 2:1 风险回报比
```
### 出场原因
| 值 | 含义 |
|----|------|
| `Signal` | 策略信号出场 |
| `StopLoss` | 触发止损 |
| `TakeProfit` | 触发止盈 |
| `TrailingStop` | 触发追踪止损 |
| `EndOfData` | 数据结束 |
| `Settlement` | 期权结算 |
| `TimeExit` | 超时出场(Tick 级) |
---
## 蒙特卡洛组合模拟
```python
result = raptorbt.simulate_portfolio_mc(
returns=[ret1, ret2], # 各策略/资产的历史日收益率数组
weights=np.array([0.6, 0.4]), # 组合权重(和为 1
correlation_matrix=[ # N×N 相关系数矩阵
np.array([1.0, 0.3]),
np.array([0.3, 1.0]),
],
initial_value=100000.0,
n_simulations=10000, # 模拟路径数
horizon_days=252, # 前瞻天数
seed=42, # 随机种子
)
print(f"预期收益: {result['expected_return']:.2f}%")
print(f"亏损概率: {result['probability_of_loss']:.2%}")
print(f"VaR (95%): {result['var_95']:.2f}%")
print(f"CVaR (95%): {result['cvar_95']:.2f}%")
```
---
## 回测结果与指标
### PyBacktestResult
```python
result.metrics # PyBacktestMetrics 对象
result.equity_curve() # 权益曲线 ndarray
result.drawdown_curve() # 回撤曲线 ndarray
result.returns() # 收益率序列 ndarray
result.trades() # 交易列表 List[PyTrade]
```
### PyBacktestMetrics33 个字段)
**核心绩效**`total_return_pct``sharpe_ratio``sortino_ratio``calmar_ratio``omega_ratio`
**回撤**`max_drawdown_pct``max_drawdown_duration`
**交易统计**`total_trades``total_closed_trades``total_open_trades``winning_trades``losing_trades``win_rate_pct`
**交易绩效**`profit_factor``expectancy``sqn``avg_trade_return_pct``avg_win_pct``avg_loss_pct``best_trade_pct``worst_trade_pct`
**持仓**`avg_holding_period``avg_winning_duration``avg_losing_duration`
**连战**`max_consecutive_wins``max_consecutive_losses`
**其他**`start_value``end_value``total_fees_paid``open_trade_pnl``exposure_pct``payoff_ratio``recovery_factor`
```python
m = result.metrics
stats = m.to_dict() # 24 个常用指标的字典(带中文友好标签)
```
### PyTrade
```python
for trade in result.trades():
trade.id # 交易 ID
trade.symbol # 标的
trade.entry_idx # 入场 bar 索引
trade.exit_idx # 出场 bar 索引
trade.entry_price # 入场价
trade.exit_price # 出场价
trade.size # 仓位大小
trade.direction # 1=多, -1=空
trade.pnl # 盈亏金额
trade.return_pct # 收益率 (%)
trade.fees # 手续费
trade.exit_reason # 出场原因
```
---
## API 参考
### PyBacktestConfig
```python
config = raptorbt.PyBacktestConfig(
initial_capital=100000.0, # 初始资金
fees=0.001, # 手续费率
slippage=0.0, # 滑点
upon_bar_close=True, # K 线收盘后执行(防止前视偏差)
)
# 止损方法
config.set_fixed_stop(percent: float)
config.set_atr_stop(multiplier: float, period: int)
config.set_trailing_stop(percent: float)
# 止盈方法
config.set_fixed_target(percent: float)
config.set_atr_target(multiplier: float, period: int)
config.set_risk_reward_target(ratio: float)
```
### PyInstrumentConfig
每标的配置:
```python
inst = raptorbt.PyInstrumentConfig(
lot_size=1.0, # 最小交易单位
alloted_capital=50000.0, # 分配资金(可选)
existing_qty=None, # 现有持仓(预留)
avg_price=None, # 现有均价(预留)
)
# 可选:每标的止损/止盈覆盖
inst.set_fixed_stop(0.02)
inst.set_trailing_stop(0.03)
```
### PyBatchSpreadItem
```python
item = raptorbt.PyBatchSpreadItem(
strategy_id="straddle_24000",
legs_premiums=[call_premiums, put_premiums],
leg_configs=[("CE", 24000.0, -1, 50), ("PE", 24000.0, -1, 50)],
entries=entries, exits=exits, spread_type="straddle",
max_loss=5000.0, target_profit=3000.0,
)
```
### simulate_portfolio_mc
```python
result = raptorbt.simulate_portfolio_mc(
returns=List[np.ndarray], # 各资产日收益率 (N 个数组)
weights=np.ndarray, # 组合权重 (长度 N, 和为 1)
correlation_matrix=List[np.ndarray], # N×N 相关系数矩阵
initial_value=float, # 初始组合价值
n_simulations=int=10000, # 模拟路径数
horizon_days=int=252, # 前瞻天数
seed=int=42, # 随机种子
) -> dict
```
返回字典包含:`expected_return``probability_of_loss``var_95``cvar_95``percentile_paths``final_values`
---
## 从源码构建
大多数用户应使用 `pip install raptorbt`。要自行构建,需要 Rust 1.70+、Python 3.10+ 和 maturin
```powershell
cd raptorbt
$env:CARGO = "C:\Users\Administrator\.cargo\bin\cargo.exe"
maturin develop --release # 开发安装到当前虚拟环境
cargo test # 运行 Rust 测试套件
```
> **注意**:如果在 Windows 上遇到「拒绝访问 (os error 5)」错误,需要设置 `CARGO` 环境变量指向 `cargo.exe` 可执行文件(而非目录)。参见 [使用手册 - 常见编译问题](https://github.com/your-repo/raptorbt/blob/main/RaptorBT使用手册.md#常见编译问题)。
### 前置依赖
| 依赖 | 版本 | 说明 |
|------|------|------|
| Rust toolchain | 1.70+ | `cargo``rustc`(从 https://rustup.rs 安装) |
| Python | 3.10+ | 与编译时 Python 版本一致 |
| maturin | latest | `pip install maturin`Rust → Python 扩展构建工具 |
| `vendor/ferro-ta-main/` | — | **已随项目提交**,提供 `ferro_ta_core` crate(80+ 指标),无需联网拉取 |
> 💡 **可移植性**`vendor/ferro-ta-main/` 是 [Cargo.toml](Cargo.toml) 中 `ferro_ta_core` 的 path 源码依赖,换电脑或部署新环境时 clone 项目即可编译,**无需担心外部 crate 源缺失**。
### 构建并安装到全局
```powershell
# 构建 whl (会自动编译 vendor/ferro-ta-main/ 下的 ferro_ta_core)
maturin build --release
# 产物: target/wheels/raptorbt-0.4.1-cp312-cp312-win_amd64.whl
# 全局 pip 安装
pip install --force-reinstall target\wheels\raptorbt-0.4.1-cp312-cp312-win_amd64.whl
```
### 开发模式(虚拟环境)
```powershell
# 在已激活的虚拟环境中编译,直接安装到 python/raptorbt/_raptorbt.*.pyd
maturin develop --release
```
> ⚠️ `maturin develop` 需要在已激活的虚拟环境(venv/conda)中运行,否则会报 "Couldn't find a virtualenv or conda environment"。若需全局安装,用 `maturin build` + `pip install` 方式。
### 验证测试
一个带种子的冒烟测试——运行两次,结果完全一致:
```python
import numpy as np
import raptorbt
np.random.seed(42)
n = 500
close = np.cumprod(1 + np.random.randn(n) * 0.02) * 100
entries = np.zeros(n, dtype=bool); entries[::20] = True
exits = np.zeros(n, dtype=bool); exits[10::20] = True
config = raptorbt.PyBacktestConfig(initial_capital=100000, fees=0.001)
result = raptorbt.run_single_backtest(
timestamps=np.arange(n, dtype=np.int64),
open=close, high=close, low=close, close=close, volume=np.ones(n),
entries=entries, exits=exits, direction=1, weight=1.0, symbol="TEST",
config=config,
)
print(f"总收益率: {result.metrics.total_return_pct:.4f}%") # -30.6192%
print(f"夏普比率: {result.metrics.sharpe_ratio:.4f}") # -0.9086
```
---
## 版本历史
### v0.4.1
- **新增 68 个扩展指标**:集成 ferro-ta 指标库
- P0 扩展:VWMA、Donchian、Choppiness Index、Hull MA、Chandelier Exit、Ichimoku、Pivot Points
- Hilbert 变换:HT Trendline、DCPeriod、DCPhase、Phasor、Sine、TrendMode
- 市场状态检测:Regime ADX、Regime Combined、CUSUM Breaks、Variance Ratio Breaks
- 投资组合工具:Rolling Beta、Drawdown Series、Z-Score Series、Relative Strength、Spread、Ratio
- 指标总数从 12 扩展到 80+
### v0.4.0
- **Tick 级回测**:全 Tick 分辨率,无需 K 线重采样
- `TickData` 结构:`timestamps``ltp``bid``ask``buy_qty_delta``sell_qty_delta``oi`
- `ExitReason::TimeExit`:最大持仓时间超时退出
- `run_tick_backtest`Tick 原生模拟引擎
- `compute_tick_entry_signals`:从特征数组计算入场信号
- `compute_tick_exit_signals`:基于时间的出场信号
- `tick_spread_pct``buy_sell_imbalance_delta``return_window``realized_vol_rolling``oi_position_pct``tick_velocity`
- 公开 `compute_backtest_metrics` 函数
### v0.3.4
- 单腿期权价差:`LongCall``LongPut``NakedCall``NakedPut`
- `ExitReason::Settlement`:期权到期结算退出
- `leg_expiry_timestamps`:每条腿的到期时间追踪
### v0.3.3
- `batch_spread_backtest`:通过 Rayon 并行运行多个价差回测
- `PyBatchSpreadItem`:批量价差回测项定义
- GIL 释放,最大 Python 并发
### v0.3.2
- `payoff_ratio` 指标:平均盈利交易收益 / 平均亏损交易收益(绝对值)
- `recovery_factor` 指标:净利润 / 最大回撤(绝对值)
### v0.3.1
- 蒙特卡洛组合模拟(`simulate_portfolio_mc`
- 几何布朗运动 + Cholesky 分解,Rayon 并行
### v0.3.0
- `PyInstrumentConfig`:每标的的配置(lot_size、分配资金、止损/止盈覆盖)
- 仓位大小正确取整到 lot_size 的倍数
### v0.2.2
- 导出 `run_spread_backtest``rolling_min``rolling_max`
### v0.2.1
- 添加 `rolling_min``rolling_max`LLV / HHV
### v0.2.0
- 多腿价差回测(straddle、strangle、vertical、iron condor、iron butterfly、butterfly、calendar、diagonal
- 会话跟踪器(NSE 股票、MCX 商品、CDS 货币)
- `StreamingMetrics`:权益/回撤追踪、交易记录、`finalize()`
### v0.1.0
- 初始版本
- 5 种策略类型、30+ 绩效指标、10 个技术指标
- 止损管理:固定、ATR、追踪
- 止盈管理:固定、ATR、风险回报
- PyO3 Python 绑定
---
## 许可证
MIT License - 详见 [LICENSE](LICENSE)