Error: IndexError: array index out of range when refering previous bars from an indicator
-
Hello
I am starting to program python with backtrader and i am writting an indicator that refers to
class ROC2(bt.Indicator): lines = ('roc2',) # output line (array) params = ( ('period', 10), # distance to previous data point ('threshold', 1), # factor to use for the division ) def __init__(self): self.addminperiod(self.params.period) self.dataclose = self.datas[0].close def next(self): roc2 = self.data.close.get(size=1, ago=-self.p.period)[0] * (1+ (self.p.threshold/100)) self.lines.roc2 = roc2
i tried several ways to refers to the close price but always i am getting error
This is the error:
File "bb2.py", line 33, in next roc2 = self.data.close.get(size=1, ago=-self.p.period)[0] * (1+ (self.p.threshold/100)) IndexError: array index out of range
Thank you in advance
-
I tried with this:
def __init__(self): self.addminperiod(self.params.period) self.dataclose = self.datas(-self.p.threshold).close def next(self): roc2 = self.dataclose[0] * (1+ (self.p.threshold/100)) self.lines.roc2 = roc2
But i get this other error:
File "bb2.py", line 31, in __init__ self.dataclose = self.datas(-self.p.threshold).close TypeError: 'list' object is not callable
-
I'm not 100% sure your objective, but I can discuss some of your errors.
- You are mixing your styles a bit, which may be causing confusion.
self.dataclose = self.datas[0].close self.data.close.get self.dataclose[0]
I emphasize this is my preference, and others will happily use shortcuts, but for me it always makes it easier if I identify the line using:
"""
self.datas[n]
"""
self.datas is a list of the the datas.n
would be the number in the list. By always using this there is absolute clarity as to which line you are using.- Let's address your first main line:
roc2 = self.data.close.get(size=1, ago=-self.p.period)[0] * (1+ (self.p.threshold/100))
.get returns a python list of the size and starting a period ago. So a couple of things, using size one will return a list of size 1 from period 10 bars ago in this case. It would be much easier to write:
self.datas[0].close[-10]
- Your next main issue in your second code block is:
self.dataclose = self.datas(-self.p.threshold).close
You are actually trying to find a datas line at -10, but I'm assuming you only have one data line. So this will fail.
- This line of code attempts to build the roc2 line bar by bar.
'''
self.lines.roc2 = roc2
'''
You need to identify the bar for the lines.
self.lines.roc2[0] = roc2
Hope this helps.