akquant 0.1.2__tar.gz → 0.1.4__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.

Potentially problematic release.


This version of akquant might be problematic. Click here for more details.

Files changed (91) hide show
  1. akquant-0.1.4/.github/workflows/deploy-docs.yml +32 -0
  2. akquant-0.1.4/.github/workflows/release.yml +97 -0
  3. akquant-0.1.4/.gitignore +9 -0
  4. akquant-0.1.4/.pre-commit-config.yaml +21 -0
  5. akquant-0.1.4/.trae/rules/env.md +8 -0
  6. {akquant-0.1.2 → akquant-0.1.4}/Cargo.lock +24 -1
  7. {akquant-0.1.2 → akquant-0.1.4}/Cargo.toml +9 -3
  8. akquant-0.1.4/DESIGN.md +183 -0
  9. {akquant-0.1.2 → akquant-0.1.4}/LICENSE +1 -1
  10. akquant-0.1.4/Makefile +25 -0
  11. akquant-0.1.4/PKG-INFO +219 -0
  12. akquant-0.1.4/README.md +183 -0
  13. akquant-0.1.4/assets/logo.svg +32 -0
  14. akquant-0.1.4/docs/api.md +281 -0
  15. {akquant-0.1.2 → akquant-0.1.4}/docs/architecture.md +27 -5
  16. akquant-0.1.4/docs/examples.md +151 -0
  17. {akquant-0.1.2 → akquant-0.1.4}/docs/index.md +147 -124
  18. {akquant-0.1.2 → akquant-0.1.4}/docs/installation.md +3 -3
  19. akquant-0.1.4/docs/ml_guide.md +201 -0
  20. akquant-0.1.4/docs/quickstart.md +299 -0
  21. akquant-0.1.4/docs/strategy_guide.md +407 -0
  22. {akquant-0.1.2 → akquant-0.1.4}/examples/benchmark_akquant_multi.py +302 -263
  23. {akquant-0.1.2 → akquant-0.1.4}/examples/benchmark_utils.py +83 -64
  24. akquant-0.1.4/examples/kan.py +97 -0
  25. akquant-0.1.4/examples/kan_bt.py +152 -0
  26. akquant-0.1.4/examples/ml_framework_demo.py +125 -0
  27. akquant-0.1.4/examples/ml_walk_forward_demo.py +171 -0
  28. {akquant-0.1.2 → akquant-0.1.4}/mkdocs.yml +4 -2
  29. akquant-0.1.4/pyproject.toml +73 -0
  30. {akquant-0.1.2 → akquant-0.1.4}/python/akquant/__init__.py +98 -81
  31. akquant-0.1.4/python/akquant/akquant.pyi +683 -0
  32. akquant-0.1.4/python/akquant/backtest.py +659 -0
  33. {akquant-0.1.2 → akquant-0.1.4}/python/akquant/config.py +30 -1
  34. akquant-0.1.4/python/akquant/data.py +136 -0
  35. {akquant-0.1.2 → akquant-0.1.4}/python/akquant/indicator.py +81 -56
  36. {akquant-0.1.2 → akquant-0.1.4}/python/akquant/log.py +20 -20
  37. akquant-0.1.4/python/akquant/ml/__init__.py +3 -0
  38. akquant-0.1.4/python/akquant/ml/model.py +234 -0
  39. akquant-0.1.4/python/akquant/py.typed +0 -0
  40. akquant-0.1.4/python/akquant/risk.py +40 -0
  41. {akquant-0.1.2 → akquant-0.1.4}/python/akquant/sizer.py +24 -10
  42. akquant-0.1.4/python/akquant/strategy.py +824 -0
  43. akquant-0.1.4/python/akquant/utils.py +386 -0
  44. akquant-0.1.4/requirements-dev.txt +9 -0
  45. {akquant-0.1.2 → akquant-0.1.4}/src/analysis.rs +31 -16
  46. {akquant-0.1.2 → akquant-0.1.4}/src/context.rs +311 -250
  47. akquant-0.1.4/src/data.rs +614 -0
  48. {akquant-0.1.2 → akquant-0.1.4}/src/engine.rs +989 -766
  49. akquant-0.1.4/src/event.rs +14 -0
  50. akquant-0.1.4/src/execution.rs +667 -0
  51. akquant-0.1.4/src/history.rs +89 -0
  52. akquant-0.1.4/src/indicators.rs +367 -0
  53. {akquant-0.1.2 → akquant-0.1.4}/src/lib.rs +65 -58
  54. {akquant-0.1.2 → akquant-0.1.4}/src/market.rs +8 -7
  55. {akquant-0.1.2 → akquant-0.1.4}/src/model/market_data.rs +11 -4
  56. {akquant-0.1.2 → akquant-0.1.4}/src/model/order.rs +3 -3
  57. {akquant-0.1.2 → akquant-0.1.4}/src/model/types.rs +2 -0
  58. {akquant-0.1.2 → akquant-0.1.4}/src/order.rs +1 -1
  59. {akquant-0.1.2 → akquant-0.1.4}/src/portfolio.rs +253 -253
  60. {akquant-0.1.2 → akquant-0.1.4}/src/risk.rs +388 -270
  61. akquant-0.1.4/tests/test_engine.py +184 -0
  62. {akquant-0.1.2 → akquant-0.1.4}/tests/test_portfolio.py +12 -8
  63. akquant-0.1.4/tests/test_risk.py +136 -0
  64. akquant-0.1.4/tests/verify_pnl.py +137 -0
  65. akquant-0.1.4/tests/verify_stop_orders.py +144 -0
  66. akquant-0.1.4/tests/verify_t_plus_one.py +221 -0
  67. akquant-0.1.2/DESIGN.md +0 -223
  68. akquant-0.1.2/PKG-INFO +0 -149
  69. akquant-0.1.2/README.md +0 -130
  70. akquant-0.1.2/data.csv +0 -728
  71. akquant-0.1.2/docs/api.md +0 -191
  72. akquant-0.1.2/docs/examples.md +0 -68
  73. akquant-0.1.2/docs/quickstart.md +0 -166
  74. akquant-0.1.2/docs/strategy_guide.md +0 -269
  75. akquant-0.1.2/pyproject.toml +0 -30
  76. akquant-0.1.2/python/akquant/akquant.pyi +0 -518
  77. akquant-0.1.2/python/akquant/backtest.py +0 -420
  78. akquant-0.1.2/python/akquant/data.py +0 -122
  79. akquant-0.1.2/python/akquant/strategy.py +0 -516
  80. akquant-0.1.2/python/akquant/utils.py +0 -167
  81. akquant-0.1.2/src/data.rs +0 -291
  82. akquant-0.1.2/src/execution.rs +0 -381
  83. akquant-0.1.2/src/indicators.rs +0 -56
  84. akquant-0.1.2/tests/test_engine.py +0 -34
  85. akquant-0.1.2/tests/test_risk.py +0 -85
  86. {akquant-0.1.2 → akquant-0.1.4}/src/bin/stub_gen.rs +0 -0
  87. {akquant-0.1.2 → akquant-0.1.4}/src/clock.rs +0 -0
  88. {akquant-0.1.2 → akquant-0.1.4}/src/model/instrument.rs +0 -0
  89. {akquant-0.1.2 → akquant-0.1.4}/src/model/mod.rs +0 -0
  90. {akquant-0.1.2 → akquant-0.1.4}/src/model/timer.rs +0 -0
  91. {akquant-0.1.2 → akquant-0.1.4}/src/types.rs +0 -0
