Institutional-grade AI trading infrastructure — capital preservation first, risk-adjusted returns second.
data sources → feature engineering → regime detection → ensemble AI → risk engine → execution
↓ ↓
PostgreSQL ← signal log ← trade log ← portfolio snapshots ← Prometheus/Grafana dashboard
# 1. Clone and install
cd quantai
pip install -r requirements.txt
# 2. Configure environment
cp .env.example .env
# Edit .env — add Alpaca keys if desired (yfinance works without any keys)
# 3. Verify everything works
python3 smoke_test.py
# 4. Run all unit tests
python3 -m pytest tests/ -v
# 5. Start the API server
python3 start.py
# API docs at http://localhost:8000/docs
# WebSocket at ws://localhost:8000/ws| Command | Description |
|---|---|
python3 start.py |
Start FastAPI server (port 8000) |
python3 start.py --signals |
Run signal scan, print results |
python3 start.py --backtest |
Demo backtest 2023-2024 |
python3 start.py --test |
Run unit tests |
python3 smoke_test.py |
Full system smoke test |
python3 training/pipeline.py |
Train LSTM model |
# Development stack
docker compose up
# Full production stack (with GPU trainer)
docker compose --profile prod --profile gpu up
# Services:
# API → http://localhost:8000
# Dashboard → http://localhost:3000
# MLflow → http://localhost:5000
# Grafana → http://localhost:3001 (admin/quantai)
# Prometheus→ http://localhost:9090GET / Platform info
GET /health Health check
GET /portfolio Full portfolio snapshot
GET /portfolio/positions Open positions
GET /portfolio/trades Trade log
GET /signals Latest signals (all)
POST /signals/refresh Trigger fresh signal scan
POST /orders Place manual order
POST /orders/execute-signal/{sym} Execute approved signal
GET /regime/{symbol} Market regime for symbol
POST /backtest Run a backtest
GET /risk/report Portfolio risk report
GET /market/{symbol} Latest bar for symbol
WS /ws Live 2-second tick stream
GET /docs Swagger UI
quantai/
├── config/settings.py Pydantic settings (env-validated)
├── core/
│ ├── types.py Shared dataclasses (signals, verdicts, positions)
│ └── database.py Async SQLAlchemy ORM
├── data_pipeline/
│ └── market_data.py MarketDataPipeline + PaperBroker
├── feature_engineering/
│ └── features.py 84 technical/statistical/microstructure features
├── models/
│ └── lstm.py BiLSTM + attention + CNN extractor
├── regime_detection/
│ └── detector.py HMM + rule-based regime classifier (8 regimes)
├── ensemble/
│ └── decision_engine.py 5-model weighted committee vote
├── risk_management/
│ └── engine.py 4-gate sequential risk veto
├── portfolio/
│ └── manager.py Allocation, health scoring, hedging
├── inference/
│ └── signal_generator.py Full pipeline orchestrator
├── execution/
│ └── order_router.py Smart routing, retry, anti-overtrading
├── training/
│ └── pipeline.py Walk-forward LSTM trainer + Optuna HPO
├── backtesting/
│ └── engine.py Event-driven backtester + metrics suite
├── monitoring/
│ ├── metrics.py Prometheus custom metrics
│ └── prometheus.yml Scrape config
├── api/
│ └── main.py FastAPI app + WebSocket streaming
├── tests/
│ └── unit/test_core.py 24 unit tests (24/24 passing)
├── dashboard/src/App.jsx React dashboard
├── docker-compose.yml Full production stack
├── Dockerfile Container image
├── start.py CLI entrypoint
└── smoke_test.py System integration test
| Control | Limit | Location |
|---|---|---|
| Daily loss circuit breaker | 2% NAV | risk_management/engine.py |
| Max position size | 5% NAV | risk_management/engine.py |
| Max sector exposure | 25% NAV | portfolio/manager.py |
| Portfolio VaR limit | 1.5% (95%, 1d) | risk_management/engine.py |
| Max drawdown halt | 15% | risk_management/engine.py |
| Min signal confidence | 60% | ensemble/decision_engine.py |
| Min model agreement | 3/5 models | ensemble/decision_engine.py |
| Min reward:risk | 1.5x | risk_management/engine.py |
| Kelly fraction | 0.5 (half-Kelly) | risk_management/engine.py |
| Order cooldown | 5 min/symbol | execution/order_router.py |
bullish · bearish · sideways · accumulation · distribution · panic_volatility · low_liquidity · macro_uncertain
Each regime dynamically adjusts: ensemble weights, ATR stop multipliers, position sizing, invested capital %.
- Trend model: Bidirectional LSTM (3-layer) + temporal attention pooling + MC-Dropout uncertainty
- CNN extractor: Dilated causal TCN for local candlestick pattern features
- Training: Walk-forward cross-validation, early stopping, AdamW + cosine LR schedule
- Validation: Auto-rollback if OOS directional accuracy < 52%
- HPO: Optuna integration in
training/pipeline.py
- yfinance — free historical OHLCV (works out-of-the-box, no API key)
- Alpaca — paper/live broker + real-time streaming (optional)
- Polygon.io — professional market data (optional)
- Finnhub — news + sentiment (optional)
See .env.example for full list. Minimum required for paper trading:
PAPER_TRADING=true
DATABASE_URL=sqlite+aiosqlite:///./quantai.db
SECRET_KEY=<any-random-string>
- Add a new model: implement
generate(df, model_name, regime) -> ModelSignalinensemble/decision_engine.py - Add a broker: subclass
BrokerAdapterindata_pipeline/market_data.py - Add features: add methods to
FeatureEngineerinfeature_engineering/features.py - Add a regime: extend
Regimeenum incore/types.pyand add rule inregime_detection/detector.py
| Phase | Feature |
|---|---|
| v1.1 | Live Alpaca order execution |
| v1.2 | TFT (Temporal Fusion Transformer) model |
| v1.3 | Sentiment engine via Finnhub NLP |
| v2.0 | PPO reinforcement learning agent as 6th ensemble member |
| v2.1 | Options Greeks-aware position sizing |
| v3.0 | Cross-market regime transfer learning |
Design principle: Every trade decision is a committee vote. No single model, indicator, or signal has unilateral authority over capital. The risk engine has absolute veto power — it is the last line of defence before any order touches the market.