Skip to main content

Alpha Trading Rust System - Ultra-fast backtest engine for A-shares

Project description

ATRS - Alpha Trading Rust System

专为 A 股高频多因子策略设计的超高速回测引擎

比主流框架快 50-150 倍 | 🇨🇳 完整支持 A 股规则 | 🎯 极简 API

🏆 核心优势

极致性能:秒级完成大规模回测

  • 53万行数据仅需 0.4 秒(Backtrader 需要 30-60 秒)
  • Rust 底层 + Polars 高效数据处理
  • 零拷贝数据传输,原生数组操作
  • 比 VectorBT 快 5-10 倍,比 Backtrader 快 100+ 倍

🇨🇳 A 股专业化:唯一完整支持 A 股规则的开源框架

  • 自融资约束:买入金额 ≤ 卖出金额(不能加杠杆)
  • 涨跌停限制:涨停不能买,跌停不能卖
  • T+1 交易:内置 A 股交易机制
  • 停牌处理:自动跳过停牌日,延迟换仓
  • 多时间点换仓:支持日内多次调仓(09:31, 14:00 等)

🎯 创新功能:滚动换仓 + 多周期持仓

  • 滚动换仓 (rolling_window):滑动平均信号,平滑波动,降低换手率
  • 多周期持仓 (holding_period):支持 1天、5天、10天等固定持仓周期
  • 灵活组合:两个参数可同时使用,满足不同策略需求

💻 极简 API:一行代码完成复杂回测

# ATRS:一行代码
result = backtest(df, rolling_window=5, holding_period=1)

# Backtrader:需要几十行配置
cerebro = bt.Cerebro()
cerebro.addstrategy(MyStrategy)
cerebro.adddata(data)
cerebro.broker.setcash(100000)
...

✨ 特性

  • 🚀 极致性能:Rust 实现,比 Python 快 50-150 倍
  • 📊 Polars 集成:零拷贝数据传输,支持大规模数据
  • 🔌 插件化架构:可扩展的数据源、执行引擎、输出器和分析器
  • 🇨🇳 A 股规则:内置自融资约束、涨跌停限制、满仓运行
  • ⏱️ 高频支持:支持日内多个时间点换仓
  • 💰 费用模型:支持自定义买卖费率
  • 📅 多周期持仓:支持固定持仓周期(1天、5天、10天等)
  • 🔄 滚动换仓:滑动平均信号,降低换手率

📦 安装

pip install atrs

或从源码编译:

git clone https://github.com/yourusername/atrs.git
cd atrs
maturin develop --release

🚀 快速开始

基础回测(1日持仓)

import polars as pl
from atrs import backtest

# 准备数据
data = pl.read_csv("factor_data.csv")

# 运行回测
result = backtest(data, limit=True)

# 查看结果
pos_df = result['pos']  # 持仓详情
ret_df = result['ret']  # 每日收益

# 计算累计收益
total_return = (1 + ret_df['long']).product() - 1
print(f"累计收益: {total_return:.2%}")

多周期持仓回测

from atrs import backtest

# 5日持仓周期,含交易费用
result = backtest(
    data,
    limit=True,
    buy_fee=0.0003,        # 买入费率 0.03%
    sell_fee=0.0013,       # 卖出费率 0.13%(含印花税)
    holding_period=5       # 每5个交易日换仓
)

# 查看扣除费用后的收益
ret_df = result['ret']
total_return = (1 + ret_df['long']).product() - 1
print(f"累计收益(5日持仓): {total_return:.2%}")

# 对比不同持仓周期
for period in [1, 5, 10]:
    result = backtest(data, holding_period=period, buy_fee=0.0003, sell_fee=0.0013)
    ret = (1 + result['ret']['long']).product() - 1
    print(f"{period}日持仓: {ret:.2%}")

滚动换仓回测(滑动平均信号)

from atrs import backtest

# 使用最近5天信号的加权平均作为target_weight
result = backtest(
    data,
    limit=True,
    buy_fee=5e-4,
    sell_fee=10e-4,
    rolling_window=5  # 5天滚动窗口
)

# 对比不同滚动窗口
for window in [0, 5, 10]:
    result = backtest(data, rolling_window=window)
    ret = (1 + result['ret']['long']).product() - 1
    print(f"{window}天滚动: {ret:.2%}")

滚动换仓优势:

  • 📉 平滑信号波动:减少噪音干扰
  • 💸 降低换手率:节省交易成本
  • 🎯 适合持续性信号:发挥因子稳定性

📋 数据格式

输入数据必须包含以下列:

列名 类型 说明
date str 日期 (YYYY-MM-DD)
time str 时间 (HH:MM:SS)
asset str/int 资产代码
price float 当前价格
prev_close float 昨日收盘价
open float 开盘价
close float 收盘价
target_weight float 目标权重
limit float 涨跌停标记(可选,>0 表示受限)

