Part III — Advanced Systems · Chapter 18 · Lesson 3 of 7 · 7 min read
Lesson 3: Interpolation, Grouped Analysis, and Seasonal Decomposition
Lesson level: Advanced
Purpose: Make incomplete series usable without inventing information, analyze many related series consistently, and separate a series into trend, seasonal, and remainder components so that each can be understood and modelled.
Learning objectives
By the end of this lesson you will be able to:
- classify gaps as true zeros, missing observations, or structural breaks
- choose between zero fill, forward fill, linear interpolation, and seasonal fill
- limit interpolation so long gaps are not silently invented
- apply the same time-series logic across many groups and compare them fairly
- decompose a series into trend, seasonal, and remainder components
- choose additive or multiplicative decomposition
3.1 Three kinds of gap
A missing period means different things in different situations, and the repair must follow the meaning:
| Kind of gap | Meaning | Repair |
|---|---|---|
| True zero | Nothing happened (no sales on a closed day) | Fill with 0 for flows |
| Missing observation | Something happened but was not recorded (feed outage) | Interpolate or estimate, and flag |
| Structural break | The series changed definition (store closed, product discontinued, new meter) | Do not bridge; split the series or model the break |
The data alone rarely tells you which kind of gap you have. Use operational sources — store opening calendars, feed health logs, product lifecycle tables — to classify gaps, and keep the classification as a column so that downstream users can see which values were observed and which were repaired.
3.2 Fill and interpolation methods
- Zero fill — correct only for flows during true inactivity.
- Forward fill — carries the last known value forward. Correct for levels that change only when an event occurs, such as a price or a status; wrong for flows.
- Linear interpolation — draws a straight line between neighbours. Reasonable for smoothly varying levels such as temperature over a short gap.
- Time-weighted interpolation — linear interpolation that respects uneven spacing in the index.
- Seasonal fill — uses the value from the same point in the previous cycle, possibly scaled to the current level. Better than linear interpolation for strongly seasonal flows, because a straight line across a weekend in a weekday-heavy series is wrong.
Illustrative listing.
full = calendar.join(daily, on="date", how="left")
repaired = (full
.sort("date")
.with_column("was_missing", col("revenue").is_null())
.with_column("revenue_filled",
col("revenue").interpolate(method="linear", limit=2))
.with_column("gap_too_long",
col("was_missing") & col("revenue_filled").is_null()))
Limit every interpolation. A two-day gap in a smooth series can be bridged; a three-week gap cannot. The limit argument leaves longer runs as null so they are visible and must be dealt with deliberately. Report the number of filled values and the longest unfilled gap with every run.
3.3 Grouped time-series analysis
Real datasets hold many series at once: revenue per store, demand per product, latency per service. Grouped analysis applies the same logic to each series independently and then compares them. The pattern is always the same: regularize per group, compute per group, compare across groups.
Illustrative listing.
grid = stores.cross_join(calendar) # every store x every date
panel = (grid
.join(daily_by_store, on=["store_id", "date"], how="left")
.sort(["store_id", "date"])
.with_column("rev_ma28",
col("revenue").rolling_mean(window=28, min_periods=14).over("store_id"))
.with_column("rev_yoy",
col("revenue") / col("revenue").shift(364).over("store_id") - 1))
The cross join builds a complete panel: one row for every group and every period. Without it, a store with no sales on a day simply has no row, and window and lag calculations for that store are silently misaligned. Then restrict the panel to each store's active life, using opening and closing dates, so a store that opened in March is not shown with zeros for January and February.
A shift of 364 days rather than 365 compares the same weekday last year, which matters for weekly-patterned series. Note the choice in the feature definition.
Comparing groups fairly. Groups differ in size. Compare growth rates, indexed series (each divided by its own baseline period), or z-scores within group, not raw values. And use the same window, fill, and validation rules for every group; a comparison is only as fair as its least consistent group.
3.4 Seasonal decomposition
Decomposition splits a series into three parts:
- Trend — the slow, long-term movement.
- Seasonal — a repeating pattern with a fixed period, such as the weekday cycle or the yearly cycle.
- Remainder — what is left: noise, one-off events, and anomalies.
In an additive decomposition, value = trend + seasonal + remainder. In a multiplicative decomposition, value = trend × seasonal × remainder. Choose additive when the seasonal swing has roughly constant size, and multiplicative when the swing grows with the level — a store whose weekend boost is always about 40% of its weekday sales. Taking logarithms turns a multiplicative series into an additive one.
The classical method works in three steps:
- Estimate the trend with a centred moving average whose length equals the seasonal period. (Centred windows are acceptable here because decomposition describes history; it is not a forecasting feature.)
- Remove the trend, then average the detrended values at each position of the cycle — every Monday, every Tuesday, and so on — to get the seasonal index. Normalize the index so it sums to zero (additive) or averages to one (multiplicative).
- Remove trend and seasonal components; what remains is the remainder.
Illustrative listing.
from pealang.data import read
series = read("daily_revenue.csv").sort("date")
parts = series.seasonal_decompose(
value="revenue", period=7, model="multiplicative")
print(parts.select(["date", "trend", "seasonal", "remainder"]).head(14))
If your installed version does not provide a decomposition helper, the three steps above can be written directly with a centred rolling mean, a group-by on the cycle position, and two calculated columns. Writing it once by hand is a good exercise even when a helper exists.
3.5 Reading a decomposition
A decomposition is a diagnostic, not an answer. Read it in order:
- Trend: Is it rising, flat, or falling? Are there kinks that coincide with known events such as a price change or a new competitor? A kink may be a structural break that should split the series.
- Seasonal: Is the pattern plausible to a domain expert? A retail weekday index that peaks on Wednesday deserves a question before it drives staffing.
- Remainder: Is it small and patternless? Remaining structure — a repeating spike every month-end, for example — means a second seasonal cycle or a calendar effect is missing.
Classical decomposition has known limits. It loses half a period of trend at each end of the series, assumes the seasonal pattern never changes, and is distorted by outliers. Robust methods based on local regression handle evolving seasonality and outliers better; where available, prefer them for long series. Whatever the method, keep the period explicit and check that the components add (or multiply) back to the original.
Common mistakes
- Treating every gap as a zero: classify gaps using operational data first.
- Unlimited interpolation: long gaps become invented data. Set a limit and report what was filled.
- Forward-filling flows: repeating yesterday's sales double-counts revenue.
- Bridging structural breaks: a new meter or a store refit starts a new series.
- Building panels without a full grid: missing rows misalign every per-group window.
- Choosing additive decomposition for growing seasonal swings: use multiplicative, or log-transform first.
- Trusting the edges of a classical trend: the first and last half-period are unreliable or missing.
Guided practice
- Remove five consecutive days from a seasonal daily series and repair them with linear interpolation and with seasonal fill. Compare both with the true values.
- Build a store-by-date panel for three stores with different opening dates. Verify that each store has exactly one row per active day.
- Decompose 18 months of daily data with period 7, additively and multiplicatively. Which remainder looks more like noise?
Hands-on lab: Store panel with repaired gaps and decomposition
- Load daily sales for ten stores, a store master with opening and closing dates, and a feed-health log.
- Build the full store-by-date grid and restrict it to each store's active dates.
- Classify each missing value as true zero (store closed), missing observation (feed outage), or out of life. Repair only missing observations of up to three days with seasonal fill; leave longer gaps null.
- Decompose each store's series with period 7 and a multiplicative model.
- Produce a comparison table: average weekday index per store, trend growth over the last 90 days, and remainder standard deviation. Highlight stores whose seasonal pattern differs markedly from the rest.
Review questions
- What are the three kinds of gap and how should each be repaired?
- When is forward fill appropriate, and when is it wrong?
- Why should interpolation have a limit?
- Why build a complete group-by-period grid before computing per-group windows?
- How do you choose between additive and multiplicative decomposition?
- What does structure remaining in the remainder tell you?
Applied challenge
An energy team has hourly meter readings for 200 sites. Some meters were replaced during the year, and the feed drops out for hours at a time. Design a repair and decomposition pipeline that detects meter changes as structural breaks, fills short outages, decomposes each site with both daily (24-hour) and weekly (168-hour) seasonality, and produces a one-page summary of sites whose consumption pattern changed after the meter replacement.
Lesson summary
Repair gaps according to what they mean, limit and flag every fill, and never bridge a structural break. Analyze many series as a complete panel computed per group and compared on normalized measures. Decomposition separates trend, seasonality, and remainder; choose the model by how seasonal swings scale, read each component critically, and confirm that the parts reconstruct the original.
Transition to Lesson 4
With a clean, understood series you can start forecasting — but first you need an honest way to measure whether a forecast is any good. Lesson 4 covers time-aware splits and error metrics.
Lesson status: Ready for review.