pandas rolling_max with groupby

What I have:

Sym  Date    close
A   1-Jan   45
A   2-Jan   15
A   3-Jan   55
B   1-Jan   41
B   2-Jan   87
B   3-Jan   82
C   1-Jan   33
C   2-Jan   15
C   3-Jan   46

What I need

Sym  Date  close  rolling_max_2day
A   1-Jan   45    NaN
A   2-Jan   15    45
A   3-Jan   55    55
B   1-Jan   41    NaN
B   2-Jan   87    87
B   3-Jan   82    87
C   1-Jan   33    NaN
C   2-Jan   15    33
C   3-Jan   46    46

The dataframe df is with multiple index(Sym, Date)

I have tried like this:

df['rolling_max_2day'] = df.groupby(level=['sym']).apply(lambda x:pd.rolling_max(x['close'].values,2))

it does not return any errors, but it also returns all null value at column rolling_max_2day

However, if only this code, not append to df, I can get a correct series.

df.groupby(level=['sym']).apply(lambda x:pd.rolling_max(x['close'].values,2))


Source: python

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.