Navigation

    Backtrader Community

    • Register
    • Login
    • Search
    • Categories
    • Recent
    • Tags
    • Popular
    • Users
    • Groups
    • Search
    For code/output blocks: Use ``` (aka backtick or grave accent) in a single line before and after the block. See: http://commonmark.org/help/

    return self.array[self.idx + ago] IndexError: array index out of range

    General Code/Help
    2
    4
    335
    Loading More Posts
    • Oldest to Newest
    • Newest to Oldest
    • Most Votes
    Reply
    • Reply as topic
    Log in to reply
    This topic has been deleted. Only users with topic management privileges can see it.
    • G
      Gleetche last edited by

      I am trying to do a execute a create buy when the previous close is below the 50ma and current close is above 50ma but I keep getting these:

      8ff1cb82-d5af-45e6-8e10-07c692900076-image.png

      class TestStrategy(bt.Strategy):
      
          stoploss = 0
          params = dict(
              pfast=50,
              pslow=300,
          )
      
          def __init__(self):
              # Keep a reference to the "close" line in the data[0] dataseries
              self.dataclose = self.datas[0].close
      
              # To keep track of pending orders and buy price/commission
              self.order = None
              self.buyprice = None
              self.buycomm = None
      
      
              # SMA use
              self.sma1 = bt.ind.SMA(period=self.p.pfast)  # fast moving average
              self.sma2 = bt.ind.SMA(period=self.p.pslow)  # slow moving average
              self.crossover = bt.ind.CrossOver(self.sma1, self.sma2)  # crossover signal
      
              # ATR use
              self.dataclose = self.datas[0].close
              self.datahigh = self.datas[0].high
              self.datalow = self.datas[0].low
              self.datapreviousclose = self.datas[0].close(-1)
              self.atr = 0
              # self.my_atr = bt.ind.ATR(period = 14,)
      
          # LOGGING FUNCTION
          def log(self, txt, dt=None):
              ''' Logging function for this strategy'''
              dt = dt or self.datas[0].datetime.date(0)
              print('%s, %s' % (dt.isoformat(), txt))
      
          def next(self):
              cash = self.broker.get_cash()
      
              #MA Function
              self.sma1 = bt.ind.SMA(period=self.p.pfast)  # fast moving average
              self.sma2 = bt.ind.SMA(period=self.p.pslow)  # slow moving average
              self.crossover = bt.ind.CrossOver(self.sma1, self.sma2)  # crossover signal
      
      
              # ATR FUNCTION
              range_total = 0
              for i in range(-13, 1):
                  x = self.datahigh[i] - self.datalow[i]
                  y = self.datahigh[i] - self.datapreviousclose[i]
                  z = self.datalow[i] - self.datapreviousclose[i]
                  if x > y:
                      temp_truerange = x
                  else:
                      temp_truerange = y
      
                  if temp_truerange > z:
                      true_range = temp_truerange
                  else:
                      true_range = z
      
                  range_total += true_range
              self.atr = range_total / 14
      
              #ATR Multiplier
              self.atr = self.atr * 1
      
              #Instants
              close = (self.dataclose[0])
              cash = (cerebro.broker.getcash())
              atr = (self.atr)
      
              self.log('C: %.8f, ATR:%.8f' % (self.dataclose[0], atr))
      
              # ORDER CHECK (If order is in place, can't place another until filled)
              if self.order:
                  return
      
              # LONG BUY CREATE CONDITION:
              if not self.position :
                  if self.datas[0].close(-1) <= self.sma1[0]:
                      if self.close() > self.sma1[0]:
                          self.order = self.buy(size=1)
      
                          print()
                          self.log(
                          '[  LONG BUY CREATE  ] P: %.8f, Qty: %.10f, B: %.8f, ATR: %.8f' % (close, 1, cash, atr))
                      self.stoploss =self.low() - self.atr
              # LONG SELL CREATE CONDITION
              elif self.data < self.stoploss:# or self.crossover < 0:  # in the market & cross to the downside
                  self.close()
                  self.log("[    LONG SELL CREATE   ] P: %.8f" % close)
      
      1 Reply Last reply Reply Quote 0
      • G
        Gleetche last edited by

        I revised the code a bit:

        class TestStrategy(bt.Strategy):
        
            '''
            Inside this "TestStrategy", there will be some "uncommon" scripts:
            - ATR Function: Self-made ATR, because I needed it for sizing.
            - Trade Period: To count the amound of bars passed after the start of an on going trade
            - Trade Count: To count trades for pyramiding function since the first trade.
            '''
        
            stoploss = 0
            params = dict(
                pfast=50,
                pslow=300,
            )
        
            def __init__(self):
                # Keep a reference to the "close" line in the data[0] dataseries
                self.dataclose = self.datas[0].close
        
                # To keep track of pending orders and buy price/commission
                self.order = None
                self.buyprice = None
                self.buycomm = None
        
        
                # SMA use
                self.sma1 = bt.ind.SMA(period=self.p.pfast)  # fast moving average
                self.sma2 = bt.ind.SMA(period=self.p.pslow)  # slow moving average
                self.crossover = bt.ind.CrossOver(self.sma1, self.sma2)  # crossover signal
        
                # ATR use
                self.dataclose = self.datas[0].close
                self.datahigh = self.datas[0].high
                self.datalow = self.datas[0].low
                self.datapreviousclose = self.datas[0].close(-1)
                self.atr = 0
                # self.my_atr = bt.ind.ATR(period = 14,)
        
            # LOGGING FUNCTION
            def log(self, txt, dt=None):
                ''' Logging function for this strategy'''
                dt = dt or self.datas[0].datetime.date(0)
                print('%s, %s' % (dt.isoformat(), txt))
        
            def next(self):
                cash = self.broker.get_cash()
        
                #MA Function
                self.sma1 = bt.ind.SMA(period=self.p.pfast)  # fast moving average
                self.sma2 = bt.ind.SMA(period=self.p.pslow)  # slow moving average
                self.crossover = bt.ind.CrossOver(self.sma1, self.sma2)  # crossover signal
        
        
                # ATR FUNCTION
                range_total = 0
                for i in range(-13, 1):
                    x = self.datahigh[i] - self.datalow[i]
                    y = self.datahigh[i] - self.datapreviousclose[i]
                    z = self.datalow[i] - self.datapreviousclose[i]
                    if x > y:
                        temp_truerange = x
                    else:
                        temp_truerange = y
        
                    if temp_truerange > z:
                        true_range = temp_truerange
                    else:
                        true_range = z
        
                    range_total += true_range
                self.atr = range_total / 14
        
                #ATR Multiplier
                self.atr = self.atr * 1
        
                #Instants
                close = (self.dataclose[0])
                cash = (cerebro.broker.getcash())
                atr = (self.atr)
        
                self.log('C: %.8f, ATR:%.8f' % (self.dataclose[0], atr))
        
                # ORDER CHECK (If order is in place, can't place another until filled)
                if self.order:
                    return
        
                # LONG BUY CREATE CONDITION:
                if not self.position :
                    if self.datas[0].close(-1) <= self.sma1[0]:
                        if self.dataclose() > self.sma1[0]:
                            self.order = self.buy(size=1)
        
                            print()
                            self.log(
                            '[  LONG BUY CREATE  ] P: %.8f, Qty: %.10f, B: %.8f, ATR: %.8f' % (close, 1, cash, atr))
                        self.stoploss =self.datalow() - self.atr
                # LONG SELL CREATE CONDITION
                elif self.dataclose() < self.stoploss:# or self.crossover < 0:  # in the market & cross to the downside
                    self.close()
                    self.log("[    LONG SELL CREATE   ] P: %.8f" % close)
        
        run-out 1 Reply Last reply Reply Quote 0
        • run-out
          run-out @Gleetche last edited by

          @gleetche said in return self.array[self.idx + ago] IndexError: array index out of range:

          #MA Function
          self.sma1 = bt.ind.SMA(period=self.p.pfast) # fast moving average
          self.sma2 = bt.ind.SMA(period=self.p.pslow) # slow moving average
          self.crossover = bt.ind.CrossOver(self.sma1, self.sma2) # crossover signal

              # ATR FUNCTION
              range_total = 0
              for i in range(-13, 1):
          

          The SMA and crossover functions need to be defined in init, then used self.sma1[0] in next.

          Also there's a built in ATR fucntion I would use unless you are modifying it.

          RunBacktest.com

          G 1 Reply Last reply Reply Quote 2
          • G
            Gleetche @run-out last edited by

            @run-out thanks!

            1 Reply Last reply Reply Quote 1
            • 1 / 1
            • First post
              Last post
            Copyright © 2016, 2017, 2018, 2019, 2020, 2021 NodeBB Forums | Contributors