Time for action – calculating the Average True Range
To calculate the ATR, perform the following steps:
The ATR is based on the low and high price of
N
days, usually the last 20 days.N = 5 h = h[-N:] l = l[-N:]
We also need to know the close price of the previous day:
previousclose = c[-N -1: -1]
For each day, we calculate the following:
The daily range—the difference between the high and low price:
h – l
The difference between the high and previous close:
h – previousclose
The difference between the previous close and the low price:
previousclose – l
The
max()
function returns the maximum of an array. Based on those three values, we calculate the so-called true range, which is the maximum of these values. We are now interested in the element-wise maxima across arrays—meaning the maxima of the first elements in the arrays, the second elements in the arrays, and so on. Use the NumPymaximum()
function instead of themax()
function for this purpose:truerange = np.maximum(h - l, h - previousclose...