Skip to main content

A packaged designed for backtesting single and multi ticker strategies

Project description

Backtest

Custom backtest framework

installation

pip install mtbacktest

To back test your strategy using this frame work we first define the strategy you want to run,

An example multi-ticker strategy (long short), the custom strategy class must contain a self.trader attribute for the framework to run

from mtbacktest.strategy import Strategy
class MultiTickerDummyStrat():
    def __init__(self):
        self.trader = Strategy() # A virtual trader that you can submit orders and contains information about the portfolio it manages, you MUST DEFINE THIS AS 'self.trader'
        self.account = self.trader.account
        def signal(dreturn):
            """
            Define the signal such that if the current day return is greater than 2% we open long position,
            and vice versa, this is performed on all tickers passed into the iter function, which runs, 1 iteration
            of the algorithm
            """
            if dreturn > 2:
                return 1
            if dreturn < -2:
                return -1
            return 0
        self.signal_func= signal
    
    def iter(self, data, tickers):
        """
        You must define an iter() method that takes in data and specify what you want to do each iteration
        Note: you can design a different strategy for each ticker, for more customisable strategies.
        """

        for ticker in tickers:

            data['dreturn_' + ticker] = (data['close_' + ticker] - data['open_' + ticker]) / data['open_' + ticker] * 100
            curr_signal = self.signal_func(data['dreturn_' + ticker])
            units = (self.account.buying_power // 3)/data['close_' + ticker]
            curr_portfolio = self.account.portfolio_snapshots.iloc[-1]['portfolio']
            open_positions = [pos for pos in curr_portfolio.positions if pos.symbol == ticker and pos.status == 'open']
            if curr_signal == 1:
                '''
                We long equity
                '''
                if len(open_positions) == 0:
                    self.trader.create_position(data['timestamp'], ticker, units, data['close_'+ticker])
            
            elif curr_signal == -1:
                '''
                We short equity
                '''
                if len(open_positions) == 0:
                    self.trader.create_position(data['timestamp'], ticker, -units, data['close_'+ticker])

            elif curr_signal == 0 and len(open_positions) > 0:
                '''
                We close position
                '''
                self.trader.close_position(data['timestamp'], ticker, data['close_'+ticker])

Then you can backtest the strategy like the following, if you choose to bring your own data

from mtbacktest.backtest import Backtest
from mtbacktest.lib.preprocessing import df_to_dict, data_preprocess
import pandas as pd
import numpy as np

data = pd.read_json('test_data1.json')
data2 = pd.read_json('test_data2.json')

# Define your own custom features
data['dreturn'] = ((data['close'] - data['open'])/data['open']) * 100
data2['dreturn'] = ((data2['close'] - data2['open'])/data2['open']) * 100
data2 = data2.iloc[-100:]
data = data.iloc[-100:]

# standardise data for passing into the backtester
data = df_to_dict([data, data2], ['AAPL', 'TSLA']) # dataframe order should align with ticker list order
data = data_preprocess(data)

# Initiate backtest
bt = Backtest(MultiTickerDummyStrat, data, ['AAPL', 'TSLA'])
bt.run(verbose=1)
bt.plot()

The library also supports data fetching utilities, you can fetch data for stocks traded on US exchanges and LSE as well as crypto, note that when requesting for crypto data you should add "-USD" as suffix, for example, "BTC-USD", "SOL-USD", are accepted tickers.

An example of usage of the data collection utility is,

from mtbacktest.data import Data
client = Data()
daily_data = client.get_daily_data(['AAPL', 'TSLA']) # for daily data
# The accepted intervals are 1m, 5m, 1h for intraday requests
intraday_data = client.get_intraday_data(['AAPL', 'TSLA'], interval='5m') # for intraday data

The data requested from the data module will be already standardised for parsing into the backtester, so no further processing is required, however, you will need to engineer your own feature if required, for future updates, we will implement a function to assist feature engineering.

Using the builtin data module, the work flow look something like this

from mtbacktest.backtest import Backtest
import pandas as pd
import numpy as np
from mtbacktest.data import Data

client = Data()
data = client.get_daily_data(['AAPL', 'TSLA'])
# Initiate backtest
bt = Backtest(MultiTickerDummyStrat, data, ['AAPL', 'TSLA'])
bt.run(verbose=1)
bt.plot()

Then produce this graph

demo output

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

mtbacktest-0.1.17.tar.gz (11.2 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

mtbacktest-0.1.17-py3-none-any.whl (12.3 kB view details)

Uploaded Python 3

File details

Details for the file mtbacktest-0.1.17.tar.gz.

File metadata

  • Download URL: mtbacktest-0.1.17.tar.gz
  • Upload date:
  • Size: 11.2 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.1.0 CPython/3.9.13

File hashes

Hashes for mtbacktest-0.1.17.tar.gz
Algorithm Hash digest
SHA256 59b76615140abdccb1b8ea2f6fb8046ac13a83c2cad1231819af3766ae7ac197
MD5 09e2f5c6167fd6207cf95b5362e0def0
BLAKE2b-256 0e282d447fd44a91f46192165cca4cabbb631e9729d69efe5bdd1944868babd3

See more details on using hashes here.

File details

Details for the file mtbacktest-0.1.17-py3-none-any.whl.

File metadata

  • Download URL: mtbacktest-0.1.17-py3-none-any.whl
  • Upload date:
  • Size: 12.3 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.1.0 CPython/3.9.13

File hashes

Hashes for mtbacktest-0.1.17-py3-none-any.whl
Algorithm Hash digest
SHA256 b4df44c264336a05f101ed3054d8d3d1ef91c68d4313fa594026df1002690c8a
MD5 52ca647486292aec488e7c7cebcb4b29
BLAKE2b-256 008b5ff79c5aed3c9696121e9d10a7105d0bc8e99aff8bd46de812e66c3dc01e

See more details on using hashes here.

Supported by

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