Classical Seasonal Decomposition

medium
Unit 14 · Time Series0/3 to milestone

Split a series into trend + seasonal + residual, the classical additive decomposition (what statsmodels.seasonal_decompose does).

Implement decompose(y, period) returning (trend, seasonal, resid), three arrays the same length as y:

  1. Trend: a centred moving average. For an odd period, average the period values centred on each point. For an even period, use a "2 × period" average: weights [0.5, 1, …, 1, 0.5] / period over period + 1 points. Positions without a full window are NaN.
  2. Seasonal: for each position in the cycle (i % period), average the detrended values y - trend (ignoring NaNs). Subtract the mean of those period averages so they sum to zero, then tile across the series.
  3. Residual: y - trend - seasonal (NaN where the trend is NaN).

Also implement seasonal_strength(seasonal, resid): max⁡(0, 1−Var(R)Var(S+R))\max\left(0,\, 1 - \frac{\mathrm{Var}(R)}{\mathrm{Var}(S + R)}\right) over positions where the residual isn't NaN.

#time-series#forecasting#smoothing2 visible + 1 hidden tests
solution.py · Python 3.13
Loading editor…
Run your code to see results. ⌘↵ to run · ⌘⇧↵ to submit
Classical Seasonal Decomposition · TechGradify