Skip to main content

backtestify

Table of Contents

Introduction

While there are already backtesting tools available, I aimed to create a tool that allows for more accurate backtesting specifically for Contract for Difference (CFD). My vision was to create a comprehensive tool that takes care of the entire backtesting process, where the trader can focus solely on strategy formulation and testing new strategies without needing to invest time in coding. This tool is envisioned to be user-friendly and fully open-source, similar to other strategy analysis builders available on the market, but with the added benefit of being completely free.

While platforms like MetaTrader 5 allow for backtesting strategies using technical indicators, they often fall short when it comes to applying advanced techniques such as machine learning. Such processes can be complicated and tedious. By creating a backtester directly in Python, this process is significantly simplified, and it also opens up the possibility of utilizing all kinds of existing Python modules.

Installation

pip install backtestify

Usage

A simple example of how to use the package is shown below. More examples will be added in the future in the examples folder.

import pandas as pd
from backtestify import Strategy, SignalEvent, SignalType, Backtester, Account, CFD, InstrumentType
import MetaTrader5 as mt5
import datetime
import talib as ta

def get_asset_info_mt5(symbol, timeframe=mt5.TIMEFRAME_D1, n=1000):
    mt5.initialize()
    utc_from = datetime.datetime.now()
    rates = mt5.copy_rates_from(symbol, timeframe, utc_from, n)
    rates_frame = pd.DataFrame(rates)

    columns = ['time', 'open', 'high', 'low', 'close', 'tick_volume']
    rates_frame = rates_frame[columns]

    rates_frame = rates_frame.set_index('time')
    rates_frame.rename(columns={'tick_volume': 'volume'}, inplace=True)
    rates_frame.index.name = 'timestamp'

    rates_frame['swap_long'] = -7.84 # This is the swap rate for SPX500. This can be found in the Market Watch window in MetaTrader 5 this could be different for a specific broker or instrument and take in consideration that this could be different depending on the day of the week.
    rates_frame['swap_short'] = 4.26

    return rates_frame

class RSIStrategy(Strategy):
    def __init__(self, market_info, rsi_period):
        self.rsi_period = rsi_period
        self.previous_trade_signal = None
        market_info["rsi"] = ta.RSI(market_info["close"], timeperiod=rsi_period)

        super().__init__(market_info)

    def on_tick(self, history):
        try:

            current = history.iloc[-1]

            if current["rsi"] is None:
                return

            if current["rsi"] < 30 and self.previous_trade_signal != SignalType.BUY:
                self.previous_trade_signal = SignalType.BUY
                return [
                    SignalEvent(signal=SignalType.EXIT),
                    SignalEvent(signal=SignalType.BUY)
                ]

            if current["rsi"] > 70 and self.previous_trade_signal != SignalType.SELL:
                self.previous_trade_signal = SignalType.SELL
                return [
                    SignalEvent(signal=SignalType.EXIT),
                    SignalEvent(signal=SignalType.SELL)
                ]

        except Exception as e:
            pass

cfd = CFD(
    instrument_type=InstrumentType.STOCK,
    lot_size=1,
    entry_lots=1,
    commission=0,
    point_value=1,
    leverage=100,
    point=0.01,
    spread=5,
    period=mt5.TIMEFRAME_D1,
    pips=0.01,
)
df = get_asset_info_mt5("SPX500")

sma = RSIStrategy(df, 14)
account = Account(10000)
backtester = Backtester(sma, cfd, account)
backtester.run()

backtester.results

Contributing

For any bug reports or recommendations, please visit our issue tracker and create a new issue. If you're reporting a bug, it would be great if you can provide a minimal reproducible example.

Thank you for your contribution!

License

Apache 2.0

Metadata

Release files for backtestify 0.1.6

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for backtestify 0.1.6
File Size Uploaded
backtestify-0.1.6.tar.gz 16.2 kB Details

Built distribution (wheel)

Table of built distributions (wheels) for backtestify 0.1.6
File Interpreter ABI Platform
backtestify-0.1.6-py3-none-any.whl Python 3 none any Details

Total release size: 34.6 kB

Release files / backtestify-0.1.6.tar.gz

Download URL backtestify-0.1.6.tar.gz
Size 16.2 kB
Tags Source
SHA-256 checksum
How to use checksums
ddf855a7e8456c797de6a8ddd7bc63d9603f14a1138a1f490ac28f7dc6a3663f
BLAKE2b-256 checksum
How to use checksums
26ee94be11364b46a6763d98fea8e54835df6ebe297644eb6ed563adc7f20510
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/4.0.2 CPython/3.9.13

Release files / backtestify-0.1.6-py3-none-any.whl

Download URL backtestify-0.1.6-py3-none-any.whl
Size 18.5 kB
Tags Python 3
SHA-256 checksum
How to use checksums
21a7bf58455944b471e0b2f1f90fdae7cdfdaa5c30268c756d367e2552bf9e6e
BLAKE2b-256 checksum
How to use checksums
1cb67f838acc26afd9c995429eb19580209f2e04d3e7e38df667c460e4e5ccdc
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/4.0.2 CPython/3.9.13

Release history Release notifications | RSS feed

This release

0.1.6 This release

2 release files

0.1.5

2 release files

0.1.4

2 release files

0.1.3

2 release files

0.1.2

2 release files

0.1.1

2 release files

0.1.0

2 release files

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page