gitmyhub

backtrader

Python ★ 22k updated 1y ago

Python Backtesting library for trading strategies

Python library for testing trading strategies against historical price data before risking real money on automated trading.

Pythonpandasmatplotlibsetup: easycomplexity 3/5

Backtrader is a Python library for backtesting trading strategies — meaning you write rules for when to buy and sell financial assets, then run them against historical price data to see how the strategy would have performed in the past. This is a standard step before risking real money on an automated trading approach.

The library gives you all the components needed to simulate a trading system. You define a strategy as a Python class, connect it to historical price data (from CSV files, online sources, or the pandas data library), and then let the engine run through the data day by day applying your rules. As it runs, a simulated brokerage account tracks your positions, cash balance, and trades. The broker simulation supports many real-world order types including market orders, limit orders (buy/sell at a specific price), stop orders, and others.

Beyond the simulation, backtrader includes a library of over 120 built-in technical indicators — mathematical calculations on price data that traders use to generate signals, such as moving averages, momentum indicators, and crossover signals. You can also write custom indicators. Once a backtest finishes, performance analyzers produce statistics like the Sharpe ratio (a measure of risk-adjusted return) and time-period returns to evaluate how well the strategy did.

The library also supports live trading connections to certain brokers, though the focus is on backtesting. Charting/plotting requires an optional install of matplotlib. Backtrader is installed via pip and requires Python 3.2 or later.

Where it fits