iwantcoding.com
🔥 Daily 👥 Rooms 🏆 Top Log in Sign up

Rolling Windows

Rolling windows and expanding windows are the bread and butter of time series analysis in pandas. They let you compute moving averages, rolling standard deviations, and other windowed statistics over an ordered index. The window can be defined by a fixed count of rows or by a time offset like "7D" for seven days.

Rolling mean, std, and expanding sum

EXAMPLE
import pandas as pd
import numpy as np

dates = pd.date_range('2026-01-01', periods=30, freq='D')
df = pd.DataFrame({'sales': np.random.randint(80, 200, 30)}, index=dates)

# Fixed-row window
df['ma_7'] = df['sales'].rolling(window=7).mean()
df['std_7'] = df['sales'].rolling(window=7).std()

# Time-offset window (handles missing days correctly)
df['ma_7d'] = df['sales'].rolling('7D').mean()

# Expanding window: all history up to current row
df['running_total'] = df['sales'].expanding().sum()

# Custom aggregation
df['range_7'] = df['sales'].rolling(7).apply(lambda x: x.max() - x.min())

print(df.tail(10))

Why it matters

Time-offset windows ("7D") differ from row-count windows (window=7) when there are gaps in your data. Use offset windows whenever the index is a real datetime and you care about calendar days, not row positions.

Tip: Tweak the snippet with Try it Yourself », then sit the quiz at the bottom of the page.

Example

Example
import pandas as pd
df['ma_7']  = df['close'].rolling(7).mean()
df['vol_7'] = df['close'].rolling(7).std()
df['ewma']  = df['close'].ewm(span=20).mean()
Try it Yourself »

Discussion

Loading…