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

Can't acees to the datas for indicators



  • Hello I am trying to run and strategy that calculates the indicators in a Hourly data frame but trade in a seconds time frame.

    I got this error:

      File "Alpha2.py", line 214, in <module>
        runstrat()
      File "Alpha2.py", line 184, in runstrat
        cerebro.run(stdstats=False)
      File "/home/milo/anaconda3/lib/python3.6/site-packages/backtrader/cerebro.py", line 1127, in run
        runstrat = self.runstrategies(iterstrat)
      File "/home/milo/anaconda3/lib/python3.6/site-packages/backtrader/cerebro.py", line 1217, in runstrategies
        strat = stratcls(*sargs, **skwargs)
      File "/home/milo/anaconda3/lib/python3.6/site-packages/backtrader/metabase.py", line 88, in __call__
        _obj, args, kwargs = cls.doinit(_obj, *args, **kwargs)
      File "/home/milo/anaconda3/lib/python3.6/site-packages/backtrader/metabase.py", line 78, in doinit
        _obj.__init__(*args, **kwargs)
      File "Alpha2.py", line 34, in __init__
        self.trigger = Alligator()
      File "/home/milo/anaconda3/lib/python3.6/site-packages/backtrader/indicator.py", line 53, in __call__
        return super(MetaIndicator, cls).__call__(*args, **kwargs)
      File "/home/milo/anaconda3/lib/python3.6/site-packages/backtrader/metabase.py", line 88, in __call__
        _obj, args, kwargs = cls.doinit(_obj, *args, **kwargs)
      File "/home/milo/anaconda3/lib/python3.6/site-packages/backtrader/metabase.py", line 78, in do in it _obj.__init__(*args, **kwargs)
      File "Alpha2.py", line 18, in __init__
        self.datamed = (self.datas[1].high + self.datas[1].low) / 2
    IndexError: list index out of range**
    

    Here is the code:

    from __future__ import (absolute_import, division, print_function,
                            unicode_literals)
    import os.path
    import sys  # To find out the script name (in argv[0])
    import argparse
    import datetime
    import backtrader as bt
    import backtrader.feeds as btfeeds
    import backtrader.plot as plt
    import backtrader.indicators as btinds
    
    class Alligator(btinds.PeriodN):
        lines = ('signal1','signal2')
        params = (('lrperiod', 89), ('jaw_wind', 13), ('teeth_wind', 8), ('lips_wind', 5),)
        #params = (('p1',5),('p2',20),('p3',50),)
        
        def __init__(self):
            self.datamed = (self.datas[1].high + self.datas[1].low) / 2
            jaw = bt.indicators.SmoothedMovingAverage(self.datamed, period=self.params.jaw_wind, plotname='Jaw')(8)
            teeth = bt.indicators.SmoothedMovingAverage(self.datamed, period=self.params.teeth_wind, plotname='Lips')(5)
            lips = bt.indicators.SmoothedMovingAverage(self.datamed, period=self.params.lips_wind, plotname='Teeth')(3)
            self.lines.signal1 = (lips - teeth)  #Buy
            self.lines.signal2 = (teeth - jaw) #Buy
    
    class St(bt.Strategy):
    
        def log(self, txt, dt=None):
            ''' Logging function for this strategy'''
            dt = dt or self.data0.datetime.datetime(0)
            print('%s, %s' % (dt.isoformat(), txt))
            print(list(enumerate(self.datas)))
            
        def __init__(self):
            self.trigger = Alligator()
            self.spread = btinds.AverageTrueRange(period=20)
    
            
        def notify_order(self, order):
            print('{}: Order ref: {} / Type {} / Status {}'.format(
                self.data.datetime.datetime(0),
                order.ref, 'Buy' * order.isbuy() or 'Sell',
                order.getstatusname()))
            
            if order.status in [order.Submitted, order.Accepted]:
                return
            
            if order.status in [order.Completed]:
                if order.isbuy():
                    self.log(
                        'BUY EXECUTED, Ref: %d, Price: %.5f, Cost: %.5f' %
                        (order.ref,order.executed.price,
                         order.executed.value))
                    
                    self.buyprice = order.executed.price
                    
                else:  # Sell
                    self.log('SELL EXECUTED, Ref: %d,Price: %.5f, Cost: %.5f' %
                             (order.ref,order.executed.price,
                              order.executed.value))
            
                self.bar_executed = len(self)
                
            elif order.status in [order.Canceled, order.Margin, order.Rejected]:
                self.log('Order Canceled/Margin/Rejected')
            
            if not order.alive() and order.ref in self.orefs:
                self.orefs.remove(order.ref)
            
        def notify_trade(self, trade):
            if not trade.isclosed:
                return
    
            self.log('OPERATION PROFIT, GROSS %.5f, NET %.5f' %
                     (trade.pnl, trade.pnlcomm))
            
        def next(self):
            txt = ','.join(
                ['%04d' % len(self.data0),
                 self.data0.datetime.datetime(0).isoformat(),
                 'Open : %.5f' % self.data0.open[0],
                 'High : %.5f' % self.data.high[0],
                 'Low : %.5f' % self.data.low[0],
                 'Close : %.5f' % self.data.close[0]]) 
            print(txt)
    
            if (self.trigger.signal1[0] < 0) and (self.trigger.signal2[0] < 0):
                 o1 = self.sell(exectype = bt.Order.Limit,price=self.data.close[-1],
                                transmit=False,valid=datetime.datetime.now()+datetime.timedelta(hours=1))
                 
                 print(self.datetime.datetime(0),' : Oref %d / Sell at %.5f' % (
                            o1.ref, self.data.close[-1]))
                
                 o2 = self.buy(exectype=bt.Order.Limit,price=(self.data.close[-1] - self.spread.atr[0] * 2),
                                parent=o1,transmit=False)
                 
                 print(self.datetime.datetime(0),' : Oref %d / Sell Take Profit at %.5f' % (
                            o2.ref, (self.data.close[-1] - self.spread.atr[0] * 2)))
                 
                 o3 = self.buy(exectype=bt.Order.Stop,price = (self.spread.atr[0] * 2 +self.data.close[-1]),
                               parent=o1,transmit = True)
                 
                 print(self.datetime.datetime(0),' : Oref %d / Sell Stop Loss at %.5f' % (
                            o3.ref, (self.spread.atr[0] * 2 +self.data.close[-1])))
                 
                 self.orefs = [o1.ref, o2.ref, o3.ref]
                 
            elif (self.trigger.signal1[0] > 0) and (self.trigger.signal2[0] > 0):
                 o1 = self.buy(exectype = bt.Order.Limit,price=self.data.close[-1],
                                transmit=False,valid= datetime.datetime.now()+datetime.timedelta(hours=1))
                 
                 print(self.datetime.datetime(0),' : Oref %d / Buy at %.5f' % (
                            o1.ref, self.data.close[-1]))
                
                 o2 = self.sell(exectype=bt.Order.Limit,price=(self.spread.atr[0] * 2 +self.data.close[-1]),
                                parent=o1,transmit=False)
                 
                 print(self.datetime.datetime(0),' : Oref %d / Buy Take Profit at %.5f' % (
                            o2.ref, (self.spread.atr[0] * 2 +self.data.close[-1])))
                 
                 o3 = self.sell(exectype=bt.Order.Stop,price = (self.data.close[-1] - self.spread.atr[0] * 2),
                               parent=o1,transmit = True)
                 
                 print(self.datetime.datetime(0),' : Oref %d / Buy Stop Loss at %.5f' % (
                            o3.ref, (self.data.close[-1] - self.spread.atr[0] * 2))) 
                 
                 self.orefs = [o1.ref, o2.ref, o3.ref]
            
            else:
                 return
                      
    def runstrat():
    
        cerebro = bt.Cerebro()
        modpath = os.path.dirname(os.path.abspath(sys.argv[0]))
        datapath0 = os.path.join(modpath, '/home/milo/Documents/Data/BT_EURUSD.csv')
        datapath1 = os.path.join(modpath, '/home/milo/Documents/Data/BT_EURUSDH.csv')
    
        data0 = btfeeds.GenericCSVData(dataname=datapath0,
                                       timeframe=bt.TimeFrame.Seconds,                                  
                                      nullvalue=0.0,
                                      dtformat=('%Y-%m-%d %H:%M:%S'),
                                      datetime=0,
                                      open=1,
                                      high=2,
                                      low=3,
                                      close=4,
                                      volume=-1,
                                      openinterest=-1)
    
        data1 = btfeeds.GenericCSVData(dataname=datapath1,
                                       timeframe=bt.TimeFrame.Minutes,                                  
                                      nullvalue=0.0,
                                      dtformat=('%Y-%m-%d %H:%M:%S'),
                                      datetime=0,
                                      open=1,
                                      high=2,
                                      low=3,
                                      close=4,
                                      volume=-1,
                                      openinterest=-1)
    
        cerebro.adddata(data0,name ="Seconds Data")
        cerebro.adddata(data1,name ="Hourly Data")
    
    if __name__ == '__main__':
        runstrat()
    

  • administrators

    The code is unreadable ... pleas see the top of the forum.



  • Done.

    Solution : It gets the datasx if I move the indicators into the init of the class (strategy). I am trying to do a Data Replay, calculating the indicators in a higher Time Frame but trading in the close of the smallest time frame.

    Is this the right approach?


Log in to reply
 

});