4

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'?

Barmar
  • 741,623
  • 53
  • 500
  • 612
John
  • 435
  • 6
  • 15

4 Answers4

2

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).

fsl
  • 3,250
  • 1
  • 10
  • 20
1
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)
Bemwa Malak
  • 1,182
  • 1
  • 5
  • 18
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)
Corralien
  • 109,409
  • 8
  • 28
  • 52
  • I upvoted all three answers as they all work and I learned something from each. I honestly have no idea of which to accept. Will ponder. – John Jan 18 '22 at 20:58
0

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()

John
  • 435
  • 6
  • 15