Python Backtesting library for trading strategies

Overview

backtrader

PyPi Version License Travis-ci Build Status Python versions

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

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, StopTrailLimit*and *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:

Read the full documentation at:

List of built-in Indicators (122)

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:

  • IbPy doesn't seem to be in PyPi. Do either:

    pip install git+https://github.com/blampe/IbPy.git
    

    or (if git is not available in your system):

    pip install https://github.com/blampe/IbPy/archive/master.zip
    

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
ARCH models in Python

arch Autoregressive Conditional Heteroskedasticity (ARCH) and other tools for financial econometrics, written in Python (with Cython and/or Numba used

Kevin Sheppard 1k Jan 04, 2023
rotki is an open source portfolio tracking, analytics, accounting and tax reporting tool that respects your privacy.

rotki is an open source portfolio tracking, analytics, accounting and tax reporting tool that respects your privacy. The mission of rotki is to bring transparency into the crypto and financial sector

Rotki 2k Dec 30, 2022
Github.com/CryptoSignal - #1 Quant Trading & Technical Analysis Bot - 2,100 + stars, 580 + forks

CryptoSignal - #1 Quant Trading & Technical Analysis Bot - 2,100 + stars, 580 + forks https://github.com/CryptoSignal/Crypto-Signal Development state:

Github.com/Signal - 2,100 + stars, 580 + forks 4.2k Jan 01, 2023
Supply a wrapper ``StockDataFrame`` based on the ``pandas.DataFrame`` with inline stock statistics/indicators support.

Stock Statistics/Indicators Calculation Helper VERSION: 0.3.2 Introduction Supply a wrapper StockDataFrame based on the pandas.DataFrame with inline s

Cedric Zhuang 1.1k Dec 28, 2022
Fourth and final milestone project

Milestone Project 4: Pound Dog Click link to visit "Pound Dog" Aim of the project The aim of this project is to provide access to a website informing

Jamie Wilson 1 Oct 31, 2021
An open source reinforcement learning framework for training, evaluating, and deploying robust trading agents.

TensorTrade: Trade Efficiently with Reinforcement Learning TensorTrade is still in Beta, meaning it should be used very cautiously if used in producti

4k Dec 30, 2022
Yahoo! Finance market data downloader (+faster Pandas Datareader)

Yahoo! Finance market data downloader Ever since Yahoo! finance decommissioned their historical data API, many programs that relied on it to stop work

Ran Aroussi 8.4k Jan 01, 2023
Common financial risk and performance metrics. Used by zipline and pyfolio.

empyrical Common financial risk metrics. Table of Contents Installation Usage Support Contributing Testing Installation pip install empyrical Usage S

Quantopian, Inc. 1k Dec 26, 2022
stock data on eink with raspberry

small python skript to display tradegate data on a waveshare e-ink important you need locale "de_AT.UTF-8 UTF-8" installed. do so in raspi-config's Lo

Simon Oberhammer 24 Feb 22, 2022
This repository contains a set of plugins for Volatility 3

volatility_plugins This repository contains a set of plugins for Volatility 3 These plugins are not compatible with Volatility 2 To use these plugins

Immersive-Labs-Sec 10 Nov 30, 2022
:mag_right: :chart_with_upwards_trend: :snake: :moneybag: Backtest trading strategies in Python.

Backtesting.py Backtest trading strategies with Python. Project website Documentation the project if you use it. Installation $ pip install backtestin

3.1k Dec 31, 2022
scrilla: A Financial Optimization Application

A python application that wraps around AlphaVantage, Quandl and IEX APIs, calculates financial statistics and optimizes portfolio allocations.

Grant Moore 6 Dec 17, 2022
High-performance TensorFlow library for quantitative finance.

TF Quant Finance: TensorFlow based Quant Finance Library Table of contents Introduction Installation TensorFlow training Development roadmap Examples

Google 3.5k Jan 01, 2023
Zipline, a Pythonic Algorithmic Trading Library

Zipline is a Pythonic algorithmic trading library. It is an event-driven system for backtesting. Zipline is currently used in production as the backte

Quantopian, Inc. 15.7k Jan 02, 2023
Python Backtesting library for trading strategies

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 v

DRo 9.8k Dec 30, 2022
Find big moving stocks before they move using machine learning and anomaly detection

Surpriver - Find High Moving Stocks before they Move Find high moving stocks before they move using anomaly detection and machine learning. Surpriver

Tradytics 1.5k Dec 31, 2022
This repository provides all Python codes and Jupyter Notebooks of the book Python for Finance

Python for Finance (O'Reilly) This repository provides all Python codes and Jupyter Notebooks of the book Python for Finance -- Analyze Big Financial

Yves Hilpisch 1.6k Jan 03, 2023
Performance analysis of predictive (alpha) stock factors

Alphalens Alphalens is a Python Library for performance analysis of predictive (alpha) stock factors. Alphalens works great with the Zipline open sour

Quantopian, Inc. 2.5k Dec 28, 2022
A proper portfolio tracker. Featuring historical allocation, cash flows and real returns.

Python Portfolio Analytics A portfolio tracker featuring account transactions, historical allocation, dividends and splits management and endless perf

Simone Precicchiani 13 Aug 13, 2022
Indicator divergence library for python

Indicator divergence library This module aims to help to find bullish/bearish divergences (regular or hidden) between two indicators using argrelextre

8 Dec 13, 2022