I am fairly new at this, and thought I had a handle on things until I started working with talib ATR. If I have history data for 40 days, when I get the SMA using length 20, what I have is the series of data that is the sma over the last 20 days. WIth na for the first 20 and then values for the last 20, makes perfect sense.
closes = history(40,'1d','close_price')[stock]
sma = talib.SMA(closes,20)
sma_two_days_ago = sma[-3]
But when I try the same thing for ATR, the data seems completely off.
closes = history(40,'1d','close_price')[stock]
highs = history(40,'1d','high')[stock]
lows = history(40,'1d','low')[stock]
atr = talib.ATR(highs, lows, closes,20)
atr_two_days_ago = atr[-3] #this and all the numbers in the series are wrong for ATR
The only way I have been able to get the right ATR for a lookback is by doing this(shifting the input series so I get exactly the one value I want, instead of rolling data):
atr = talib.ATR(highs[-23:-2],lows[-23:-2],closes[-23:-2],20)
atr_two_days_ago = atr[-1]
Why is the ATR calculation not rolling properly like the SMA and BBANDS and other indicators so nicely do? Shouldnt putting the time period of 20 in the ATR function take care of this? I think understanding this might give me a nice little breakthrough, this has been rattling my brain.