A comprehensive backtesting framework designed for testing trading strategies, investment models, and algorithmic trading systems. This tool provides advanced analytics, performance metrics, and risk assessment capabilities for quantitative analysis and strategy development.
Features
- Strategy Backtesting - Comprehensive backtesting engine for trading strategies
- Performance Analytics - Advanced performance metrics and risk analysis
- Data Management - Historical data import and management capabilities
- Risk Assessment - Comprehensive risk metrics and portfolio analysis
- Visualization - Interactive charts and performance visualization
- Strategy Optimization - Parameter optimization and strategy tuning
- Multi-Asset Support - Support for stocks, forex, crypto, and commodities
- Real-time Testing - Paper trading and real-time strategy testing
Backtesting Engine
Strategy Framework
- Signal Generation - Technical indicator-based signal generation
- Position Sizing - Dynamic position sizing and risk management
- Order Management - Advanced order types and execution simulation
- Portfolio Management - Multi-asset portfolio management
- Risk Controls - Stop-loss, take-profit, and risk management rules
Data Sources
- Historical Data - OHLCV data from multiple sources
- Real-time Feeds - Live market data integration
- Alternative Data - News, sentiment, and alternative data sources
- Custom Data - Support for custom data formats and sources
Performance Metrics
Return Metrics
- Total Return - Overall strategy performance
- Annualized Return - Annualized performance metrics
- Sharpe Ratio - Risk-adjusted return measure
- Sortino Ratio - Downside risk-adjusted return
- Calmar Ratio - Maximum drawdown-adjusted return
Risk Metrics
- Maximum Drawdown - Largest peak-to-trough decline
- Value at Risk (VaR) - Potential loss at confidence level
- Expected Shortfall - Average loss beyond VaR
- Volatility - Standard deviation of returns
- Beta - Market correlation measure
Trading Metrics
- Win Rate - Percentage of profitable trades
- Profit Factor - Ratio of gross profit to gross loss
- Average Trade - Average profit/loss per trade
- Maximum Consecutive Losses - Longest losing streak
- Recovery Factor - Total return divided by maximum drawdown
Tech Stack
- Language: Python 3.8+
- Data Analysis: Pandas, NumPy, SciPy
- Visualization: Matplotlib, Plotly, Seaborn
- Machine Learning: Scikit-learn, TensorFlow
- Database: PostgreSQL, SQLite
- Web Interface: Streamlit, Dash
Installation & Setup
-
Clone the repository:
git clone https://github.com/1cbyc/ict-model-backtester.git cd ict-model-backtester
-
Install dependencies:
pip install -r requirements.txt
-
Set up database:
python setup_database.py
-
Configure data sources:
cp config.example.yaml config.yaml # Edit configuration with your data sources
-
Run backtester:
python backtester.py --strategy moving_average --data data/spy.csv
Usage Examples
Basic Strategy Backtest
from backtester import Backtester
from strategies import MovingAverageStrategy
# Initialize backtester
backtester = Backtester(
data_source='data/spy.csv',
initial_capital=100000,
commission=0.001
)
# Create strategy
strategy = MovingAverageStrategy(
short_window=10,
long_window=30
)
# Run backtest
results = backtester.run(strategy)
# Print results
print(f"Total Return: {results.total_return:.2%}")
print(f"Sharpe Ratio: {results.sharpe_ratio:.2f}")
print(f"Max Drawdown: {results.max_drawdown:.2%}")
Custom Strategy Implementation
class CustomStrategy:
def __init__(self, rsi_period=14, oversold=30, overbought=70):
self.rsi_period = rsi_period
self.oversold = oversold
self.overbought = overbought
def generate_signals(self, data):
rsi = calculate_rsi(data['close'], self.rsi_period)
signals = pd.Series(index=data.index, data=0)
signals[rsi < self.oversold] = 1 # Buy signal
signals[rsi > self.overbought] = -1 # Sell signal
return signals
Parameter Optimization
from optimizer import StrategyOptimizer
# Define parameter ranges
param_ranges = {
'short_window': range(5, 21),
'long_window': range(20, 51)
}
# Optimize strategy
optimizer = StrategyOptimizer(
strategy_class=MovingAverageStrategy,
param_ranges=param_ranges,
metric='sharpe_ratio'
)
best_params = optimizer.optimize(data_source='data/spy.csv')
print(f"Best parameters: {best_params}")
Strategy Library
Technical Analysis Strategies
- Moving Average Crossover - Simple and exponential moving averages
- RSI Strategy - Relative Strength Index-based trading
- MACD Strategy - Moving Average Convergence Divergence
- Bollinger Bands - Mean reversion and breakout strategies
- Stochastic Oscillator - Stochastic-based trading signals
Statistical Arbitrage
- Pairs Trading - Cointegration-based pairs trading
- Mean Reversion - Statistical mean reversion strategies
- Momentum Trading - Price momentum-based strategies
- Volatility Trading - Volatility-based trading strategies
Machine Learning Strategies
- Classification Models - ML-based buy/sell classification
- Regression Models - Price prediction and forecasting
- Ensemble Methods - Combined multiple model predictions
- Deep Learning - Neural network-based strategies
Data Management
Data Sources
- Yahoo Finance - Free historical data
- Alpha Vantage - Real-time and historical data
- Quandl - Alternative data sources
- Custom APIs - Integration with custom data providers
Data Processing
- Data Cleaning - Handle missing data and outliers
- Feature Engineering - Create technical indicators
- Data Validation - Validate data quality and consistency
- Data Storage - Efficient data storage and retrieval
Visualization and Reporting
Performance Charts
- Equity Curve - Portfolio value over time
- Drawdown Chart - Drawdown analysis
- Returns Distribution - Return distribution analysis
- Rolling Metrics - Rolling performance metrics
Risk Analysis
- Risk-Return Scatter - Risk-return analysis
- Correlation Matrix - Asset correlation analysis
- VaR Analysis - Value at Risk visualization
- Stress Testing - Stress test results visualization
Project Impact
This backtester has been used for:
- Strategy Development - Testing and refining trading strategies
- Risk Management - Portfolio risk analysis and management
- Academic Research - Quantitative finance research
- Professional Trading - Professional trading strategy development
Future Enhancements
- Real-time Trading - Live trading integration
- Advanced ML Models - Enhanced machine learning capabilities
- Multi-Asset Optimization - Portfolio optimization features
- Cloud Deployment - Cloud-based backtesting platform
- Mobile App - Mobile monitoring and control