🔧 API 参考

backtest(weight_df, limit=True, buy_fee=0.0, sell_fee=0.0, holding_period=1, rolling_window=0)

超高速回测引擎(支持多周期持仓、滚动换仓和费用)。

参数:

  • weight_df: Polars DataFrame,输入数据
  • limit: bool,是否启用涨跌停限制(默认 True)
  • buy_fee: float,买入费率(默认 0.0)
  • sell_fee: float,卖出费率(默认 0.0)
  • holding_period: int,持仓周期(交易日数),默认 1(每日换仓)
  • rolling_window: int,滚动换仓窗口大小(天数),默认 0(不启用)

返回:

{
    'pos': DataFrame,  # 持仓详情
    'ret': DataFrame   # 每日收益
}

示例:

# 1日持仓(每日换仓)
result = backtest(data, holding_period=1)

# 5日持仓(每5个交易日换仓)
result = backtest(data, holding_period=5, buy_fee=0.0003, sell_fee=0.0013)

# 10日持仓
result = backtest(data, holding_period=10)

# 滚动换仓(5天滑动平均)
result = backtest(data, rolling_window=5)

# 组合使用:5日持仓 + 10天滚动
result = backtest(data, holding_period=5, rolling_window=10)

bt(weight_df, period="1d", buy_fee=5e-4, sell_fee=10e-4)

完整回测引擎(支持持仓周期和费用,性能略低于backtest())。

💡 推荐:优先使用 backtest() 函数,它已经支持所有功能且性能更优。

参数:

  • weight_df: Polars DataFrame,输入数据
  • period: str,持仓周期,如 "1d", "5d", "10d"
  • buy_fee: float,买入费率(默认 0.05%)
  • sell_fee: float,卖出费率(默认 0.1%,含印花税)

返回:backtest()

📊 输出说明

持仓详情 (pos)

列名 说明
date 日期
time 时间
asset 资产代码
price 价格
forward_ret 向前收益率
target_weight 目标权重
limit 涨跌停标记
avail_sell 可卖出权重
beg_weight 期初权重
chg_weight 目标权重变化
change_weight 实际权重变化(经约束调整)
real_weight 实际持仓权重
end_weight 期末权重(含收益)

每日收益 (ret)

列名 说明
date 日期
long 当日收益率(已扣除费用)

🎯 A 股规则支持

1. 自融资约束

  • 买入金额 ≤ 卖出金额(不能加杠杆)
  • 首日建仓不受限制
  • 后续交易日严格执行约束

2. 涨跌停限制

  • 涨停时不能买入
  • 跌停时不能卖出
  • 通过 limit 列控制

3. 满仓运行

  • 每次调仓后自动归一化权重
  • 确保总仓位始终为 100%

4. 首日逐步建仓

  • 首日目标权重分摊到各个时间点
  • 确保首日结束时达到满仓

5. 多周期持仓

  • 支持固定持仓周期(1天、5天、10天等)
  • 到期日统一换仓,期间保持持仓不变
  • 停牌或涨跌停时跳过换仓,继续持有
  • 基于交易日索引判断换仓日,即使一天有多个时间点也能正确工作

6. 滚动换仓

  • 使用最近n天信号的加权平均作为target_weight
  • 平滑信号波动,降低换手率
  • 按 (asset, time) 分组计算过去n天的同一时间点信号之和
  • 性能开销仅约10%,完全可接受

🔌 插件化架构

ATRS 采用插件化设计,支持扩展自定义功能。

详见 CONTRIBUTING.md 了解如何贡献代码。

📈 性能对比

⚡ 超高速引擎 vs 主流框架

框架 语言 53万行数据回测时间 相对速度
ATRS (超高速引擎) Rust + Polars 0.4s ⚡⚡⚡ 1x (基准)
VectorBT Python+Numba 2-5s 5-12x 慢
Qlib Python+C++ 5-10s 12-25x 慢
Zipline Python 20-40s 50-100x 慢
Backtrader Python 30-60s 75-150x 慢
Rqalpha Python 15-30s 38-75x 慢

测试环境:MacBook Pro M3, Apple Silicon

超高速引擎优化技术

我们引入了全新的超高速回测引擎,通过以下优化技术实现显著性能提升:

  • ✅ 零 DataFrame 循环操作
  • ✅ 索引代替 String (减少 90% 内存)
  • ✅ 紧凑数据结构 (cache-friendly)
  • ✅ 预分配内存 (零动态 alloc)
  • ✅ 多周期持仓支持(固定持仓模式)
  • ✅ 滚动换仓支持(Polars over窗口函数)
数据规模 原始引擎 超高速引擎 提升倍数
半年数据 (533K行) 1.56s 0.35s 4.5x ⚡⚡⚡
5年数据预估 ~9.4s ~2.1s 4.5x ⚡⚡⚡

结果一致性: 两种引擎收益完全一致 (误差 < 1e-16) ✅

