# RaptorBT [](https://uppercase.org/licenses/MIT) [](https://www.python.org/downloads/) [](https://www.rust-lang.org/) **高性能 Rust 回测引擎,亚毫秒级回测,80+ 技术指标,位级确定性执行。** RaptorBT 是一个用 Rust 编写的高性能回测引擎,通过 PyO3 提供 Python 绑定。支持单标的、篮子、配对、期权、价差、多策略、Tick 级回测,在亚毫秒级时间内返回完整的 33 项绩效指标报告。
亚毫秒级回测 · 编译后 < 1 MB · 80+ 技术指标 · 位级确定性 · 原生并行
--- ## 快速开始 ### 安装 ```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 提供 **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] ``` ### PyBacktestMetrics(33 个字段) **核心绩效**:`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#常见编译问题)。 ### 构建并安装到全局 ```powershell # 构建 whl maturin build --release # 全局 pip 安装 pip install --force-reinstall target\wheels\raptorbt-0.4.1-cp312-cp312-win_amd64.whl ``` ### 验证测试 一个带种子的冒烟测试——运行两次,结果完全一致: ```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)