Change percent of rolling 5 secs window

Panda's dataframe has an inbuilt function rolling where it provide rolling window calculations (non-exhaustively) such as:

  • mean
  • sum

If we want to calculate the change percent of rolling 5 secs window,

def rolling_chgpct(dataset):
  if len(dataset) == 1:
    return np.nan
  first_data = dataset[0]
  last_data = dataset[-1]
  rchgpct = (last_data - first_data) / first_data
  return rchgpct

# calculate chgpct of rolling 5 secs
df['rchgpct'] = df.rolling('5s').apply(rolling_chgpct)