Window Functions & Moving Averages in Pandas
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 Type | Method | Scope of Calculation | Typical Use Case |
|---|---|---|---|
| Rolling Window | .rolling(window=N) | Fixed size $N$ past rows sliding forward | 7-day or 30-day Moving Averages |
| Expanding Window | .expanding(min_periods=1) | All historical rows up to current row | Year-To-Date (YTD) cumulative metrics |
| Exponential (EWM) | .ewm(span=N) | Decaying weights giving recent data higher priority | Technical analysis, algorithmic trading |
2. Practical Rolling Calculations
To compute a rolling metric, ensure the DataFrame is sorted chronologically:
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():
4. Expanding Windows for Cumulative Insights
Expanding windows evaluate performance trajectory from the start of an experiment or fiscal period:
5. Exponentially Weighted Moving Average (EWMA)
EWMA reacts faster to sudden changes than simple moving averages because recent observations receive exponentially higher weights:
Multiple Choice Questions
min_periods parameter in df['sales'].rolling(window=7, min_periods=3).mean() do?pd.Series([10, 20, 30]).expanding().mean()?Trend, Seasonality & Residual Decomposition
Continue learning with hands-on practice, examples, and exercises in the upcoming topic.
Related Lessons
| Previous Lesson | Next Lesson |
|---|---|
| Method Chaining (pipe, assign) for Clean Production Pipelines | Trend, Seasonality & Residual Decomposition |
Practice Quiz
Test your understanding of this lesson with 5 questions. Each question has one correct answer.