view source

Time Series Analysis: Trend, Seasonality, Anomalies

skill

Describe a time series before forecasting: gaps, trend, seasonality, STL, anomalies, change points and before-and-after claims. Use on dated metrics.

Apache-2.0 Python 3 with pandas, statsmodels, scipy and ruptures, or uv to fetch them. No network access needed.

agents that use this skill

instructions

Overview

A forecast, an alert or a claim about a change is only as good as the description of the series under it. This skill covers checking spacing and gaps, separating trend, seasonality and calendar effects, comparing across time fairly, flagging anomalies and level shifts, knowing why autocorrelation breaks ordinary tests, and stating what a before-and-after comparison can support. The deliverable is a short diagnosis: a cleaned and documented series, its components, a list of flagged points and breaks with the evidence for each, and a plain statement of what can and cannot be claimed.

Mental model

  • A time series has trend (long-term rise or fall), seasonality (a pattern with a fixed, known period such as the day of the week) and a remainder. A cycle with no fixed period is not seasonality (Hyndman and Athanasopoulos, abbreviated FPP3 below).
  • Neighbouring points are not independent: a high day tends to follow a high day. Tests that assume independent points report too much certainty.
  • An anomaly is judged against what the series would normally do at that time, so remove trend and seasonality first, then look at what is left.
  • A change in level is a different object from a one-day spike. A spike is a point to explain; a level shift is a new normal.

Rules

Check spacing and gaps first

  1. Print the distinct gaps between timestamps. One value means regular; anything else needs a decision.
  2. Put the series on a regular grid (asfreq or resample), count the missing points, and list where they are. A missing day and a day that is zero are different facts; do not fill zeros for missing data unless the system counts zero.
  3. Fill short gaps by interpolation with a stated limit, for example three points. Leave long gaps as gaps and analyze the stretches on each side. The STL function in the book's R package does not handle missing values, so fill before decomposing.
  4. Resample with the right aggregate: sum for counts, mean for rates and levels, last for balances. A partial last period (a month still running) is dropped or marked.

Remove calendar effects

A month of 31 days has more sales than a month of 28. Adjust to a per-day or per-trading-day figure before comparing months, as Hyndman and Athanasopoulos suggest. Holidays and known events get an indicator column; keep them out of the seasonal estimate. Use a log when the size of the swings grows with the level: an additive decomposition of the log is a multiplicative one of the original, and logs need strictly positive values.

Decompose with STL

text
from statsmodels.tsa.seasonal import STL
res = STL(y, period=7, robust=True).fit()    # res.trend, res.seasonal, res.resid
  • Give period for a plain array; a pandas series with a regular frequency lets STL infer it. Use 7 for daily data with a weekly pattern, 12 for monthly data.
  • The robust flag stops occasional outliers from bending the trend and seasonal estimates, so they appear in the remainder where they can be seen.
  • Window lengths are odd. Smaller windows let the component move faster. FPP3 defaults to a seasonal window of 11 and says to experiment; statsmodels defaults to 7 and advises 7 or more. Try two settings and keep the one whose remainder shows no pattern.
  • STL is additive. Take logs for a multiplicative series.
  • Look at the seasonal plot and the remainder before using any output.

Compare across time

ComparisonUse whenFailure
Year over yearSeasonality exists; compares same calendar positionShifted holidays, a different number of weekdays, a one-off last year
Period over periodSeries has no seasonality, or after seasonal adjustmentReads seasonal swings as growth
Rolling windowSmoothing noise; a 7-day window removes a weekly patternWindow length not a multiple of the period leaves seasonality; the line lags the data

State the window and alignment. On monthly sums, pct_change(12) is year over year; check that both months are complete.

Flag anomalies

  1. Decompose with a robust STL and take the remainder.
  2. Score each point by distance from the median of the remainder in units of the median absolute deviation. SciPy's median_abs_deviation with scale="normal" divides by 0.67449 so that the unit matches a standard deviation for normal data:
