Skip to main content

High-performance quantitative trading framework based on Rust and Python

Project description

AKQuant

PyPI Version Python Versions License AKShare Downloads

AKQuant 是一款专为量化投研设计的下一代高性能混合框架。核心引擎采用 Rust 编写以确保极致的执行效率,同时提供优雅的 Python 接口以维持灵活的策略开发体验。

🚀 核心亮点:

  • 极致性能:得益于 Rust 的零开销抽象与 Zero-Copy 数据架构,回测速度较传统纯 Python 框架(如 Backtrader)提升 X倍+
  • 原生 ML 支持:内置 Walk-forward Validation(滚动训练)框架,无缝集成 PyTorch/Scikit-learn,让 AI 策略开发从实验到回测一气呵成。
  • 因子表达式引擎:内置 Polars 驱动的高性能因子计算引擎,支持 Rank(Ts_Mean(Close, 5)) 等 Alpha101 风格公式,自动处理并行计算与数据对齐。
  • 参数优化:内置多进程网格搜索(Grid Search)框架,支持策略参数的高效并行优化。
  • 专业级风控:内置完善的订单流管理与即时风控模块,支持多资产组合回测。

👉 阅读完整文档 | English Documentation

快速导航

安装说明

AKQuant 已发布至 PyPI,无需安装 Rust 环境即可直接使用。

pip install akquant

快速开始

以下是一个简单的策略示例:

import akquant as aq
import akshare as ak
from akquant import Strategy

# 1. 准备数据
# 使用 akshare 获取 A 股历史数据 (需安装: pip install akshare)
df = ak.stock_zh_a_daily(symbol="sh600000", start_date="20250212", end_date="20260212")


class MyStrategy(Strategy):
    def on_bar(self, bar):
        # 简单策略示例:
        # 当收盘价 > 开盘价 (阳线) -> 买入
        # 当收盘价 < 开盘价 (阴线) -> 卖出

        # 获取当前持仓
        current_pos = self.get_position(bar.symbol)

        if current_pos == 0 and bar.close > bar.open:
            self.buy(symbol=bar.symbol, quantity=100)
            print(f"[{bar.timestamp_str}] Buy 100 at {bar.close:.2f}")

        elif current_pos > 0 and bar.close < bar.open:
            self.close_position(symbol=bar.symbol)
            print(f"[{bar.timestamp_str}] Sell 100 at {bar.close:.2f}")


# 运行回测
result = aq.run_backtest(
    data=df,
    strategy=MyStrategy,
    initial_cash=100000.0,
    symbol="sh600000"
)

# 打印回测结果
print("\n=== Backtest Result ===")
print(result)

运行结果示例:

=== Backtest Result ===
BacktestResult:
                                            Value
start_time              2025-02-12 00:00:00+08:00
end_time                2026-02-12 00:00:00+08:00
duration                        365 days, 0:00:00
total_bars                                    249
trade_count                                  62.0
initial_market_value                     100000.0
end_market_value                          99804.0
total_pnl                                  -196.0
unrealized_pnl                                0.0
total_return_pct                           -0.196
annualized_return                        -0.00196
volatility                               0.002402
total_profit                                548.0
total_loss                                 -744.0
total_commission                              0.0
max_drawdown                                345.0
max_drawdown_pct                         0.344487
win_rate                                22.580645
loss_rate                               77.419355
winning_trades                               14.0
losing_trades                                48.0
avg_pnl                                  -3.16129
avg_return_pct                          -0.199577
avg_trade_bars                           1.967742
avg_profit                              39.142857
avg_profit_pct                           3.371156
avg_winning_trade_bars                        4.5
avg_loss                                    -15.5
avg_loss_pct                            -1.241041
avg_losing_trade_bars                    1.229167
largest_win                                 120.0
largest_win_pct                         10.178117
largest_win_bars                              7.0
largest_loss                                -70.0
largest_loss_pct                        -5.380477
largest_loss_bars                             1.0
max_wins                                      2.0
max_losses                                    9.0
sharpe_ratio                            -0.816142
sortino_ratio                           -1.066016
profit_factor                            0.736559
ulcer_index                              0.001761
upi                                     -1.113153
equity_r2                                0.399577
std_error                                68.64863
calmar_ratio                            -0.568962
exposure_time_pct                       48.995984
var_95                                   -0.00023
var_99                                   -0.00062
cvar_95                                 -0.000405
cvar_99                                  -0.00069
sqn                                     -0.743693
kelly_criterion                         -0.080763
max_leverage                              0.01458
min_margin_level                        68.587671

