Backtrader

1.9.78.123 · active · verified Thu Apr 16

backtrader is a powerful and flexible Python framework for backtesting trading strategies, analyzing financial data, and live trading. It provides a robust engine for simulating market conditions, managing portfolios, and executing trades based on defined rules. The current stable version is 1.9.78.123, with a major 2.x release under active development that introduces significant changes. Its release cadence is sporadic but active, with bug fixes and minor features released as needed.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to set up a basic backtesting strategy with backtrader. It involves defining a strategy with two moving averages, adding a CSV data feed (a dummy one created for demonstration), setting initial cash and commission, running the backtest, and printing the portfolio value. The `cerebro.plot()` line is commented out but shows how to visualize results if `matplotlib` is installed.

import backtrader as bt
import datetime
import os

# Dummy CSV data for demonstration. In a real scenario, this would be a file.
dummy_csv_content = (
    "Date,Open,High,Low,Close,Volume,OpenInterest\n"
    "2020-01-01,100,102,99,101,1000,0\n"
    "2020-01-02,101,103,100,102,1200,0\n"
    "2020-01-03,102,104,101,103,1100,0\n"
    "2020-01-06,103,105,102,104,1300,0\n"
)

# Create a dummy CSV file
dummy_csv_path = 'dummy_data.csv'
with open(dummy_csv_path, 'w') as f:
    f.write(dummy_csv_content)

class SmaCross(bt.Strategy):
    params = (('fast_period', 10), ('slow_period', 30),)

    def __init__(self):
        self.sma_fast = bt.indicators.SMA(self.data.close, period=self.p.fast_period)
        self.sma_slow = bt.indicators.SMA(self.data.close, period=self.p.slow_period)
        self.crossover = bt.indicators.CrossOver(self.sma_fast, self.sma_slow)

    def next(self):
        if not self.position:  # Not in the market
            if self.crossover > 0:  # fast crosses slow upwards
                self.buy()
        elif self.crossover < 0:  # fast crosses slow downwards
            self.close()

cerebro = bt.Cerebro()
cerebro.addstrategy(SmaCross)

# Add data feed
data = bt.feeds.CSVData(
    dataname=dummy_csv_path,
    datetimeformat='%Y-%m-%d',
    fromdate=datetime.datetime(2020, 1, 1),
    todate=datetime.datetime(2020, 1, 31)
)
cerebro.adddata(data)

cerebro.broker.setcash(100000.0)
cerebro.broker.setcommission(commission=0.001)

print(f'Starting Portfolio Value: {cerebro.broker.getvalue():.2f}')
cerebro.run()
print(f'Final Portfolio Value: {cerebro.broker.getvalue():.2f}')

# Clean up dummy file
os.remove(dummy_csv_path)

# To plot results (requires matplotlib):
# cerebro.plot()

view raw JSON →