text
from scipy.stats import median_abs_deviation
z = (r - r.median()) / median_abs_deviation(r, scale="normal")
  1. FPP3 prefers a rule that flags points more than three interquartile ranges beyond the middle half of the remainder (1.5 is the looser version).
  2. Flag points whose absolute score is above a cutoff you state, for example 3.5, and count the flags. Many flags mean the decomposition is wrong, not that the series is full of anomalies: revisit the decomposition before raising the cutoff.
  3. Sort flags by size and explain the largest ones (deploy, outage, promotion, holiday). Do not replace an outlier without knowing why it occurred; it may carry information.

Find change points

Run change-point detection on the series with seasonality removed (the series minus res.seasonal), because a seasonal pattern is read as many breaks otherwise. With ruptures:

text
import numpy as np
import ruptures as rpt
sa = (y - res.seasonal).to_numpy()
penalty = np.log(len(sa)) * res.resid.var()
bk = rpt.Pelt(model="l2", min_size=30, jump=5).fit(sa.reshape(-1, 1)).predict(pen=penalty)

min_size sets the minimum spacing between breaks and jump the grid of candidate positions; predict returns the end index of each segment, so the last value is the series length. The penalty sets how large a shift must be to count; the starting value above, the log of the series length times the noise variance, is the one the ruptures guide uses in its example. Run it at a tenth and at ten times that value and keep the breaks that survive all three. The l2 model detects shifts in the mean, so a steady slope comes out as a staircase of small breaks: drop breaks whose shift is smaller than a size you state. Then check each surviving break against a known event.

Why autocorrelation matters

Autocorrelation is the correlation of a series with its own lagged values. For white noise, about 95% of autocorrelation spikes fall within plus or minus 1.96 over the square root of the series length; one large spike outside the bounds, or clearly more than 5% outside, means the series is not white noise. Test remainders with Ljung-Box, using 10 lags for a non-seasonal series and twice the period for a seasonal one (FPP3), capped at a fifth of the series length:

text
from statsmodels.stats.diagnostic import acorr_ljungbox
acorr_ljungbox(res.resid, lags=[14])

A small p-value means structure is left in the remainder. Ignoring autocorrelated errors makes regression p-values too small, so predictors look important when they are not (spurious regression, FPP3 chapter on dynamic regression). Difference or detrend first, or use methods built for dependent data. Never run a plain t-test on daily values before and after a date.

Before and after an intervention

A change at a date supports a claim of association with that date. To go further:

  • Show the level and slope before and after on the seasonally adjusted series, with the pre-period long enough to cover at least one full seasonal cycle.
  • Compare with a series the change could not affect and that tracked this one before the date. If that series moves too, the cause is general.
  • Model the change as an intervention term (FPP3: a step for a lasting level shift, a spike for one period, a change of slope for a bend in trend) in a regression that also holds trend and seasonal terms, and test the remainder for autocorrelation.
  • Check what else happened on that date.

Without a comparison series or randomization, write "coincided with", not "caused".

Examples

Year over year on a shifted holiday. Bad: "March is down 12% year over year." Good: "March is down 12%; Easter fell in March last year and April this year. Combined March and April are down 2%."

Many flags. Bad: "Dozens of anomalies found." Good: "Dozens of points exceed the cutoff and the remainder has autocorrelation (Ljung-Box p = 0.002), so the decomposition is under-fit. After refitting, three remain: an outage, a promotion and a data gap."

Intervention. Bad: "Signups rose 15% after launch, so the launch worked." Good: "The level rose by about 15 signups a week on the adjusted series from week 33; the comparison market did not move; it coincided with the launch."

Checklist

  • Gaps listed; fill rule and limit stated; the partial last period removed.
  • Calendar effects adjusted; log used only for positive, level-dependent swings.
  • STL period and settings stated; the remainder inspected.
  • Anomaly cutoff stated; a large flag count led back to the decomposition; each flag explained or labeled unexplained.
  • Change points checked at several penalties and against known events.
  • Remainder tested for autocorrelation; no test assumes independent points.
  • Before-and-after claim worded as association unless a comparison series supports more.

When the user cannot be asked, state the period and the fill rule you assumed.

Composition / References

Scope limits: training and backtesting forecast models, charts of the series and warehouse pipelines are separate jobs.