Git Product home page Git Product logo

backtesting.py's Introduction

Backtesting.py

Build Status Code Coverage Backtesting on PyPI

Backtest trading strategies with Python.

Project website

Documentation

Installation

$ pip install backtesting

Usage

from backtesting import Backtest, Strategy
from backtesting.lib import crossover

from backtesting.test import SMA, GOOG


class SmaCross(Strategy):
    def init(self):
        price = self.data.Close
        self.ma1 = self.I(SMA, price, 10)
        self.ma2 = self.I(SMA, price, 20)

    def next(self):
        if crossover(self.ma1, self.ma2):
            self.buy()
        elif crossover(self.ma2, self.ma1):
            self.sell()


bt = Backtest(GOOG, SmaCross, commission=.002,
              exclusive_orders=True)
stats = bt.run()
bt.plot()

Results in:

Start                     2004-08-19 00:00:00
End                       2013-03-01 00:00:00
Duration                   3116 days 00:00:00
Exposure Time [%]                       94.27
Equity Final [$]                     68935.12
Equity Peak [$]                      68991.22
Return [%]                             589.35
Buy & Hold Return [%]                  703.46
Max. Drawdown [%]                      -33.08
Avg. Drawdown [%]                       -5.58
Max. Drawdown Duration      688 days 00:00:00
Avg. Drawdown Duration       41 days 00:00:00
# Trades                                   93
Win Rate [%]                            53.76
Best Trade [%]                          57.12
Worst Trade [%]                        -16.63
Avg. Trade [%]                           1.96
Max. Trade Duration         121 days 00:00:00
Avg. Trade Duration          32 days 00:00:00
Profit Factor                            2.13
Expectancy [%]                           6.91
SQN                                      1.78
Sharpe Ratio                             0.18
Sortino Ratio                            0.44
Calmar Ratio                             0.06
_strategy              SmaCross(n1=10, n2=20)
_equity_curve                          Equ...
_trades                       Size  EntryB...

plot of trading simulation

Find more usage examples in the documentation.

Features

  • Simple, well-documented API
  • Blazing fast execution
  • Built-in optimizer
  • Library of composable base strategies and utilities
  • Indicator-library-agnostic
  • Supports any financial instrument with candlestick data
  • Detailed results
  • Interactive visualizations

Alternatives

The thing with backtesting is, unless you dug into the dirty details yourself, you can't rely on execution correctness, and you may lose your house. In addition, everyone has their own preconveived ideas about how a mechanical trading strategy should be conducted, so everyone (and their brothers) just rolls their own backtesting frameworks.

If after reviewing the docs and exmples perchance you find Backtesting.py is not your cup of tea, you can have a look at some similar alternative Python backtesting frameworks:

  • bt - a framework based on reusable and flexible blocks of strategy logic that support multiple instruments and output detailed statistics and useful charts.
  • vectorbt - a pandas-based library for quickly analyzing trading strategies at scale.
  • Backtrader - a pure-python feature-rich framework for backtesting and live algotrading with a few brokers.
  • PyAlgoTrade - event-driven algorithmic trading library with focus on backtesting and support for live trading.
  • Zipline - the backtesting and live-trading engine powering Quantopian โ€” the community-centered, hosted platform for building and executing strategies.
  • Pinkfish - a lightweight backtester for intraday strategies on daily data.
  • finmarketpy - a library for analyzing financial market data.
  • QuantStart QSTrader - a modular schedule-driven backtesting framework for long-short equities and ETF-based systematic trading strategies.
  • pysystemtrade - the open-source version of Robert Carver's backtesting engine that implements systems according to his book Systematic Trading: A unique new method for designing trading and investing systems.
  • QTPyLib - a versatile, event-driven algorithmic trading library.
  • Gemini - a backtester namely focusing on cryptocurrency markets.
  • Quantdom - a Qt-based framework that lets you focus on modeling financial strategies, portfolio management, and analyzing backtests.
  • Clairvoyant - software for identifying and monitoring social / historical cues for short-term stock movement.
  • optopsy - a nimble backtesting library for options trading.
  • RQalpha - a complete solution for programmatic traders from data acquisition, algorithmic trading, backtesting, real-time simulation, live trading to mere data analysis. Documentation in Chinese.
  • zvt - a quant trading platform which includes data recorder, factor calculation, stock picking, backtesting, and unified visualization. Documentation in Chinese.
  • AwesomeQuant - A somewhat curated list of libraries, packages, and resources for quants.

Obsolete / Unmaintained

The following projects are mainly old, stale, incomplete, incompatible, abandoned, and here for posterity reference only:

  • AlephNull - extends the features of Zipline, for use within an institutional environment.
  • ProfitPy - a set of libraries and tools for the development, testing, and execution of automated stock trading systems.
  • prophet - a microframework for financial markets, focusing on modeling strategies and portfolio management.
  • pybacktest - a vectorized pandas-based backtesting framework, designed to make backtesting compact, simple and fast.
  • quant - a technical analysis tool for trading strategies with a particularily simplistic view of the market.
  • QuantSoftware Toolkit - a toolkit by the guys that soon after went to form Lucena Research.
  • QuantStart QSForex - an event-driven backtesting and live-trading platform for use in the foreign exchange markets,
  • tia: Toolkit for integration and analysis - a toolkit providing Bloomberg data access, PDF generation, technical analysis and backtesting functionality.
  • TradingWithPython - boiler-plate code for the (no longer active) course Trading With Python.
  • Ultra-Finance - real-time financial data collection, analyzing and backtesting trading strategies.
  • visualize-wealth - a library to construct, backtest, analyze, and evaluate portfolios and their benchmarks, with comprehensive documentation illustrating all underlying methodologies and statistics.

backtesting.py's People

Contributors

kernc avatar nemi83 avatar tankorsmash avatar andremiras avatar eervin123 avatar tomaszlakota avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.