Institutional-grade quantitative trading โข Multi-factor alpha โข Regime-adaptive exposure
Beat the market when it crashes. Keep up when it soars.
Get Started โข Documentation โข Performance โข How It Works
| ๐ฏ Sharpe Optimized | ๐ Cross-Asset | ๐ญ Regime Blend | ๐ Buy & Hold | |
|---|---|---|---|---|
| Period | 19 Years | 19 Years | 5 Years | 19 Years |
| Total Return | +1806% | +348% | +317% | +5638% |
| Sharpe Ratio | 0.97 | 0.93 | 0.98 | 0.87 |
| Max Drawdown | 35.4% | 14.8% | 45.5% | 56.4% |
| Sortino | 1.24 | 1.25 | 1.48 | 1.19 |
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ CROSS-ASSET MULTI-REGIME PERFORMANCE (2006-2024) โ
โ Including 2008 Financial Crisis โ
โ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโฃ
โ โ
โ ๐ BULL Markets (12%) โโโโโโโโโโโโโโโโโโโโโโโโ +13.1% โ
โ Avg Return per Period: +0.19% โ
โ โ
โ ๐ SIDEWAYS (61%) โโโโโโโโโโโโโโโโโโโโโโโโ +68.5% โ
โ Avg Return per Period: +0.46% | Primary driver โ
โ โ
โ โก HIGH VOL (8%) โโโโโโโโโโโโโโโโโโโโโโโโ +22.8% โ
โ Avg Return per Period: +0.39% โ
โ โ
โ ๐ป BEAR Markets (19%) โโโโโโโโโโโโโโโโโโโโโโโโ +51.8% โ
โ ๐ POSITIVE returns during crises! (incl. 2008) โ
โ โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
# Clone & enter
git clone https://github.com/blackms/FinRL-Adaptive.git && cd FinRL-Adaptive
# Setup (30 seconds)
python3 -m venv venv && source venv/bin/activate && pip install -r requirements.txt
# Run cross-asset diversified backtest ๐ (recommended - Sharpe 0.93)
python3 scripts/advanced_sharpe_backtest.py
# Or run Sharpe-optimized regime blend ๐ฏ (Sharpe 0.97)
python3 scripts/sharpe_optimized_backtest.py
# Or run original regime blend backtest ๐ญ
python3 scripts/regime_blend_backtest.py๐บ See it in action
================================================================================
ADVANCED CROSS-ASSET SHARPE-OPTIMIZED BACKTEST
================================================================================
Configuration:
Equities: AAPL, MSFT, AMZN, JPM, JNJ, XOM, PG, KO, WMT, IBM
Bonds: TLT, IEF
Commodities: GLD
International: EFA
Period: 2006-01-01 to 2024-12-31 (19 Years)
Capital: $100,000
================================================================================
BACKTEST RESULTS
================================================================================
Strategy Return Sharpe Max DD Vol
----------------------------------------------------------------------
Cross-Asset Regime +348.32% 0.93 14.80% 8.93%
Diversified B&H +3440.83% 0.96 39.07% 21.52%
Equity B&H +5638.49% 0.87 56.43% 27.44%
================================================================================
REGIME-SPECIFIC PERFORMANCE (Positive in ALL regimes!)
================================================================================
Regime Periods Total Return Avg Return
--------------------------------------------------------
bull_trending 68 +13.1% +0.19%
bear_crisis 107 +51.8% +0.48% ๐
sideways_neutral 149 +68.5% +0.46%
high_volatility 59 +22.8% +0.39%
================================================================================
KEY ACHIEVEMENT: +51.8% during Bear Markets (including 2008 Crisis)
================================================================================
flowchart LR
A[๐ Multi-Asset Data] --> B[๐ญ Regime Detector]
B --> C{๐ก๏ธ Regime?}
C -->|๐ Bull| D[Equities 75%]
C -->|๐ป Bear| E[Bonds 35% + Gold 25%]
C -->|๐ Sideways| F[Equities 70% + Bonds 18%]
C -->|โก High Vol| G[Gold 15% + Bonds 30%]
D & E & F & G --> H[๐ Factor Selection]
H --> I[โ๏ธ Risk Parity]
I --> J[๐ฏ Portfolio]
|
4 Market Regimes detected using ensemble indicators:
|
Multi-factor ranking for stock selection: # Factor weights (Z-score normalized)
MOMENTUM: 40% # 12-1 month returns
LOW_VOL: 35% # Inverse volatility
REVERSAL: 25% # Short-term mean reversion
# Cross-asset allocation
equities + bonds + gold + international
Risk parity weighting within each |
๐ญ Level 1: System Context - The Big Picture
C4Context
title System Context Diagram - FinRL Adaptive Trading System
Person(trader, "Quant Trader", "Runs backtests, trains models, analyzes regime performance")
Person(researcher, "Research Analyst", "Develops strategies, optimizes regime thresholds")
System(finrl, "FinRL Adaptive", "Regime-aware quantitative trading system with dynamic strategy blending across Bull/Bear/Sideways/HighVol markets")
System_Ext(yahoo, "Yahoo Finance", "Historical OHLCV market data")
System_Ext(broker, "Broker API", "Live trading execution (future)")
Rel(trader, finrl, "Runs regime backtests, analyzes regime-specific alpha")
Rel(researcher, finrl, "Optimizes regime detection, tunes strategy weights")
Rel(finrl, yahoo, "Fetches historical data", "REST API")
Rel(finrl, broker, "Executes regime-aware trades", "REST API")
UpdateLayoutConfig($c4ShapeInRow="2", $c4BoundaryInRow="1")
๐ฆ Level 2: Container Diagram - Inside the System
C4Container
title Container Diagram - FinRL Adaptive
Person(trader, "Quant Trader", "Power user")
System_Boundary(finrl, "FinRL Adaptive") {
Container(cli, "CLI Interface", "Python/Click", "Regime blend backtest, HF backtest, RL training")
Container(backtest, "Backtest Engine", "Python", "Walk-forward validation, regime-aware analytics")
Container(regime, "Regime Engine", "Python", "4-regime detection: Bull/Bear/Sideways/HighVol")
Container(blender, "Strategy Blender", "Python", "Dynamic strategy weighting by regime")
Container(strategies, "Strategy Engine", "Python", "Momentum, Adaptive HF, Market Neutral")
Container(rl, "RL Environment", "Gymnasium/SB3", "Training environment for PPO, SAC, A2C, DDPG, TD3")
Container(data, "Data Layer", "Python/Pandas", "Market data fetching, caching, preprocessing")
ContainerDb(cache, "Data Cache", "Parquet Files", "Cached OHLCV data")
ContainerDb(results, "Results Store", "JSON/PNG", "Backtest results, visualizations")
}
System_Ext(yahoo, "Yahoo Finance", "Market data provider")
Rel(trader, cli, "Runs regime_blend_backtest.py")
Rel(cli, backtest, "Triggers backtests")
Rel(backtest, regime, "Detects market regime")
Rel(regime, blender, "Provides regime state")
Rel(blender, strategies, "Weights strategy signals")
Rel(strategies, data, "Requests market data")
Rel(backtest, results, "Stores metrics")
Rel(data, yahoo, "Fetches data", "yfinance")
Rel(data, cache, "Reads/writes cache")
UpdateLayoutConfig($c4ShapeInRow="3", $c4BoundaryInRow="1")
๐ง Level 3: Component Diagram - Strategy Engine Deep Dive
C4Component
title Component Diagram - Strategy Engine
Container_Boundary(strategies, "Strategy Engine") {
Component(blender, "Strategy Blender", "Python Class", "Dynamic regime-weighted strategy allocation")
Component(hedge_fund, "HedgeFundStrategy", "Python Class", "Momentum/factor-based adaptive strategy")
Component(factors, "Factor Calculator", "Python Module", "Momentum, Value, Quality, Low Vol factors")
Component(regime, "Regime Detector", "Python Module", "4-regime: Bull/Bear/Sideways/HighVol")
Component(portfolio, "Portfolio Constructor", "Python Module", "Risk parity, volatility targeting")
Component(risk, "Risk Manager", "Python Module", "Position limits, exposure constraints")
Component(costs, "Cost Model", "Python Module", "Commission, slippage, borrow costs")
}
Container(backtest, "Backtest Engine", "Python", "Orchestrates strategy execution")
Container(data, "Data Layer", "Python", "Provides OHLCV data")
Rel(backtest, blender, "Runs blended strategy")
Rel(blender, regime, "Gets current regime")
Rel(blender, hedge_fund, "Allocates to strategies")
Rel(hedge_fund, factors, "Calculates alpha scores")
Rel(hedge_fund, portfolio, "Constructs portfolio")
Rel(portfolio, risk, "Applies constraints")
Rel(hedge_fund, costs, "Calculates transaction costs")
Rel(factors, data, "Uses price history")
Rel(regime, data, "Analyzes trends/volatility")
UpdateLayoutConfig($c4ShapeInRow="3", $c4BoundaryInRow="1")
โก Trading Flow Sequence - How Trades Happen
sequenceDiagram
autonumber
participant CLI as ๐ฅ๏ธ CLI
participant BE as ๐ Backtest Engine
participant SB as ๐ญ Strategy Blender
participant RD as ๐ก๏ธ Regime Detector
participant HF as ๐ง Hedge Fund Strategy
participant FC as ๐ Factor Calculator
participant PC as โ๏ธ Portfolio Constructor
participant RM as ๐ก๏ธ Risk Manager
CLI->>BE: Run backtest(config)
BE->>BE: Load historical data
loop Each Trading Day
BE->>SB: Process day(prices)
alt Rebalance Day
SB->>RD: Detect regime(history)
RD-->>SB: Bull/Bear/Sideways/HighVol
SB->>SB: Get regime weights
SB->>HF: Calculate strategy signals
HF->>FC: Calculate factors(history)
FC-->>HF: Factor scores
HF-->>SB: Strategy allocation
SB->>PC: Construct portfolio(blended_weights, regime)
PC->>RM: Apply constraints(weights)
RM-->>PC: Adjusted weights
PC-->>SB: Final portfolio
SB->>SB: Calculate transaction costs
SB-->>BE: New positions
end
BE->>BE: Update portfolio value
end
BE-->>CLI: Performance metrics
๐ค RL Training Architecture - How Agents Learn
flowchart TB
subgraph Environment["๐ฎ Trading Environment (Gymnasium)"]
STATE["State Vector<br/>โโโโโโโโโโโโโโ<br/>โข Cash balance<br/>โข Stock holdings<br/>โข Current prices<br/>โข Technical indicators"]
ACTION["Action Space<br/>โโโโโโโโโโโโโโ<br/>Continuous [-1, 1]<br/>per stock<br/>(sell โ buy)"]
REWARD["Reward Function<br/>โโโโโโโโโโโโโโ<br/>Portfolio value<br/>change ร scaling"]
end
subgraph Agent["๐ง RL Agent (Stable-Baselines3)"]
POLICY["Policy Network<br/>โโโโโโโโโโโโโโ<br/>MLP: 64โ64โactions"]
VALUE["Value Network<br/>โโโโโโโโโโโโโโ<br/>MLP: 64โ64โ1"]
BUFFER["Replay Buffer<br/>โโโโโโโโโโโโโโ<br/>(s, a, r, s', done)"]
end
subgraph Training["๐ Training Loop"]
SAMPLE["Sample batch"]
UPDATE["Update networks"]
EXPLORE["Explore vs Exploit"]
end
STATE --> POLICY
POLICY --> ACTION
ACTION --> REWARD
REWARD --> BUFFER
BUFFER --> SAMPLE
SAMPLE --> UPDATE
UPDATE --> POLICY
UPDATE --> VALUE
EXPLORE --> POLICY
style Environment fill:#1a1a2e,stroke:#16213e,color:#fff
style Agent fill:#0f3460,stroke:#16213e,color:#fff
style Training fill:#533483,stroke:#16213e,color:#fff
๐ Data Flow Architecture - From Market to Alpha
flowchart LR
subgraph External["๐ External"]
YAHOO["Yahoo Finance<br/>API"]
end
subgraph DataLayer["๐ Data Layer"]
FETCH["Fetcher<br/>โโโโโโโโ<br/>yfinance"]
CACHE["Cache<br/>โโโโโโโโ<br/>.parquet"]
PREP["Preprocessor<br/>โโโโโโโโ<br/>Normalize<br/>Add indicators"]
end
subgraph RegimeEngine["๐ญ Regime Engine"]
TREND["Trend Analysis<br/>โโโโโโโโ<br/>SMA signals<br/>ADX strength"]
VOLAT["Volatility<br/>โโโโโโโโ<br/>Rolling std<br/>VIX proxy"]
CLASS["Classifier<br/>โโโโโโโโ<br/>Bull/Bear/<br/>Sideways/HighVol"]
end
subgraph FactorEngine["๐งฎ Factor Engine"]
MOM["Momentum<br/>โโโโโโโโ<br/>60d return"]
QUAL["Quality<br/>โโโโโโโโ<br/>Rยฒ ร pos%"]
VOL["Low Vol<br/>โโโโโโโโ<br/>1/ฯ"]
end
subgraph Blender["โ๏ธ Strategy Blender"]
WEIGHTS["Regime<br/>Weights<br/>โโโโโโโโ<br/>Dynamic<br/>allocation"]
BLEND["Blend<br/>Signals<br/>โโโโโโโโ<br/>Weighted<br/>composite"]
end
subgraph Portfolio["๐ผ Portfolio"]
ALLOC["Portfolio<br/>Allocation"]
RISK["Risk<br/>Constraints"]
end
YAHOO --> FETCH
FETCH <--> CACHE
FETCH --> PREP
PREP --> TREND & VOLAT
TREND & VOLAT --> CLASS
PREP --> MOM & QUAL & VOL
CLASS --> WEIGHTS
MOM & QUAL & VOL --> BLEND
WEIGHTS --> BLEND
BLEND --> ALLOC
ALLOC --> RISK
style External fill:#e74c3c,stroke:#c0392b,color:#fff
style DataLayer fill:#3498db,stroke:#2980b9,color:#fff
style RegimeEngine fill:#e67e22,stroke:#d35400,color:#fff
style FactorEngine fill:#9b59b6,stroke:#8e44ad,color:#fff
style Blender fill:#1abc9c,stroke:#16a085,color:#fff
style Portfolio fill:#f39c12,stroke:#d68910,color:#fff
Train AI agents that learn to trade. Five algorithms, one goal: alpha.
# Train a PPO agent (recommended)
python scripts/train_rl_agent.py --algorithm ppo --timesteps 100000
# Or try others
python scripts/train_rl_agent.py --algorithm sac --timesteps 200000| Algorithm | Type | Best For |
|---|---|---|
| PPO | On-Policy | Stable training, great baseline |
| A2C | On-Policy | Fast iteration |
| SAC | Off-Policy | Sample efficiency |
| DDPG | Off-Policy | Continuous actions |
| TD3 | Off-Policy | Reduced overestimation |
FinRL-Adaptive/
โ
โโโ ๐ง src/trading/
โ โโโ strategies/
โ โ โโโ hedge_fund.py # โญ Adaptive hedge fund
โ โ โโโ momentum.py # ๐ Trend following
โ โ โโโ regime_detector.py # ๐ญ Market regime detection
โ โ โโโ strategy_blender.py # ๐ Dynamic blending
โ โ โโโ multi_regime_system.py # ๐ Multi-regime orchestrator
โ โ โโโ enhanced_bear_system.py # ๐ Inverse ETF strategies
โ โ โโโ enhanced_risk_manager.py# ๐ VIX-based risk management
โ โ โโโ ensemble.py # ๐ญ Multi-strategy
โ โโโ backtest/ # ๐ Time machine
โ โโโ data/ # ๐ Market data
โ โโโ rl/ # ๐ค AI environment
โ
โโโ ๐ scripts/
โ โโโ advanced_sharpe_backtest.py # ๐ Cross-asset + factors (Sharpe 0.93)
โ โโโ sharpe_optimized_backtest.py # ๐ฏ Sharpe-optimized (0.97)
โ โโโ regime_blend_backtest.py # ๐ญ Regime-aware backtest
โ โโโ hedge_fund_backtest.py # Run HF strategy
โ โโโ train_rl_agent.py # Train AI agents
โ โโโ optimize_strategy.py # Find best params
โ
โโโ ๐ docs/
โ โโโ adaptive_hedge_fund_strategy.md # HF deep dive
โ โโโ regime_blend_architecture.md # ๐ญ Regime system design
โ
โโโ ๐ output/
โ โโโ advanced_sharpe_results.json # ๐ Cross-asset results
โ โโโ sharpe_optimized_results.json # ๐ Optimized results
โ โโโ regime_blend_results.json # Regime blend results
โ
โโโ ๐งช tests/ # 38+ validity tests
| Period | Market | Strategy | Buy & Hold | Alpha | Verdict |
|---|---|---|---|---|---|
| 2020 Q4 โ 2021 Q1 | ๐ Bull | +0.23% | +4.57% | -4.35% | ๐ |
| 2021 Q4 โ 2022 Q1 | ๐ Transition | +1.54% | -9.99% | +11.52% | ๐ |
| 2022 Q2 | ๐ป Bear | +10.32% | -21.70% | +32.02% | ๐๐ |
| 2022 Q3 | ๐ป Bear | -2.20% | -5.59% | +3.40% | ๐ |
| 2023 Q3 | ๐ Pullback | +13.77% | -2.87% | +16.65% | ๐ |
| 2024 Q1 | ๐ Bull | +21.34% | +12.53% | +8.82% | ๐ |
Win Rate: 47% โข Average Alpha in Down Markets: +15.6%
"Be fearful when others are greedy, and greedy when others are fearful."
- Multi-factor alpha model
- Regime-adaptive exposure
- Walk-forward validation
- RL integration (5 algorithms)
- Transaction cost modeling
- Regime Blend Strategy - Dynamic multi-strategy blending
- Optimized Regime Detection - 4 regimes with ensemble indicators
- Backtest Validity Tests - 38 tests for correctness
- Cross-Asset Validation - ETFs, bonds, commodities
- ๐ Cross-Asset Diversification - Equities, bonds (TLT/IEF), gold (GLD), international (EFA)
- ๐ Factor-Based Selection - Momentum 12-1, Low Volatility, Short-term Reversal
- ๐ VIX-Based Risk Management - Leading indicator for bear detection
- ๐ Enhanced Bear System - Inverse ETF strategies with decay modeling
- ๐ Multi-Regime Orchestrator - Bull/Bear/Sideways/HighVol specialized systems
- ๐ Sharpe Optimization - Achieved 0.93 Sharpe with 14.8% max drawdown
- Live trading integration
- Web dashboard
- Options overlay
- Crypto support
- Sentiment analysis
We love contributions! Whether it's:
- ๐ Bug fixes
- โจ New features
- ๐ Documentation
- ๐งช Tests
Just open a PR. Let's build the future of quant trading together.
MIT License - Go wild. Build something amazing.
This software is for educational and research purposes only.
Not financial advice. Past performance โ future results.
Trading involves substantial risk of loss.
If this helped you, drop a โญ