Skip to main content

Yet another backtesting engine

Project description

yabte - Yet Another BackTesting Engine

Python module for backtesting trading strategies.

Features

  • Event driven, ie on_open, on_close, etc.
  • Multiple assets.
  • OHLC Asset. Extendable (e.g support additional fields, e.g. Volatility, or entirely different fields, e.g. Barrels per day).
  • Multiple books.
  • Positional and Basket orders. Extendible (e.g. can support stop loss).
  • Batch runs (for optimization).
  • Captures book history including transactions & daily cash, MtM and total values.

The module provides basic statistics like book cash, mtm and total value. Currently, everything else needs to be deferred to a 3rd party module like empyrical.

Core dependencies

The core module uses pandas and scipy.

Installation

pip install yatbe

Usage

Below is an example usage (the economic performance of the example strategy won't be good).

import pandas as pd

from yabte.backtest import Book, SimpleOrder, Strategy, StrategyRunner
from yabte.tests._helpers import generate_nasdaq_dataset
from yabte.utilities.plot.plotly.strategy_runner import plot_strategy_runner_result
from yabte.utilities.strategy_helpers import crossover


class SMAXO(Strategy):
    def init(self):
        # enhance data with simple moving averages

        p = self.params
        days_short = p.get("days_short", 10)
        days_long = p.get("days_long", 20)

        close_sma_short = (
            self.data.loc[:, (slice(None), "Close")]
            .rolling(days_short)
            .mean()
            .rename({"Close": "CloseSMAShort"}, axis=1, level=1)
        )
        close_sma_long = (
            self.data.loc[:, (slice(None), "Close")]
            .rolling(days_long)
            .mean()
            .rename({"Close": "CloseSMALong"}, axis=1, level=1)
        )
        self.data = pd.concat(
            [self.data, close_sma_short, close_sma_long], axis=1
        ).sort_index(axis=1)

    def on_close(self):
        # create some orders

        for symbol in ["GOOG", "MSFT"]:
            df = self.data[symbol]
            ix_2d = df.index[-2:]
            data = df.loc[ix_2d, ("CloseSMAShort", "CloseSMALong")].dropna()
            if len(data) == 2:
                if crossover(data.CloseSMAShort, data.CloseSMALong):
                    self.orders.append(SimpleOrder(asset_name=symbol, size=-100))
                elif crossover(data.CloseSMALong, data.CloseSMAShort):
                    self.orders.append(SimpleOrder(asset_name=symbol, size=100))


# load some data
assets, df_combined = generate_nasdaq_dataset()

# create a book with 100000 cash
book = Book(name="Main", cash="100000")

# run our strategy
sr = StrategyRunner(
    data=df_combined,
    assets=assets,
    strategies=[SMAXO()],
    books=[book],
)
srr = sr.run()

# see the trades or book history
th = srr.transaction_history
bch = srr.book_history.loc[:, (slice(None), "cash")]

# plot the trades against book value
plot_strategy_runner_result(srr, sr)

Output from code

Examples

Jupyter notebook examples can be found under the notebooks folder.

Documentation

Documentation can be found on Read the Docs.

Development

Before commit run following format commands in project folder:

poetry run black .
poetry run isort . --profile black
poetry run docformatter . --recursive --in-place --black --exclude _unittest_numpy_extensions.py

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

yabte-0.4.1.tar.gz (284.9 kB view details)

Uploaded Source

Built Distributions

yabte-0.4.1-py3-none-any.whl (292.5 kB view details)

Uploaded Python 3

yabte-0.4.1-cp310-cp310-manylinux_2_35_x86_64.whl (292.5 kB view details)

Uploaded CPython 3.10 manylinux: glibc 2.35+ x86-64

File details

Details for the file yabte-0.4.1.tar.gz.

File metadata

  • Download URL: yabte-0.4.1.tar.gz
  • Upload date:
  • Size: 284.9 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: poetry/1.3.1 CPython/3.10.12 Linux/6.5.0-1018-azure

File hashes

Hashes for yabte-0.4.1.tar.gz
Algorithm Hash digest
SHA256 340fe005825648c3298190ceafcda070cc6add7b6a1ebfd1d744696170bc43c7
MD5 87af19c062c9d653c15602e77da2ea1c
BLAKE2b-256 10210de0b5a8b5abdef7f00ae3258312b1183e3480957f25f93bcbdfeb046374

See more details on using hashes here.

File details

Details for the file yabte-0.4.1-py3-none-any.whl.

File metadata

  • Download URL: yabte-0.4.1-py3-none-any.whl
  • Upload date:
  • Size: 292.5 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: poetry/1.3.1 CPython/3.10.12 Linux/6.5.0-1018-azure

File hashes

Hashes for yabte-0.4.1-py3-none-any.whl
Algorithm Hash digest
SHA256 be42d7ca7576dd8fc7d65dddf6cb1cf717aee9e9f2cfc88afaca3b3dc24e5c3a
MD5 99dad87a3f869e3ec60e5e433caf7b1f
BLAKE2b-256 826062dddb9a3222286023b5685deba506cedded33b7b2eaacdf216d4269e527

See more details on using hashes here.

File details

Details for the file yabte-0.4.1-cp310-cp310-manylinux_2_35_x86_64.whl.

File metadata

  • Download URL: yabte-0.4.1-cp310-cp310-manylinux_2_35_x86_64.whl
  • Upload date:
  • Size: 292.5 kB
  • Tags: CPython 3.10, manylinux: glibc 2.35+ x86-64
  • Uploaded using Trusted Publishing? No
  • Uploaded via: poetry/1.3.1 CPython/3.10.12 Linux/6.5.0-1018-azure

File hashes

Hashes for yabte-0.4.1-cp310-cp310-manylinux_2_35_x86_64.whl
Algorithm Hash digest
SHA256 86059eb9dbbbb8413d3fca0f0fcfa9aaf16312ab20e90a55862a7536ad67de7f
MD5 ab472e1b255c095f79f83752bc475557
BLAKE2b-256 b5c66eeb5b0d9913bb38b03cdc9aa5fecf6f2d008548cbf72bb556f5da325174

See more details on using hashes here.

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