复杂订单助手 (OCO / Bracket)

AKQuant 提供了两组复杂订单助手,减少手写订单联动逻辑:

  • create_oco_order_group(first_order_id, second_order_id, group_id=None):将两个订单绑定为 OCO,任一成交后自动撤销另一单。
  • place_bracket_order(symbol, quantity, entry_price=None, stop_trigger_price=None, take_profit_price=None, ...):一次性提交 Bracket 结构;进场成交后自动挂出止损/止盈,并在双退出单场景下自动绑定 OCO。
from akquant import OrderStatus, Strategy

class BracketHelperStrategy(Strategy):
    def __init__(self):
        self.entry_order_id = ""

    def on_bar(self, bar):
        if self.get_position(bar.symbol) > 0 or self.entry_order_id:
            return

        self.entry_order_id = self.place_bracket_order(
            symbol=bar.symbol,
            quantity=100,
            stop_trigger_price=bar.close * 0.98,
            take_profit_price=bar.close * 1.04,
            entry_tag="entry",
            stop_tag="stop",
            take_profit_tag="take",
        )

    def on_order(self, order):
        if order.id == self.entry_order_id and order.status in (
            OrderStatus.Cancelled,
            OrderStatus.Rejected,
        ):
            self.entry_order_id = ""

可直接运行完整示例:

python examples/06_complex_orders.py

流式回测 (Streaming)

如果你希望在回测执行过程中实时消费事件,可直接使用 run_backtest 并传入 on_event

def on_event(event):
    if event["event_type"] == "finished":
        payload = event["payload"]
        print("status:", payload.get("status"))
        print("callback_error_count:", payload.get("callback_error_count"))

result = aq.run_backtest(
    data=df,
    strategy=MyStrategy,
    symbol="sh600000",
    on_event=on_event,
    show_progress=False,
    stream_progress_interval=10,
    stream_equity_interval=10,
    stream_batch_size=32,
    stream_max_buffer=256,
    stream_error_mode="continue",
)

run_backtest 也支持可选 on_event。如果不传,框架会使用内部 no-op 回调, 保持与传统阻塞调用一致的返回语义;如果传入 on_event,即可在保持 run_backtest(...) 调用方式不变的同时接入实时事件。

关键参数:

  • stream_progress_interval / stream_equity_interval: 进度与权益事件采样间隔
  • stream_batch_size / stream_max_buffer: 缓冲与批量刷新控制
  • stream_error_mode: 回调异常策略,支持 "continue""fail_fast"

阶段 5 迁移 FAQ:

  • run_backtest 是否改名?不改名,调用方式保持不变。
  • run_backtest 是否还能不传 on_event?可以,不传时仍返回同样的结果对象语义。
  • 如何回滚?阶段 5 后不再支持 _engine_mode 参数级回滚,建议使用版本级回滚。
  • 文档入口在哪里?可从 中文文档首页的阶段 5 迁移入口 快速跳转到 quickstart FAQ 和 API 兼容说明。
  • 英文入口在哪里?可从 English docs Quick Links 跳转到 Phase-5 Migration FAQ 与 Compatibility Notes。

可视化 (Visualization)

AKQuant 内置了基于 Plotly 的强大可视化模块,仅需一行代码即可生成包含权益曲线、回撤分析、月度热力图等详细指标的交互式 HTML 报告。

# 生成交互式 HTML 报告,自动在浏览器中打开
result.report(
    show=True,
    compact_currency=True,  # 金额列按 K/M/B 紧凑显示(默认 True)
)

# 如果你希望金额列保留原始数值精度(不缩写),可关闭:
result.report(
    show=False,
    filename="report_raw_amount.html",
    compact_currency=False,
)

你也可以直接复用结构化分析结果做二次研究:

exposure = result.exposure_df()             # 暴露分解(净暴露/总暴露/杠杆)
attr_by_symbol = result.attribution_df(by="symbol")
attr_by_tag = result.attribution_df(by="tag")
capacity = result.capacity_df()             # 容量代理(成交率/换手等)
orders_by_strategy = result.orders_by_strategy()         # 按策略归属聚合订单
executions_by_strategy = result.executions_by_strategy() # 按策略归属聚合成交

