A full-featured Python backtesting framework for options and equities trading strategies. Supports pluggable signal systems, multi-broker live paper trading, Monte Carlo simulation, and comprehensive performance analytics with visualizations.
Built over 30+ agentic coding sessions β see journal/ for the full development narrative.
- Multi-instrument Trading: Trade equities, options (calls/puts), or both separately
- Pluggable Signal Systems:
indicator_pairβ any two indicators with configurable sync windowsema_233β EMA crossover on resampled barsarmed_modeβ arm/fire logic for indicator pairs (prevents signal stacking)trigger_chainβ sequential trigger chain with N indicators
- Options Greeks Calculation: Compute and track delta, theta, gamma, vega for options positions
- Portfolio Management: Track multiple concurrent positions with P&L calculation including costs/slippage
- Flexible Exit Logic: Profit target, stop loss, opposite signal, EOD close, and options expiration
- Monte Carlo Simulation: Bootstrap trade P&Ls to produce equity curve distributions and percentile bands
- Live Paper Trading: Multi-broker support β Alpaca paper orders and IBKR paper orders via separate live runners
- Comprehensive Metrics: Sharpe, Sortino, max drawdown, win rate, profit factor, Probabilistic Sharpe Ratio, Deflated Sharpe Ratio, and more
- Visualization: Equity curves, drawdown charts, and signal overlays on price
- YAML Configuration: Adjust all strategy parameters without code changes
- IS/OOS Split: In-sample / out-of-sample evaluation built into the backtest engine
- Trade Logging: Detailed CSV output of all trades with entry/exit reasons
- Streamlit Dashboard: Interactive 4-view results browser
backTestingTraderBot/
βββ requirements.txt
βββ config/
β βββ strategy_params.example.yaml # Example strategy parameters
βββ data/
β βββ Alpaca/equities/SYMBOL/[1min|5min]/[YYYY]/
β βββ DataBento/equities/SYMBOL/[1min|5min]/[YYYY]/
β βββ DataBento/options/SYMBOL/1min/
β βββ TV/equities/SYMBOL/5min/
βββ main_runner/
β βββ run_backtest_db.py # Databento backtest entry point
β βββ run_backtest_with_alpaca.py # Alpaca backtest entry point
β βββ run_backtest_tv.py # TradingView backtest entry point
β βββ run_monte_carlo.py # Monte Carlo post-processor
βββ live_runner/
β βββ run_live_db.py # Databento stream β Alpaca paper orders
β βββ run_live_ibkr.py # IBKR stream β IBKR paper orders
βββ scripts_bash/
β βββ run_backtest_db.sh
β βββ run_backtest_alpaca.sh
β βββ run_backtest_tv.sh
β βββ run_mc.sh
βββ scripts_py/
β βββ dashboard.py # Streamlit results dashboard
β βββ download_and_aggregate_databento.py
β βββ download_options_databento.py # Options cache pre-warmer
β βββ armed_mode_comparison.py
βββ src/
β βββ data/
β β βββ alpaca_loader.py
β β βββ databento_loader.py
β β βββ aggregator.py # 1-min β 5-min resampler
β β βββ tradingview_loader.py
β βββ indicators/
β β βββ base.py # Shared primitives (rolling_high_low, double_ema_smooth)
β β βββ smi.py
β β βββ williams_r.py
β β βββ ema.py
β β βββ rsi.py
β β βββ macd.py
β β βββ vwap.py
β βββ signals/
β β βββ strategy.py # SignalStrategy ABC + factory + concrete classes
β β βββ indicator_pair_pipeline.py # Unified signal generation for all systems
β βββ options/
β β βββ greeks.py
β β βββ option_pricer.py
β β βββ strike_selector.py
β β βββ entry_logic.py
β β βββ exit_rules.py
β β βββ utils.py
β β βββ position.py
β βββ backtest/
β β βββ engine.py
β β βββ trade_logic.py
β β βββ portfolio.py
β βββ analysis/
β β βββ metrics.py
β β βββ monte_carlo.py
β β βββ visualize.py
β βββ live/
β β βββ live_engine.py
β β βββ alpaca_trader.py
β β βββ ibkr_trader.py
β β βββ databento_streamer.py
β β βββ ibkr_streamer.py
β β βββ broker_protocol.py
β βββ utils/
β βββ logging_config.py
βββ journal/
β βββ INDEX.md
β βββ log/ # Chronological dev log
β βββ decisions/ # Key design rationale docs
β βββ runbooks/ # Operational how-to guides
β βββ concepts/ # Reference / educational docs
β βββ tutorials/ # Multi-part crash courses
β βββ docs/ # _state.md, _modules.md (living state)
βββ tests/
β βββ test_indicators.py
β βββ test_greeks.py
β βββ test_signals.py
β βββ test_portfolio.py
β βββ ... # 900+ tests total
βββ results/
βββ db/ # Databento results
βββ alpaca/ # Alpaca results
βββ tv/ # TradingView results
βββ others/ # Comparison reports
-
Clone and navigate to the project:
git clone https://github.com/Jaggia/backTestingTraderBot.git cd backTestingTraderBot -
Create a virtual environment (recommended):
python3 -m venv venv source venv/bin/activate # macOS/Linux # or venv\Scripts\activate # Windows
-
Install dependencies:
pip install -r requirements.txt
-
Set up environment variables (if using live data sources):
Export these in
~/.zshrcor equivalent:export DATA_BENTO_PW=your_databento_api_key_here export ALPACA_UN=your_alpaca_api_key_here export ALPACA_PW=your_alpaca_secret_key_here
Copy the example config and edit to your needs:
cp config/strategy_params.example.yaml config/strategy_params.yamlKey configurable sections:
strategy:
timeframe: "5min" # 1min or 5min bars
trade_mode: "equities" # equities or options
signal_system: "indicator_pair" # indicator_pair, ema_233, armed_mode, trigger_chain
initial_capital: 100000 # Starting portfolio value
signals:
# Indicator parameters vary by signal system β see strategy_params.example.yaml
# sync_window: X # Bars to synchronize indicator events
# vwap_filter: true/false # Optional VWAP filter
options:
target_dte: X # Days to expiration
strike_selection: "ATM" # ATM, 1_ITM, 1_OTM, target_delta
exits:
profit_target_pct: XX.X # Take profit at +XX%
stop_loss_pct: XX.X # Stop loss at -XX%
eod_close: false # Close all positions at market close
opposite_signal: true # Exit on opposite signal
position:
sizing_mode: "percent_of_equity" # fixed or percent_of_equity
sizing_pct: XX # % of equity per trade
max_concurrent_positions: X
costs:
commission_per_contract: X.XX # Per contract commission
slippage_pct: X.XX # Slippage as % of priceDatabento Data (Default):
./scripts_bash/run_backtest_db.sh
# Or directly:
python main_runner/run_backtest_db.py START_DATE END_DATEAlpaca Data:
./scripts_bash/run_backtest_alpaca.sh
# Or directly:
python main_runner/run_backtest_with_alpaca.py START_DATE END_DATETradingView Data:
./scripts_bash/run_backtest_tv.sh
# Or directly:
python main_runner/run_backtest_tv.py START_DATE END_DATE| Source | Timeframe | Instrument | Best For |
|---|---|---|---|
| Databento | 1min β 5min (aggregated) | Equities + Options | Production, closest to IB |
| Alpaca | 1min, 5min | Equities | Testing, development |
| TradingView | 5min | Equities | Chart validation |
After backtesting, check results/{db,alpaca,tv}/{date_range}/{mode}/{timeframe}/:
- backtest.csv: Detailed trade log with entry/exit prices, P&L, and exit reasons
- report.md: Summary of strategy configuration and performance metrics
- config.yaml: Full config snapshot at run time
- equity_curve.png: Portfolio value over time
- drawdown.png: Underwater plot showing drawdown periods
- signals.png: Price chart with entry/exit signals overlaid
- equity_data.csv: Equity curve data used by the interactive dashboard
streamlit run scripts_py/dashboard.pyBrowse results across data sources and dates with 4 views:
- Overview: Metric cards, charts, config used, full report
- Trade Explorer: Interactive table with filters, P&L histogram, cumulative P&L
- Comparison: Armed mode comparison tables
- Cross-Run: Metrics across all runs plotted over time
| System | Config Value | Description |
|---|---|---|
| Indicator Pair | indicator_pair |
Two indicators with configurable sync windows. Supports any combination from the indicator library. |
| EMA 233 | ema_233 |
EMA crossover on resampled higher-timeframe bars. Uses intrabar-cross detection for precise fills. |
| Armed Mode | armed_mode |
First indicator arms the system; second fires and disarms. Prevents stacking signals from a single event. |
| Trigger Chain | trigger_chain |
Sequential N-indicator trigger chain with ordered execution. |
All signal systems share the same backtest engine, exit logic, and portfolio management. Switch between them via strategy.signal_system in config β no code changes needed.
fixed: Trade a fixed number of contracts per tradepercent_of_equity: Size each trade as a % of current portfolio value
- Profit Target: Close when position reaches +X% gain
- Stop Loss: Close when position reaches -X% loss
- Opposite Signal: Close when opposite trading signal fires
- End-of-Day: Auto-close all positions at market close (if enabled)
- Expiration: Options automatically closed at expiration
For options trades, the system calculates delta, theta, gamma, and vega. Realized P&L includes time decay for accurate options P&L.
| Source | Timeframe | Instrument | Format |
|---|---|---|---|
| Alpaca API | 1min, 5min | Equities | OHLCV |
| TradingView | 5min | Equities | OHLCV |
| Databento | 1min (aggregated to 5min) | Equities | OHLCV |
| Databento API | 1min | Options | OHLCV |
CSV caching: All data is cached locally to avoid repeated API calls.
The backtest engine computes:
- Win Rate (%): % of trades that finished with profit
- Sharpe Ratio: Risk-adjusted return (annualized)
- Probabilistic Sharpe Ratio: Corrects for sample size, skewness, and kurtosis
- Deflated Sharpe Ratio: Multiple-testing-corrected PSR
- Max Drawdown (%): Largest peak-to-trough decline
- Profit Factor: Gross profit / gross loss
- Average Win/Loss: Mean profit/loss per trade
- Total P&L: Sum of all trade P&L
- Total Return (%): Final equity / initial capital - 1
Bootstrap trade P&Ls to get a distribution of equity curve outcomes:
# Inline β runs automatically after the backtest
python main_runner/run_backtest_db.py START END --mc
# Post-hoc β run on any existing results folder
python main_runner/run_monte_carlo.py results/db/RUN_PATH/equities/5min
python main_runner/run_monte_carlo.py results/db/RUN_PATH/equities/5min --n 2000Two broker integrations for forward-testing:
Alpaca (via Databento data):
python live_runner/run_live_db.pyIBKR (via IB Gateway):
python live_runner/run_live_ibkr.pyBoth use the same signal pipeline and exit logic as backtesting. Live bars and trades are automatically logged for later analysis.
pytest tests/ # All tests (900+)
pytest tests/test_indicators.py -v # Single test file
pytest --cov=src tests/ # With coverageTo extend the system:
- New Indicators: Add to
src/indicators/and register insrc/indicators/base.py - New Signal Systems: Implement a concrete class in
src/signals/strategy.pyand register in_STRATEGY_MAP - New Exit Rules: Update
check_exit()insrc/backtest/trade_logic.py - New Metrics: Add to
compute_metrics()insrc/analysis/metrics.py
Always add tests in tests/ for new functionality.
This project is provided as-is for educational and research purposes.