Backtesting


NameBacktesting JSON
Version 0.2.3 PyPI version JSON
download
home_pagehttps://kernc.github.io/backtesting.py/
SummaryBacktest trading strategies in Python
upload_time2020-09-16 17:40:29
maintainer
docs_urlNone
authorZach Lûster
requires_python>=3.4
licenseAGPL-3.0
keywords algo algorithmic ashi backtest backtesting bitcoin bokeh bonds candle candlestick cboe chart cme commodities crash crypto currency doji drawdown equity etf ethereum exchange finance financial forecast forex fund futures fx fxpro gold heiken historical indicator invest investing investment macd market mechanical money oanda ohlc ohlcv order price profit quant quantitative rsi silver stocks strategy ticker trader trading tradingview usd
VCS
bugtrack_url
requirements No requirements were recorded.
Travis-CI No Travis.
coveralls test coverage No coveralls.
            [![](https://i.imgur.com/E8Kj69Y.png)](https://kernc.github.io/backtesting.py/)

Backtesting.py
==============
[![Build Status](https://img.shields.io/travis/kernc/backtesting.py.svg?style=for-the-badge)](https://travis-ci.org/kernc/backtesting.py)
[![Code Coverage](https://img.shields.io/codecov/c/gh/kernc/backtesting.py.svg?style=for-the-badge)](https://codecov.io/gh/kernc/backtesting.py)
[![Backtesting on PyPI](https://img.shields.io/pypi/v/backtesting.svg?color=blue&style=for-the-badge)](https://pypi.org/project/backtesting)

Backtest trading strategies with Python.

[**Project website**][website]

[Documentation]

[website]: https://kernc.github.io/backtesting.py/
[Documentation]: https://kernc.github.io/backtesting.py/doc/backtesting/


Installation
------------

    $ pip install backtesting


Usage
-----
```python
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:

```text
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](https://i.imgur.com/xRFNHfg.png)](https://kernc.github.io/backtesting.py/#example)

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_][website] is not your cup of tea,
you can have a look at some similar alternative Python backtesting frameworks:

- [bt](http://pmorissette.github.io/bt/) -
  a framework based on reusable and flexible blocks of
  strategy logic that support multiple instruments and
  output detailed statistics and useful charts.
- [vectorbt](https://polakowo.io/vectorbt/) -
  a pandas-based library for quickly analyzing trading strategies at scale.
- [Backtrader](https://www.backtrader.com/) -
  a pure-python feature-rich framework for backtesting
  and live algotrading with a few brokers.
- [PyAlgoTrade](https://gbeced.github.io/pyalgotrade/) -
  event-driven algorithmic trading library with focus on
  backtesting and support for live trading.
- [Zipline](https://www.zipline.io/) -
  the backtesting and live-trading engine powering Quantopian — the
  community-centered, hosted platform for building and executing strategies.
- [Pinkfish](http://fja05680.github.io/pinkfish/) -
  a lightweight backtester for intraday strategies on daily data.
- [finmarketpy](https://github.com/cuemacro/finmarketpy) -
  a library for analyzing financial market data.
- [QuantStart QSTrader](https://github.com/mhallsmoore/qstrader/) -
  a modular schedule-driven backtesting framework for long-short equities
  and ETF-based systematic trading strategies.
- [pysystemtrade](https://github.com/robcarver17/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](https://github.com/ranaroussi/qtpylib) -
  a versatile, event-driven algorithmic trading library.
- [Gemini](https://github.com/anfederico/Gemini) -
  a backtester namely focusing on cryptocurrency markets.
- [Quantdom](https://github.com/constverum/Quantdom) -
  a Qt-based framework that lets you focus on modeling financial strategies,
  portfolio management, and analyzing backtests.
- [Clairvoyant](https://github.com/anfederico/Clairvoyant) -
  software for identifying and monitoring social / historical cues
  for short-term stock movement.
- [optopsy](https://github.com/michaelchu/optopsy) -
  a nimble backtesting library for options trading.
- [RQalpha](https://github.com/ricequant/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](https://github.com/zvtvz/zvt) -
  a quant trading platform which includes data recorder, factor calculation,
  stock picking, backtesting, and unified visualization. Documentation in Chinese.
- [AwesomeQuant](https://github.com/wilsonfreitas/awesome-quant#trading--backtesting) -
  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](https://github.com/CarterBain/AlephNull) -
  extends the features of Zipline, for use within an institutional environment.
- [ProfitPy](https://code.google.com/p/profitpy/) -
  a set of libraries and tools for the development, testing, and execution of
  automated stock trading systems.
- [prophet](https://github.com/Emsu/prophet) -
  a microframework for financial markets, focusing on modeling
  strategies and portfolio management.
- [pybacktest](https://github.com/ematvey/pybacktest) -
  a vectorized pandas-based backtesting framework,
  designed to make backtesting compact, simple and fast.
- [quant](https://github.com/maihde/quant) -
  a technical analysis tool for trading strategies with a particularily
  simplistic view of the market.
- [QuantSoftware Toolkit](https://github.com/QuantSoftware/QuantSoftwareToolkit) -
  a toolkit by the guys that soon after went to form Lucena Research.
- [QuantStart QSForex](https://github.com/mhallsmoore/qsforex) -
  an event-driven backtesting and live-trading platform for use in
  the foreign exchange markets,
- [tia: Toolkit for integration and analysis](https://github.com/PaulMest/tia/) -
  a toolkit providing Bloomberg data access, PDF generation,
  technical analysis and backtesting functionality.
- [TradingWithPython](https://github.com/sjev/trading-with-python) -
  boiler-plate code for the (no longer active) course _Trading With Python_.
- [Ultra-Finance](https://github.com/panpanpandas/ultrafinance) -
  real-time financial data collection, analyzing and backtesting trading strategies.
- [visualize-wealth](https://github.com/benjaminmgross/visualize-wealth) -
  a library to construct, backtest, analyze, and evaluate portfolios
  and their benchmarks, with comprehensive documentation illustrating
  all underlying methodologies and statistics.
            

Raw data

            {
    "_id": null,
    "home_page": "https://kernc.github.io/backtesting.py/",
    "name": "Backtesting",
    "maintainer": "",
    "docs_url": null,
    "requires_python": ">=3.4",
    "maintainer_email": "",
    "keywords": "algo,algorithmic,ashi,backtest,backtesting,bitcoin,bokeh,bonds,candle,candlestick,cboe,chart,cme,commodities,crash,crypto,currency,doji,drawdown,equity,etf,ethereum,exchange,finance,financial,forecast,forex,fund,futures,fx,fxpro,gold,heiken,historical,indicator,invest,investing,investment,macd,market,mechanical,money,oanda,ohlc,ohlcv,order,price,profit,quant,quantitative,rsi,silver,stocks,strategy,ticker,trader,trading,tradingview,usd",
    "author": "Zach L\u00fbster",
    "author_email": "",
    "download_url": "https://files.pythonhosted.org/packages/4a/1b/69dea1132b620b6d32e410af760e551844344a0ede7378865150c8714a32/Backtesting-0.2.3.tar.gz",
    "platform": "",
    "description": "[![](https://i.imgur.com/E8Kj69Y.png)](https://kernc.github.io/backtesting.py/)\n\nBacktesting.py\n==============\n[![Build Status](https://img.shields.io/travis/kernc/backtesting.py.svg?style=for-the-badge)](https://travis-ci.org/kernc/backtesting.py)\n[![Code Coverage](https://img.shields.io/codecov/c/gh/kernc/backtesting.py.svg?style=for-the-badge)](https://codecov.io/gh/kernc/backtesting.py)\n[![Backtesting on PyPI](https://img.shields.io/pypi/v/backtesting.svg?color=blue&style=for-the-badge)](https://pypi.org/project/backtesting)\n\nBacktest trading strategies with Python.\n\n[**Project website**][website]\n\n[Documentation]\n\n[website]: https://kernc.github.io/backtesting.py/\n[Documentation]: https://kernc.github.io/backtesting.py/doc/backtesting/\n\n\nInstallation\n------------\n\n    $ pip install backtesting\n\n\nUsage\n-----\n```python\nfrom backtesting import Backtest, Strategy\nfrom backtesting.lib import crossover\n\nfrom backtesting.test import SMA, GOOG\n\n\nclass SmaCross(Strategy):\n    def init(self):\n        price = self.data.Close\n        self.ma1 = self.I(SMA, price, 10)\n        self.ma2 = self.I(SMA, price, 20)\n\n    def next(self):\n        if crossover(self.ma1, self.ma2):\n            self.buy()\n        elif crossover(self.ma2, self.ma1):\n            self.sell()\n\n\nbt = Backtest(GOOG, SmaCross, commission=.002,\n              exclusive_orders=True)\nstats = bt.run()\nbt.plot()\n```\n\nResults in:\n\n```text\nStart                     2004-08-19 00:00:00\nEnd                       2013-03-01 00:00:00\nDuration                   3116 days 00:00:00\nExposure Time [%]                       94.27\nEquity Final [$]                     68935.12\nEquity Peak [$]                      68991.22\nReturn [%]                             589.35\nBuy & Hold Return [%]                  703.46\nMax. Drawdown [%]                      -33.08\nAvg. Drawdown [%]                       -5.58\nMax. Drawdown Duration      688 days 00:00:00\nAvg. Drawdown Duration       41 days 00:00:00\n# Trades                                   93\nWin Rate [%]                            53.76\nBest Trade [%]                          57.12\nWorst Trade [%]                        -16.63\nAvg. Trade [%]                           1.96\nMax. Trade Duration         121 days 00:00:00\nAvg. Trade Duration          32 days 00:00:00\nProfit Factor                            2.13\nExpectancy [%]                           6.91\nSQN                                      1.78\nSharpe Ratio                             0.18\nSortino Ratio                            0.44\nCalmar Ratio                             0.06\n_strategy              SmaCross(n1=10, n2=20)\n_equity_curve                          Equ...\n_trades                       Size  EntryB...\n```\n[![plot of trading simulation](https://i.imgur.com/xRFNHfg.png)](https://kernc.github.io/backtesting.py/#example)\n\nFind more usage examples in the [documentation].\n\nFeatures\n--------\n* Simple, well-documented API\n* Blazing fast execution\n* Built-in optimizer\n* Library of composable base strategies and utilities\n* Indicator-library-agnostic\n* Supports _any_ financial instrument with candlestick data\n* Detailed results\n* Interactive visualizations\n\n\nAlternatives\n------------\nThe thing with backtesting is, unless you dug into the dirty details yourself,\nyou can't rely on execution correctness, and you may lose your house.\nIn addition, everyone has their own preconveived ideas about how a mechanical\ntrading strategy should be conducted, so everyone (and their brothers)\njust rolls their own backtesting frameworks.\n\nIf after reviewing the docs and exmples perchance you find\n[_Backtesting.py_][website] is not your cup of tea,\nyou can have a look at some similar alternative Python backtesting frameworks:\n\n- [bt](http://pmorissette.github.io/bt/) -\n  a framework based on reusable and flexible blocks of\n  strategy logic that support multiple instruments and\n  output detailed statistics and useful charts.\n- [vectorbt](https://polakowo.io/vectorbt/) -\n  a pandas-based library for quickly analyzing trading strategies at scale.\n- [Backtrader](https://www.backtrader.com/) -\n  a pure-python feature-rich framework for backtesting\n  and live algotrading with a few brokers.\n- [PyAlgoTrade](https://gbeced.github.io/pyalgotrade/) -\n  event-driven algorithmic trading library with focus on\n  backtesting and support for live trading.\n- [Zipline](https://www.zipline.io/) -\n  the backtesting and live-trading engine powering Quantopian \u2014 the\n  community-centered, hosted platform for building and executing strategies.\n- [Pinkfish](http://fja05680.github.io/pinkfish/) -\n  a lightweight backtester for intraday strategies on daily data.\n- [finmarketpy](https://github.com/cuemacro/finmarketpy) -\n  a library for analyzing financial market data.\n- [QuantStart QSTrader](https://github.com/mhallsmoore/qstrader/) -\n  a modular schedule-driven backtesting framework for long-short equities\n  and ETF-based systematic trading strategies.\n- [pysystemtrade](https://github.com/robcarver17/pysystemtrade) -\n  the open-source version of Robert Carver's backtesting engine that\n  implements systems according to his book _Systematic Trading:\n  A unique new method for designing trading and investing systems_.\n- [QTPyLib](https://github.com/ranaroussi/qtpylib) -\n  a versatile, event-driven algorithmic trading library.\n- [Gemini](https://github.com/anfederico/Gemini) -\n  a backtester namely focusing on cryptocurrency markets.\n- [Quantdom](https://github.com/constverum/Quantdom) -\n  a Qt-based framework that lets you focus on modeling financial strategies,\n  portfolio management, and analyzing backtests.\n- [Clairvoyant](https://github.com/anfederico/Clairvoyant) -\n  software for identifying and monitoring social / historical cues\n  for short-term stock movement.\n- [optopsy](https://github.com/michaelchu/optopsy) -\n  a nimble backtesting library for options trading.\n- [RQalpha](https://github.com/ricequant/rqalpha) -\n  a complete solution for programmatic traders from data acquisition,\n  algorithmic trading, backtesting, real-time simulation, live trading\n  to mere data analysis. Documentation in Chinese.\n- [zvt](https://github.com/zvtvz/zvt) -\n  a quant trading platform which includes data recorder, factor calculation,\n  stock picking, backtesting, and unified visualization. Documentation in Chinese.\n- [AwesomeQuant](https://github.com/wilsonfreitas/awesome-quant#trading--backtesting) -\n  A somewhat curated list of libraries, packages, and resources for quants.\n\n#### Obsolete / Unmaintained\n\nThe following projects are mainly old, stale, incomplete, incompatible,\nabandoned, and here for posterity reference only:\n\n- [AlephNull](https://github.com/CarterBain/AlephNull) -\n  extends the features of Zipline, for use within an institutional environment.\n- [ProfitPy](https://code.google.com/p/profitpy/) -\n  a set of libraries and tools for the development, testing, and execution of\n  automated stock trading systems.\n- [prophet](https://github.com/Emsu/prophet) -\n  a microframework for financial markets, focusing on modeling\n  strategies and portfolio management.\n- [pybacktest](https://github.com/ematvey/pybacktest) -\n  a vectorized pandas-based backtesting framework,\n  designed to make backtesting compact, simple and fast.\n- [quant](https://github.com/maihde/quant) -\n  a technical analysis tool for trading strategies with a particularily\n  simplistic view of the market.\n- [QuantSoftware Toolkit](https://github.com/QuantSoftware/QuantSoftwareToolkit) -\n  a toolkit by the guys that soon after went to form Lucena Research.\n- [QuantStart QSForex](https://github.com/mhallsmoore/qsforex) -\n  an event-driven backtesting and live-trading platform for use in\n  the foreign exchange markets,\n- [tia: Toolkit for integration and analysis](https://github.com/PaulMest/tia/) -\n  a toolkit providing Bloomberg data access, PDF generation,\n  technical analysis and backtesting functionality.\n- [TradingWithPython](https://github.com/sjev/trading-with-python) -\n  boiler-plate code for the (no longer active) course _Trading With Python_.\n- [Ultra-Finance](https://github.com/panpanpandas/ultrafinance) -\n  real-time financial data collection, analyzing and backtesting trading strategies.\n- [visualize-wealth](https://github.com/benjaminmgross/visualize-wealth) -\n  a library to construct, backtest, analyze, and evaluate portfolios\n  and their benchmarks, with comprehensive documentation illustrating\n  all underlying methodologies and statistics.",
    "bugtrack_url": null,
    "license": "AGPL-3.0",
    "summary": "Backtest trading strategies in Python",
    "version": "0.2.3",
    "split_keywords": [
        "algo",
        "algorithmic",
        "ashi",
        "backtest",
        "backtesting",
        "bitcoin",
        "bokeh",
        "bonds",
        "candle",
        "candlestick",
        "cboe",
        "chart",
        "cme",
        "commodities",
        "crash",
        "crypto",
        "currency",
        "doji",
        "drawdown",
        "equity",
        "etf",
        "ethereum",
        "exchange",
        "finance",
        "financial",
        "forecast",
        "forex",
        "fund",
        "futures",
        "fx",
        "fxpro",
        "gold",
        "heiken",
        "historical",
        "indicator",
        "invest",
        "investing",
        "investment",
        "macd",
        "market",
        "mechanical",
        "money",
        "oanda",
        "ohlc",
        "ohlcv",
        "order",
        "price",
        "profit",
        "quant",
        "quantitative",
        "rsi",
        "silver",
        "stocks",
        "strategy",
        "ticker",
        "trader",
        "trading",
        "tradingview",
        "usd"
    ],
    "urls": [
        {
            "comment_text": "",
            "digests": {
                "md5": "17492f069e105faae5392872afead2c0",
                "sha256": "21fd7111bda9ca64e71a3804c901df5192fa813137e55472142a1e492c48ca0d"
            },
            "downloads": -1,
            "filename": "Backtesting-0.2.3.tar.gz",
            "has_sig": false,
            "md5_digest": "17492f069e105faae5392872afead2c0",
            "packagetype": "sdist",
            "python_version": "source",
            "requires_python": ">=3.4",
            "size": 171571,
            "upload_time": "2020-09-16T17:40:29",
            "upload_time_iso_8601": "2020-09-16T17:40:29.083061Z",
            "url": "https://files.pythonhosted.org/packages/4a/1b/69dea1132b620b6d32e410af760e551844344a0ede7378865150c8714a32/Backtesting-0.2.3.tar.gz",
            "yanked": false,
            "yanked_reason": null
        }
    ],
    "upload_time": "2020-09-16 17:40:29",
    "github": false,
    "gitlab": false,
    "bitbucket": false,
    "lcname": "backtesting"
}
        
Elapsed time: 0.16751s