PeaBox Lab › PeaLang › Learn › Chapter 18 › Lesson 3

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:

3.1 Three kinds of gap

A missing period means different things in different situations, and the repair must follow the meaning:

Kind of gapMeaningRepair
True zeroNothing happened (no sales on a closed day)Fill with 0 for flows
Missing observationSomething happened but was not recorded (feed outage)Interpolate or estimate, and flag
Structural breakThe 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

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:

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:

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:

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

Guided practice

Hands-on lab: Store panel with repaired gaps and decomposition

Review questions

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.

← Previous Next →