self coded ATR
-
I am trying to build my own ATR, and I don't know if I coded it correctly or not, can someone confirm or point out any mistakes that I have?
https://www.investopedia.com/terms/a/atr.asp
I found a blog that teaches you how to build your own indicator, in this case which is ATR.
But the code from the blog only has current high - current close, the original atr includes:
- current high - current low
- current high - previous close
- current low - previous close
class AverageTrueRange(bt.Strategy): def log(self, txt, dt=None): dt = dt or self.datas[0].datetime.date(0) print(f'{dt.isoformat()} {txt}') # Print date and close def __init__(self): self.dataclose = self.datas[0].close self.datahigh = self.datas[0].high self.datalow = self.datas[0].low self.datapreviousclose = self.datas[-1].close self.my_atr = bt.ind.ATR(period = 14,) def next(self): 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 atr = range_total / 14 # h-l , h - previous close , l - previous close self.log(f'Close: {self.dataclose[0]:.2f}, ATR: {atr:.4f}') self.log('bt.ATR:%.2f' % (self.my_atr*1))
-
I forgot to add that, i compared the results of the builtin atr and the self-coded atr, and it is different :
-
@Gleetche said in self coded ATR:
self.datapreviousclose = self.datas[-1].close
I haven't looked at all your code, this jumps out. You need to use:
self.datapreviousclose = self.datas[0].close(-1)
Use round brackets to back up in init. Square brackets in next.
-
@run-out Oh, thanks!
What does self.datas[-1].close mean then? -
@Gleetche Isn't that what you wrote in your code ? There is no such object. In BT data indexing starts at 0 and grows progressively as one adds more data. self.datas[0].close(-1) is using the concept delayed indexing. This doc could clear lots of your doubts.
-
@rajanprabu I thought self.datas[-1].close means previous close.
thanks! -
datas[0] this indexing is for the data that feed to BT.. if you load two data sets then you will have datas[0] and datas[1].
datas[0].close[0] is current close for data[0] and data[0].close[-1] is previous close.