A comprehensive Python framework for backtesting various trading strategies using historical market data. Built with the backtesting library and featuring a command-line interface for easy strategy testing and parameter optimization.
- π Multiple built-in trading strategies (SMA, RSI, MACD, FVG, ChatGPT)
- π Interactive plots and performance metrics
- βοΈ Parameter optimization capabilities
- π― Flexible data loading (symbols, date ranges, intervals)
- π₯οΈ Command-line interface for easy execution
- π Support for stocks, ETFs, and cryptocurrencies via Yahoo Finance
python3 -m venv venv
source venv/bin/activate # On Windows: venv\Scripts\activatepip install -r requirements.txtexport OPENAI_API_KEY='your-api-key-here'python src/main.py --list-strategiespython src/main.py --strategy sma --symbol AAPL --period 1ypython src/main.py --strategy rsi --symbol TSLA --period 6mo --rsi-period 21 --rsi-overbought 75| Strategy | Key | Description |
|---|---|---|
| Simple Moving Average | sma, smacross |
Classic SMA crossover strategy |
| RSI | rsi |
Relative Strength Index overbought/oversold |
| SMA + MACD | smamacd, sma_macd |
Combined SMA and MACD signals |
| Fair Value Gap | fvg, fairvaluegap |
Price gap trading strategy |
| ChatGPT | chatgpt |
AI-powered trading decisions (requires OpenAI API) |
python src/main.py --strategy STRATEGY --symbol SYMBOL [OPTIONS]| Argument | Description | Example |
|---|---|---|
--strategy, -s |
Strategy to use | --strategy sma |
--symbol |
Stock/crypto symbol | --symbol AAPL |
--list-strategies |
Show all available strategies |
| Argument | Description | Example |
|---|---|---|
--period |
Time period | --period 1y, --period 6mo |
--interval |
Data interval | --interval 1d, --interval 1h |
--start |
Start date (YYYY-MM-DD) | --start 2023-01-01 |
--end |
End date (YYYY-MM-DD) | --end 2023-12-31 |
| Argument | Description | Default | Example |
|---|---|---|---|
--cash |
Initial cash amount | 100000 | --cash 50000 |
--commission |
Commission rate | 0.002 (0.2%) | --commission 0.001 |
--exclusive-orders |
Use exclusive orders | True |
| Argument | Description | Example |
|---|---|---|
--optimize |
Run parameter optimization (strategy-specific) | --optimize |
--plot |
Show backtest plot (default) | --plot |
--no-plot |
Disable plotting | --no-plot |
--plot-volume |
Include volume in plots | --plot-volume |
| Argument | Description | Default |
|---|---|---|
--n1 |
Short period | 10 |
--n2 |
Long period | 20 |
| Argument | Description | Default |
|---|---|---|
--rsi-period |
RSI calculation period | 14 |
--rsi-overbought |
Overbought threshold | 70 |
--rsi-oversold |
Oversold threshold | 30 |
| Argument | Description | Default |
|---|---|---|
--sma-period |
SMA period | 10 |
--macd-fast |
MACD fast period | 12 |
--macd-slow |
MACD slow period | 26 |
--macd-signal |
MACD signal period | 9 |
# Simple SMA strategy on Apple stock
python src/main.py --strategy sma --symbol AAPL
# RSI strategy on Tesla with custom parameters
python src/main.py --strategy rsi --symbol TSLA --rsi-period 21 --rsi-overbought 75
# Bitcoin trading with FVG strategy
python src/main.py --strategy fvg --symbol BTC-USD --period 1y# Optimize strategy parameters (each strategy defines its own optimization ranges)
python src/main.py --strategy sma --symbol SPY --period 2y --optimize
python src/main.py --strategy rsi --symbol AAPL --period 1y --optimize
python src/main.py --strategy fvg --symbol BTC-USD --period 6mo --optimize
# High-frequency trading simulation
python src/main.py --strategy sma --symbol AAPL --period 5d --interval 5m --cash 10000
# Custom date range with specific commission
python src/main.py --strategy rsi --symbol MSFT --start 2023-01-01 --end 2023-12-31 --commission 0.001
# Multiple parameter customization
python src/main.py --strategy smamacd --symbol QQQ --period 1y --sma-period 20 --macd-fast 10 --macd-slow 30# Set API key first
export OPENAI_API_KEY='your-api-key-here'
# Run ChatGPT strategy
python src/main.py --strategy chatgpt --symbol AAPL --period 3mo
# Bitcoin example with higher cash for expensive asset
python src/main.py --strategy chatgpt --symbol BTC-USD --start 2024-01-01 --cash 1000000The framework provides comprehensive performance metrics including:
- Returns: Strategy vs Buy & Hold comparison
- Risk Metrics: Sharpe Ratio, Sortino Ratio, Maximum Drawdown
- Trade Analysis: Win Rate, Average Trade, Profit Factor
- Timing: Exposure Time, Trade Duration
- Visualization: Equity curves, drawdown plots, trade markers
- Create your strategy file in
src/strategies/ - Inherit from
backtesting.Strategy - Add import and registry entry in
src/strategies/__init__.py - (Optional) Add CLI parameters in
src/main.py
Example:
# src/strategies/my_strategy.py
from backtesting import Strategy
class MyStrategy(Strategy):
param1 = 10
def init(self):
# Initialize indicators
pass
def next(self):
# Trading logic
pass- "Module not found" errors: Ensure virtual environment is activated
- "No data loaded": Check symbol name and date ranges
- ChatGPT API errors: Verify API key is set and has credits
- Plot not showing: Use
--plotflag or check display settings
python src/main.py --helpbacktesting- Core backtesting engineyfinance- Market data providerpandas- Data manipulationnumpy- Numerical computingtalib- Technical analysis (for MACD strategy)openai- ChatGPT integration (optional)
Open source - feel free to modify and extend for your trading research!