how to calculate true range

Viewed 139

In technical analysis true range is the difference between the high and the low plus any gap that occurred between sessions. So if today's high is 10 and the low is 9 range is 1. If yesterdays close was 9.5 then true range is also one, but if yesterdays close was 11 then true range is 2.

I have a pandas data frame indexed by date so range is simply:

df['range'] = df['High'] - df['Low']

True range would be something like:

df['tr'] = max(df['High'], df['Close'].shift(1)) - min(df['Low'], df['Close'].shift(1))

But max() and min() aren't applicable to pandas data frames. How can I reference the 'Close' from the prior row to create the column 'tr'?

4 Answers

Here is another approach, assuming your DataFrame contains exclusively OHLC data:

data = df.drop("Open", axis=1)
data.Close = data.Close.shift()
true_range = data.max(1) - data.min(1)

Some explanation: if you shift the Close column inplace, the true range becomes difference between the max and min values (row-wise).

def calculate_true_range(a,b,c):
    true_range = max(a, b.shift(1)) - min(c, b.shift(1))
    return true_range


df['tr'] = df.apply(lambda row : calculate_true_range(row['High'], row['Close'], row['Low'], axis = 1)

Use pd.concat to get the min and the max of each series:

df['tr'] = pd.concat([df['High'], df['Close'].shift()], axis=1).max(axis=1) \
           - pd.concat([df['Low'], df['Close'].shift()], axis=1).min(axis=1)

All three answers above work to calculate true range. True range is usually used in average true range. An typical usage example would be Chandelier stops.

atrLength = 10

data['atr'] = data['tr'].rolling(window=atrLength).mean()

Related