多周期持仓性能:

  • 1日持仓: 0.389s (基准)
  • 5日持仓: 0.356s (提速 1.09x)
  • 10日持仓: 0.352s (提速 1.11x)

滚动换仓性能:

  • 无滚动: 0.371s (基准)
  • 3天滚动: 0.432s (+16.3%)
  • 5天滚动: 0.404s (+8.8%)
  • 10天滚动: 0.397s (+6.9%)
  • 平均开销: 10.7% (完全可接受) ✅

详见 PERFORMANCE_OPTIMIZATION.md

📝 示例

查看 tests/test_engine_with_real_data.py 获取完整示例。

🤝 贡献

欢迎提交 Issue 和 Pull Request!

📄 许可证

MIT License

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distributions

No source distribution files available for this release.See tutorial on generating distribution archives.

Built Distributions

If you're not sure about the file name format, learn more about wheel file names.

atrs-1.0.0-cp310-abi3-manylinux2014_x86_64.manylinux_2_17_x86_64.whl (8.7 MB view details)

Uploaded CPython 3.10+manylinux: glibc 2.17+ x86-64

atrs-1.0.0-cp310-abi3-manylinux2014_aarch64.manylinux_2_17_aarch64.whl (7.9 MB view details)

Uploaded CPython 3.10+manylinux: glibc 2.17+ ARM64

atrs-1.0.0-cp310-abi3-macosx_11_0_arm64.whl (7.3 MB view details)

Uploaded CPython 3.10+macOS 11.0+ ARM64

File details

Details for the file atrs-1.0.0-cp310-abi3-manylinux2014_x86_64.manylinux_2_17_x86_64.whl.

File metadata

  • Download URL: atrs-1.0.0-cp310-abi3-manylinux2014_x86_64.manylinux_2_17_x86_64.whl
  • Upload date:
  • Size: 8.7 MB
  • Tags: CPython 3.10+, manylinux: glibc 2.17+ x86-64
  • Uploaded using Trusted Publishing? No
  • Uploaded via: uv/0.11.5 {"installer":{"name":"uv","version":"0.11.5","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"macOS","version":null,"id":null,"libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":null}

File hashes

Hashes for atrs-1.0.0-cp310-abi3-manylinux2014_x86_64.manylinux_2_17_x86_64.whl
Algorithm Hash digest
SHA256 2bb6e92caae2543330ec72fccb91304125b371ebdd603c7bd654c01970d943c2
MD5 6b79633c93c8afdf34c1e0528869f0b7
BLAKE2b-256 93a138dc11ac470dfbfc031d13cf1c1abc69c9eebdbf29ca5ed0f2aa85b68ebb

See more details on using hashes here.

File details

Details for the file atrs-1.0.0-cp310-abi3-manylinux2014_aarch64.manylinux_2_17_aarch64.whl.

File metadata

  • Download URL: atrs-1.0.0-cp310-abi3-manylinux2014_aarch64.manylinux_2_17_aarch64.whl
  • Upload date:
  • Size: 7.9 MB
  • Tags: CPython 3.10+, manylinux: glibc 2.17+ ARM64
  • Uploaded using Trusted Publishing? No
  • Uploaded via: uv/0.11.5 {"installer":{"name":"uv","version":"0.11.5","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"macOS","version":null,"id":null,"libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":null}

File hashes

Hashes for atrs-1.0.0-cp310-abi3-manylinux2014_aarch64.manylinux_2_17_aarch64.whl
Algorithm Hash digest
SHA256 4ab4955c5c5feaa869cd369057aad4e3b21ce7fde5fa223fbd368f182729f296
MD5 263612c5f45a8cf5941b93781c9fa688
BLAKE2b-256 6266ecc57924f4d6fb98b838624f66f6a36f5aa74fe584d2c6b793e804d9d31e

See more details on using hashes here.

File details

Details for the file atrs-1.0.0-cp310-abi3-macosx_11_0_arm64.whl.

File metadata

  • Download URL: atrs-1.0.0-cp310-abi3-macosx_11_0_arm64.whl
  • Upload date:
  • Size: 7.3 MB
  • Tags: CPython 3.10+, macOS 11.0+ ARM64
  • Uploaded using Trusted Publishing? No
  • Uploaded via: uv/0.11.5 {"installer":{"name":"uv","version":"0.11.5","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"macOS","version":null,"id":null,"libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":null}

File hashes

Hashes for atrs-1.0.0-cp310-abi3-macosx_11_0_arm64.whl
Algorithm Hash digest
SHA256 2a2d70ffbf65ebdabfa05e99e88fde4299c40eb674f2e354476fef68441cad71
MD5 663020a9e09886688937d5d61897ac73
BLAKE2b-256 c558ec6abeb7fee257c0c0aafea7dae0893c4b2b397d670a267645fd4bb48a85

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page