Spaces:
Running
Running
| title: Quant AI - Advanced Quant Trading Engine & Backtest Simulator | |
| emoji: ๐ | |
| colorFrom: blue | |
| colorTo: indigo | |
| sdk: docker | |
| app_port: 7860 | |
| pinned: false | |
| # Quant.ai - Advanced Quant Trading Engine & Backtest Simulator | |
| <p align="center"> | |
| <img src="https://img.shields.io/badge/Python-3.8%2B-blue.svg" alt="Python Version" /> | |
| <img src="https://img.shields.io/badge/FastAPI-v0.95%2B-009688.svg" alt="FastAPI" /> | |
| <img src="https://img.shields.io/badge/React-v18-61dafb.svg" alt="React" /> | |
| <img src="https://img.shields.io/badge/Vite-v4-646cff.svg" alt="Vite" /> | |
| <img src="https://img.shields.io/badge/License-MIT-green.svg" alt="License" /> | |
| </p> | |
| Quant.ai is a production-ready, fully-automated stock trading engine and interactive backtest simulator. Built with a Python FastAPI backend and a React (Vite) frontend, it features real-time K-line pattern recognition, dynamic market regime routing, ATR-based risk sizing, and out-of-sample walk-forward optimization. | |
| <p align="center"> | |
| <img src="assets/desktop_terminal.png" width="100%" alt="Quant.ai Desktop Trading Terminal" /> | |
| </p> | |
| --- | |
| ## ๐ Key Features | |
| ### 1. ๐ Advanced K-Line Feature & Pattern Recognition | |
| - **12 K-Line Numerical Features**: Computes body ratio, upper/lower shadow ratios, gaps, relative volume (RVOL), and trend context dynamically. | |
| - **22 Quantifiable Candlestick Patterns**: Vectorized detection for patterns like Hammer, Shooting Star, Bullish/Bearish Engulfing, Piercing, Dark Cloud Cover, Morning/Evening Star, Three White Soldiers, Rising/Falling Three Methods, Gap Breakout, Exhaustion Gaps, and Neckline breakouts for W-Bottoms and M-Tops. | |
| ### 2. ๐ฆ Dynamic Market Regime Router | |
| - Dynamically classifies the market into four regimes: | |
| - `trend_up`: Strong bullish trend. Activates trend-following strategies (Donchian breakout, EMA crossover). | |
| - `trend_down`: Bearish trend. Suspends buy operations and goes into defense. | |
| - `high_volatility`: Extreme volatility (ATR/Close in top 10%). Enforces cash preservation. | |
| - `range_bound`: Oscillating market. Activates mean reversion (Bollinger Bands oversold) and candlestick reversals. | |
| ### 3. ๐ก๏ธ Institutional-Grade Multi-Layer Risk Control | |
| - **ATR-Based Sizing**: Calculates trade size based on account equity, ATR stop-distance, and risk percentage. | |
| - **Soft Drawdown Limit (7%) & Consecutive Losses (5)**: Triggers a 50% reduction in position size. | |
| - **Hard Drawdown Limit (12%)**: Temporarily locks the trading engine (risk multiplier goes to 0) to prevent capital blowups. | |
| ### 4. ๐ Walk-Forward Parameter Optimization | |
| - Features a rolling optimization pipeline (`walk_forward.py`) that divides history into training and test intervals. | |
| - Optimizes parameters (strategy mode, ATR multiplier, RSI) by maximizing the drawdown-penalized net profit (Calmar-like metric) and validates performance out-of-sample. | |
| ### 5. ๐ Market Open Focus & Opening Range Breakout (ORB) Strategy | |
| - **Market Open Focus Mode**: Targets the high-volatility market opening (09:30 - 10:15 EST). Restricts buying to this high-momentum window and performs a force liquidation at 10:30 EST to protect capital from the midday choppy sideways trend. | |
| - **Opening Range Breakout (ORB)**: Precomputes the opening high and low from the first 5 minutes of regular hours (09:30 - 09:35 EST) and triggers high-probability breakout buys on high volume (RVOL > 1.2), using the opening range low as a hard failure stop-loss. | |
| ### 6. ๐ค AI Auto-Pilot Parameter Tuning (ๆบ่ฝๆ็ฎก) | |
| - Dynamically grid-searches strategy settings over the recent 5 days of 1-minute bar data for the selected ticker. | |
| - Optimizes for the best risk-adjusted performance (Sharpe ratio and max drawdown mitigation) and automatically applies parameters to the active trading dashboard. | |
| ### 7. ๐ฌ Historical Replay Mode (ๅๅฒๅผ็ๅค็ๆจกๆๅจ) | |
| - **Granular 1m Simulation**: Allows developers and traders to replay the market open sequence step-by-step for any trading day within the last 5 days. | |
| - **Interactive Controls**: Supports Play, Pause, Single-Step tick progression, Reset, and speed tuning (with simulated intervals down to 50ms per bar). | |
| - **Synchronized Portfolio updates**: Portfolio equity, cash, holdings, and transactions update dynamically on each step to observe execution points. | |
| ### 8. ๐ Intraday Trade Inspector (ๆฅๅ ๆไบค็ฒพ็ปๅ้่ง) | |
| - **High-Frequency Audit**: In daily backtests, clicking any ledger row fetches the 1-minute candlestick data for the execution date and overlays the exact BUY/SELL orders at the market open (9:30 AM EST). | |
| - **Auto-scroll focus**: In intraday/1m backtests, clicking any ledger row centers the main chart's time axis precisely on the selected transaction bar. | |
| --- | |
| ## ๐ Project Structure | |
| ```text | |
| โโโ backend/ | |
| โ โโโ app/ | |
| โ โ โโโ config.py # Trade and risk configurations | |
| โ โ โโโ data_manager.py # YFinance data loading, technical indicators, and regimes | |
| โ โ โโโ patterns.py # 22 K-line patterns and W-Bottom/M-Top detection | |
| โ โ โโโ strategy.py # Strategy routing and evaluation | |
| โ โ โโโ simulator.py # Universal backtesting simulator | |
| โ โ โโโ trading_engine.py # Portfolio ledger, execution, and risk gates | |
| โ โโโ main.py # CLI Backtest interface | |
| โ โโโ main_api.py # FastAPI REST Server | |
| โ โโโ walk_forward.py # Walk-Forward rolling optimization engine | |
| โโโ frontend/ # React Vite dashboard with TradingView charts | |
| โโโ README.md | |
| ``` | |
| --- | |
| ## ๐ ๏ธ Installation & Getting Started | |
| ### Prerequisites | |
| - Python 3.8+ | |
| - Node.js 16+ | |
| ### 1. Backend Setup | |
| Navigate to the root directory and install dependencies: | |
| ```bash | |
| pip install pandas numpy yfinance fastapi uvicorn pydantic | |
| ``` | |
| Run a CLI backtest simulation: | |
| ```bash | |
| # Run minute-level day trading simulation for TSLA | |
| python backend/main.py --ticker TSLA --period 5d --interval 1m | |
| # Run daily-level swing trading simulation for TSLA | |
| python backend/main.py --ticker TSLA --period 1y --interval 1d | |
| ``` | |
| Run Walk-Forward rolling parameter optimization: | |
| ```bash | |
| python backend/walk_forward.py --ticker TSLA --period 1y --interval 1d | |
| ``` | |
| Start the FastAPI API server: | |
| ```bash | |
| python backend/main_api.py | |
| ``` | |
| ### 2. Frontend Setup | |
| Navigate to the frontend folder, install dependencies, and start the development server: | |
| ```bash | |
| cd frontend | |
| npm install | |
| npm run dev | |
| ``` | |
| --- | |
| ## ๐ Backtest Indicators & Performance | |
| Our universal backtest simulator calculates standard trading metrics including: | |
| - **Net PnL & Return Percentage** | |
| - **Max Account Equity Drawdown** | |
| - **Win Rate & Round Trip Trade Count** | |
| - **Transaction Commission and Slippage Friction Cost** | |
| - **Market Regime Distributions** | |
| --- | |
| ## ๐ License & Disclaimer | |
| This software is provided for educational and research purposes only. Algorithmic trading carries substantial risk, and past performance is not indicative of future results. | |