This project provides a comprehensive Python-based framework for backtesting and analyzing sophisticated quantitative trading strategies. Built around the powerful Backtrader engine, it offers multiple interfaces for strategy development, testing, and portfolio analysis:
- π Individual Strategy Execution: Direct strategy scripts for focused testing and development
- π₯οΈ Command-Line Tool (
main.py): Advanced CLI with interactive HTML reporting - π Web Application (
app_server.py): Browser-based interface with real-time backend processing
- π€ AI-Powered Trading Strategies with Transformer and LSTM models
- π Advanced Portfolio Management with dual-asset cerebro implementation
- π Interactive Visualization with mouse-hover charts and real-time data display
- β‘ Asynchronous Processing for non-blocking web-based backtesting
- π¨ Professional HTML Reports with Lightweight Chartsβ’ integration
- π Modular Strategy System for easy development and testing
The platform supports three distinct execution modes, each optimized for different use cases:
# Run individual strategies directly for development and testing
python src/strategies/dual_asset_strategy.py
python src/strategies/transformer_signal_strategy.py
python src/strategies/lstm_signal_strategy.pyFeatures:
- β Dual Asset Portfolio Trading - EURUSD + USDCHF with independent cerebro instances
- β Interactive Charts - Mouse hover with real-time price/date display
- β Portfolio Aggregation - Combined performance analysis and risk metrics
- β AI Trading Integration - Pre-trained Transformer and LSTM models
- β Advanced Risk Management - Drawdown analysis, Sharpe ratios, win rates
# Generate comprehensive HTML reports with advanced visualizations
python main.py --plot --fromdate 2023-01-01 --strat "p_fast_d0=15"Features:
- π Self-Contained HTML Reports - Portable analysis with embedded charts
- π¨ Lightweight Chartsβ’ Integration - Professional-grade financial visualizations
- βοΈ Advanced Parameter Control - Full strategy customization via CLI arguments
- π Comprehensive Analytics - Trade analysis, performance metrics, indicators
# Launch interactive web-based backtesting platform
python src/app_server.pyFeatures:
- π Browser-Based Interface - Easy access via http://127.0.0.1:5000/
- β‘ Asynchronous Backend - Non-blocking processing with SQLite task management
- π Dynamic Configuration - Real-time parameter adjustment and strategy selection
- π Statistical Reporting - Detailed numerical analysis and performance metrics
π¦ quant_bot_project/
β£ π src/ # Core application modules
β β£ π app_server.py # π Flask web server & API endpoints
β β£ π worker.py # β‘ Background async task processor
β β£ π database.py # ποΈ SQLite database management
β β£ π train_transformer.py # π€ ML model training pipeline
β β£ π strategies/ # π Trading strategy implementations
β β β£ π dual_asset_strategy.py # π― EURUSD+USDCHF portfolio system
β β β£ π transformer_signal_strategy.py # π€ AI Transformer trading
β β β£ π lstm_signal_strategy.py # π§ LSTM neural network strategy
β β β£ π macd_signal_strategy.py # π Technical analysis strategies
β β β π ... (additional strategies)
β β£ π ml_models/ # π€ Trained model artifacts (.pth, .pkl)
β β£ π visualization/ # π Chart generation & HTML reports
β β β£ π web_plotter.py # π¨ Lightweight Chartsβ’ integration
β β β π report_template.html # π HTML report template
β β£ π backtesting/ # βοΈ Core backtest execution engine
β β β π runner.py # π Backtrader integration layer
β β£ π utils/ # π οΈ Utility functions & helpers
β β β π serialization.py # πΎ JSON serialization utilities
β β π templates/ # π Web interface templates
β β π index.html # π₯οΈ Main web application UI
β£ π main.py # π₯οΈ CLI entry point & report generator
β£ π data/ # π Financial data files (CSV format)
β£ π requirements.txt # π¦ Python dependencies specification
β π README.MD # π Project documentation (this file)
- Python 3.8+ (Tested with Python 3.8-3.11)
- Minimum 4GB RAM (Recommended 8GB+ for ML strategies)
- Windows/Linux/macOS (Cross-platform compatible)
# 1. Clone the repository
git clone <your-repo-url>
cd quant_bot_project
# 2. Install all dependencies
pip install -r requirements.txt
# 3. Verify installation by running a strategy
python src/strategies/dual_asset_strategy.py# Interactive dual-asset portfolio with EURUSD + USDCHF
python src/strategies/dual_asset_strategy.py
# AI-powered Transformer strategy
python src/strategies/transformer_signal_strategy.py
# LSTM neural network strategy
python src/strategies/lstm_signal_strategy.py# Basic report generation
python main.py --plot
# Advanced parameter customization
python main.py --plot --fromdate 2023-01-01 --todate 2023-12-31 --strat "p_fast_d0=15,p_slow_d0=30"# Start web server
python src/app_server.py
# Open browser to http://127.0.0.1:5000/# Train Transformer model for time series prediction
python src/train_transformer.py
# Models are saved to src/ml_models/ directory# Use pre-trained Transformer model for trading signals
python src/strategies/transformer_signal_strategy.py
# LSTM neural network strategy with technical indicators
python src/strategies/lstm_signal_strategy.py# Run comprehensive dual-asset portfolio analysis
python src/strategies/dual_asset_strategy.pyKey Features:
- β Independent Cerebro Instances - Separate strategy execution per asset
- β Portfolio Aggregation - Combined performance and risk analysis
- β Interactive Charts - Mouse hover with real-time data display
- β Risk Metrics - Sharpe ratio, drawdown analysis, win rates
# Generate interactive HTML report with default parameters
python main.py --plot# Custom date range and strategy parameters
python main.py --plot --fromdate 2023-01-01 --todate 2023-12-31 --strat "p_fast_d0=15,p_slow_d0=30"
# Multiple data files and custom cash
python main.py --plot --data "EURUSD_1h.csv,USDCHF_1h.csv" --cash 50000CLI Arguments:
--plot- Generate HTML report with Lightweight Chartsβ’--fromdate/--todate- Date range (YYYY-MM-DD format)--strat- Strategy parameters (comma-separated)--data- Data file names (supports multiple files)--cash- Initial capital amount
# Launch Flask web application
python src/app_server.py- Access: Open browser to
http://127.0.0.1:5000/ - Configure: Select data files, date ranges, and strategy parameters
- Execute: Start backtest with asynchronous processing
- Analyze: View detailed statistical reports and performance metrics
Web Features:
- π Browser-Based UI - No command-line required
- β‘ Asynchronous Processing - Non-blocking backtests
- π Dynamic Configuration - Real-time parameter adjustment
- π Statistical Analysis - Comprehensive numerical reports
This platform includes sophisticated AI-powered trading strategies with pre-trained models:
- Model: Attention-based architecture for financial time series prediction
- Training Data: EUR/USD 5-minute timeframe with technical indicators
- Usage:
python src/strategies/transformer_signal_strategy.py - Research Repository: Applied ML Trading Transformer for EUR/USD
- Model: Recurrent neural networks optimized for sequential financial data
- Features: Multi-timeframe analysis with technical indicator integration
- Usage:
python src/strategies/lstm_signal_strategy.py
# Template for new strategy development
from backtrader import Strategy
import backtrader.indicators as btind
class MyCustomStrategy(Strategy):
params = (
('period', 14),
('threshold', 0.02),
)
def __init__(self):
self.indicator = btind.RSI(period=self.params.period)
def next(self):
if self.indicator > (100 - self.params.threshold):
self.sell()
elif self.indicator < self.params.threshold:
self.buy()- Place strategy file in
src/strategies/directory - The system automatically discovers and integrates new strategies
- Parameters become available in both CLI and web interfaces
# Expected CSV format for financial data
Date,Open,High,Low,Close,Volume
2023-01-01 00:00:00,1.0350,1.0365,1.0340,1.0355,1500
2023-01-01 01:00:00,1.0355,1.0370,1.0345,1.0360,1750
- Memory Management: Use
--maxcpusfor parallel processing - Data Sampling: Configure date ranges to limit computational load
- Model Caching: ML models are cached to avoid retraining
- Async Processing: Web interface uses background workers for responsiveness
- Sharpe Ratio: Risk-adjusted return calculation
- Maximum Drawdown: Peak-to-trough decline analysis
- Win Rate: Percentage of profitable trades
- Profit Factor: Gross profit vs gross loss ratio
- Fixed Size: Constant position sizing across trades
- Percentage Risk: Position sizing based on account percentage
- Volatility Adjusted: Dynamic sizing based on market volatility
# Ensure all dependencies are installed
pip install -r requirements.txt --upgrade
# Check Python version compatibility
python --version # Should be 3.8+# Reduce model complexity or data range
python src/strategies/transformer_signal_strategy.py --fromdate 2023-06-01# Use alternative port if 5000 is occupied
python src/app_server.py --port 8080- CPU Usage: Monitor during backtests with
htopor Task Manager - Memory Usage: ML strategies require 4GB+ RAM for optimal performance
- Disk Space: HTML reports and model artifacts require storage space
# Production environment setup
python -m venv production_env
source production_env/bin/activate # Linux/macOS
# OR
production_env\Scripts\activate # Windows
pip install -r requirements.txt# Production server with Gunicorn (Linux/macOS)
pip install gunicorn
gunicorn -w 4 -b 0.0.0.0:5000 src.app_server:app
# Windows deployment with Waitress
pip install waitress
waitress-serve --port=5000 src.app_server:app- Time Series Transformer Research: Applied ML Trading Transformer for EUR/USD
- Backtrader Documentation: Official Backtrader Docs
- Technical Analysis: TA-Lib Integration Guide
# Example: Adding a Custom Strategy
# File: src/strategies/my_custom_strategy.py
from src.strategies.base_strategy import BaseStrategy
import backtrader.indicators as btind
class MyCustomStrategy(BaseStrategy):
params = (
('rsi_period', 14),
('rsi_upper', 70),
('rsi_lower', 30),
)
@staticmethod
def get_parameter_definitions():
return {
'rsi_period': {'type': 'int', 'default': 14, 'min': 5, 'max': 50},
'rsi_upper': {'type': 'float', 'default': 70.0, 'min': 60, 'max': 90},
'rsi_lower': {'type': 'float', 'default': 30.0, 'min': 10, 'max': 40},
}
def __init__(self):
super().__init__()
self.rsi = btind.RSI(period=self.params.rsi_period)
self.signals = [] # For HTML report visualization
def next(self):
if self.rsi > self.params.rsi_upper and self.position:
self.sell()
self.signals.append(('SELL', self.data.datetime.date(0), self.data.close[0]))
elif self.rsi < self.params.rsi_lower and not self.position:
self.buy()
self.signals.append(('BUY', self.data.datetime.date(0), self.data.close[0]))class BaseStrategy(bt.Strategy):
"""Base class for all trading strategies"""
@staticmethod
def get_parameter_definitions():
"""Return parameter definitions for web UI"""
pass
def __init__(self):
"""Initialize strategy indicators and signals"""
pass
def next(self):
"""Execute trading logic for each bar"""
pass# CSV Data Requirements
REQUIRED_COLUMNS = ['Date', 'Open', 'High', 'Low', 'Close', 'Volume']
DATE_FORMAT = '%Y-%m-%d %H:%M:%S' # ISO format preferred
TIMEZONE = 'UTC' # Recommended for consistency- π Strategy Optimization: Automated parameter optimization with genetic algorithms
- π Portfolio Rebalancing: Dynamic asset allocation strategies
- π Real-Time Data: Integration with live market data feeds
- π± Mobile Interface: Responsive web design for mobile devices
- π€ Advanced ML Models: Integration with latest transformer architectures
# Contributing to the project
git fork <repository-url>
git checkout -b feature/new-strategy
# Implement your changes
git commit -m "Add new momentum strategy"
git push origin feature/new-strategy
# Create pull requestThis project is licensed under the MIT License - see the LICENSE file for details.
- Backtrader: Core backtesting engine by Daniel Rodriguez
- Lightweight Chartsβ’: Professional financial charts by TradingView
- Hugging Face Transformers: State-of-the-art ML models
- TensorFlow/Keras: Neural network implementation framework
Made with β€οΈ for the quantitative trading community
Distributed under the MIT License.