Strategy Dashboard
👉 点击查看交互式报表示例 (Interactive Demo)

文档索引

🧪 测试与质量保证

AKQuant 采用严格的测试流程以确保回测引擎的准确性:

  • 单元测试: 覆盖核心 Rust 组件与 Python 接口。
  • 黄金测试 (Golden Tests): 使用合成数据验证关键业务逻辑(如 T+1、涨跌停、保证金、期权希腊值),并与锁定的基线结果进行比对,防止算法回退。

运行测试:

# 1. 安装开发依赖
pip install -e ".[dev]"

# 2. 运行所有测试
pytest

# 3. 运行 Rust 核心测试(自动处理 macOS + conda 动态库路径)
./scripts/cargo-test.sh -q

# 4. 仅运行黄金测试
pytest tests/golden/test_golden.py

贡献指南

Citation

Please use this bibtex if you want to cite this repository in your publications:

@misc{akquant,
    author = {Albert King and Yaojie Zhang and Chao Liang},
    title = {AKQuant},
    year = {2026},
    publisher = {GitHub},
    journal = {GitHub repository},
    howpublished = {\url{https://github.com/akfamily/akquant}},
}

License

MIT License

Project details


Release history Release notifications | RSS feed

Download files

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

Source Distribution

akquant-0.1.72.tar.gz (1.2 MB view details)

Uploaded Source

Built Distributions

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

akquant-0.1.72-pp311-pypy311_pp73-manylinux_2_17_x86_64.manylinux2014_x86_64.whl (6.0 MB view details)

Uploaded PyPymanylinux: glibc 2.17+ x86-64

akquant-0.1.72-cp310-abi3-win_amd64.whl (5.9 MB view details)

Uploaded CPython 3.10+Windows x86-64

akquant-0.1.72-cp310-abi3-musllinux_1_2_aarch64.whl (5.8 MB view details)

Uploaded CPython 3.10+musllinux: musl 1.2+ ARM64

akquant-0.1.72-cp310-abi3-manylinux_2_17_x86_64.manylinux2014_x86_64.whl (6.0 MB view details)

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

akquant-0.1.72-cp310-abi3-manylinux_2_17_aarch64.manylinux2014_aarch64.whl (5.6 MB view details)

Uploaded CPython 3.10+manylinux: glibc 2.17+ ARM64

akquant-0.1.72-cp310-abi3-macosx_11_0_arm64.whl (5.3 MB view details)

Uploaded CPython 3.10+macOS 11.0+ ARM64

File details

Details for the file akquant-0.1.72.tar.gz.

File metadata

  • Download URL: akquant-0.1.72.tar.gz
  • Upload date:
  • Size: 1.2 MB
  • Tags: Source
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.1.0 CPython/3.13.7

File hashes

Hashes for akquant-0.1.72.tar.gz
Algorithm Hash digest
SHA256 cb9de2689c75cf2582aca6c142a375ef7db337216f8da0e69c73dd6d643bd255
MD5 8f6420f510a5901fbc08afbb091b3602
BLAKE2b-256 4b005ebab515b22f93cf865868c071fbe53b0f769354c602955a6464900b0b69

See more details on using hashes here.

Provenance

The following attestation bundles were made for akquant-0.1.72.tar.gz:

Publisher: release.yml on akfamily/akquant

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

File details

Details for the file akquant-0.1.72-pp311-pypy311_pp73-manylinux_2_17_x86_64.manylinux2014_x86_64.whl.

File metadata

File hashes

Hashes for akquant-0.1.72-pp311-pypy311_pp73-manylinux_2_17_x86_64.manylinux2014_x86_64.whl
Algorithm Hash digest
SHA256 e0abcaa659cceda6e04552dca34ebdc07bde64ff4b6bfc049f7003691a1467e3
MD5 30aa23016159f9377b9530052fe4b6a5
BLAKE2b-256 5e908a24482398956e3015e07b7033e8907e31a250ec318de55fee3af42ca1fb

See more details on using hashes here.

Provenance

The following attestation bundles were made for akquant-0.1.72-pp311-pypy311_pp73-manylinux_2_17_x86_64.manylinux2014_x86_64.whl:

Publisher: release.yml on akfamily/akquant

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

File details

Details for the file akquant-0.1.72-cp310-abi3-win_amd64.whl.

File metadata

  • Download URL: akquant-0.1.72-cp310-abi3-win_amd64.whl
  • Upload date:
  • Size: 5.9 MB
  • Tags: CPython 3.10+, Windows x86-64
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.1.0 CPython/3.13.7

File hashes

Hashes for akquant-0.1.72-cp310-abi3-win_amd64.whl
Algorithm Hash digest
SHA256 4269104fb43384745f988015d0ac6c25a28411b9ebf4926351f723b5a1bda0ad
MD5 f535f0288ce5dce9e64659b2358f50e6
BLAKE2b-256 6af678a28f8a82abe56f6e3ac023c220a3333d578fd2011721413ad46258ffc5

See more details on using hashes here.

Provenance

The following attestation bundles were made for akquant-0.1.72-cp310-abi3-win_amd64.whl:

Publisher: release.yml on akfamily/akquant

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

File details

Details for the file akquant-0.1.72-cp310-abi3-musllinux_1_2_aarch64.whl.

File metadata

File hashes

Hashes for akquant-0.1.72-cp310-abi3-musllinux_1_2_aarch64.whl
Algorithm Hash digest
SHA256 d50fa687d22fdda4ce4401334720d672c124705ea3bf94a602e217d8606cddfe
MD5 bab99aed324f8310990ce87ed31c494c
BLAKE2b-256 4b01c13c7a2fb2226f161beff2df010a4ee39ae5ea5f235f792b9f43c4c59bc6

See more details on using hashes here.

Provenance

The following attestation bundles were made for akquant-0.1.72-cp310-abi3-musllinux_1_2_aarch64.whl:

Publisher: release.yml on akfamily/akquant

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

File details

Details for the file akquant-0.1.72-cp310-abi3-manylinux_2_17_x86_64.manylinux2014_x86_64.whl.

File metadata

File hashes

Hashes for akquant-0.1.72-cp310-abi3-manylinux_2_17_x86_64.manylinux2014_x86_64.whl
Algorithm Hash digest
SHA256 72e1da1e052960688c4372a832690df8517e84ffc94a9aa593360ceef084a57e
MD5 2d85edf8ead542ab38a28e5d3c315361
BLAKE2b-256 656397e7922924bc8139361f1547f8f724c3b09af0d196b098821d8913ef3351

See more details on using hashes here.

Provenance

The following attestation bundles were made for akquant-0.1.72-cp310-abi3-manylinux_2_17_x86_64.manylinux2014_x86_64.whl:

Publisher: release.yml on akfamily/akquant

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

File details

Details for the file akquant-0.1.72-cp310-abi3-manylinux_2_17_aarch64.manylinux2014_aarch64.whl.

File metadata

File hashes

Hashes for akquant-0.1.72-cp310-abi3-manylinux_2_17_aarch64.manylinux2014_aarch64.whl
Algorithm Hash digest
SHA256 b1b31d812e131ad0aa36d9a0cb9cce0f87f15aae08efa1697c2fc5c545dd232a
MD5 64eba1f57ccf21066d595bb9ea04a8c2
BLAKE2b-256 f6fd9e4c75484e4452784a8de09366233d01608454bb0b5d12d20c562f1aa6e6

See more details on using hashes here.

Provenance

The following attestation bundles were made for akquant-0.1.72-cp310-abi3-manylinux_2_17_aarch64.manylinux2014_aarch64.whl:

Publisher: release.yml on akfamily/akquant

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

File details

Details for the file akquant-0.1.72-cp310-abi3-macosx_11_0_arm64.whl.

File metadata

File hashes

Hashes for akquant-0.1.72-cp310-abi3-macosx_11_0_arm64.whl
Algorithm Hash digest
SHA256 969ed9e0560aa8136c7bd0862a38b40b338a9d01594c3f1f372ec2887d597a26
MD5 12a23f07ecc3897e542babc1735201b4
BLAKE2b-256 be1eccece914c18b74411ce90583e01f9a769dc7ab7f57148c9d0737cc50adfb

See more details on using hashes here.

Provenance

The following attestation bundles were made for akquant-0.1.72-cp310-abi3-macosx_11_0_arm64.whl:

Publisher: release.yml on akfamily/akquant

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

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