sirokinl
sirokinl

Reputation: 51

Pandas & Timeseries: Get last date for max rolling window

I have a dataset based on a timeseries with stock price data. I'm able to calculate the highest price within the last x number of days (example: 60 days). When there are multiple occurrences of this highest price, I would like to know the latest date when this highest price occurred.

So to calculate the highest price I already have the following code:

df_shift['High'].shift(1).rolling(60).max()

How would I go about of getting date value that this price occurred. And in case of multiple rows, getting the latest date.

My dataframe consists of the following columns:

Date, Open, High, Low, Close, Volume

Thanks!

Upvotes: 0

Views: 768

Answers (1)

Muhammad Hassan
Muhammad Hassan

Reputation: 4229

Try:

df['last_max'] = df['High'].rolling(60).apply(lambda x: x[::-1].idxmax()).shift(1)
df['last_max_date'] = df['last_max'].apply(lambda x: df['date'].loc[x] if not pd.isnull(x) else x)
df.drop(columns=['last_max'], axis=1, inplace=True)

Upvotes: 1

Related Questions