For code/output blocks: Use ``` (aka backtick or grave accent) in a single line before and after the block. See: http://commonmark.org/help/

Prenext - does something weird



  • Hi,

    I'm trying to backtest over multiple stocks at once. One of the stocks was only listed after testing date and I found that adding prenext allowed the code to be run over the entire testing range. However, it does something odd regarding that stock:

    oneplot = Force all datas to plot on the same master.
    
    params = (
        ('ema50', 50),
        ('ema200', 200),
        ('cci20', 20),
        ('oneplot', True)
    )
    
    def __init__(self):
        '''
        Create an dictionary of indicators so that we can dynamically add the
        indicators to the strategy using a loop. This mean the strategy will
        work with any number of data feeds.
        '''
        self.inds = dict()
        for i, d in enumerate(self.datas):
            self.inds[d] = dict()
            self.inds[d]['ema50'] = bt.indicators.ExponentialMovingAverage(
                d.close, period=self.params.ema50)
            self.inds[d]['ema200'] = bt.indicators.ExponentialMovingAverage(
                d.close, period=self.params.ema200)
            self.inds[d]['cci20'] = bt.indicators.CommodityChannelIndex(
                period=self.params.cci20)
            self.inds[d]['crossUp'] = bt.indicators.CrossOver(self.inds[d]['cci20'], -100)  # crossup = 1
            self.inds[d]['EMAcross'] = bt.indicators.CrossOver(self.inds[d]['ema50'], self.inds[d]['ema200'])
            self.inds[d]['crossDown'] = bt.indicators.CrossOver(self.inds[d]['cci20'], 100)  # crossdown = -1
    
            if i > 0:  # Check we are not on the first loop of data feed:
                if self.p.oneplot == True:
                    d.plotinfo.plotmaster = self.datas[0]
    
    def prenext(self):
        self.next()
    
    def next(self):
    
        for i, d in enumerate(self.datas):
            # calculate risk/ stop price
            risk = 100  # risk = 100 dollars
            stop = 0.05  # stop 5% below close
            stop_price = self.datas[i].close[0] * (1 - stop)
    
            dt, dn = self.datetime.date(), d._name
            pos = self.getposition(d).size
            if not pos:  # no market / no orders
                if self.inds[d]['ema50'] >= self.inds[d]['ema200']:
                    if self.inds[d]['crossUp'][0] == 1:  # if CCI crosses up -100
                        if self.datas[i].close[0] - stop_price > 0:  # check if risk is acceptable/ valid
                            qty = round(risk / (self.datas[i].close[0] - stop_price), 0)  # get no. of shares to trade
                            eofthisday = self.datas[i].datetime.date()  #get current date
                            expiry = eofthisday + timedelta(days=4) #keep order active for 4 days (over weekend + public hol)
                            self.buy_bracket(data=d, limitprice=10000, price=self.datas[i].close[0],
                                             stopprice=stop_price, exectype=bt.Order.Limit, size=qty, valid=expiry)
                        else:
                            pass
                    else:
                        pass
                else:
                    pass
    
            else:
                if self.inds[d]['crossDown'][0] == -1:  # if cci crosses down 100
                    self.close(data=d)
    
    def notify_trade(self, trade):
        dt = self.data.datetime.date()
        if trade.isclosed:
            print('{} {} Closed: PnL Gross {}, Net {}'.format(
                dt,
                trade.data._name,
                round(trade.pnl, 2),
                round(trade.pnlcomm, 2)))
    

    The results I got seemed alright, except for the starred line (see below). It makes a very weird trade on the day of listing (data start) for A2M. I think this can be fixed using prenext but am not quite sure how to. Any help is greatly appreciated. Thank you.

    results:

    2014-08-29 BSL.AX Closed: PnL Gross -66.25, Net -79.45
    2014-10-21 CSL.AX Closed: PnL Gross 37.16, Net 23.96
    2015-02-03 CSL.AX Closed: PnL Gross 83.01, Net 69.81
    2015-02-25 CSL.AX Closed: PnL Gross 106.62, Net 93.42
    2015-03-30 A2M.AX Closed: PnL Gross -1894.41, Net -1907.61 ***********
    2015-07-24 CSL.AX Closed: PnL Gross 60.94, Net 47.74
    2015-10-12 CSL.AX Closed: PnL Gross 35.94, Net 22.74
    2015-11-15 CSL.AX Closed: PnL Gross 117.94, Net 104.74
    2016-04-29 CSL.AX Closed: PnL Gross 56.86, Net 43.66


  • administrators

    @howardhh said in Prenext - does something weird:

    2015-03-30 A2M.AX Closed: PnL Gross -1894.41, Net -1907.61 ***********

    It's a losing trade. What's weird?

    @howardhh said in Prenext - does something weird:

    I found that adding prenext allowed the code to be run over the entire testing range

    This is basically wrong. Read Docs - Operating the Platform it will simply give you access to a period in which all guarantees (like values of indicators being available) cannot yet be met.


Log in to reply
 

});