pythonintermediate

Cumulative Max & Streak Detection

Detect streaks, new highs, and consecutive-day patterns in time-series using cummax and groupby.

python
import pandas as pd
import numpy as np

df = pd.DataFrame({'date': pd.date_range('2024-01-01', periods=30),'value': np.random.randint(0, 100, 30)})

df['all_time_high'] = df['value'] >= df['value'].cummax()

# Winning streak (consecutive positives)
df['pos']     = (df['value'] > df['value'].shift(1)).astype(int)
df['streak']  = df['pos'] * (df['pos'].groupby((df['pos'] != df['pos'].shift()).cumsum()).cumcount() + 1)

print(df[['date','value','all_time_high','streak']].head(15))

Use Cases

  • sports analytics
  • trading signals
  • performance streaks

Tags

Related Snippets

Similar patterns you can reuse in the same workflow.