Quantopian's community platform is shutting down. Please read this post for more information and download your code.
Back to Community
Batch Average True Range

Recently I've been playing around with Quantopian/Zipline building a library of indicators I might find useful in the future. I came across the previous implementations of ATR shared, and thought I'd share my own stab at it, both iteratively in a custom event window and using a batch transform.

Happy Hacking!

7-11

Previous Posts:
https://www.quantopian.com/posts/average-true-range-basic-implementation
https://www.quantopian.com/posts/python-classes-implementing-true-range-and-average-true-range-indicators

8 responses

self.alpha = 2.0 / (self.window_length + 1)

atr = (window_length*atr + tr)/(window_length + 1)
= ((window_length+1) atr + (tr - atr)) / (window_length + 1)
= atr + (1./(window_length + 1)) * (tr - atr)

why the 2.0?

Its arbitrary, but usually I like to give more weight to recent events (and is customary technical analysis) so I always bump up the alpha that way.

Hello Jason,

That looks like a lot of effort went in to it. With TA-Lib we can just use:

import talib

def initialize(context):  
    context.sid = sid(26578)  


def handle_data(context, data):  
    high        = history(15, '1d', 'high')  
    low         = history(15, '1d', 'low')  
    close       = history(15, '1d', 'close_price')  
    ATR         = talib.ATR(high[context.sid], low[context.sid], close[context.sid])  
    record(ATR=float(ATR[-1:]))  

P.

Yes now that talib is available for import on the quantopian platform its much easier, the above code predates this feature.

For a very simple ATR implementation, check out the code for this example.

Dyno, if you want more weight to recent events, just shorten your time window. Your alpha calc is wrong (or at least it doesn't provide the correct ATR). ATR is an exponentially weighted moving average of the True Range, where the weight on the most recent observation (alpha) is equal to 1 / time_period and the weight on previous ATR value is 1 - alpha.

Here is the TaLib implementation of ATR in C.

Check out the code for this ATR example which makes it clear how the calculation is actually done. It manually calculates the ATR values and then compares them to the Talib ATR value. They are an exact match.

Hey Colin,

It looks like cloning the following code, results in the message: Undefined name 'ta'

Any ideas?

Thanks,

Christos


import math

Set up the ATR indicator.

atr_data = ta.ATR(timeperiod=15)

def initialize(context):
context.stock = sid(26578) # GOOG

def handle_data(context, data):
atr = atr_data(data)[context.stock]
record(ATR=atr)

I believe "ta" is short for "talib" so

import talib as ta

may do the trick.