{"id":15034963,"url":"https://github.com/ai4finance-foundation/finrl-trading","last_synced_at":"2026-04-02T13:25:11.162Z","repository":{"id":37633591,"uuid":"282652875","full_name":"AI4Finance-Foundation/FinRL-Trading","owner":"AI4Finance-Foundation","description":"For trading. Please star.","archived":false,"fork":false,"pushed_at":"2024-07-01T08:09:06.000Z","size":145360,"stargazers_count":2340,"open_issues_count":45,"forks_count":792,"subscribers_count":99,"default_branch":"master","last_synced_at":"2025-05-15T01:07:11.375Z","etag":null,"topics":["a2c-algorithm","automated-stock-trading","ddpg","deep-reinforcement-learning","ensemble-strategy","openai-gym","ppo","sharpe-ratio","stock-trading","stock-trading-strategy"],"latest_commit_sha":null,"homepage":"https://ai4finance.org","language":"Jupyter Notebook","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/AI4Finance-Foundation.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2020-07-26T13:12:53.000Z","updated_at":"2025-05-14T08:50:50.000Z","dependencies_parsed_at":"2024-11-13T08:41:32.861Z","dependency_job_id":null,"html_url":"https://github.com/AI4Finance-Foundation/FinRL-Trading","commit_stats":null,"previous_names":["ai4finance-foundation/deep-reinforcement-learning-for-automated-stock-trading-ensemble-strategy-icaif-2020"],"tags_count":0,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/AI4Finance-Foundation%2FFinRL-Trading","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/AI4Finance-Foundation%2FFinRL-Trading/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/AI4Finance-Foundation%2FFinRL-Trading/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/AI4Finance-Foundation%2FFinRL-Trading/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/AI4Finance-Foundation","download_url":"https://codeload.github.com/AI4Finance-Foundation/FinRL-Trading/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":254254041,"owners_count":22039792,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["a2c-algorithm","automated-stock-trading","ddpg","deep-reinforcement-learning","ensemble-strategy","openai-gym","ppo","sharpe-ratio","stock-trading","stock-trading-strategy"],"created_at":"2024-09-24T20:27:01.605Z","updated_at":"2026-04-02T13:25:11.156Z","avatar_url":"https://github.com/AI4Finance-Foundation.png","language":"Jupyter Notebook","funding_links":[],"categories":[],"sub_categories":[],"readme":"\n\u003cdiv align=\"center\"\u003e\n\n# FinRL-X\n\n### An AI-Native Modular Infrastructure for Quantitative Trading\n\n\u003cimg src=\"https://github.com/user-attachments/assets/80fe89bb-fb09-4267-b29a-76030512f8cf\" width=\"420\"\u003e\n\n[![Paper](https://img.shields.io/badge/Paper-arXiv_2603.21330-b31b1b?style=for-the-badge)](https://arxiv.org/abs/2603.21330)\n\u0026nbsp;\n[![PyPI](https://img.shields.io/badge/PyPI-finrl--trading-3775A9?style=for-the-badge\u0026logo=pypi\u0026logoColor=white)](https://pypi.org/project/finrl-trading/)\n\n[![Python 3.11](https://img.shields.io/badge/python-3.11+-blue.svg)](https://www.python.org/downloads/)\n![License](https://img.shields.io/github/license/AI4Finance-Foundation/FinRL-Trading.svg?color=brightgreen)\n[![Downloads](https://static.pepy.tech/badge/finrl-trading)](https://pepy.tech/project/finrl-trading)\n[![Downloads](https://static.pepy.tech/badge/finrl-trading/week)](https://pepy.tech/project/finrl-trading)\n[![Join Discord](https://img.shields.io/badge/Discord-Join-5865F2?logo=discord\u0026logoColor=white)](https://discord.gg/trsr8SXpW5)\n\n![](https://img.shields.io/github/issues-raw/AI4Finance-Foundation/FinRL-Trading?label=Issues)\n![](https://img.shields.io/github/issues-pr-raw/AI4Finance-Foundation/FinRL-Trading?label=PRs)\n![Visitors](https://api.visitorbadge.io/api/VisitorHit?user=AI4Finance-Foundation\u0026repo=FinRL-Trading\u0026countColor=%23B17A)\n\n*A deployment-consistent trading system that unifies data processing, strategy composition, backtesting, and broker execution through a weight-centric interface.*\n\n[Paper](https://arxiv.org/abs/2603.21330) | [Quick Start](#quick-start) | [Strategies](#strategies) | [Results](#results) | [Discord](https://discord.gg/trsr8SXpW5)\n\n\u003c/div\u003e\n\n---\n\n## About\n\n**FinRL-X** is a next-generation, **AI-native** quantitative trading infrastructure that redefines how researchers and practitioners build, test, and deploy algorithmic trading strategies. \n\nIntroduced in our paper *\"FinRL-X: An AI-Native Modular Infrastructure for Quantitative Trading\"* ([arXiv:2603.21330](https://arxiv.org/abs/2603.21330)), FinRL-X succeeds the original [FinRL](https://github.com/AI4Finance-Foundation/FinRL) framework with a fully modernized architecture designed for the LLM and agentic AI era.\n\n\u003e FinRL-X is **not just a library** — it is a full-stack trading platform engineered around modularity, reproducibility, and production-readiness, supporting everything from ML-based stock selection and professional backtesting to live brokerage execution.\n\nAt its core is a **weight-centric architecture** — the target portfolio weight vector is the sole interface contract between strategy logic and downstream execution:\n\n$$w_t = \\mathcal{R}_t\\bigl(\\mathcal{T}_t\\bigl(\\mathcal{A}_t\\bigl(\\mathcal{S}_t(\\mathcal{X}_{\\le t})\\bigr)\\bigr)\\bigr)$$\n\nwhere $\\mathcal{S}$ denotes stock selection, $\\mathcal{A}$ portfolio allocation, $\\mathcal{T}$ timing adjustment, and $\\mathcal{R}$ portfolio-level risk overlay. Each transformation is contract-preserving — you can swap any module (e.g. equal-weight $\\to$ DRL allocator) without touching the rest of the pipeline, and the same weights flow identically through backtesting and live execution.\n\n---\n\n## Architecture\n\n\u003cdiv align=\"center\"\u003e\n  \u003cimg src=\"https://github.com/AI4Finance-Foundation/FinRL-Trading/blob/master/figs/FinRL_X_Framework.png\" width=\"880\"/\u003e\n\u003c/div\u003e\n\n\u003cbr/\u003e\n\n| Layer | Role | Components |\n|:------|:-----|:-----------|\n| **Data** | Unified market data pipeline | FMP, Yahoo Finance, WRDS; LLM sentiment preprocessing; SQLite cache |\n| **Strategy** | Weight-centric signal generation | Stock selection, portfolio allocation, timing adjustment, risk overlay |\n| **Backtest** | Offline evaluation | `bt`-powered engine with multi-benchmark comparison and transaction costs |\n| **Execution** | Live/paper trading | Alpaca multi-account integration with pre-trade risk checks |\n\n```\nfinrl-trading/\n├── src/\n│   ├── config/                     # ⚙️  Centralized configuration management\n│   │   └── settings.py             #     Pydantic-based settings + environment variables\n│   ├── data/                       # 🗄️  Data acquisition and processing\n│   │   ├── data_fetcher.py         #     Multi-source integration (Yahoo / FMP / WRDS)\n│   │   ├── data_processor.py       #     Feature engineering \u0026 data cleaning\n│   │   └── data_store.py           #     SQLite persistence with caching\n│   ├── backtest/                   # 📊  Backtesting engine\n│   │   └── backtest_engine.py      #     bt-powered engine with benchmark comparison\n│   ├── strategies/                 # 🤖  Trading strategies\n│   │   ├── base_strategy.py        #     Abstract strategy framework\n│   │   └── ml_strategy.py          #     Random Forest stock selection\n│   ├── trading/                    # 💰  Live trading execution\n│   │   ├── alpaca_manager.py       #     Alpaca API integration (multi-account)\n│   │   ├── trade_executor.py       #     Order management \u0026 risk controls\n│   │   └── performance_analyzer.py #     Real-time P\u0026L tracking\n│   └── main.py                     # 🚀  CLI entry point\n├── examples/\n│   ├── FinRL_Full_Workflow.ipynb   # 📓  Complete workflow tutorial (start here!)\n│   └── README.md\n├── data/                           # Runtime data storage (gitignored)\n├── logs/                           # Application logs (gitignored)\n├── requirements.txt\n└── setup.py\n```\n\n---\n\n## Strategies\n\nFinRL-X implements three use cases from the paper, each demonstrating different compositions of the weight-centric pipeline.\n\n### Use Case 1 — Portfolio Allocation Paradigms\n\nCompares heterogeneous allocation methods under a unified interface:\n\n| Method | Type | Description |\n|:-------|:-----|:------------|\n| Equal Weight | Classical | Uniform 1/N allocation |\n| Mean-Variance | Classical | Markowitz optimization |\n| Minimum Variance | Classical | Minimize portfolio volatility |\n| DRL Allocator | Learning | PPO/SAC continuous weight generation |\n| KAMA Timing | Signal | Kaufman adaptive trend overlay |\n\nAll methods output the same weight vector, making them directly composable with timing and risk overlays.\n\n\u003cdiv align=\"center\"\u003e\n  \u003cimg src=\"https://github.com/AI4Finance-Foundation/FinRL-Trading/blob/master/figs/DRL_Timing_Backtest.png\" width=\"900\"/\u003e\n\u003c/div\u003e\n\n### Use Case 2 — Rolling Stock Selection + DRL\n\nQuarterly selection of top-25% NASDAQ-100 stocks via ML fundamental scoring, combined with DRL-based portfolio allocation. Strict no-lookahead semantics prevent data leakage.\n\n### Use Case 3 — Adaptive Multi-Asset Rotation\n\nA research-grade, walk-forward-safe rotation strategy with daily risk monitoring:\n\n| Component | Detail |\n|:----------|:-------|\n| **Asset Groups** | Growth Tech, Real Assets, Defensive — max 2 active per week |\n| **Group Selection** | Information Ratio relative to QQQ benchmark |\n| **Intra-Group Ranking** | Residual momentum with robust Z-score exception handling |\n| **Market Regime** | Slow regime (26-week trend + VIX) + Fast Risk-Off (3-day shock) |\n| **Risk Controls** | Trailing stop-loss, absolute stop-loss, cooldown periods |\n| **Rebalance** | Weekly (full) + daily monitoring (fast risk-off, stop-loss adjustments) |\n\n```bash\n# Run the adaptive rotation backtest\n./deploy.sh --strategy adaptive_rotation --mode backtest --start 2023-01-01 --end 2024-12-31\n\n# Paper trade with Alpaca\n./deploy.sh --strategy adaptive_rotation --mode paper --dry-run\n```\n\n---\n\n## Results\n\n### Historical Backtest (Jan 2018 – Oct 2025)\n\n\u003cdiv align=\"center\"\u003e\n  \u003cimg src=\"https://github.com/AI4Finance-Foundation/FinRL-Trading/blob/master/figs/All_Backtests_v2.png\" width=\"900\"/\u003e\n\u003c/div\u003e\n\n| Metric | Rolling Strategy | Adaptive Rotation | QQQ | SPY |\n|:-------|:---:|:---:|:---:|:---:|\n| Cumulative Return | 5.98x | 4.80x | 4.02x | 2.80x |\n| Annualized Return | 25.85% | 22.32% | 19.56% | 14.14% |\n| Annualized Volatility | 27.85% | 20.30% | 24.20% | 19.61% |\n| **Sharpe Ratio** | 0.93 | **1.10** | 0.81 | 0.72 |\n| Max Drawdown | -38.95% | **-21.46%** | -35.12% | -33.72% |\n| **Calmar Ratio** | 0.66 | **1.04** | 0.56 | 0.42 |\n| Win Rate | 54.36% | 54.77% | 56.25% | 55.28% |\n\n### Paper Trading (Oct 2025 – Mar 2026)\n\n\u003cdiv align=\"center\"\u003e\n  \u003cimg src=\"https://github.com/AI4Finance-Foundation/FinRL-Trading/blob/master/figs/Paper_Trading.png\" width=\"900\"/\u003e\n\u003c/div\u003e\n\nEnsemble of Rolling Selection + Adaptive Rotation deployed on Alpaca paper trading:\n\n| Metric | Strategy | SPY | QQQ |\n|:-------|:---:|:---:|:---:|\n| Cumulative Return | **1.20x** | 0.97x | 0.95x |\n| Total Return | **+19.76%** | -2.51% | -4.79% |\n| Annualized Return | **62.16%** | -6.60% | -12.32% |\n| Annualized Volatility | 31.75% | 11.96% | 16.79% |\n| **Sharpe Ratio** | **1.96** | -0.55 | -0.73 |\n| Max Drawdown | -12.22% | -5.35% | -7.88% |\n| **Calmar Ratio** | **5.09** | -1.23 | -1.56 |\n| Win Rate | **64.89%** | 52.13% | 54.02% |\n\n### Dynamic Sector Rotation\n\n\u003cdiv align=\"center\"\u003e\n  \u003cimg src=\"https://github.com/AI4Finance-Foundation/FinRL-Trading/blob/master/figs/Sector_Rotation_Standalone.png\" width=\"900\"/\u003e\n\u003c/div\u003e\n\nThe Adaptive Rotation strategy dynamically shifts capital across three asset groups — **Growth Tech**, **Real Assets**, and **Defensive** — based on market regime signals. During risk-on regimes, the portfolio tilts toward high-momentum growth and commodity plays; when regime detection flags risk-off or fast risk-off conditions, capital rotates into bonds and utilities with an automatic cash buffer. Weekly rebalancing is complemented by daily stop-loss and fast risk-off monitoring, enabling rapid de-risking without waiting for the next scheduled rebalance.\n\n---\n\n## Quick Start\n\n### Option A — One-Command Deploy\n\n`deploy.sh` handles everything automatically: dependency check, data download, and strategy execution.\n\n```bash\ngit clone https://github.com/AI4Finance-Foundation/FinRL-Trading.git\ncd FinRL-Trading\n\n# Backtest (downloads data + runs strategy)\n./deploy.sh --strategy adaptive_rotation --mode backtest\n\n# Custom date range\n./deploy.sh --strategy adaptive_rotation --mode backtest --start 2020-01-01 --end 2025-12-31\n\n# Single date signal\n./deploy.sh --strategy adaptive_rotation --mode single --date 2024-12-31\n\n# Paper trading (requires Alpaca credentials in .env)\n./deploy.sh --strategy adaptive_rotation --mode paper --dry-run   # preview\n./deploy.sh --strategy adaptive_rotation --mode paper              # execute\n\n# See all options\n./deploy.sh --help\n```\n\n### Option B — Manual Setup with venv\n\n```bash\n# 1. Clone\ngit clone https://github.com/AI4Finance-Foundation/FinRL-Trading.git\ncd FinRL-Trading\n\n# 2. Create and activate virtual environment\npython3 -m venv venv\nsource venv/bin/activate        # Linux / macOS\n# venv\\Scripts\\activate         # Windows\n\n# 3. Install dependencies\npip install -r requirements.txt\n\n# 4. (Optional) Configure API keys for paper trading\ncp .env.example .env\n# Edit .env — set APCA_API_KEY, APCA_API_SECRET, etc.\n```\n\n#### Running Strategies via Python\n\n```bash\n# Backtest — Adaptive Rotation (2023-01-01 to 2024-12-31)\npython src/strategies/run_adaptive_rotation_strategy.py \\\n    --config src/strategies/AdaptiveRotationConf_v1.2.1.yaml \\\n    --backtest --start 2023-01-01 --end 2024-12-31\n\n# Single date signal\npython src/strategies/run_adaptive_rotation_strategy.py \\\n    --config src/strategies/AdaptiveRotationConf_v1.2.1.yaml \\\n    --date 2024-12-31\n\n# Full workflow tutorial (Jupyter)\njupyter notebook examples/FinRL_Full_Workflow.ipynb\n```\n\n\u003e **Note:** Data files (`{SYMBOL}_daily.csv`) must exist under `data/fmp_daily/` before running.\n\u003e `deploy.sh` downloads them automatically; for manual setup, either run `deploy.sh --strategy adaptive_rotation --mode backtest` once, or prepare CSV files with columns `date,open,high,low,close,volume`.\n\n### Configuration\n\n```bash\ncp .env.example .env\n```\n\n```bash\n# Alpaca (required for paper/live trading)\nAPCA_API_KEY=your_key\nAPCA_API_SECRET=your_secret\nAPCA_BASE_URL=https://paper-api.alpaca.markets\n\n# Data source (optional; Yahoo Finance is the free default)\nFMP_API_KEY=your_fmp_key\n```\n\n### Python API\n\n```python\n# Data\nfrom src.data.data_fetcher import get_data_manager\nmanager = get_data_manager()\nprices = manager.get_price_data(['AAPL', 'MSFT'], '2020-01-01', '2024-12-31')\n\n# Strategy\nfrom src.strategies.ml_strategy import MLStockSelectorStrategy\nstrategy = MLStockSelectorStrategy(config)\nresult = strategy.generate_weights(data)\n\n# Backtest\nfrom src.backtest.backtest_engine import BacktestEngine, BacktestConfig\nengine = BacktestEngine(BacktestConfig(start_date='2020-01-01', end_date='2024-12-31'))\nresult = engine.run_backtest(\"My Strategy\", weights, prices)\n\n# Live trade\nfrom src.trading.alpaca_manager import create_alpaca_account_from_env, AlpacaManager\nalpaca = AlpacaManager([create_alpaca_account_from_env()])\nalpaca.execute_portfolio_rebalance(target_weights={'AAPL': 0.3, 'MSFT': 0.7})\n```\n\n---\n\n## Evolution from FinRL\n\n| | FinRL (2020) | FinRL-X (2026) |\n|:---|:---|:---|\n| **Paradigm** | DRL-only | AI-Native (ML + DRL + LLM-ready) |\n| **Architecture** | Coupled monolith | Decoupled modular layers |\n| **Interface** | Gym state/action spaces | Weight-centric contract |\n| **Data** | 14 manual processors | Auto-select: Yahoo / FMP / WRDS |\n| **Backtesting** | Hand-rolled loops | `bt` engine + multi-benchmark |\n| **Live Trading** | Basic Alpaca | Multi-account + risk controls |\n| **Config** | `config.py` | Pydantic + `.env` |\n| **Paper** | [arXiv:2011.09607](https://arxiv.org/abs/2011.09607) | [arXiv:2603.21330](https://arxiv.org/abs/2603.21330) |\n\n### Migration from FinRL\n\n```\nFinRL                                →  FinRL-X\n─────────────────────────────────────────────────────────────\nfinrl/meta/data_processor.py         →  src/data/data_fetcher.py\nfinrl/train.py                       →  strategy.generate_weights()\nfinrl/trade.py                       →  TradeExecutor.execute_portfolio_rebalance()\nconfig.py + config_tickers.py        →  src/config/settings.py (Pydantic + .env)\ngym.Env subclassing                  →  BaseStrategy.generate_weights()\n```\n\n---\n\n## Comparison with Existing Platforms\n\n| Feature | 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) |\n|:--------|:-------:|:----:|:-------------:|:------------------:|:-----------------:|\n| Primary Orientation | End-to-End System | ML Research | Agent-Based Trading | Backtesting | End-to-End Platform |\n| Broker Integration | Yes | - | - | - | Yes |\n| Deployment-Consistent Interface | Yes | - | - | - | Partial |\n| Reinforcement Learning Support | Yes | Limited | Yes | - | Partial |\n| Modular Strategy Pipeline | Yes | - | - | - | Partial |\n| Portfolio-Level Risk Overlay | Yes | - | - | - | Partial |\n| Open Source License | Apache 2.0 | MIT | Apache 2.0 | Apache 2.0 | Apache 2.0 |\n\n---\n\n## Contributing\n\n```bash\ngit checkout -b feature/your-feature\npip install -r requirements.txt\n# make changes, add tests\ngit commit -m \"Add: your feature\"\ngit push origin feature/your-feature\n# open a Pull Request\n```\n\nAdding a custom strategy:\n\n```python\nfrom src.strategies.base_strategy import BaseStrategy, StrategyConfig, StrategyResult\n\nclass MyStrategy(BaseStrategy):\n    def generate_weights(self, data, **kwargs) -\u003e StrategyResult:\n        # your alpha logic — return portfolio weights\n        pass\n```\n\n---\n\n## Citation\n\n```bibtex\n@inproceedings{yang2026finrlx,\n  title     = {FinRL-X: An AI-Native Modular Infrastructure for Quantitative Trading},\n  author    = {Yang, Hongyang and Zhang, Boyu and She, Yang and Liao, Xinyu and Zhang, Xiaoli},\n  booktitle = {Proceedings of the 2nd International Workshop on Decision Making and Optimization in Financial Technologies (DMO-FinTech)},\n  year      = {2026},\n  note      = {Workshop at PAKDD 2026}\n}\n```\n\n## License\n\nApache License 2.0 — see [LICENSE](LICENSE).\n\n## Disclaimer\n\nThis software is for **educational and research purposes only**. Not financial advice. Always consult qualified professionals before making investment decisions. Past performance does not guarantee future results.\n\n---\n\n\u003cdiv align=\"center\"\u003e\n\n**[AI4Finance Foundation](https://github.com/AI4Finance-Foundation)**\n\n\u003cimg src=\"https://github.com/AI4Finance-Foundation/FinGPT/assets/31713746/e0371951-1ce1-488e-aa25-0992dafcc139\" width=\"200\"/\u003e\n\n\u003c/div\u003e\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fai4finance-foundation%2Ffinrl-trading","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fai4finance-foundation%2Ffinrl-trading","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fai4finance-foundation%2Ffinrl-trading/lists"}