Window Functions & Moving Averages in Pandas0%

Window Functions & Moving Averages in Pandas

Beginner12 min read•Updated: Jul 11, 2026
Study Materials

Window Functions & Moving Averages in Pandas

In business intelligence and algorithmic finance, static metrics (like total monthly sales) hide critical intra-period dynamics. Window functions allow analysts to calculate moving averages, rolling volatility, cumulative totals, and exponential trends across temporal and partitioned sequences without collapsing the underlying dataset.


1. Rolling vs Expanding vs Exponential Windows

Window TypeMethodScope of CalculationTypical Use Case
Rolling Window.rolling(window=N)Fixed size $N$ past rows sliding forward7-day or 30-day Moving Averages
Expanding Window.expanding(min_periods=1)All historical rows up to current rowYear-To-Date (YTD) cumulative metrics
Exponential (EWM).ewm(span=N)Decaying weights giving recent data higher priorityTechnical analysis, algorithmic trading

2. Practical Rolling Calculations

To compute a rolling metric, ensure the DataFrame is sorted chronologically:

Python
import pandas as pd
import numpy as np
 
# Ensure chronological sorting
df = df.sort_values(by=['date']).reset_index(drop=True)
 
# 7-Day Simple Moving Average (SMA)
df['revenue_7d_sma'] = df['revenue'].rolling(window=7, min_periods=1).mean()
 
# 30-Day Rolling Standard Deviation (Volatility indicator)
df['revenue_30d_std'] = df['revenue'].rolling(window=30, min_periods=5).std()
 
# Rolling sum over 14 periods
df['orders_14d_sum'] = df['orders'].rolling(window=14).sum()
Note
Note on min_periods: By default, .rolling(window=7) returns NaN for the first 6 rows. Setting min_periods=1 begins computing averages immediately from the first row.

3. Groupby with Rolling Windows (Partitioned Windows)

When analyzing metrics partitioned by entity (e.g., individual retail store branches, user accounts, or product categories), pair .groupby() with .rolling():

Python
# Compute 7-day rolling sales per store branch
df['store_7d_avg'] = (
df
.groupby('store_id')['sales']
.rolling(window=7, min_periods=1)
.mean()
.reset_index(level=0, drop=True) # Drop the extra groupby index level
)

4. Expanding Windows for Cumulative Insights

Expanding windows evaluate performance trajectory from the start of an experiment or fiscal period:

Python
# Cumulative Running Total (same as .cumsum(), but extensible to custom funcs)
df['cumulative_revenue'] = df['revenue'].expanding(min_periods=1).sum()
 
# Running historical maximum drawdown baseline
df['peak_historical_sales'] = df['revenue'].expanding().max()

5. Exponentially Weighted Moving Average (EWMA)

EWMA reacts faster to sudden changes than simple moving averages because recent observations receive exponentially higher weights:

Python
# 12-day Span Exponentially Weighted Moving Average
df['ewma_12'] = df['revenue'].ewm(span=12, adjust=False).mean()

Interactive Quiz

Multiple Choice Questions

Question 1
What does the min_periods parameter in df['sales'].rolling(window=7, min_periods=3).mean() do?
Question 2
How does an expanding window differ fundamentally from a rolling window?
Question 3
Why must a DataFrame be sorted chronologically before computing rolling metrics on time-series data?
Question 4
Which Pandas method calculates an exponentially weighted moving average where recent observations carry exponentially greater weight?
Question 5
What is the output of pd.Series([10, 20, 30]).expanding().mean()?

Next Lesson

Trend, Seasonality & Residual Decomposition

Continue learning with hands-on practice, examples, and exercises in the upcoming topic.

Practice Quiz

Test your understanding of this lesson with 5 questions. Each question has one correct answer.

PrevNext