Back to Community
Problem with ATR

Hi all,
I run the example about ATR in Quantopian help, I try with SPY and date_range (2015/05/01 -2015/05/05)

My fisrt code

 high =  history(40, '1d', 'high')  
    low =   history(40, '1d', 'low')  
    close = history(40, '1d', 'close_price')  
    # Calculate the ATR for the stock  
    atr = talib.ATR(high[context.stock],  
                    low[context.stock],  
                    close[context.stock],  
                    timeperiod=14)[-1]  
    print atr  

output
2015-05-01 PRINT 2.01582660149
2015-05-04 PRINT 1.97759589997
2015-05-05 PRINT 2.01836594903

And second time I try with

high =  history(30, '1d', 'high')  
    low =   history(30, '1d', 'low')  
    close = history(30, '1d', 'close_price')  
    # Calculate the ATR for the stock  
    atr = talib.ATR(high[context.stock],  
                    low[context.stock],  
                    close[context.stock],  
                    timeperiod=14)[-1]  
    print atr  

output:
2015-05-01 PRINT 1.98596195586
2015-05-04 PRINT 1.95915123556
2015-05-05 PRINT 2.02193389204

Another bar_count and another value. Why it have this difference? I understand that in high = history(30, '1d', 'high') is only innit 30 or 40 bar, but I only use 14 so no things change in here.

Please help me,

Thanks

3 responses

Hi Linh,

I can't tell you why, but in general you need to use a history dataframe of the same length or one bar longer than the corresponding time-period parameter in TALIB functions.

Hi Robby,

Before talking with you, I just thought that it only get only 14 bar in array high.

Thanks for your support.

So the number in bar_count must be 30 to get the right ATR number?

Thanks,
Linh

No.

I THINK the bar_count of the history dataframe should be 15 for an ATR with timeperiod=14, but it has been a while. So for a 30-day ATR, the bar_count should be 31 and timeperiod 30. For many TALIB functions, the history bar_count must equal timeperiod + 1. And sometimes bar_count must equal timeperiod. I doubt their is a good reason to understand why.
Try doing the manual arithmetic to make sure it is giving you the right numbers for the right timeperiod.