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