Files

7.0 KiB

AGENTS.md — AI Agent 项目规则

本文件会被 AI agent 自动加载为系统上下文。开发策略前请完整阅读。

项目概述

RaptorBT — Rust 高性能回测引擎 + Python 绑定 + MT5 桥接,目标是让 AI agent 自主开发、优化并交付交易策略。

  • 引擎层: Rust (PyO3 绑定,亚毫秒级,7 种回测类型,33 项绩效指标)
  • 应用层: app/ (Python,relative imports)
  • 策略层: strategies/ (自动发现)
  • 第三方源码: vendor/ferro-ta-main/ (80+ 指标的 Rust 原生实现,必须随项目提交)
  • 文档: docs/
  • 输出: backtest_output/ deliverables/ (gitignore)

编译

项目用 maturin 编译 Rust → Python 扩展。换电脑或修改 Rust 源码后:

# 生成 whl 包 (会用到 vendor/ferro-ta-main/ 下的 ferro_ta_core 源码)
maturin build --release
# 产物: target/wheels/raptorbt-*.whl

# 安装到当前 Python 环境
pip install --force-reinstall target/wheels/raptorbt-*.whl

# 或在虚拟环境中开发模式 (会编译到 python/raptorbt/_raptorbt.*.pyd)
maturin develop --release

前置依赖: Rust toolchain (cargo/rustc)、Python 3.10+、maturin。

硬约束 (必须遵守)

  1. CLI 入口: 必须用 python -m app.main <command>,禁止 python main.py
  2. 包结构: 应用层模块在 app/,策略在 strategies/,文档在 docs/
  3. 导入: 应用层模块用相对导入 (from .xxx import yyy),策略用 from .base import Strategy, SignalResult
  4. API Key: 用环境变量 MT5_BRIDGE_KEY,禁止 hardcode
  5. 数据源: 默认 --source csv(离线研究),MT5 仅用于最终验证
  6. 输出目录: backtest_output/ deliverables/ data/ 必须在 .gitignore

AI agent 策略开发流程 (0→8)

0. list --indicators --json    查询 80 个可用指标 (签名/默认值/返回值)
   ↓
1. scaffold --name XXX          生成策略模板 (自带前视警告头部)
   ↓
2. 编辑 strategies/XXX.py       填入信号逻辑 (用 raptorbt.<指标名>)
   ↓
3. check --strategy XXX         前视偏差检测 ★强制 (静态+动态)
   ↓
4. optimize --strategy XXX      参数网格搜索
   ↓
5. walkforward --strategy XXX   Walk-Forward 验证
   ↓
6. validate --strategy XXX      验收 (4 条标准 + 失败诊断)
   ↓
7. 未通过 → 读 suggestions 调整, 回到 2/4
   通过 → 继续 8
   ↓
8. deliver --strategy XXX       交付 (再次强制前视检测, 失败拒绝生成)

所有命令支持 --json 输出,AI agent 应优先用 --json 解析结构化结果。

前视偏差禁令 (最重要)

信号生成只能用当前 bar 及之前的数据,严禁访问未来 bar。

禁止模式 (会被 check 检测并拒绝交付):

  • .shift(-N) (N>0) — 访问未来 bar
  • close[-1] / high[-1] — 负索引访问未来
  • df.iloc[i+N:] — 切片到未来索引
  • 滚动统计后 shift 负值
  • np.roll(arr, -N) — 循环移位可能引入前视

正确做法:

  • 用基类的 cross_above / cross_below (已内置前视安全)
  • 信号在 bar 收盘后生成,引擎默认 upon_bar_close=True,以 close 成交
  • 检测命令: python -m app.main check --strategy XXX --dynamic

指标调用

import raptorbt
import numpy as np

close = df["close"].values.astype(np.float64)
high = df["high"].values.astype(np.float64)
low = df["low"].values.astype(np.float64)

# 单返回
sma = raptorbt.sma(close, period=14)
rsi = raptorbt.rsi(close, period=14)

# 多返回
adx, plus_di, minus_di = raptorbt.adx_all(high, low, close, period=14)
upper, middle, lower = raptorbt.bollinger_bands(close, period=20, std_dev=2.0)
macd, signal, hist = raptorbt.macd(close, fast_period=12, slow_period=26, signal_period=9)

查询全部 80 个指标:

python -m app.main list --indicators        # 文本版
python -m app.main list --indicators --json # JSON 版 (AI agent 用)

策略模板结构

"""<name> — <description>

⚠️ 前视偏差注意事项: (scaffold 自动生成, 不要删除)
"""

from __future__ import annotations
import numpy as np
import raptorbt
from .base import Strategy, SignalResult


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)
        # ... 指标计算和信号生成 (只用当前及之前的数据) ...
        entries = np.zeros(len(close), dtype=bool)
        exits = np.zeros(len(close), dtype=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, slippage=0.0005,
        )
        config.set_fixed_stop(0.02)
        config.set_fixed_target(0.04)
        return config

    def description(self) -> str:
        return "..."


STRATEGY_CLASS = MyStrategy  # 必须暴露此变量供自动发现

验收标准 (4 条)

标准 阈值 失败建议方向
OOS 夏普比率 ≥ 1.0 放宽止损 / 加趋势过滤 / 反向信号 / 切大周期
OOS 最大回撤 ≤ 15% 收紧止损 / ATR 止损 / 追踪止损 / 降仓位
OOS 总交易数 ≥ 30 缩短指标周期 / 降阈值 / 切小周期 / 检查 warmup
IS/OOS 衰减比 ≥ 0.5 缩小参数空间 / 增 WF 窗口 / 简化策略 / 检查前视

validate --json 输出中每条失败标准都带 suggestions 数组(5 条具体建议)。

常用命令速查

# 查询
python -m app.main list                           # 策略列表
python -m app.main list --indicators --json       # 指标目录 (80 个)

# 开发
python -m app.main scaffold --name XXX --template breakout
python -m app.main check --strategy XXX --dynamic --bars 500 --json

# 测试和优化
python -m app.main run --strategy XXX --bars 500 --json
python -m app.main optimize --strategy XXX --param period=10,15,20 --json
python -m app.main walkforward --strategy XXX --param period=10,15,20 --bars 2000 --json

# 验收和交付
python -m app.main validate --strategy XXX --param period=10,15,20 --bars 2000 --json
python -m app.main deliver --strategy XXX --param period=10,15 --bars 2000 --json

命名规范

  • 策略文件: snake_case.py (如 sma_cross.py)
  • 策略类: PascalCaseStrategy (如 SmaCrossStrategy)
  • 应用模块: 语义命名 (如 indicators.py 而非 my_indicators.py)
  • 必须暴露 STRATEGY_CLASS 变量供 strategies/__init__.py 自动发现

文档