AI 原生量化交易框架 — Rust 实现高性能内核,Python 提供 RL 训练接口,一套代码贯穿回测、训练、优化、验证、生产的完整链路。
Project description
An event-driven trading engine for quantitative trading and reinforcement learning. Designed from the ground up with AI at its core, rather than "bolting on" ML modules to a traditional quant system.
Rust core for high-performance, Python interface for RL training, one codebase for the complete pipeline from backtesting to production.
Online Documentation · Design Docs · ADR · Changelog · Examples
Design Philosophy
- AI First: RL environment and backtesting engine share the same data structures, zero difference between training and production
- Rust Core: Nanosecond timestamps, deterministic matching, zero-cost abstractions, backtesting throughput > 1M events/sec
- Python Front: Gymnasium-compatible interface via PyO3, directly compatible with Stable-Baselines3 / Ray RLlib
- Full Pipeline: Backtest → Train → HPO → Walk-forward → Track → Register → Deploy, all built-in
- 100% Open Source: Apache-2.0 license, no enterprise edition, no feature restrictions
Features
Backtesting Engine
- Multi-Level Matching: L1 basic matching → L2 order book → L3 multi-asset crossing
- Impact Models: Almgren-Chriss permanent/temporary impact + probabilistic latency + tiered fees
- Deterministic Replay:
SimulatedClock+ crossbeam-channel bounded 100K event queue - Columnar Storage: Arrow/Parquet, 1M tick read/write < 15ms
RL Environment
- Gymnasium API: Discrete / continuous / hybrid action spaces
- Reward Functions: PnL / Sharpe / Sortino, based on unified
ReturnHistory - Vectorized:
VecEnvsupports multi-environment parallel rollout - PyO3 Bindings: maturin packaging, 6 submodules
Training Pipeline
- Hyperparameter Optimization: Optuna integration + NSGA-II multi-objective + Pareto frontier + early stopping
- Rolling Forward Validation: Purged + Embargo + leakage detection + Deflated Sharpe Ratio
- Experiment Tracking: MLflow / WandB / Local / Memory four backends
- Model Registry: SemVer + stage lifecycle + auto-archiving + rollback
- Distributed Training: Ray Actor + Parameter Server + Checkpoint fault tolerance
AI Enhancement
- LLM Agents: ReAct + Tool Calling, built-in
PlaceOrder/QueryPortfoliotrading tools with SafetyMode risk control - Agent Swarm: Multi-Agent collaboration with Actor model, voting consensus, dynamic scaling
- MarketAgent: Market analysis and signal generation
- RiskAgent: Pre-trade risk assessment and compliance checks
- ExecutionAgent: Order execution with TWAP/VWAP strategies
- AuditAgent: Decision logging and compliance reporting
- SwarmOrchestrator: Agent lifecycle management, message routing, auto-scaling
- Model Ensemble: Voting / Stacking / dynamic weighting, online Sharpe ratio monitoring for auto-adjustment
- Explainability: SHAP feature attribution + counterfactual explanations +
Explainertrait built-in - Compliance Audit: Immutable trade logs + decision report archiving
Production Deployment
- Exchange Integration: Binance / OKX REST + WebSocket (auto-reconnect)
- Risk Engine: Pre-trade checks (12ns), real-time circuit breaker, position limits
- Inference Engine: ONNX / Candle dual backends + CPU/GPU affinity pinning + batch inference
DeFi Integration (Experimental)
Note: DeFi features are experimental and under active development. APIs may change.
- EVM Chain Support: Ethereum / Arbitrum / Optimism / Polygon
- DEX Integration: Uniswap V3 direct integration with optimal routing
- MEV Protection: MEV-Share for sandwich attack prevention
- Smart Contract Risk: Hybrid risk checks (off-chain fast + on-chain authoritative)
- Cross-Chain Bridge: LayerZero integration for multi-chain asset transfers
Quick Start
Install (Recommended)
# Basic install (core + data processing)
pip install axon_quant
# With ONNX inference support (onnxruntime, auto-loaded)
pip install axon_quant[onnx]
# With RL training dependencies (gymnasium, stable-baselines3, torch)
pip install axon_quant[rl]
# Full install
pip install axon_quant[onnx,rl]
Verify installation:
python -c "import axon_quant; print(axon_quant.__version__)"
Build from Source
For developers who want to modify the Rust core:
git clone https://github.com/pengwow/axon_quant.git
cd axon_quant
# Build
cargo build
# Test (2300+ test cases)
cargo test --workspace
# Static analysis
cargo clippy --workspace -- -D warnings
# Build and install Python wheel
maturin build --release
pip install target/wheels/axon_quant-*.whl
Training Examples
# Random baseline
python examples/01_random_agent.py
# PPO training
python examples/02_train_ppo.py --timesteps 50000
# HPO optimization
python examples/03_hpo/hpo_single_objective.py
# Rolling forward validation
python examples/08_walk_forward/walk_forward_basic.py
📖 Detailed RL training documentation: RL Training Guide
Architecture
AXON uses Cargo Workspace to manage 21 crates, organized in 9 layers:
┌─────────────────────────────────────────────────────────────┐
│ Layer 9: Application Entry │
│ ├─ axon-cli CLI tool │
│ └─ axon-python PyO3 unified entry (axon_quant package) │
├─────────────────────────────────────────────────────────────┤
│ Layer 8: AI Agents │
│ ├─ axon-llm ReAct agent + Tool Calling │
│ └─ axon-explain SHAP / Counterfactual / Decision Report │
├─────────────────────────────────────────────────────────────┤
│ Layer 7: Model Services │
│ ├─ axon-inference ONNX / Candle / tch inference engine │
│ └─ axon-ensemble Model ensemble (Voting / Stacking) │
├─────────────────────────────────────────────────────────────┤
│ Layer 6: Training Pipeline │
│ ├─ axon-rl Gymnasium env + VecEnv + Reward functions│
│ ├─ axon-hpo Optuna hyperparameter optimization │
│ ├─ axon-distributed Ray Actor distributed training │
│ └─ axon-walk-forward Rolling forward validation │
├─────────────────────────────────────────────────────────────┤
│ Layer 5: Experiment Governance │
│ ├─ axon-tracker MLflow / WandB / Local / Memory tracking │
│ └─ axon-registry Model registry (SemVer + Lifecycle) │
├─────────────────────────────────────────────────────────────┤
│ Layer 4: Production Execution │
│ ├─ axon-exchange Binance / OKX adapters (REST + WebSocket)│
│ ├─ axon-risk Risk engine (Position / Drawdown / VaR) │
│ ├─ axon-oms Order management system │
│ └─ axon-monitor Monitoring + Health checks │
├─────────────────────────────────────────────────────────────┤
│ Layer 3: Backtesting Engine │
│ ├─ axon-backtest L1/L2/L3 matching + Almgren-Chriss impact│
│ └─ axon-compliance Compliance audit + Reports │
├─────────────────────────────────────────────────────────────┤
│ Layer 2: Data Services │
│ └─ axon-data Arrow columnar storage + CSV/Parquet │
├─────────────────────────────────────────────────────────────┤
│ Layer 1: Core Types │
│ └─ axon-core Timestamp / Price / Quantity / Order │
│ / Event / Queue / Portfolio / SIMD │
└─────────────────────────────────────────────────────────────┘
Threading Model
- Core Matching Engine: Single-threaded, avoids lock contention, ensures determinism
- I/O Thread Pool: tokio runtime, handles WebSocket / REST / file I/O
- Compute Thread Pool: rayon, factor calculation / data transformation / parallel backtesting
- Event Queue: crossbeam-channel bounded 100K, zero-lock design
Data Pipeline
All AXON modules share the same Arrow RecordBatch, zero-copy passthrough, no format conversion gaps:
Data Sources (CSV/Parquet/WebSocket/Mock/Exchange API)
│
▼
axon-data (schema validation / time alignment / dedup / mmap cache)
│
▼
Arrow RecordBatch (memory) ──→ TradingEnv / FeaturePipeline / BacktestEngine
│
▼
InferenceEngine (ONNX/Candle batch inference < 1ms)
│
▼
ExchangeAdapter (Binance/OKX live trading)
Layer Descriptions
-
axon-core: Foundation of the entire system. Provides
Timestamp(nanosecond precision),Price/Quantity(based onrust_decimal),Order,Event,Queue,Portfoliocore types, and SIMD-accelerated normalization and order book operations. -
axon-data: Unified data access layer. Based on Apache Arrow's
RecordBatchcolumnar storage, supports CSV / Parquet / Mock data sources, built-inFeaturePipeline(Z-Score normalization + sliding window). -
axon-backtest: Event-driven backtesting engine. Supports L1 (price priority), L2 (order book), L3 (dark pool / auction) three-level matching, integrated Almgren-Chriss market impact model and probabilistic latency simulation.
-
axon-exchange: Production-grade exchange adapter. Unified
ExchangeAdaptertrait, implemented Binance / OKX REST + WebSocket integration, built-in exponential backoff reconnection and token bucket rate limiting. -
axon-rl: Reinforcement learning environment.
TradingEnvimplements Gymnasium standard interface (reset/step/render), supports continuous actions (target position ratio[-1, 1]), discrete actions (position bins), multi-objective rewards and vectorized parallel environmentVecEnv. -
axon-inference: Model inference engine. Supports ONNX Runtime, Candle (pure Rust), tch-rs (PyTorch C++) three backends, with async batch inference pipeline, CPU/GPU affinity binding and model hot update capability.
-
axon-llm: Large language model agent. Based on ReAct reasoning loop, built-in "market analysis", "query portfolio", "place order" three tools, supports OpenAI-compatible backends and streaming responses.
-
axon-explain: Explainability engine. Integrates SHAP feature attribution, counterfactual explanations ("What if I hadn't bought, how would returns change") and structured decision reports, meeting compliance and strategy iteration needs.
-
axon-ensemble: Model ensemble. Provides HardVote, SoftVote, WeightedVote, Stacking, DynamicWeighted five strategies, supports online performance monitoring and automatic weight adjustment.
Repository Structure
axon_quant/
├── crates/ # 21 Rust crates
│ ├── axon-core/ # Core types (time/types/market/order/event/queue/portfolio)
│ ├── axon-backtest/ # Backtesting engine (L1/L2/L3 matching + impact models)
│ ├── axon-rl/ # RL environment (Gymnasium + VecEnv)
│ ├── axon-hpo/ # Hyperparameter optimization (Optuna + NSGA-II)
│ ├── axon-walk-forward/ # Rolling forward validation (Purged + Embargo)
│ ├── axon-distributed/ # Distributed training (Ray)
│ ├── axon-tracker/ # Experiment tracking (MLflow/WandB/Local/Memory)
│ ├── axon-registry/ # Model registry (SemVer + lifecycle)
│ ├── axon-exchange/ # Exchange adapters (Binance/OKX)
│ ├── axon-inference/ # Inference engine (ONNX/Candle)
│ ├── axon-risk/ # Risk engine
│ ├── axon-oms/ # Order management system
│ ├── axon-monitor/ # Monitoring alerts
│ ├── axon-llm/ # LLM agent
│ ├── axon-python/ # Python bindings entry
│ └── axon-cli/ # CLI tool
├── python/ # Python package (axon_quant)
├── examples/ # Training example scripts
├── tests/ # Tests (Rust + Python)
├── docs/ # Design docs + ADR
├── scripts/ # Build and test scripts
├── pyproject.toml # Python packaging config
├── Makefile # Development commands
└── Dockerfile # Multi-stage build
Crate Matrix
| Crate | Function |
|---|---|
| axon-core | Core types (11 modules) |
| axon-backtest | Backtesting engine (L1/L2/L3) |
| axon-rl | RL environment (Gymnasium + VecEnv) |
| axon-hpo | Hyperparameter optimization (Optuna) |
| axon-walk-forward | Rolling forward validation |
| axon-distributed | Distributed training (Ray) |
| axon-tracker | Experiment tracking |
| axon-registry | Model registry |
| axon-exchange | Exchange adapters (Binance/OKX) |
| axon-inference | Inference engine (ONNX/Candle) |
| axon-python | Python bindings (PyO3) |
| axon-cli | CLI tool |
| axon-risk | Risk engine |
| axon-oms | Order management |
| axon-monitor | Monitoring alerts |
| axon-llm | LLM agent |
| axon-explain | SHAP explainability |
| axon-ensemble | Model ensemble |
| axon-compliance | Compliance audit |
| axon-data | Data services |
| axon-integration-tests | Integration tests |
Performance
| Metric | Value |
|---|---|
| Backtesting Throughput | > 1M events/sec |
| Matching Latency | < 1μs (P99) |
| Risk Check | 12ns (AtomicBool circuit breaker + HashMap position) |
| Order Submission | 1.2μs (idempotent + UUID v7 + state machine) |
| RL Training | > 10K steps/sec (8 env VecEnv) |
| Distributed Speedup | > 5x (8 workers) |
| Test Cases | 1200+ Rust + 24 Python |
Benchmarks
Workspace has established 50+ Criterion benches across 5 crates:
| Crate | Bench Entry | Coverage |
|---|---|---|
axon-core |
benches/core_bench.rs |
28: impact model/volatility/latency/order book/order/event/fee |
axon-backtest |
benches/impact_bench.rs |
8: matching latency/impact models/order book depth/permanent decay/multi-fill/TOML config |
axon-data |
benches/axon_data_bench.rs |
7 groups (8+ bench): LRU/Dataset lazy/CSV/Parquet streaming/Bar aggregation/Mock/Mmap |
axon-rl |
benches/rl_bench.rs |
11: observation/reward/TradingEnv end-to-end/Action conversion |
| Phase 4 crates | benches/phase4_bench.rs |
15: risk/OMS/monitoring latency |
make bench # Full workspace, 5-10 minutes locally
make bench-cmp # Save main baseline for PR comparison
make bench-one CRATE=axon-core BENCH=event_builder_tick # Single bench
cargo bench -p axon-core -- impact_linear # Direct cargo run
CI doesn't run bench (to avoid main runner performance noise). Report: target/criterion/<group>/report/index.html.
CPU/GPU Affinity
axon-inference provides affinity module for cross-platform core pinning to reduce cross-core cache misses:
use axon_inference::affinity::{AffinityPlan, pin_to};
let plan = AffinityPlan::new().with_cpus(vec![0, 1]).with_cuda(0);
pin_to(&plan)?;
Or via BatchConfig configuration (auto-called at BatchInferencePipeline::new startup):
[batch]
collect_cpu_cores = [0, 1, 2, 3]
collect_gpu_device_id = 0
Platform support: Linux / macOS full support, Windows runtime returns Err(AffinityError::NotAvailable) (use WSL2 / numactl instead).
Engineering Practices
- TDD Driven — Test first, implement later, CI enforces
-D warnings - 1200+ Tests — Unit tests + integration tests + Python scenario tests
- cargo clippy — Zero warning policy
- cargo-mutants — Mutation test coverage
- cargo-fuzz — Fuzz testing (matching engine / order book / risk control)
- Miri — Data race detection
- Loom — Deterministic concurrency testing
Documentation
- Installation & Quick Start
- AI-Native Core Design
- Strategy Development Pipeline
- LLM Agent Trading
- Production Deployment
- Traditional Strategy Migration
- API Reference
- FAQ
License
Disclaimer
This project is an open-source quantitative trading framework intended for research and educational purposes only.
- No investment advice: Nothing in this repository constitutes financial, investment, or trading advice.
- No guarantee of profits: Past performance (including backtesting results) does not guarantee future returns.
- Use at your own risk: The authors and contributors are not responsible for any financial losses incurred through the use of this software.
- Not production-ready: This software is provided "as is" without warranty of any kind. Use in live trading environments requires thorough testing and risk assessment.
- Regulatory compliance: Users are solely responsible for ensuring compliance with applicable laws and regulations in their jurisdiction.
By using this software, you acknowledge that you understand and accept these terms.
Project details
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distributions
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file axon_quant-0.2.0.tar.gz.
File metadata
- Download URL: axon_quant-0.2.0.tar.gz
- Upload date:
- Size: 912.3 kB
- Tags: Source
- Uploaded using Trusted Publishing? Yes
- Uploaded via: twine/6.1.0 CPython/3.13.12
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
40aa041b61bff71796541771fc04864ce3afbcd56e0d389584e47cf37dce95aa
|
|
| MD5 |
f64e0aa98eb02dd7b27f0b8c0156f6c2
|
|
| BLAKE2b-256 |
dd8c25abf7a1ac16b96e148381d3add8f453a7069c6ba48a5d6184b892ffbc8b
|
Provenance
The following attestation bundles were made for axon_quant-0.2.0.tar.gz:
Publisher:
publish.yml on pengwow/axon_quant
-
Statement:
-
Statement type:
https://in-toto.io/Statement/v1 -
Predicate type:
https://docs.pypi.org/attestations/publish/v1 -
Subject name:
axon_quant-0.2.0.tar.gz -
Subject digest:
40aa041b61bff71796541771fc04864ce3afbcd56e0d389584e47cf37dce95aa - Sigstore transparency entry: 1976838894
- Sigstore integration time:
-
Permalink:
pengwow/axon_quant@eab5b1ce8679404c8553548fbe12516d0256cc2e -
Branch / Tag:
refs/heads/0.2.0 - Owner: https://github.com/pengwow
-
Access:
public
-
Token Issuer:
https://token.actions.githubusercontent.com -
Runner Environment:
github-hosted -
Publication workflow:
publish.yml@eab5b1ce8679404c8553548fbe12516d0256cc2e -
Trigger Event:
workflow_dispatch
-
Statement type:
File details
Details for the file axon_quant-0.2.0-cp314-cp314-win_amd64.whl.
File metadata
- Download URL: axon_quant-0.2.0-cp314-cp314-win_amd64.whl
- Upload date:
- Size: 6.6 MB
- Tags: CPython 3.14, Windows x86-64
- Uploaded using Trusted Publishing? Yes
- Uploaded via: twine/6.1.0 CPython/3.13.12
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
f98ea89731dc2a6e1e3ef75c7b88ed357bf027ae8d191df492d2cd129f7fc533
|
|
| MD5 |
592123d33e5c066685a8d54168a0bb00
|
|
| BLAKE2b-256 |
d631e74183ff6d0e52b5ed18759f7fce3a9123096ff66851de08a15ef18abd37
|
Provenance
The following attestation bundles were made for axon_quant-0.2.0-cp314-cp314-win_amd64.whl:
Publisher:
publish.yml on pengwow/axon_quant
-
Statement:
-
Statement type:
https://in-toto.io/Statement/v1 -
Predicate type:
https://docs.pypi.org/attestations/publish/v1 -
Subject name:
axon_quant-0.2.0-cp314-cp314-win_amd64.whl -
Subject digest:
f98ea89731dc2a6e1e3ef75c7b88ed357bf027ae8d191df492d2cd129f7fc533 - Sigstore transparency entry: 1976839367
- Sigstore integration time:
-
Permalink:
pengwow/axon_quant@eab5b1ce8679404c8553548fbe12516d0256cc2e -
Branch / Tag:
refs/heads/0.2.0 - Owner: https://github.com/pengwow
-
Access:
public
-
Token Issuer:
https://token.actions.githubusercontent.com -
Runner Environment:
github-hosted -
Publication workflow:
publish.yml@eab5b1ce8679404c8553548fbe12516d0256cc2e -
Trigger Event:
workflow_dispatch
-
Statement type:
File details
Details for the file axon_quant-0.2.0-cp314-cp314-manylinux_2_34_x86_64.whl.
File metadata
- Download URL: axon_quant-0.2.0-cp314-cp314-manylinux_2_34_x86_64.whl
- Upload date:
- Size: 7.0 MB
- Tags: CPython 3.14, manylinux: glibc 2.34+ x86-64
- Uploaded using Trusted Publishing? Yes
- Uploaded via: twine/6.1.0 CPython/3.13.12
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
5ab9cded6e9eca893651c9e085a397586980c3c15320d94cebc61b65e7a2e57d
|
|
| MD5 |
bfbf3309cd0b76b252ba903e245fdc4b
|
|
| BLAKE2b-256 |
802032eb9f3c63daa5a0ee5fa949d73ddc1a0044a473f55aeb48bbcf1aa1c9bc
|
Provenance
The following attestation bundles were made for axon_quant-0.2.0-cp314-cp314-manylinux_2_34_x86_64.whl:
Publisher:
publish.yml on pengwow/axon_quant
-
Statement:
-
Statement type:
https://in-toto.io/Statement/v1 -
Predicate type:
https://docs.pypi.org/attestations/publish/v1 -
Subject name:
axon_quant-0.2.0-cp314-cp314-manylinux_2_34_x86_64.whl -
Subject digest:
5ab9cded6e9eca893651c9e085a397586980c3c15320d94cebc61b65e7a2e57d - Sigstore transparency entry: 1976840041
- Sigstore integration time:
-
Permalink:
pengwow/axon_quant@eab5b1ce8679404c8553548fbe12516d0256cc2e -
Branch / Tag:
refs/heads/0.2.0 - Owner: https://github.com/pengwow
-
Access:
public
-
Token Issuer:
https://token.actions.githubusercontent.com -
Runner Environment:
github-hosted -
Publication workflow:
publish.yml@eab5b1ce8679404c8553548fbe12516d0256cc2e -
Trigger Event:
workflow_dispatch
-
Statement type:
File details
Details for the file axon_quant-0.2.0-cp314-cp314-macosx_11_0_arm64.whl.
File metadata
- Download URL: axon_quant-0.2.0-cp314-cp314-macosx_11_0_arm64.whl
- Upload date:
- Size: 6.4 MB
- Tags: CPython 3.14, macOS 11.0+ ARM64
- Uploaded using Trusted Publishing? Yes
- Uploaded via: twine/6.1.0 CPython/3.13.12
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
c465c41433a8f6ac32009c75a61c38381d8b637b89ca0ea995f51552bfc33c37
|
|
| MD5 |
32e4bc18b0310db75d381e2be770843d
|
|
| BLAKE2b-256 |
335ddfb67a892660d5a4df4ac043ef4139b9723ae95c71097502753d2d62d07f
|
Provenance
The following attestation bundles were made for axon_quant-0.2.0-cp314-cp314-macosx_11_0_arm64.whl:
Publisher:
publish.yml on pengwow/axon_quant
-
Statement:
-
Statement type:
https://in-toto.io/Statement/v1 -
Predicate type:
https://docs.pypi.org/attestations/publish/v1 -
Subject name:
axon_quant-0.2.0-cp314-cp314-macosx_11_0_arm64.whl -
Subject digest:
c465c41433a8f6ac32009c75a61c38381d8b637b89ca0ea995f51552bfc33c37 - Sigstore transparency entry: 1976839637
- Sigstore integration time:
-
Permalink:
pengwow/axon_quant@eab5b1ce8679404c8553548fbe12516d0256cc2e -
Branch / Tag:
refs/heads/0.2.0 - Owner: https://github.com/pengwow
-
Access:
public
-
Token Issuer:
https://token.actions.githubusercontent.com -
Runner Environment:
github-hosted -
Publication workflow:
publish.yml@eab5b1ce8679404c8553548fbe12516d0256cc2e -
Trigger Event:
workflow_dispatch
-
Statement type: