AI4Finance-Foundation/FinRL-Trading

GitHub: AI4Finance-Foundation/FinRL-Trading

FinRL-X 是一个 AI 原生量化交易基础设施,提供从数据、策略、回测到实盘的一致性权重接口,解耦模块以提升策略研发与部署效率。

Stars: 2992 | Forks: 922

### 面向量化交易的AI原生模块化基础设施 [![Paper](https://img.shields.io/badge/Paper-arXiv_2603.21330-b31b1b?style=for-the-badge)](https://arxiv.org/abs/2603.21330)   [![PyPI](https://img.shields.io/badge/PyPI-finrl--trading-3775A9?style=for-the-badge&logo=pypi&logoColor=white)](https://pypi.org/project/finrl-trading/) [![Python 3.11](https://img.shields.io/badge/python-3.11+-blue.svg)](https://www.python.org/downloads/) ![License](https://img.shields.io/github/license/AI4Finance-Foundation/FinRL-Trading.svg?color=brightgreen) [![Downloads](https://static.pepy.tech/badge/finrl-trading)](https://pepy.tech/project/finrl-trading) [![Downloads](https://static.pepy.tech/badge/finrl-trading/week)](https://pepy.tech/project/finrl-trading) [![Join Discord](https://img.shields.io/badge/Discord-Join-5865F2?logo=discord&logoColor=white)](https://discord.gg/trsr8SXpW5) ![](https://img.shields.io/github/issues-raw/AI4Finance-Foundation/FinRL-Trading?label=Issues) ![](https://img.shields.io/github/issues-pr-raw/AI4Finance-Foundation/FinRL-Trading?label=PRs) ![Visitors](https://api.visitorbadge.io/api/VisitorHit?user=AI4Finance-Foundation&repo=FinRL-Trading&countColor=%23B17A) *一个部署一致的交易系统,通过以权重为中心的接口统一数据处理、策略组合、回测与经纪商执行。*
## 关于 **FinRL-X** 是一个下一代**AI原生**量化交易基础设施,重新定义了研究人员与实践者构建、测试和部署算法交易策略的方式。 在论文 *《FinRL-X: An AI-Native Modular Infrastructure for Quantitative Trading》*([arXiv:2603.21330](https://arxiv.org/abs/2603.21330))中提出,FinRL-X 继承了原始 [FinRL](https://github.com/AI4Finance-Foundation/FinRL) 框架,并采用完全现代化的架构,专为 LLM 与代理式 AI 时代而设计。 其核心是**以权重为中心的结构**——目标投资组合权重向量是策略逻辑与下游执行之间的唯一接口契约: $$w_t = \mathcal{R}_t\bigl(\mathcal{T}_t\bigl(\mathcal{A}_t\bigl(\mathcal{S}_t(\mathcal{X}_{\le t})\bigr)\bigr)\bigr)$$ 其中 $\mathcal{S}$ 表示股票选择,$\mathcal{A}$ 表示组合分配,$\mathcal{T}$ 表示时机调整,$\mathcal{R}$ 表示组合级风险覆盖。每种转换都保持接口不变——你可以替换任意模块(例如等权重 $\to$ DRL 分配器),而无需改动流水线其余部分,且相同的权重会一致地流经回测与实盘执行。 ## 架构

| 层 | 角色 | 组件 | |:------|:-----|:-----------| | **数据** | 统一市场数据流水线 | FMP、Yahoo Finance、WRDS;LLM 情感预处理;SQLite 缓存 | | **策略** | 以权重为中心的信号生成 | 股票选择、组合分配、时机调整、风险覆盖 | | **回测** | 离线评估 | 支持 `bt` 引擎的多基准对比与交易成本 | | **执行** | 实时/模拟交易 | Alpaca 多账户集成与预交易风险检查 | ``` finrl-trading/ ├── src/ │ ├── config/ # ⚙️ Centralized configuration management │ │ └── settings.py # Pydantic-based settings + environment variables │ ├── data/ # 🗄️ Data acquisition and processing │ │ ├── data_fetcher.py # Multi-source integration (Yahoo / FMP / WRDS) │ │ ├── data_processor.py # Feature engineering & data cleaning │ │ └── data_store.py # SQLite persistence with caching │ ├── backtest/ # 📊 Backtesting engine │ │ └── backtest_engine.py # bt-powered engine with benchmark comparison │ ├── strategies/ # 🤖 Trading strategies │ │ ├── base_strategy.py # Abstract strategy framework │ │ └── ml_strategy.py # Random Forest stock selection │ ├── trading/ # 💰 Live trading execution │ │ ├── alpaca_manager.py # Alpaca API integration (multi-account) │ │ ├── trade_executor.py # Order management & risk controls │ │ └── performance_analyzer.py # Real-time P&L tracking │ └── main.py # 🚀 CLI entry point ├── examples/ │ ├── FinRL_Full_Workflow.ipynb # 📓 Complete workflow tutorial (start here!) │ └── README.md ├── data/ # Runtime data storage (gitignored) ├── logs/ # Application logs (gitignored) ├── requirements.txt └── setup.py ``` ## 策略 FinRL-X 实现了论文中的三个用例,每个用例展示了权重中心流水线的不同组合。 ### 用例 1 — 组合分配范式 在统一接口下比较多种分配方法: | 方法 | 类型 | 描述 | |:-------|:-----|:------------| | 等权重 | 经典 | 均匀 1/N 分配 | | 均值-方差 | 经典 | 马科维茨优化 | | 最小方差 | 经典 | 最小化组合波动率 | | DRL 分配器 | 学习 | PPO/SAC 连续权重生成 | | KAMA 时机 | 信号 | 考夫曼自适应趋势叠加 | 所有方法输出相同的权重向量,可直接与时机和风险覆盖层组合。
### 用例 2 — 滚动股票选择 + DRL 通过机器学习基本面评分,每季度选择 NASDAQ-100 中排名前 25% 的股票,并与基于 DRL 的组合分配结合。严格的无前瞻语义防止数据泄露。 ### 用例 3 — 自适应多资产轮动 一个研究级、走前安全的轮动策略,包含每日风险监控: | 组件 | 细节 | |:----------|:-------| | **资产组** | 成长科技、实物资产、防御性 —— 每周最多激活 2 组 | | **组选择** | 相对 QQQ 基准的信息比率 | | **组内排名** | 残差动量与稳健 Z 得分异常处理 | | **市场状态** | 慢速状态(26 周趋势 + VIX)+ 快速风险规避(3 日冲击) | | **风险控制** | 跟踪止损、绝对止损、冷静期 | | **再平衡** | 每周(完整)+ 每日监控(快速风险规避、止损调整) | ``` # 运行自适应轮动回测 ./deploy.sh --strategy adaptive_rotation --mode backtest --start 2023-01-01 --end 2024-12-31 # 使用 Alpaca 进行模拟交易 ./deploy.sh --strategy adaptive_rotation --mode paper --dry-run ``` ## 结果 ### 历史回测(2018 年 1 月 – 2025 年 10 月)
| 指标 | 轮动策略 | 自适应轮动 | QQQ | SPY | |:-------|:---:|:---:|:---:|:---:| | 累计收益 | 5.98x | 4.80x | 4.02x | 2.80x | | 年化收益 | 25.85% | 22.32% | 19.56% | 14.14% | | 年化波动率 | 27.85% | 20.30% | 24.20% | 19.61% | | **夏普比率** | 0.93 | **1.10** | 0.81 | 0.72 | | 最大回撤 | -38.95% | **-21.46%** | -35.12% | -33.72% | | **Calmar 比率** | 0.66 | **1.04** | 0.56 | 0.42 | | 胜率 | 54.36% | 54.77% | 56.25% | 55.28% | ### 纸面交易(2025 年 10 月 – 2026 年 3 月)
在 Alpaca 上部署的轮动选择 + 自适应轮动组合: | 指标 | 策略 | SPY | QQQ | |:-------|:---:|:---:|:---:| | 累计收益 | **1.20x** | 0.97x | 0.95x | | 总收益 | **+19.76%** | -2.51% | -4.79% | | 年化收益 | **62.16%** | -6.60% | -12.32% | | 年化波动率 | 31.75% | 11.96% | 16.79% | | **夏普比率** | **1.96** | -0.55 | -0.73 | | 最大回撤 | -12.22% | -5.35% | -7.88% | | **Calmar 比率** | **5.09** | -1.23 | -1.56 | | 胜率 | **64.89%** | 52.13% | 54.02% | ### 动态行业轮动
自适应轮动策略根据市场状态信号在三类资产组之间动态调仓:**成长科技**、**实物资产** 与防御性** —— 每周最多激活两组。在风险偏好状态时,组合偏向高动量成长与商品类资产;当状态检测触发风险规避或快速风险规避时,资金将轮动至债券与公用事业,并自动保留现金缓冲。每周再平衡辅以每日止损与快速风险规避监控,可在下一轮定期调仓前快速降险。 ## 快速开始 ### 选项 A — 一键部署 `deploy.sh` 自动处理所有步骤:依赖检查、数据下载与策略执行。 ``` git clone https://github.com/AI4Finance-Foundation/FinRL-Trading.git cd FinRL-Trading # 回测(下载数据 + 运行策略) ./deploy.sh --strategy adaptive_rotation --mode backtest # 自定义日期范围 ./deploy.sh --strategy adaptive_rotation --mode backtest --start 2020-01-01 --end 2025-12-31 # 单日信号 ./deploy.sh --strategy adaptive_rotation --mode single --date 2024-12-31 # 模拟交易(需要 .env 中的 Alpaca 凭证) ./deploy.sh --strategy adaptive_rotation --mode paper --dry-run # preview ./deploy.sh --strategy adaptive_rotation --mode paper # execute # 查看所有选项 ./deploy.sh --help ``` ### 选项 B — 使用 venv 手动设置 ``` # 1. 克隆 git clone https://github.com/AI4Finance-Foundation/FinRL-Trading.git cd FinRL-Trading # 2. 创建并激活虚拟环境 python3 -m venv venv source venv/bin/activate # Linux / macOS # venv\Scripts\activate # Windows # 3. 安装依赖 pip install -r requirements.txt # 4. (可选)配置模拟交易的 API 密钥 cp .env.example .env # 编辑 .env — 设置 APCA_API_KEY、APCA_API_SECRET 等 ``` #### 通过 Python 运行策略 ``` # 回测 — 自适应轮动(2023-01-01 至 2024-12-31) python src/strategies/run_adaptive_rotation_strategy.py \ --config src/strategies/AdaptiveRotationConf_v1.2.1.yaml \ --backtest --start 2023-01-01 --end 2024-12-31 # 单日信号 python src/strategies/run_adaptive_rotation_strategy.py \ --config src/strategies/AdaptiveRotationConf_v1.2.1.yaml \ --date 2024-12-31 # 完整工作流教程(Jupyter) jupyter notebook examples/FinRL_Full_Workflow.ipynb ``` ### 配置 ``` cp .env.example .env ``` ``` # Alpaca(模拟/实盘交易必需) APCA_API_KEY=your_key APCA_API_SECRET=your_secret APCA_BASE_URL=https://paper-api.alpaca.markets # 数据源(可选;Yahoo Finance 为默认免费源) FMP_API_KEY=your_fmp_key ``` ### Python API ``` # 数据 from src.data.data_fetcher import get_data_manager manager = get_data_manager() prices = manager.get_price_data(['AAPL', 'MSFT'], '2020-01-01', '2024-12-31') # 策略 from src.strategies.ml_strategy import MLStockSelectorStrategy strategy = MLStockSelectorStrategy(config) result = strategy.generate_weights(data) # 回测 from src.backtest.backtest_engine import BacktestEngine, BacktestConfig engine = BacktestEngine(BacktestConfig(start_date='2020-01-01', end_date='2024-12-31')) result = engine.run_backtest("My Strategy", weights, prices) # 实盘交易 from src.trading.alpaca_manager import create_alpaca_account_from_env, AlpacaManager alpaca = AlpacaManager([create_alpaca_account_from_env()]) alpaca.execute_portfolio_rebalance(target_weights={'AAPL': 0.3, 'MSFT': 0.7}) ``` ## 从 FinRL 演进 | | FinRL (2020) | FinRL-X (2026) | |:---|:---|:---| | **范式** | 仅 DRL | AI原生(ML + DRL + LLM-ready) | | **架构** | 耦合单体 | 解耦模块化层 | | **接口** | Gym 状态/动作空间 | 以权重为中心的契约 | | **数据** | 14 个手动处理器 | 自动选择:Yahoo / FMP / WRDS | | **回测** | 手工循环 | `bt` 引擎 + 多基准对比 | | **实盘交易** | 基础 Alpaca | 多账户 + 风险控制 | | **配置** | `config.py` | Pydantic + `.env` | | **论文** | [arXiv:2011.09607](https://arxiv.org/abs/2011.09607) | [arXiv:2603.21330](https://arxiv.org/abs/2603.21330) | ### 从 FinRL 迁移 ``` FinRL → FinRL-X ───────────────────────────────────────────────────────────── finrl/meta/data_processor.py → src/data/data_fetcher.py finrl/train.py → strategy.generate_weights() finrl/trade.py → TradeExecutor.execute_portfolio_rebalance() config.py + config_tickers.py → src/config/settings.py (Pydantic + .env) gym.Env subclassing → BaseStrategy.generate_weights() ``` ## 与现有平台对比 | 特性 | FinRL-X | [Qlib](https://github.com/microsoft/qlib) | [TradingAgents](https://github.com/TauricResearch/TradingAgents) | [Zipline](https://github.com/quantopian/zipline)/[Backtrader](https://github.com/mementum/backtrader) | [QuantConnect Lean](https://github.com/QuantConnect/Lean) | |:--------|:-------:|:----:|:-------------:|:------------------:|:-----------------:| | 主要定位 | 全流程系统 | 机器学习研究 | 代理式交易 | 回测 | 全流程平台 | | 经纪商集成 | 是 | - | - | - | 是 | | 部署一致接口 | 是 | - | - | - | 部分 | | 强化学习支持 | 是 | 有限 | 是 | - | 部分 | | 模块化策略流水线 | 是 | - | - | - | 部分 | | 组合级风险覆盖 | 是 | - | - | - | 部分 | | 开源协议 | Apache 2.0 | MIT | Apache 2.0 | Apache 2.0 | Apache 2.0 | ## 贡献 ``` git checkout -b feature/your-feature pip install -r requirements.txt # 修改代码,添加测试 git commit -m "Add: your feature" git push origin feature/your-feature # 提交拉取请求 ``` 添加自定义策略: ``` from src.strategies.base_strategy import BaseStrategy, StrategyConfig, StrategyResult class MyStrategy(BaseStrategy): def generate_weights(self, data, **kwargs) -> StrategyResult: # your alpha logic — return portfolio weights pass ``` ## 引用 ``` @inproceedings{yang2026finrlx, title = {FinRL-X: An AI-Native Modular Infrastructure for Quantitative Trading}, author = {Yang, Hongyang and Zhang, Boyu and She, Yang and Liao, Xinyu and Zhang, Xiaoli}, booktitle = {Proceedings of the 2nd International Workshop on Decision Making and Optimization in Financial Technologies (DMO-FinTech)}, year = {2026}, note = {Workshop at PAKDD 2026} } ``` ## 许可证 Apache License 2.0 — 见 [LICENSE](LICENSE)。 ## 免责声明 本软件仅供**教育与研究用途**。不构成金融建议。在做出投资决策前请咨询专业人士。过去表现不代表未来结果。
**[AI4Finance Foundation](https://github.com/AI4Finance-Foundation)**
标签:AI原生, arXiv, FinRL, PyPI, Python, Python 3.11, 交易回测, 交易系统, 凭据扫描, 回测, 因子工程, 学术研究, 市场数据, 开源量化, 强化学习, 执行算法, 数据管道, 无后门, 时间序列, 智能投顾, 机器学习平台, 权重中心接口, 模块化基础设施, 模型训练, 生产部署, 策略开发, 策略组合, 算法交易, 经纪商执行, 订单路由, 软件工程, 逆向工具, 部署一致性, 量化交易, 量化投资, 金融AI, 金融工程, 风控