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/

    Line Coupling - array index error

    General Code/Help
    1
    2
    205
    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.
    • monstrar
      monstrar last edited by

      Dear all,

      Thanks once again for the backtesting library! I am trying to make a simple strategy using multiple timeframes using the docs and I have the following error:

      IndexError                                Traceback (most recent call last)
      <ipython-input-93-1e09a42bc364> in <module>
           35 print('Starting Portfolio Value: %.2f' % cerebro.broker.getvalue())
           36 
      ---> 37 cerebro.run(runonce=False)
           38 
           39 print('Final Portfolio Value: %.2f' % cerebro.broker.getvalue())
      
      ~\Anaconda3\envs\user\lib\site-packages\backtrader\cerebro.py in run(self, **kwargs)
         1125             # let's skip process "spawning"
         1126             for iterstrat in iterstrats:
      -> 1127                 runstrat = self.runstrategies(iterstrat)
         1128                 self.runstrats.append(runstrat)
         1129                 if self._dooptimize:
      
      ~\Anaconda3\envs\user\lib\site-packages\backtrader\cerebro.py in runstrategies(self, iterstrat, predata)
         1296                     self._runnext_old(runstrats)
         1297                 else:
      -> 1298                     self._runnext(runstrats)
         1299 
         1300             for strat in runstrats:
      
      ~\Anaconda3\envs\user\lib\site-packages\backtrader\cerebro.py in _runnext(self, runstrats)
         1628                 self._check_timers(runstrats, dt0, cheat=False)
         1629                 for strat in runstrats:
      -> 1630                     strat._next()
         1631                     if self._event_stop:  # stop if requested
         1632                         return
      
      ~\Anaconda3\envs\user\lib\site-packages\backtrader\strategy.py in _next(self)
          345 
          346     def _next(self):
      --> 347         super(Strategy, self)._next()
          348 
          349         minperstatus = self._getminperstatus()
      
      ~\Anaconda3\envs\user\lib\site-packages\backtrader\lineiterator.py in _next(self)
          261 
          262         for indicator in self._lineiterators[LineIterator.IndType]:
      --> 263             indicator._next()
          264 
          265         self._notify()
      
      ~\Anaconda3\envs\user\lib\site-packages\backtrader\linebuffer.py in _next(self)
          619         elif clock_len == self._minperiod:
          620             # only called for the 1st value
      --> 621             self.nextstart()
          622         else:
          623             self.prenext()
      
      ~\Anaconda3\envs\user\lib\site-packages\backtrader\lineroot.py in nextstart(self)
          142         calling next
          143         '''
      --> 144         self.next()
          145 
          146     def next(self):
      
      ~\Anaconda3\envs\user\lib\site-packages\backtrader\linebuffer.py in next(self)
          742     def next(self):
          743         if self.bline:
      --> 744             self[0] = self.operation(self.a[0], self.b[0])
          745         elif not self.r:
          746             if not self.btime:
      
      ~\Anaconda3\envs\user\lib\site-packages\backtrader\linebuffer.py in __getitem__(self, ago)
          161 
          162     def __getitem__(self, ago):
      --> 163         return self.array[self.idx + ago]
          164 
          165     def get(self, ago=0, size=1):
      
      IndexError: array index out of range
      

      The code I use (for completeness sake added the pandasdata class as well):

      class PandasData(bt.feeds.PandasData):
          params = (
              ('datetime', None),
      
              ('open', 'op'),
              ('high', 'hi'),
              ('low', 'lo'),
              ('close', 'clo'),
              ('volume', 'volume'),
              ('openinterest', None),
              ('number_of_trades', 'number_of_trades')
          )
      
      
      class TestCrossStrategy(bt.Strategy):
          def __init__(self):
              sma0 = btind.SMA(self.data0, period=5)
              sma1 = btind.SMA(self.data1, period=10) 
      
              self.strategyline = sma0 > sma1()
              
          def next(self):
              print('LTF Strategy: ', len(self.datas[0]))
              print('HTF Strategy: ', len(self.datas[1]))
              print('Strategy line', self.strategyline[0])
      
      cerebro = bt.Cerebro()
      ltf_data = PandasData(dataname=ltf_train, timeframe=bt.TimeFrame.Minutes, compression=1, plot=True)
      htf_data = PandasData(dataname=htf_train, timeframe=bt.TimeFrame.Minutes, compression=30, plot=True)
      
      data = cerebro.adddata(ltf_data)
      data2 = cerebro.adddata(htf_data)
      
      cerebro.addstrategy(TestCrossStrategy)
      cerebro.broker.set_cash(10000)
       
      cerebro.run(runonce=False)
      
      

      The strange thing for me is that when I change my htf_train to 5minute data, the code works fine and I dont get an error. If I use htf_train as 30 minute timeframe, 1 hour timeframe, 4 hour timeframe, or more, it all gives the same error.

      I think there is something wrong with my data then but I dont know what could be wrong with it. Below is the data (experts of it, index is datetime):

      ltf_train

      train_ltf.JPG

      htf_train

      htf_train.JPG

      Thanks in advance!

      Kind regards,

      monstrar

      1 Reply Last reply Reply Quote 0
      • monstrar
        monstrar last edited by

        Fixed this. My self.datas[1] has to start at same time as self.datas[0]. So I deleted the first 29 entries of self.datas[0] and it's fixed! :)

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