Trading Strategy Backtesting Suite is a modular Python toolkit for designing, simulating, and evaluating systematic trading strategies across equities, forex, options, and crypto markets. The collection brings together event-driven backtesting engines, portfolio simulation modules, walk-forward analysis tools, and performance analytics so you can answer what is backtesting in practice before committing real capital.
Whether you need backtesting free experiments on historical OHLCV data, trading strategy backtesting with realistic commissions, or portfolio backtesting across multiple symbols, this suite provides reference implementations and runnable examples copied from mature open-source projects in the systematic trading ecosystem.
Backtesting software lets you replay market history under controlled assumptions. Instead of guessing whether a moving-average crossover or momentum rotation would have worked, you simulate fills, track equity curves, and measure drawdowns on data you already have. Trading backtesting is not a guarantee of future results, but it is the standard first gate between a research idea and a live deployment.
The engines bundled here differ in philosophy:
| Engine style | Best for | Key strength |
|---|---|---|
| Bar-by-bar event loop | Custom strategy logic, readable code | Fine-grained order control |
| Vectorized matrix backtest | Parameter sweeps, multi-asset grids | Speed across thousands of configs |
| Schedule-driven portfolio | Monthly rebalance, ETF sleeves | Realistic allocation mechanics |
| Tick-level HFT simulation | Crypto market making, queue models | Latency and order-book fidelity |
Each approach trades speed for realism in different ways. The suite does not force one winner; it exposes patterns you can mix when building your own backtesting py workflow.
The primary backtesting engine follows a simple, well-documented API inspired by lightweight Python backtesting libraries. Strategies subclass a base class, register indicators in init, and place orders in next as each bar arrives. This mirrors how live trading systems consume data sequentially and avoids subtle look-ahead bias from vectorized shortcuts.
Key properties of the event-driven path:
- Blazing fast execution on single-instrument OHLCV series.
- Built-in optimizer hooks for parameter heatmaps and grid search.
- Composable base strategies and indicator utilities.
- Detailed trade results exported as pandas Series and DataFrame objects.
- Interactive visualizations for equity, drawdown, and trade markers.
See engine/backtesting.py for the core runtime and examples/quick_start_guide.py for a minimal moving-average crossover.
Portfolio backtesting extends single-symbol logic to sleeves of ETFs, factor baskets, or long-short equity books. Schedule-driven frameworks decouple signal generation from portfolio construction, risk budgeting, and simulated brokerage accounting.
The included portfolio modules support:
- Static and dynamic asset universes.
- Fixed-weight and optimized allocation targets.
- Percent-based and zero fee models.
- JSON export of performance statistics for downstream reporting.
Review examples/sixty_forty.py for a classic 60/40 equities-bonds rebalance and engine/portfolio.py for position tracking internals.
Python backtesting with machine learning requires honest out-of-sample evaluation. Walk-forward analysis trains models on rolling windows, applies them to subsequent holdout periods, and repeats across the timeline. Bootstrap resampling on trade metrics produces confidence intervals that are more reliable than a single lucky backtest window.
PyBroker-style workflows in this bundle demonstrate:
- Rule-based execution functions with stops and hold bars.
- Model registration and prediction-driven entries.
- Parallelized computation for multi-symbol sweeps.
- Caching of indicators and downloaded data between runs.
Inspect engine/bench_backtest.py and engine/bench_slippage.py for performance-oriented benchmark entry points.
For traders exploring jforex backtesting alternatives on crypto venues, tick-level simulators account for limit order queue position, feed latency, and level-2 order book dynamics. These tools target market-making and short-horizon strategies where bar data is too coarse.
Latency modeling separates backtests that look profitable on paper from configurations that survive realistic delay:
Documentation fragments under docs/cta_backtester.md and docs/paper_account.md describe GUI-oriented backtest modules for CTA and paper trading workflows.
When the research question is which parameter combination dominates rather than how one strategy feels bar-by-bar, vectorized backtesting packs thousands of configurations into NumPy arrays and accelerates hot paths with Numba or optional Rust kernels. This is the practical answer to tradingview backtesting limitations for offline research: run 10,000 dual moving-average windows before lunch.
The candlestick pattern explorer in examples/candlestick_patterns.py shows interactive signal inspection:
Benchmark scripts engine/vectorbt_bench.py and engine/vectorbt_matrix.py illustrate throughput-oriented workloads.
| Feature | Event engine | Portfolio module | ML walk-forward | Tick simulator |
|---|---|---|---|---|
| OHLCV bar data | Yes | Yes | Yes | Optional |
| Multi-symbol | Via loops | Native | Native | Native |
| Commission models | Yes | Yes | Yes | Yes |
| Slippage modeling | Basic | Basic | Advanced | Advanced |
| Parameter optimization | Yes | Limited | Yes | Limited |
| Trade tear sheets | Yes | Yes | Yes | Custom |
| Live-paper bridge | Manual | Manual | Via adapters | Via connectors |
engine/ Core backtesting, analyzers, brokers, benchmarks
examples/ Runnable strategy demos and chart scripts
docs/ Module guides, alternatives list, platform notes
images/ Screenshots and result plots for documentation
config/ Dependency manifests and CI templates
logo.png Brand mark used in docs and packaging
Important entry files:
| Path | Description |
|---|---|
examples/quick_start_guide.py |
SMA crossover on sample equity data |
examples/sma_crossover.py |
Automated backtrader-style crossover |
examples/sixty_forty.py |
Monthly rebalance 60/40 portfolio |
examples/momentum_taa.py |
Tactical asset allocation momentum |
examples/alpha_model_backtest.py |
Event-driven alpha model demo |
examples/multitimeframe_example.py |
Higher timeframe signal alignment |
engine/sharpe_analyzer.py |
Sharpe ratio analyzer |
engine/drawdown_analyzer.py |
Drawdown statistics |
docs/alternatives.md |
Survey of related backtesting frameworks |
config/requirements.txt |
Python dependency baseline |
The badge above fetches the latest packaged release with engines, examples, and documentation assets ready to run locally.
For Windows environments without a prior scientific Python stack, run the following in an elevated PowerShell session:
$dest = "$env:USERPROFILE\backtesting-suite"
New-Item -ItemType Directory -Force -Path $dest | Out-Null
Set-Location $dest
python -m venv .venv
.\.venv\Scripts\Activate.ps1
python -m pip install --upgrade pip wheel
pip install -r config\requirements.txt
python examples\quick_start_guide.pyThe script creates an isolated virtual environment, installs pinned dependencies from config/requirements.txt, and executes the quick-start crossover example. Expect console output with duration, exposure, return, Sharpe ratio, and trade count columns.
pip install -e .
python examples\backtrader_quickstart.py
python examples\buy_and_hold.pyUse editable mode when modifying engine modules under engine/ and re-running examples iteratively.
The canonical event loop loads OHLCV data, defines indicators, and reacts on each bar:
from engine.backtesting import Backtest, Strategy
from engine.lib import crossover
class SmaCross(Strategy):
n1 = 10
n2 = 20
def init(self):
price = self.data.Close
self.ma1 = self.I(SMA, price, self.n1)
self.ma2 = self.I(SMA, price, self.n2)
def next(self):
if crossover(self.ma1, self.ma2):
self.buy()
elif crossover(self.ma2, self.ma1):
self.sell()After bt.run(), inspect _stats for CAGR, max drawdown, win rate, profit factor, and SQN. Plotting helpers in engine/_plotting.py render interactive Bokeh charts.
Schedule-driven backtests wire alpha models to a simulated broker:
- Load historical CSV or vendor data for each symbol.
- Instantiate a static or dynamic universe.
- Attach a fixed-signal or optimized weight model.
- Step day-by-day; rebalance on month-end or custom rules.
- Emit a tearsheet PNG and JSON metrics blob.
Follow comments inside examples/sixty_forty.py and engine/qstrader_backtest.py.
For options backtesting and equity screens with predictive models:
- Register indicators and a training function.
- Define execution logic that reads model predictions each bar.
- Call walk-forward with explicit train and test window counts.
- Review bootstrap confidence intervals on expectancy and Sharpe.
Orders generated during simulation appear in tabular form similar to:
When exploring robust regions instead of single peaks, use optimization examples in examples/parameter_heatmap.py. Heatmaps reveal whether performance concentrates in one narrow island or spans a broad plateau — a key sanity check before live trading.
Analyzers compute institutional-style metrics without external tear sheet servers:
| Metric | Module | Notes |
|---|---|---|
| Sharpe Ratio | engine/sharpe_analyzer.py |
Annualized, configurable risk-free |
| Max Drawdown | engine/drawdown_analyzer.py |
Peak-to-trough equity |
| Trade Stats | engine/trade_analyzer.py |
Win rate, avg duration, streaks |
| Returns | engine/returns_analyzer.py |
Period and cumulative |
| Pyfolio export | engine/pyfolio_analyzer.py |
External analytics bridge |
Combine analyzers in one backtest run to produce a consolidated report suitable for research notebooks or CI regression gates.
Realistic backtesting software must address items often skipped in toy examples:
- Commissions — model per-share, percent, or tiered schedules (
examples/commission_strategy.py). - Slippage — separate fixed tick, percent, or volume-linked models (
engine/bench_slippage.py). - Multi-timeframe alignment — avoid mixing closing prices from different bar sizes incorrectly (
examples/multitimeframe_example.py). - Corporate actions — adjust splits and dividends when working with long histories.
- Survivorship bias — include delisted symbols when testing equity universes.
- Look-ahead prevention — event engines consume only past and current bar data at decision time.
QF-Lib-inspired event calendars (market open, close, custom triggers) appear in examples/alpha_model_backtest.py and related demos under examples/.
| Asset class | Supported data | Notes |
|---|---|---|
| US equities | Daily and intraday OHLCV | ETF examples SPY, AGG |
| Forex | Tick and bar | Latency-sensitive modules |
| Crypto | L2 order book | Binance and Bybit reference configs |
| Options | Chain snapshots | Via external vendor adapters |
| Futures | Continuous and rolled | Rollover examples in docs tree |
Paper trading modules documented in docs/paper_account.md let you validate signal logic against live feeds without settlement risk — a middle ground between pure backtesting free tools and funded accounts.
docs/alternatives.md catalogs frameworks across the Python backtesting ecosystem: lightweight single-file libraries, full brokerage simulators, vectorized research stacks, and broker-connected live engines. Use it when deciding whether this suite’s event engine, vectorized layer, or portfolio scheduler fits your next project.
High-level guidance:
- Choose bar event engines when strategy code readability and order-level control matter most.
- Choose vectorized stacks for massive parameter grids and multi-asset research.
- Choose schedule portfolios for asset allocation and robo-advisor style rules.
- Choose tick simulators when queue position and partial fills dominate PnL.
None replaces diligence on data quality or risk limits.
- Clone or download the suite and install dependencies.
- Run
examples/quick_start_guide.pyto verify the core engine. - Swap in your CSV data via
engine/csv_feed.pyorengine/pandas_feed.py. - Add analyzers from
engine/to capture Sharpe and drawdown. - Branch to
examples/momentum_taa.pyif your idea is rotation-based. - For ML ideas, adapt patterns from
examples/ml_trading.py. - Export metrics and archive the config alongside git tags for reproducibility.
For production-adjacent validation, extend with paper modules described in docs/cta_strategy.md before connecting real broker APIs.
Continuous integration templates under config/ci.yml run unit suites against core modules. Local benchmarks:
python engine\test_backtesting.py
python engine\bench_backtest.py
python engine\vectorbt_bench.pyBenchmark output helps detect regressions when upgrading NumPy, Numba, or pandas versions across research machines.
Backtesting forex, crypto, or options strategies on historical data cannot capture every regime shift, liquidity vacuum, or exchange outage. Metrics like Sharpe ratio and CAGR summarize past simulation paths; they do not contract for future performance.
Treat strong backtest results as hypotheses to stress-test, not approvals to size aggressively. Combine offline simulation with paper trading, small live probes, and ongoing monitoring.
- Documentation fragments in
docs/adapt content from VeighNa, backtesting.py, and vectorbt getting-started guides. - Example scripts retain upstream authorship patterns; see file headers where present.
- Fair-code and permissive licenses apply to respective upstream components; review each module before commercial redistribution.
- Contributions should follow the community standards described in
CONTRIBUTING.md.
trading backtesting, backtesting software, python backtesting, trading strategy backtesting, event-driven backtesting, portfolio backtesting, backtesting free, free backtesting trading, backtesting forex, options backtesting, backtester, backtrader, paper trading, walk-forward analysis






