Having a pandas dataframe with multiple columns, I would like to get the max difference between column 'high' and subsequent values column 'low' over n observations, for each row.
close high low open
0 12.65 13.16 12.63 12.80
1 12.46 12.84 12.28 12.70
2 13.14 13.25 12.63 13.16
3 12.92 13.14 12.79 12.98
4 12.95 13.05 12.69 13.00
5 13.40 13.71 13.03 13.10
Let's take an example:
Say we have a n=3. In this case df.max_loss[0] would be:
max([df.high[0] - df.low[0],
df.high[0] - df.low[1], <---
df.high[0] - df.low[2],
df.high[1] - df.low[1],
df.high[1] - df.low[2],
df.high[2] - df.low[2]]
0.88
The value for a given subset can be computed, but I would like to apply it to the whole df, computing the max_loss over next three rows for every observation.
def max_loss(high, low, window=3):
lst = []
for ih in np.arange(0,window):
for il in np.arange(ih,window):
dd = round(high[ih] - low[il], 2)
lst.append(dd)
return max(lst)
max_loss(df.high, df.low, 3)
I could make another for loop, but I feel there must be a more elegant way... . I tried using rolling().apply(), but no success yet.
Is it possible to apply to a rolling window a function that involves multiple rows and columns?
Any idea?