@@ -0,0 +1,32 @@
1
+ name: Deploy Docs
2
+
3
+ on:
4
+ push:
5
+ branches:
6
+ - main
7
+ workflow_dispatch:
8
+
9
+ permissions:
10
+ contents: write
11
+
12
+ jobs:
13
+ deploy:
14
+ runs-on: ubuntu-latest
15
+ steps:
16
+ - uses: actions/checkout@v4
17
+ - name: Configure Git Credentials
18
+ run: |
19
+ git config user.name github-actions[bot]
20
+ git config user.email 41898282+github-actions[bot]@users.noreply.github.com
21
+ - uses: actions/setup-python@v5
22
+ with:
23
+ python-version: 3.x
24
+ - run: echo "cache_id=$(date --utc '+%V')" >> $GITHUB_ENV
25
+ - uses: actions/cache@v4
26
+ with:
27
+ key: mkdocs-material-${{ env.cache_id }}
28
+ path: .cache
29
+ restore-keys: |
30
+ mkdocs-material-
31
+ - run: pip install mkdocs-material
32
+ - run: mkdocs gh-deploy --force
@@ -0,0 +1,97 @@
1
+ name: CI
2
+
3
+ on:
4
+ push:
5
+ branches:
6
+ - main
7
+ tags:
8
+ - '*'
9
+ pull_request:
10
+ workflow_dispatch:
11
+
12
+ permissions:
13
+ contents: read
14
+
15
+ jobs:
16
+ linux:
17
+ runs-on: ubuntu-latest
18
+ strategy:
19
+ matrix:
20
+ target: [x86_64]
21
+ steps:
22
+ - uses: actions/checkout@v4
23
+ - uses: actions/setup-python@v5
24
+ with:
25
+ python-version: '3.13'
26
+ - name: Build wheels
27
+ uses: PyO3/maturin-action@v1
28
+ with:
29
+ target: ${{ matrix.target }}
30
+ args: --release --out dist --find-interpreter
31
+ sccache: 'true'
32
+ manylinux: auto
33
+ - name: Upload wheels
34
+ uses: actions/upload-artifact@v4
35
+ with:
36
+ name: wheels-linux-${{ matrix.target }}
37
+ path: dist
38
+
39
+ windows:
40
+ runs-on: windows-latest
41
+ strategy:
42
+ matrix:
43
+ target: [x64]
44
+ steps:
45
+ - uses: actions/checkout@v4
46
+ - uses: actions/setup-python@v5
47
+ with:
48
+ python-version: '3.13'
49
+ architecture: ${{ matrix.target }}
50
+ - name: Build wheels
51
+ uses: PyO3/maturin-action@v1
52
+ with:
53
+ target: ${{ matrix.target }}
54
+ args: --release --out dist --find-interpreter
55
+ sccache: 'true'
56
+ - name: Upload wheels
57
+ uses: actions/upload-artifact@v4
58
+ with:
59
+ name: wheels-windows-${{ matrix.target }}
60
+ path: dist
61
+
62
+ macos:
63
+ runs-on: macos-latest
64
+ strategy:
65
+ matrix:
66
+ target: [aarch64]
67
+ steps:
68
+ - uses: actions/checkout@v4
69
+ - uses: actions/setup-python@v5
70
+ with:
71
+ python-version: '3.13'
72
+ - name: Build wheels
73
+ uses: PyO3/maturin-action@v1
74
+ with:
75
+ target: ${{ matrix.target }}
76
+ args: --release --out dist --find-interpreter
77
+ sccache: 'true'
78
+ - name: Upload wheels
79
+ uses: actions/upload-artifact@v4
80
+ with:
81
+ name: wheels-macos-${{ matrix.target }}
82
+ path: dist
83
+
84
+ sdist:
85
+ runs-on: ubuntu-latest
86
+ steps:
87
+ - uses: actions/checkout@v4
88
+ - name: Build sdist
89
+ uses: PyO3/maturin-action@v1
90
+ with:
91
+ command: sdist
92
+ args: --out dist
93
+ - name: Upload sdist
94
+ uses: actions/upload-artifact@v4
95
+ with:
96
+ name: wheels-sdist
97
+ path: dist
@@ -0,0 +1,9 @@
1
+ target/
2
+ __pycache__/
3
+ *.so
4
+ *.dylib
5
+ *.pyd
6
+ .env
7
+ .venv
8
+ venv/
9
+ .DS_Store
@@ -0,0 +1,21 @@
1
+ repos:
2
+ - repo: https://github.com/pre-commit/pre-commit-hooks
3
+ rev: v6.0.0
4
+ hooks:
5
+ - id: trailing-whitespace
6
+ - id: end-of-file-fixer
7
+ - id: check-yaml
8
+ - id: check-added-large-files
9
+
10
+ - repo: https://github.com/astral-sh/ruff-pre-commit
11
+ rev: v0.14.14
12
+ hooks:
13
+ - id: ruff
14
+ args: [ --fix ]
15
+ - id: ruff-format
16
+
17
+ - repo: https://github.com/pre-commit/mirrors-mypy
18
+ rev: v1.19.1
19
+ hooks:
20
+ - id: mypy
21
+ additional_dependencies: [types-pytz, pandas-stubs, numpy]
@@ -0,0 +1,8 @@
1
+ 1. 必须激活本地的 conda 环境,才行执行相关命令,通过 `conda activate <env_name>` 激活环境。
2
+ 2. 生成的代码如果是 Python,则必须符合 PEP8 规范。
3
+ 3. 生成的代码如果是 Python,必须通过 `ruff check .` 和 `mypy .` 检查。
4
+ 4. 如果有开源项目或者文档,则使用 context7 的 mcp
5
+ 5. 本项目是一个基于 AKQuant 的回测框架,用于回测股票、期货、期权等金融产品。
6
+ 6. 文档或者注释中出现 akquant,则用 AKQuant 替换。
7
+ 7. 本项目主要参考:https://github.com/nautechsystems/nautilus_trader 量化框架
8
+ 8. 本项目用 PyO3 绑定 Rust 代码,实现高性能的回测引擎。绑定的 API 参考:https://github.com/nautechsystems/nautilus_trader,请使用最新的 API 版本
@@ -30,11 +30,13 @@ dependencies = [
30
30
 
31
31
  [[package]]
32
32
  name = "akquant"
33
- version = "0.1.2"
33
+ version = "0.1.4"
34
34
  dependencies = [
35
35
  "anyhow",
36
36
  "chrono",
37
+ "csv",
37
38
  "indicatif",
39
+ "numpy",
38
40
  "polars",
39
41
  "pyo3",
40
42
  "pyo3-stub-gen",
@@ -580,6 +582,27 @@ dependencies = [
580
582
  "typenum",
581
583
  ]
582
584
 
585
+ [[package]]
586
+ name = "csv"
587
+ version = "1.4.0"
588
+ source = "registry+https://github.com/rust-lang/crates.io-index"
589
+ checksum = "52cd9d68cf7efc6ddfaaee42e7288d3a99d613d4b50f76ce9827ae0c6e14f938"
590
+ dependencies = [
591
+ "csv-core",
592
+ "itoa",
593
+ "ryu",
594
+ "serde_core",
595
+ ]
596
+
597
+ [[package]]
598
+ name = "csv-core"
599
+ version = "0.1.13"
600
+ source = "registry+https://github.com/rust-lang/crates.io-index"
601
+ checksum = "704a3c26996a80471189265814dbc2c257598b96b8a7feae2d31ace646bb9782"
602
+ dependencies = [
603
+ "memchr",
604
+ ]
605
+
583
606
  [[package]]
584
607
  name = "debug_unsafe"
585
608
  version = "0.1.3"
@@ -1,6 +1,6 @@
1
1
  [package]
2
2
  name = "akquant"
3
- version = "0.1.2"
3
+ version = "0.1.4"
4
4
  edition = "2024"
5
5
  readme = "README.md"
6
6
 
@@ -11,11 +11,11 @@ name = "akquant"
11
11
  crate-type = ["cdylib", "rlib"]
12
12
 
13
13
  [dependencies]
14
- pyo3 = { version = "0.27.2", features = ["extension-module", "abi3-py39"] }
14
+ pyo3 = { version = "0.27.2", features = ["abi3-py310"] }
15
+ numpy = "0.27"
15
16
  pyo3-stub-gen = "0.6.0"
16
17
  serde = { version = "1.0", features = ["derive"] }
17
18
  polars = { version = "0.51.0", features = ["lazy", "parquet", "ipc", "csv"] }
18
- # arrow = "50.0.0" # 暂时注释掉,避免与 polars 依赖冲突
19
19
  rayon = "1.11"
20
20
  uuid = { version = "1.20.0", features = ["v4", "fast-rng", "macro-diagnostics"] }
21
21
 
@@ -24,3 +24,9 @@ chrono = { version = "0.4", features = ["serde"] }
24
24
  anyhow = "1.0"
25
25
  rust_decimal = { version = "1.40", features = ["serde-with-str", "maths"] }
26
26
  indicatif = "0.18"
27
+ csv = "1.3"
28
+
29
+ [features]
30
+ default = ["extension-module"]
31
+ extension-module = ["pyo3/extension-module"]
32
+ test-utils = ["pyo3/auto-initialize"]
@@ -0,0 +1,183 @@
1
+ # AKQuant 设计与开发指南
2
+
3
+ 本文档详细介绍了 `AKQuant` 的内部设计原理、核心组件架构以及扩展开发指南。旨在帮助开发者深入理解项目结构,以便进行二次开发和功能扩展。
4
+
5
+ ## 1. 项目概览
6
+
7
+ ### 1.1 设计理念
8
+
9
+ `AKQuant` 遵循以下核心设计原则:
10
+
11
+ 1. **核心计算下沉 (Rust Core)**: 所有的计算密集型任务(事件循环、订单撮合、风控检查、数据管理、绩效计算、历史数据维护)都在 Rust 层实现,以确保高性能和内存安全。
12
+ 2. **策略逻辑上浮 (Python API)**: 策略编写、参数配置、数据分析、机器学习模型定义等用户交互层保留在 Python 中,利用其动态特性和丰富的生态系统 (Pandas, Scikit-learn, PyTorch 等)。
13
+ 3. **模块化与解耦 (Modularity)**: 借鉴 `NautilusTrader` 等成熟框架,将数据、执行、策略、风控、机器学习等模块严格分离,通过清晰的接口(Traits)交互。
14
+
15
+ ### 1.2 项目目录结构
16
+
17
+ ```text
18
+ akquant/
19
+ ├── Cargo.toml # Rust 项目依赖与配置
20
+ ├── pyproject.toml # Python 项目构建配置 (Maturin)
21
+ ├── src/ # Rust 核心源码 (底层实现)
22
+ │ ├── lib.rs # PyO3 模块入口,注册 Python 模块
23
+ │ ├── engine.rs # 回测引擎:驱动时间轴与事件循环
24
+ │ ├── execution.rs # 执行层:模拟交易所撮合逻辑
25
+ │ ├── market.rs # 市场层:定义佣金、印花税、T+1 规则
26
+ │ ├── portfolio.rs # 账户层:管理资金、持仓与可用头寸
27
+ │ ├── data.rs # 数据层:管理 Bar/Tick 数据流
28
+ │ ├── analysis.rs # 分析层:计算绩效指标 (Sharpe, Drawdown)
29
+ │ ├── context.rs # 上下文:用于 Python 回调的数据快照
30
+ │ ├── clock.rs # 时钟模块:统一时间管理
31
+ │ ├── event.rs # 事件系统:定义系统内部事件
32
+ │ ├── history.rs # 历史数据:高效的环形缓冲区管理
33
+ │ ├── indicators.rs # 技术指标:Rust 原生指标实现 (如 SMA)
34
+ │ └── model/ # 数据模型:定义基础数据结构
35
+ │ ├── order.rs # 订单 (Order) 与成交 (Trade)
36
+ │ ├── instrument.rs # 标的物信息 (Instrument)
37
+ │ ├── timer.rs # 定时器事件
38
+ │ └── types.rs # 基础枚举 (Side, Type, ExecutionMode)
39
+ ├── python/
40
+ │ └── akquant/ # Python 包源码 (用户接口)
41
+ │ ├── __init__.py # 导出公共 API
42
+ │ ├── strategy.py # Strategy 基类:封装上下文,提供 ML 训练与交易接口
43
+ │ ├── config.py # 配置定义:BacktestConfig, StrategyConfig, RiskConfig
44
+ │ ├── risk.py # 风控配置适配层
45
+ │ ├── data.py # 数据加载与目录服务 (DataCatalog)
46
+ │ ├── sizer.py # Sizer 基类:提供多种仓位管理实现
47
+ │ ├── analyzer.py # TradeAnalyzer:交易记录分析工具
48
+ │ ├── indicator.py # Python 指标接口
49
+ │ ├── log.py # 日志模块
50
+ │ ├── ml/ # 机器学习框架 (New)
51
+ │ │ ├── __init__.py
52
+ │ │ └── model.py # QuantModel, SklearnAdapter, ValidationConfig
53
+ │ └── akquant.pyi # 类型提示文件 (IDE 补全支持)
54
+ └── examples/ # 示例代码
55
+ ├── ml_framework_demo.py # ML 框架基础示例
56
+ └── ml_walk_forward_demo.py # 滚动训练示例
57
+ ```
58
+
59
+ ## 2. 核心组件架构详解
60
+
61
+ ### 2.1 数据模型层 (`src/model/`)
62
+
63
+ 为了保证跨语言交互的性能与类型安全,核心数据结构均在 Rust 中定义并导出。
64
+
65
+ * **`types.rs`**:
66
+ * `ExecutionMode`: `CurrentClose` (当前收盘价成交,即 Cheat-on-Close) vs `NextOpen` (次日开盘价成交,更真实)。
67
+ * `OrderSide`: `Buy` / `Sell`。
68
+ * `OrderType`: `Market` (市价), `Limit` (限价)。
69
+ * `TimeInForce`: `Day` (当日有效), `GTC` (撤前有效), `IOC`/`FOK`。
70
+ * **`instrument.rs`**: `Instrument` 包含 `multiplier` (合约乘数) 和 `tick_size`。
71
+ * **`market_data.rs`**: `Bar` (OHLCV) 和 `Tick` (最新价/量)。
72
+
73
+ ### 2.2 执行层 (`src/execution.rs`)
74
+
75
+ `ExchangeSimulator` 是回测准确性的核心,负责模拟交易所的撮合逻辑。
76
+
77
+ * **撮合机制**:
78
+ * **限价单 (Limit)**: 买入需 `Low <= Price`,卖出需 `High >= Price`。
79
+ * **市价单 (Market)**: 根据 `ExecutionMode` 决定按 `Close` 或 `Open` 成交。
80
+ * **触发机制**: 支持 `trigger_price` (止损/止盈单)。
81
+
82
+ ### 2.3 市场规则层 (`src/market.rs`)
83
+
84
+ 通过 `MarketModel` Trait 实现不同市场的规则隔离。目前内置 `ChinaMarket` (A股市场规则):
85
+
86
+ * **佣金计算**: 支持股票 (印花税、过户费、佣金) 和期货 (按手或按金额)。
87
+ * **交易限制**: 严格的 T+1 (股票) 与 T+0 (期货) 可用持仓管理。
88
+
89
+ ### 2.4 风控层 (`src/risk.rs`)
90
+
91
+ `RiskManager` 独立于执行层,拦截每一笔订单:
92
+
93
+ * **检查规则**: 限制名单、最大单笔数量/金额、最大持仓比例。
94
+ * **配置**: Python 端 `RiskConfig` 自动注入 Rust 引擎。
95
+
96
+ ### 2.5 账户层 (`src/portfolio.rs`)
97
+
98
+ `Portfolio` 结构体维护账户状态:
99
+
100
+ * `cash`: 可用资金。
101
+ * `positions`: 总持仓。
102
+ * `available_positions`: 可卖持仓 (T+1 逻辑的核心)。
103
+ * **权益计算**: 实时 Mark-to-Market 计算。
104
+
105
+ ### 2.6 引擎层 (`src/engine.rs` & `src/history.rs`)
106
+
107
+ `Engine` 是系统的驱动器:
108
+
109
+ * **事件循环**: 消费 `Bar` 或 `Tick` 事件。
110
+ * **历史数据管理**: `Engine` 内部维护 `History` 模块,这是一个高效的环形缓冲区,用于存储最近 N 个 Bar 的数据,供策略通过 `get_history` 快速访问,无需在 Python 端累积数据。
111
+ * **日切处理**: 触发 T+1 解锁、过期订单清理。
112
+
113
+ ### 2.7 分析层 (`src/analysis.rs`)
114
+
115
+ 遵循标准 PnL 计算:`Gross PnL` (毛利), `Net PnL` (净利), `Commission` (佣金)。
116
+
117
+ ### 2.8 Python 抽象层 (`python/akquant/`)
118
+
119
+ * **`Strategy` (`strategy.py`)**:
120
+ * **历史数据访问**:
121
+ * `set_history_depth(depth)`: 开启 Rust 端历史数据记录。
122
+ * `get_history(count)` / `get_history_df(count)`: 获取最近 N 个 Bar 的 OHLCV 数据 (Numpy/DataFrame)。
123
+ * **ML 集成**:
124
+ * `set_rolling_window(train, step)`: 配置滚动训练参数。
125
+ * `on_train_signal(context)`: 周期性触发模型训练。
126
+ * `prepare_features(df)`: 特征工程接口。
127
+ * **`Sizer` (`sizer.py`)**: 仓位管理基类。
128
+ * **`TradeAnalyzer` (`analyzer.py`)**: 交易记录分析。
129
+
130
+ ### 2.9 机器学习框架 (`python/akquant/ml/`)
131
+
132
+ `AKQuant` 提供了一套标准化的 ML 接口,旨在简化“滚动训练-预测”流程。
133
+
134
+ * **`QuantModel` (`model.py`)**:
135
+ * 所有模型的抽象基类。
136
+ * 接口: `fit(X, y)`, `predict(X)`, `save(path)`, `load(path)`。
137
+ * **`set_validation`**: 配置 Walk-forward Validation 参数 (训练窗口、测试窗口、滚动步长)。
138
+ * **`SklearnAdapter`**:
139
+ * 封装 Scikit-learn 风格的模型 (如 RandomForest, LinearRegression),使其适配 `QuantModel` 接口。
140
+ * **工作流**:
141
+ 1. 用户在策略中定义模型 `self.model = SklearnAdapter(RandomForestClassifier())`。
142
+ 2. 设置滚动参数 `self.set_rolling_window(train_window=250, step=20)`。
143
+ 3. 重写 `prepare_features` 将原始 OHLCV 转换为特征 (X) 和 标签 (y)。
144
+ 4. 回测过程中,引擎自动在指定步长触发 `on_train_signal`,策略自动获取历史数据并训练模型。
145
+ 5. 在 `on_bar` 中调用 `self.model.predict` 生成信号。
146
+
147
+ ## 3. 关键工作流详解
148
+
149
+ ### 3.1 回测主循环与执行模式
150
+
151
+ `Engine::run` 的流程依赖 `ExecutionMode`:
152
+
153
+ * **NextOpen**: 推荐模式。Bar Close 生成信号 -> Next Bar Open 成交。
154
+ * **CurrentClose**: 简化模式。Bar Close 生成信号 -> Current Bar Close 成交 (Cheat-on-Close)。
155
+
156
+ ### 3.2 订单全生命周期
157
+
158
+ Signal -> Creation -> Submission -> Risk Check (Rust) -> Matching (Rust) -> Settlement (Rust) -> Reporting。
159
+
160
+ ## 4. 扩展开发指南
161
+
162
+ ### 4.1 如何添加新的订单类型
163
+
164
+ 1. `src/model/types.rs`: 添加枚举。
165
+ 2. `src/model/order.rs`: 更新结构体。
166
+ 3. `src/execution.rs`: 实现撮合逻辑。
167
+ 4. `akquant.pyi`: 更新类型提示。
168
+
169
+ ### 4.2 如何自定义指标
170
+
171
+ 1. **Python 侧 (快速原型)**: 继承 `akquant.Indicator`,在 `on_bar` 中计算。
172
+ 2. **Rust 侧 (高性能)**:
173
+ * 在 `src/indicators.rs` 中实现 `Indicator` Trait。
174
+ * 通过 `#[pyclass]` 导出到 Python。
175
+
176
+ ### 4.3 如何接入新的数据源
177
+
178
+ 将数据转换为 pandas DataFrame,构造 `akquant.Bar` 对象列表,调用 `engine.add_feed` 即可。
179
+
180
+ ## 5. Rust 与 Python 交互注意事项
181
+
182
+ * **GIL**: Rust 仅在回调 Python 时获取 GIL,计算密集型任务释放 GIL (视实现而定,目前主要是单线程模型)。
183
+ * **数据拷贝**: 尽量减少 Python 与 Rust 之间的大规模数据传输。`get_history` 返回的是 Numpy 视图或拷贝,效率远高于 Python list。
@@ -1,6 +1,6 @@
1
1
  MIT License
2
2
 
3
- Copyright (c) 2024 akquant developers
3
+ Copyright (c) 2026 akquant developers
4
4
 
5
5
  Permission is hereby granted, free of charge, to any person obtaining a copy
6
6
  of this software and associated documentation files (the "Software"), to deal
akquant-0.1.4/Makefile ADDED
@@ -0,0 +1,25 @@
1
+ .PHONY: install dev lint format clean test
2
+
3
+ install:
4
+ pip install -e .
5
+
6
+ dev:
7
+ pip install -r requirements-dev.txt
8
+ pre-commit install
9
+
10
+ lint:
11
+ ruff check .
12
+ mypy .
13
+
14
+ format:
15
+ ruff format .
16
+
17
+ test:
18
+ pytest
19
+
20
+ clean:
21
+ rm -rf build/
22
+ rm -rf dist/
23
+ rm -rf *.egg-info
24
+ find . -name "*.pyc" -delete
25
+ find . -name "__pycache__" -delete
akquant-0.1.4/PKG-INFO ADDED
@@ -0,0 +1,219 @@
1
+ Metadata-Version: 2.4
2
+ Name: akquant
3
+ Version: 0.1.4
4
+ Classifier: Programming Language :: Rust
5
+ Classifier: Programming Language :: Python :: Implementation :: CPython
6
+ Classifier: Programming Language :: Python :: Implementation :: PyPy
7
+ Classifier: Programming Language :: Python :: 3.10
8
+ Classifier: Programming Language :: Python :: 3.11
9
+ Classifier: Programming Language :: Python :: 3.12
10
+ Classifier: Programming Language :: Python :: 3.13
11
+ Classifier: Programming Language :: Python :: 3.14
12
+ Classifier: License :: OSI Approved :: MIT License
13
+ Requires-Dist: pandas>=3.0.0
14
+ Requires-Dist: numpy>=2.4.1
15
+ Requires-Dist: pyarrow>=14.0.0
16
+ Requires-Dist: ruff>=0.1.0 ; extra == 'dev'
17
+ Requires-Dist: pre-commit>=3.0.0 ; extra == 'dev'
18
+ Requires-Dist: mypy>=1.0.0 ; extra == 'dev'
19
+ Requires-Dist: pytest>=7.0.0 ; extra == 'dev'
20
+ Requires-Dist: mkdocs>=1.5.0 ; extra == 'dev'
21
+ Requires-Dist: mkdocs-material>=9.5.0 ; extra == 'dev'
22
+ Requires-Dist: matplotlib>=3.0.0 ; extra == 'full'
23
+ Requires-Dist: scikit-learn>=1.0.0 ; extra == 'ml'
24
+ Requires-Dist: torch>=2.0.0 ; extra == 'ml'
25
+ Requires-Dist: matplotlib>=3.0.0 ; extra == 'plot'
26
+ Provides-Extra: dev
27
+ Provides-Extra: full
28
+ Provides-Extra: ml
29
+ Provides-Extra: plot
30
+ License-File: LICENSE
31
+ Summary: High-performance quantitative trading framework based on Rust and Python
32
+ Author: Akquant Developers
33
+ Requires-Python: >=3.10
34
+ Description-Content-Type: text/markdown; charset=UTF-8; variant=GFM
35
+
36
+ <p align="center">
37
+ <img src="assets/logo.svg" alt="AKQuant" width="400">
38
+ </p>
39
+
40
+ # AKQuant
41
+
42
+ **AKQuant** 是一个基于 **Rust** 和 **Python** 构建的高性能量化投研框架。它旨在结合 Rust 的极致性能和 Python 的易用性,为量化交易者提供强大的回测和研究工具。
43
+
44
+ 最新版本参考了 [NautilusTrader](https://github.com/nautechsystems/nautilus_trader) 和 [PyBroker](https://github.com/edtechre/pybroker) 的架构理念,引入了模块化设计、独立的投资组合管理、高级订单类型支持以及便捷的数据加载与缓存机制。
45
+
46
+ 📖 **[设计与开发指南 (DESIGN.md)](DESIGN.md)**: 如果你想深入了解内部架构、学习如何设计此类系统或进行二次开发,请阅读此文档。
47
+
48
+ ## 核心特性
49
+
50
+ * **极致性能**: 核心回测引擎采用 Rust 编写,通过 PyO3 提供 Python 接口。
51
+ * **基准测试**: 在 200k K线数据的 SMA 策略回测中,AKQuant 耗时仅 **1.31s** (吞吐量 ~152k bars/sec),相比 Backtrader (26.55s) 和 PyBroker (23.61s) 快约 **20倍**。
52
+ * **Zero-Copy Access (New)**: 历史数据 (`ctx.history`) 通过 PyO3 Buffer Protocol / Numpy View 直接映射 Rust 内存,实现零拷贝访问,大幅提升 Python 端指标计算性能。
53
+ * **模块化架构**:
54
+ * **Engine**: 事件驱动的核心撮合引擎,采用二进制堆 (BinaryHeap) 管理事件队列。
55
+ * **Clock**: 参考 NautilusTrader 设计的交易时钟,精确管理交易时段 (TradingSession) 和时间流逝。
56
+ * **Portfolio**: 独立的投资组合管理,支持实时权益计算。
57
+ * **MarketModel**: 可插拔的市场模型,内置 A 股 T+1 和期货 T+0 规则。
58
+ * **T+1 严格风控**: 针对股票/基金,严格执行 T+1 可用持仓检查,防止当日买入当日卖出(除非配置为 T+0 市场)。
59
+ * **可用持仓管理**: 自动维护 `available_positions`,并扣除未成交的卖单冻结数量,防止超卖。
60
+ * **事件系统**:
61
+ * **Timer**: 支持 `schedule(timestamp, payload)` 注册定时事件,触发 `on_timer` 回调,实现复杂的盘中定时逻辑。
62
+ * **风控系统 (New)**:
63
+ * **独立拦截层**: 内置 `RiskManager`,在 Rust 引擎层直接拦截违规订单。
64
+ * **可用持仓检查**: 下单前实时检查可用持仓(Available - Pending Sell),防止超卖违规。
65
+ * **灵活配置**: 通过 `RiskConfig` 可配置最大单笔金额、最大持仓比例、黑名单等。
66
+ * **机器学习 (New)**:
67
+ * **Walk-forward Validation**: 内置滚动训练框架,彻底杜绝未来函数。
68
+ * **统一适配器**: 提供 `SklearnAdapter` 和 `PyTorchAdapter`,统一 Scikit-learn 和 PyTorch 接口。
69
+ * **信号解耦**: 提倡 Signal (预测) 与 Action (执行) 分离的设计模式。
70
+ * **数据生态**:
71
+ * **Streaming CSV (New)**: 支持流式加载超大 CSV 文件 (`DataFeed.from_csv`),极大降低内存占用。
72
+ * **Live Trading (New)**: 支持通过 `DataFeed.create_live()` 创建实时数据源,支持 CTP/Gateway 实时数据推送。
73
+ * **Parquet Data Catalog (New)**: 采用 Apache Parquet 格式存储数据,相比 Pickle 读写速度更快,压缩率更高,便于跨语言使用。
74
+ * **Pandas 集成**: 支持直接加载 Pandas DataFrame 数据,兼容各类数据源。
75
+ * **显式订阅**: 策略通过 `subscribe` 方法明确声明所需数据,引擎自动按需加载。
76
+ * **多资产支持**:
77
+ * **股票 (Stock)**: 默认支持 T+1,买入 100 股一手限制,印花税/过户费。
78
+ * **基金 (Fund)**: 支持基金特有费率配置。
79
+ * **期货 (Futures)**: 支持 T+0,保证金交易,合约乘数。
80
+ * **期权 (Option)**: 支持 Call/Put,行权价,按张收费模式。
81
+ * **高级订单 (New)**:
82
+ * **Stop Orders**: Rust 引擎原生支持止损单触发,提供 StopMarket 和 StopLimit。
83
+ * **Target Position**: 内置 `order_target_value` 等辅助函数,自动计算调仓数量。
84
+ * **架构抽象 (New)**:
85
+ * **ExecutionClient**: 抽象执行层,支持 `SimulatedExecutionClient` (内存撮合) 和 `RealtimeExecutionClient` (实盘对接)。
86
+ * **DataClient**: 抽象数据层,支持 `SimulatedDataClient` (内存/回放) 和 `RealtimeDataClient` (实时流)。
87
+ * **无缝切换**: 策略代码无需修改,仅需通过 `engine.use_realtime_execution()` 和 `DataFeed.create_live()` 即可切换至实盘模式。
88
+ * **灵活配置**:
89
+ * **Typed Config (New)**: 引入 `BacktestConfig`, `StrategyConfig`, `RiskConfig` 类型化配置对象,替代散乱的 `**kwargs`,提供更好的 IDE 提示和参数校验。
90
+ * **ExecutionMode**: 支持 `CurrentClose` (信号当根K线收盘成交) 和 `NextOpen` (次日开盘成交) 模式。
91
+ * **丰富的分析工具**:
92
+ * **PerformanceMetrics**:
93
+ * **收益**: Total Return, Annualized Return, Alpha.
94
+ * **风险**: Max Drawdown, Sharpe Ratio, Sortino Ratio, Ulcer Index, UPI (Ulcer Performance Index).
95
+ * **拟合**: Equity R² (线性回归拟合度).
96
+ * **TradeAnalyzer**: 包含胜率、盈亏比、最大连续盈亏等详细交易统计,支持未结盈亏 (Unrealized PnL) 计算。
97
+ * **仿真增强**:
98
+ * **滑点模型 (Slippage)**: 支持 Fixed (固定金额) 和 Percent (百分比) 滑点模型,模拟真实交易成本。
99
+ * **成交量限制 (Volume Limit)**: 支持按 K 线成交量比例限制单笔撮合数量,并实现分批成交 (Partial Fill)。
100
+
101
+ ## 为什么选择 AKQuant?
102
+
103
+ 传统的 Python 回测框架(如 backtrader)在处理大规模数据或复杂逻辑时往往面临性能瓶颈。纯 C++/Rust 框架虽然性能优越,但开发和调试门槛较高。
104
+
105
+ **AKQuant** 试图在两者之间找到平衡点:
106
+
107
+ 1. **性能**: Rust 核心保证了回测速度,特别适合大规模参数优化。
108
+ 2. **易用**: 策略编写完全使用 Python,提供类似 PyBroker 的简洁 API。
109
+ 3. **专业**: 严格遵守中国市场交易规则(T+1、印花税、最低佣金等)。
110
+
111
+ ## 前置要求
112
+
113
+ - **Rust**: [安装 Rust](https://www.rust-lang.org/tools/install)
114
+ - **Python**: 3.10+
115
+ - **Maturin**: `pip install maturin`
116
+
117
+ ## 安装说明
118
+
119
+ ### 开发模式(推荐)
120
+
121
+ 如果你正在开发该项目并希望更改即时生效:
122
+
123
+ ```bash
124
+ maturin develop
125
+ ```
126
+
127
+ ## 快速开始
128
+
129
+ ### 1. 使用 helper 快速回测 (推荐)
130
+
131
+ `AKQuant` 提供了一个类似 Zipline 的便捷入口 `run_backtest`,可以快速运行策略。
132
+
133
+ ```python
134
+ import akquant
135
+ from akquant.backtest import run_backtest
136
+ from akquant import Strategy
137
+ from akquant.config import BacktestConfig
138
+
139
+ # 1. 定义策略
140
+ class MyStrategy(Strategy):
141
+ def on_start(self):
142
+ # 显式订阅数据
143
+ self.subscribe("600000")
144
+
145
+ def on_bar(self, bar):
146
+ # 简单的双均线逻辑 (示例)
147
+ # 实际回测推荐使用 IndicatorSet 进行向量化计算
148
+ if self.ctx.position.size == 0:
149
+ self.buy(symbol=bar.symbol, quantity=100)
150
+ elif bar.close > self.ctx.position.avg_price * 1.1:
151
+ self.sell(symbol=bar.symbol, quantity=100)
152
+
153
+ # 2. 配置回测
154
+ config = BacktestConfig(
155
+ start_date="20230101",
156
+ end_date="20241231",
157
+ cash=500_000.0,
158
+ commission=0.0003
159
+ )
160
+
161
+ # 3. 运行回测
162
+ # 自动加载数据、设置资金、费率等
163
+ result = run_backtest(
164
+ strategy=MyStrategy, # 传递类
165
+ config=config # 传递配置对象
166
+ )
167
+
168
+ # 4. 查看结果
169
+ print(f"Total Return: {result.metrics.total_return_pct:.2f}%")
170
+ print(f"Sharpe Ratio: {result.metrics.sharpe_ratio:.2f}")
171
+ print(f"Max Drawdown: {result.metrics.max_drawdown_pct:.2f}%")
172
+
173
+ # 4. 获取详细数据 (DataFrame)
174
+ # 绩效指标表
175
+ print(result.metrics_df)
176
+ # 交易记录表
177
+ print(result.trades_df)
178
+ # 每日持仓表
179
+ print(result.daily_positions_df)
180
+ ```
181
+
182
+ ### 2. 函数式 API (Zipline 风格)
183
+
184
+ 如果你习惯 Zipline 或 Backtrader 的函数式写法,也可以直接使用:
185
+
186
+ ```python
187
+ from akquant.backtest import run_backtest
188
+
189
+ def initialize(ctx):
190
+ ctx.stop_loss_pct = 0.05
191
+
192
+ def on_bar(ctx, bar):
193
+ if ctx.position.size == 0:
194
+ ctx.buy(symbol=bar.symbol, quantity=100)
195
+ elif bar.close < ctx.position.avg_price * (1 - ctx.stop_loss_pct):
196
+ ctx.sell(symbol=bar.symbol, quantity=100)
197
+
198
+ run_backtest(
199
+ strategy=on_bar,
200
+ initialize=initialize,
201
+ symbol="600000",
202
+ start_date="20230101",
203
+ end_date="20231231"
204
+ )
205
+ ```
206
+
207
+ 更多示例请参考 `examples/` 目录。
208
+
209
+ ## 结果分析
210
+ `run_backtest` 返回的 `BacktestResult` 对象提供了丰富的数据用于后续分析:
211
+
212
+ * **`result.metrics`**: 包含 Total Return, Sharpe, Max Drawdown 等核心指标的对象。
213
+ * **`result.metrics_df`**: 包含上述指标的 Pandas DataFrame (单行)。
214
+ * **`result.trades_df`**: 包含所有已平仓交易的详细记录 (Entry/Exit Time/Price, PnL, Commission 等)。
215
+ * **`result.daily_positions_df`**: 包含每日持仓快照的 DataFrame。
216
+ * **`result.equity_curve`**: 权益曲线数据列表 `[(timestamp, equity), ...]`。
217
+
218
+ ## 快速链接
219
+