Backtest Strategy Using Backtrader Framework

Generating CSV/TXT Data:


import pandas as pd
from upstox_api.api import*
from datetime import datetime

api_key=open('api_key.txt','r').read()
access_token=open('access_token.txt','r').read().strip()
u=Upstox(api_key,access_token)
master_contract=u.get_master_contract('nse_eq')
master_contract=pd.DataFrame(master_contract)
exchange='nse_eq'
tradingsymbol='reliance'
from_date='01/09/2018'
now=datetime.now()
to_date=datetime.strftime(now,'%d/%m/%Y')

data=u.get_ohlc(u.get_instrument_by_symbol(exchange,tradingsymbol),OHLCInterval.Minute_1,
datetime.strptime('%s'%(from_date),'%d/%m/%Y').date(),datetime.strptime('%s'%(to_date),'%d/%m/%Y').date())
data=pd.DataFrame(data)
data['timestamp']=pd.to_datetime(data['timestamp'],unit='ms')
data['timestamp']=data['timestamp'].dt.tz_localize('UTC').dt.tz_convert('Asia/Kolkata')
data.set_index('timestamp',inplace=True)
data.to_csv('RELIANCE_'+str(datetime.now().strftime('%Y_%m_%d')),date_format='%Y-%m-%d %H:%M:%S')
print(data)

For backtesting use Backtrader just pip install backtrader in cmd then go for the code:


import backtrader as bt
import backtrader.feeds as btfeeds
import os
import datetime


class TestStrategy(bt.Strategy):

    def log(self, txt, dt=None):
        dt = dt or self.datas[0].datetime.date(0)
        print('%s, %s' % (dt.isoformat(), txt))

    def __init__(self):
        self.dataclose = self.datas[0].close
        self.order = None
        self.buyprice = None
        self.buycomm = None

        bt.indicators.ExponentialMovingAverage(self.datas[0], period=25)

    def notify_order(self, order):
        if order.status in [order.Submitted, order.Accepted]:
            # Buy/Sell order submitted/accepted to/by broker - Nothing to do
            return

        if order.status in [order.Completed]:
            if order.isbuy():
                self.log(
                    'BUY EXECUTED, Price: %.2f, Cost: %.2f, Comm %.2f' %
                    (order.executed.price,
                     order.executed.value,
                     order.executed.comm))

                self.buyprice = order.executed.price
                self.buycomm = order.executed.comm
            else:
                self.log('SELL EXECUTED, Price: %.2f, Cost: %.2f, Comm %.2f' %
                         (order.executed.price,
                          order.executed.value,
                          order.executed.comm))

            self.bar_executed = len(self)

        elif order.status in [order.Canceled, order.Margin, order.Rejected]:
            self.log('Order Canceled/Margin/Rejected')

        self.order = None

    def notify_trade(self, trade):
        if not trade.isclosed:
            return

        self.log('OPERATION PROFIT, GROSS %.2f, NET %.2f' %
                 (trade.pnl, trade.pnlcomm))

    def next(self):
        self.log('Close, %.2f' % self.dataclose[0])

        if self.order:
            return

        if not self.position:

            if self.dataclose[0] - self.dataclose[-1] > 3:

                self.log('BUY CREATE, %.2f' % self.dataclose[0])
                self.order = self.buy()

        else:

            if self.dataclose[0] - self.dataclose[-1] < -3:
                self.log('SELL CREATE, %.2f' % self.dataclose[0])
                self.order = self.sell()


if __name__ == '__main__':
    cerebro = bt.Cerebro()
    cerebro.addstrategy(TestStrategy)
    datapath = os.path.abspath(os.getcwd() + '/RELIANCE_' + str(datetime.datetime.now().strftime("%Y_%m_%d")))

    # Create a Data Feed
    data = btfeeds.GenericCSVData(
        dataname=datapath,
        fromdate=datetime.datetime(2018,9,1),
        dtformat=('%Y-%m-%d %H:%M:%S'),
        timestamp=0,
        high=3,
        low=4,
        open=5,
        close=1,
        volume=6,
        timeframe= bt.TimeFrame.Minutes,
        compression= 1
    )

    cerebro.adddata(data)

    cerebro.broker.setcash(1000.0)

    cerebro.addsizer(bt.sizers.FixedSize, stake=0.05)

    cerebro.broker.setcommission(commission=0.01)

    print('Starting Balance: %.2f' % cerebro.broker.getvalue())

    cerebro.run()

    print('Final Balance: %.2f' % cerebro.broker.getvalue())

    cerebro.plot()