Convert Figma logo to code with AI

mementum logobacktrader

Python Backtesting library for trading strategies

13,966
3,849
13,966
51

Top Related Projects

17,485

Zipline, a Pythonic Algorithmic Trading Library

12,935

Download market data from Yahoo! Finance's API

Python wrapper for TA-Lib (http://ta-lib.org/).

2,172

bt - flexible backtesting for Python

An Algorithmic Trading Library for Crypto-Assets in Python

Extract data from a wide range of Internet sources into a pandas DataFrame.

Quick Overview

Backtrader is a Python library for backtesting trading strategies. It provides a comprehensive framework for developing, testing, and analyzing trading algorithms using historical market data. The library is designed to be flexible, extensible, and user-friendly, making it suitable for both beginners and experienced traders.

Pros

  • Easy to use and intuitive API for creating trading strategies
  • Supports multiple data feeds and asset classes
  • Extensive documentation and active community support
  • Built-in plotting and reporting capabilities for visualizing results

Cons

  • Performance can be slow for large datasets or complex strategies
  • Limited real-time trading capabilities compared to some other platforms
  • Steeper learning curve for advanced features and customizations
  • Some users report occasional bugs and inconsistencies in newer versions

Code Examples

  1. Creating a simple Moving Average Crossover strategy:
import backtrader as bt

class SmaCross(bt.Strategy):
    params = (('fast', 10), ('slow', 30))

    def __init__(self):
        sma1 = bt.ind.SMA(period=self.p.fast)
        sma2 = bt.ind.SMA(period=self.p.slow)
        self.crossover = bt.ind.CrossOver(sma1, sma2)

    def next(self):
        if self.crossover > 0:
            self.buy()
        elif self.crossover < 0:
            self.sell()
  1. Adding data and running a backtest:
cerebro = bt.Cerebro()
data = bt.feeds.YahooFinanceData(dataname='AAPL', fromdate=datetime(2010, 1, 1),
                                 todate=datetime(2020, 12, 31))
cerebro.adddata(data)
cerebro.addstrategy(SmaCross)
cerebro.run()
cerebro.plot()
  1. Implementing a custom indicator:
class CustomIndicator(bt.Indicator):
    lines = ('signal',)
    params = (('period', 20),)

    def __init__(self):
        self.addminperiod(self.params.period)
        self.lines.signal = bt.indicators.SMA(self.data, period=self.params.period)

    def next(self):
        if self.data[0] > self.lines.signal[0]:
            self.lines.signal[0] = 1
        else:
            self.lines.signal[0] = -1

Getting Started

To get started with Backtrader, follow these steps:

  1. Install Backtrader using pip:

    pip install backtrader
    
  2. Import the library and create a Cerebro instance:

    import backtrader as bt
    cerebro = bt.Cerebro()
    
  3. Add data and a strategy:

    data = bt.feeds.YahooFinanceData(dataname='AAPL', fromdate=datetime(2010, 1, 1),
                                     todate=datetime(2020, 12, 31))
    cerebro.adddata(data)
    cerebro.addstrategy(YourStrategy)
    
  4. Run the backtest and plot results:

    results = cerebro.run()
    cerebro.plot()
    

Competitor Comparisons

17,485

Zipline, a Pythonic Algorithmic Trading Library

Pros of Zipline

  • More extensive documentation and community support
  • Built-in integration with Quantopian's research platform
  • Robust data handling capabilities for large datasets

Cons of Zipline

  • Steeper learning curve for beginners
  • Less flexible in terms of customization compared to Backtrader
  • Development has slowed down since Quantopian's closure

Code Comparison

Zipline example:

from zipline.api import order, record, symbol

def initialize(context):
    context.asset = symbol('AAPL')

def handle_data(context, data):
    order(context.asset, 10)
    record(AAPL=data.current(context.asset, 'price'))

Backtrader example:

import backtrader as bt

class MyStrategy(bt.Strategy):
    def __init__(self):
        self.dataclose = self.datas[0].close

    def next(self):
        if self.dataclose[0] < self.dataclose[-1]:
            self.buy()

Both frameworks offer powerful backtesting capabilities, but Backtrader tends to be more intuitive for Python developers due to its object-oriented approach. Zipline provides a more structured environment with built-in features for quantitative finance, while Backtrader offers greater flexibility for custom strategies and indicators.

12,935

Download market data from Yahoo! Finance's API

Pros of yfinance

  • Focused solely on fetching financial data from Yahoo Finance
  • Simpler to use for quick data retrieval tasks
  • Lightweight and easy to integrate into existing projects

Cons of yfinance

  • Limited to Yahoo Finance as a data source
  • Lacks built-in backtesting and trading strategy capabilities
  • May require additional libraries for comprehensive financial analysis

Code Comparison

yfinance:

import yfinance as yf
ticker = yf.Ticker("AAPL")
hist = ticker.history(period="1mo")
print(hist)

backtrader:

import backtrader as bt
cerebro = bt.Cerebro()
data = bt.feeds.YahooFinanceData(dataname="AAPL", fromdate=datetime(2020, 1, 1))
cerebro.adddata(data)
cerebro.run()

Summary

yfinance is a specialized library for fetching financial data from Yahoo Finance, offering simplicity and ease of use. backtrader, on the other hand, is a comprehensive backtesting framework that includes data fetching capabilities along with advanced trading strategy development and testing features. While yfinance excels in quick data retrieval tasks, backtrader provides a more robust environment for developing and testing trading strategies.

Python wrapper for TA-Lib (http://ta-lib.org/).

Pros of ta-lib-python

  • Extensive library of technical analysis functions
  • Optimized C implementation for faster calculations
  • Well-established and widely used in the financial industry

Cons of ta-lib-python

  • Requires separate installation of TA-Lib C library
  • Limited to technical analysis functions, not a full backtesting framework
  • Less flexibility for custom indicators and strategies

Code Comparison

ta-lib-python:

import talib
import numpy as np

close_prices = np.random.random(100)
sma = talib.SMA(close_prices, timeperiod=20)

backtrader:

import backtrader as bt

class MyStrategy(bt.Strategy):
    def __init__(self):
        self.sma = bt.indicators.SimpleMovingAverage(period=20)

    def next(self):
        if self.data.close[0] > self.sma[0]:
            self.buy()

ta-lib-python focuses on providing technical analysis functions, while backtrader offers a complete backtesting framework with strategy implementation capabilities. ta-lib-python is more suitable for quick calculations and integration into existing systems, whereas backtrader is better for developing and testing complete trading strategies.

2,172

bt - flexible backtesting for Python

Pros of bt

  • More modern codebase with better Python 3 support
  • Faster execution due to vectorized operations
  • Cleaner API and easier to use for beginners

Cons of bt

  • Smaller community and less documentation compared to backtrader
  • Fewer built-in features and indicators
  • Less flexibility for complex trading strategies

Code Comparison

backtrader:

class MyStrategy(bt.Strategy):
    def __init__(self):
        self.sma = bt.indicators.SimpleMovingAverage(self.data.close, period=20)

    def next(self):
        if self.data.close[0] > self.sma[0]:
            self.buy()
        elif self.data.close[0] < self.sma[0]:
            self.sell()

bt:

def my_strategy(data):
    sma = data.Close.rolling(20).mean()
    signals = bt.signals.from_series((data.Close > sma).astype(int))
    return signals

Both libraries offer backtesting capabilities for trading strategies, but they differ in their approach and syntax. backtrader uses an object-oriented design with strategies defined as classes, while bt employs a more functional programming style with strategies as functions. bt's vectorized operations can lead to faster execution, especially for large datasets, but backtrader's design may be more intuitive for some users and offers greater flexibility for complex strategies.

An Algorithmic Trading Library for Crypto-Assets in Python

Pros of Catalyst

  • Built on top of Enigma, providing enhanced privacy and security features
  • Supports both cryptocurrency and traditional asset trading
  • Offers a more comprehensive ecosystem with data feeds and exchange integrations

Cons of Catalyst

  • Steeper learning curve due to its complexity and broader feature set
  • Less active community and fewer resources compared to Backtrader
  • More resource-intensive, potentially slower for large-scale backtesting

Code Comparison

Catalyst example:

from catalyst import run_algorithm

def initialize(context):
    context.asset = symbol('btc_usdt')

def handle_data(context, data):
    current_price = data.current(context.asset, 'price')
    context.order_target_percent(context.asset, 1.0)

run_algorithm(capital_base=10000, data_frequency='minute', initialize=initialize, handle_data=handle_data)

Backtrader example:

import backtrader as bt

class MyStrategy(bt.Strategy):
    def __init__(self):
        self.dataclose = self.datas[0].close

    def next(self):
        if self.dataclose[0] > self.dataclose[-1]:
            self.buy()

cerebro = bt.Cerebro()
cerebro.addstrategy(MyStrategy)
cerebro.run()

Both libraries offer powerful backtesting capabilities, but Catalyst provides a more comprehensive ecosystem for cryptocurrency trading, while Backtrader is simpler and more focused on traditional asset backtesting.

Extract data from a wide range of Internet sources into a pandas DataFrame.

Pros of pandas-datareader

  • Simpler and more straightforward for basic data retrieval tasks
  • Integrates seamlessly with pandas DataFrames
  • Supports a wide range of data sources out of the box

Cons of pandas-datareader

  • Limited functionality for complex trading strategies and backtesting
  • Less active development and community support
  • Fewer built-in tools for analysis and visualization

Code Comparison

pandas-datareader:

import pandas_datareader as pdr
data = pdr.get_data_yahoo('AAPL', start='2020-01-01', end='2021-01-01')
print(data.head())

backtrader:

import backtrader as bt
cerebro = bt.Cerebro()
data = bt.feeds.YahooFinanceData(dataname='AAPL', fromdate=datetime(2020, 1, 1), todate=datetime(2021, 1, 1))
cerebro.adddata(data)
cerebro.run()

While pandas-datareader is more straightforward for simple data retrieval, backtrader offers a more comprehensive framework for developing and testing trading strategies. pandas-datareader is better suited for quick data analysis tasks, while backtrader excels in complex backtesting scenarios and strategy development.

Convert Figma logo designs to code with AI

Visual Copilot

Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.

Try Visual Copilot

README

backtrader

.. image:: https://img.shields.io/pypi/v/backtrader.svg :alt: PyPi Version :scale: 100% :target: https://pypi.python.org/pypi/backtrader/

.. .. image:: https://img.shields.io/pypi/dm/backtrader.svg :alt: PyPi Monthly Donwloads :scale: 100% :target: https://pypi.python.org/pypi/backtrader/

.. image:: https://img.shields.io/pypi/l/backtrader.svg :alt: License :scale: 100% :target: https://github.com/backtrader/backtrader/blob/master/LICENSE .. image:: https://travis-ci.org/backtrader/backtrader.png?branch=master :alt: Travis-ci Build Status :scale: 100% :target: https://travis-ci.org/backtrader/backtrader .. image:: https://img.shields.io/pypi/pyversions/backtrader.svg :alt: Python versions :scale: 100% :target: https://pypi.python.org/pypi/backtrader/

Yahoo API Note:

[2018-11-16] After some testing it would seem that data downloads can be again relied upon over the web interface (or API v7)

Tickets

The ticket system is (was, actually) more often than not abused to ask for advice about samples.

For feedback/questions/... use the Community <https://community.backtrader.com>_

Here a snippet of a Simple Moving Average CrossOver. It can be done in several different ways. Use the docs (and examples) Luke! ::

from datetime import datetime import backtrader as bt

class SmaCross(bt.SignalStrategy): def init(self): sma1, sma2 = bt.ind.SMA(period=10), bt.ind.SMA(period=30) crossover = bt.ind.CrossOver(sma1, sma2) self.signal_add(bt.SIGNAL_LONG, crossover)

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

data0 = bt.feeds.YahooFinanceData(dataname='MSFT', fromdate=datetime(2011, 1, 1), todate=datetime(2012, 12, 31)) cerebro.adddata(data0)

cerebro.run() cerebro.plot()

Including a full featured chart. Give it a try! This is included in the samples as sigsmacross/sigsmacross2.py. Along it is sigsmacross.py which can be parametrized from the command line.

Features:

Live Trading and backtesting platform written in Python.

  • Live Data Feed and Trading with

    • Interactive Brokers (needs IbPy and benefits greatly from an installed pytz)
    • Visual Chart (needs a fork of comtypes until a pull request is integrated in the release and benefits from pytz)
    • Oanda (needs oandapy) (REST API Only - v20 did not support streaming when implemented)
  • Data feeds from csv/files, online sources or from pandas and blaze

  • Filters for datas, like breaking a daily bar into chunks to simulate intraday or working with Renko bricks

  • Multiple data feeds and multiple strategies supported

  • Multiple timeframes at once

  • Integrated Resampling and Replaying

  • Step by Step backtesting or at once (except in the evaluation of the Strategy)

  • Integrated battery of indicators

  • TA-Lib indicator support (needs python ta-lib / check the docs)

  • Easy development of custom indicators

  • Analyzers (for example: TimeReturn, Sharpe Ratio, SQN) and pyfolio integration (deprecated)

  • Flexible definition of commission schemes

  • Integrated broker simulation with Market, Close, Limit, Stop, StopLimit, StopTrail, StopTrailLimitand OCO orders, bracket order, slippage, volume filling strategies and continuous cash adjustmet for future-like instruments

  • Sizers for automated staking

  • Cheat-on-Close and Cheat-on-Open modes

  • Schedulers

  • Trading Calendars

  • Plotting (requires matplotlib)

Documentation

The blog:

  • Blog <http://www.backtrader.com/blog>_

Read the full documentation at:

  • Documentation <http://www.backtrader.com/docu>_

List of built-in Indicators (122)

  • Indicators Reference <http://www.backtrader.com/docu/indautoref.html>_

Python 2/3 Support

  • Python >= 3.2

  • It also works with pypy and pypy3 (no plotting - matplotlib is not supported under pypy)

Installation

backtrader is self-contained with no external dependencies (except if you want to plot)

From pypi:

  • pip install backtrader

  • pip install backtrader[plotting]

    If matplotlib is not installed and you wish to do some plotting

.. note:: The minimum matplotlib version is 1.4.1

An example for IB Data Feeds/Trading:

For other functionalities like: Visual Chart, Oanda, TA-Lib, check the dependencies in the documentation.

From source:

  • Place the backtrader directory found in the sources inside your project

Version numbering

X.Y.Z.I

  • X: Major version number. Should stay stable unless something big is changed like an overhaul to use numpy
  • Y: Minor version number. To be changed upon adding a complete new feature or (god forbids) an incompatible API change.
  • Z: Revision version number. To be changed for documentation updates, small changes, small bug fixes
  • I: Number of Indicators already built into the platform