Skip to main content

Backtest trading strategies in Python

Project description

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)
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.

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.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

Backtesting-0.2.0.tar.gz (170.3 kB view hashes)

Uploaded Source

Supported by

AWS AWS Cloud computing and Security Sponsor Datadog Datadog Monitoring Fastly Fastly CDN Google Google Download Analytics Microsoft Microsoft PSF Sponsor Pingdom Pingdom Monitoring Sentry Sentry Error logging StatusPage StatusPage Status page