AI Hints
Home›Data Science Tutorial›Time and Journeys
Data Science · Lesson 33 of 101

Rolling Windows

Smoothing the noise of daily data.

⏱ 2 min read▶ Video at 58:03🎓 Free
Watch this lesson in the Data Science courseWatch on YouTube ↗Full Data Science course

Daily sales bounce around so much that it's impossible to see what's going on. Up on Saturday, down on Monday. If you react to each wobble, you'll panic every week. Good analysts look through the noise, and rolling windows are how they do it.

Rolling Windows
From the video: Rolling Windows
  • Daily sales bounce around
  • Reacting to each wobble
  • Look through the noise

Three time tools

These three tools show up in nearly every business report. Rolling seven takes the average of the past seven days, which removes the weekly rhythm. Percent change with seven compares each day with the same day last week. And cumulative sum, grouped by year, gives you a year to date total, that restarts every January. Run it. Three columns, and each one answers a question that the raw number can't. Is the trend up? How does this compare with last week? And where are we for the year?

rolling.pypython
import pandas as pd

sales = pd.read_csv("sales.csv", parse_dates=["date"])
d = sales.groupby("date")["revenue"].sum().asfreq("D").to_frame("revenue")

d["week_avg"] = d["revenue"].rolling(7).mean()
d["vs_last_week"] = d["revenue"].pct_change(7)
d["year_to_date"] = d.groupby(d.index.year)["revenue"].cumsum()

print(d.tail(3).round(2).to_string())
Output
             revenue  week_avg  vs_last_week  year_to_date
date
2025-12-29  11099.28  11817.07          0.03    3432402.54
2025-12-30  10619.96  11732.38         -0.05    3443022.50
2025-12-31  11017.36  11763.60          0.02    3454039.86

Choosing a window

The window length is a choice. Match it to the rhythm in your data. Seven days removes a weekly pattern exactly, because every window holds one of each day. A window that's too short leaves in the noise. A window that's too long hides real changes, and reacts late. Also remember that a rolling average always lags behind, so a sudden drop takes days to show up.

Match the rhythmseven for weekly
Too shortstill noisy
Too longhides real change
Always lagssudden drops show late

Summary

Rolling averages show the trend. But what about the sudden events, the days that something really went wrong? Next, we'll build an alarm.

Key takeaways
  • Rolling means smooth noise
  • Compare with the same day last week
  • Year to date restarts each year
Next up: Catching Anomalies — an alarm for your data