Skip to content

Trend, season and remainder

Split a series into its parts with classical, STL and MSTL decomposition, measure how strong each part is, and spot when seasonality grows with the level.

Applied ~12 min10 steps

What runs in CodeSplash

You will be able to

  • Choose between additive and multiplicative decomposition
  • Use STL's seasonal window and MSTL's several periods
  • Read the strengths of trend and seasonality

Read first

01

Three parts

Read

Most business and environmental series look like a mix of three parts:

yt=Tt+St+Rty_t = T_t + S_t + R_t
  • Trend TtT_t: the long-run level.
  • SeasonalSeasonalityA pattern that repeats at a fixed period — daily, weekly, yearly. StS_t: a pattern that repeats with a known period.
  • Remainder RtR_t: what's left.

A decomposition is a description of the past. It doesn't say why these parts exist, and it isn't a forecast.

02

Build a series, then take it apart

Explore

DExplorable · Compose and decompose a series

How much of a series is trend, how much is season, and how much is noise?

How strong is the seasonality on a 0–1 scale?

0.50
How sure?
0.10
3.0
1.0

The series

Trend

Seasonal

Remainder

Commit your prediction above to see the result

Make your prediction first; the figure appears when you commit.

Make your prediction to see the result.

Raise Seasonal amplitude, then Noise, and watch Strength of seasonality. Then turn on Seasonality grows with the level with a steep trend. What goes wrong with the seasonal part?

03

Add or multiply?

Predict

Predict first

Airline passenger counts grow for years, and the summer peaks grow along with them.

Which decomposition suits that?

AdditiveMultiplicativeNeither: use differencing
Reveal

Multiplicative: yt=Tt×St×Rty_t = T_t \times S_t \times R_t. Each month is a percentage of the trend, not a fixed number above it. Taking logs and decomposing additively has much the same effect.

Here, the seasonal factors span a range of 0.43 around 1, so a peak month sits well above the trend and a trough month well below.

04

STL on CO₂

In the app

STL fits the trend and season with local regression (loess), and it allows the seasonal pattern to change.

Seasonal decompositionRecorded · Python and R agreeRecorded 2026-11-17 · 6 values compared
R

F_T = 1.00, F_S = 0.98

Trend strength
0.9997
Seasonal strength
0.9841
Season length
12

Plots

STL decomposition of co2How much of the series is trend, how much a repeating season, and what is left?
View data
co2remainderseasonaltrendmonth
315.420.2856−0.0610315.20−347,155,200,000
316.310.41310.5946315.30−344,476,800,000
316.50−0.23831.329315.41−342,057,600,000
317.56−0.42372.469315.51−339,379,200,000
318.13−0.44712.957315.62−336,787,200,000
318−0.03782.318315.72−334,108,800,000
316.39−0.25050.8217315.82−331,516,800,000
314.65−0.0380−1.227315.91−328,838,400,000
313.680.7011−3.032316.01−326,160,000,000
313.180.2772−3.217316.12−323,568,000,000
314.660.4609−2.030316.23−320,889,600,000
315.430.0213−0.9232316.33−318,297,600,000
316.27−0.1036−0.0610316.43−315,619,200,000
316.81−0.29730.5946316.51−312,940,800,000
317.42−0.49971.329316.59−310,435,200,000
318.87−0.24202.469316.64−307,756,800,000
319.870.21762.957316.70−305,164,800,000
319.430.36442.318316.75−302,486,400,000
318.010.38920.8217316.80−299,894,400,000
315.740.1166−1.227316.85−297,216,000,000
3140.1307−3.032316.90−294,537,600,000
313.68−0.0392−3.217316.94−291,945,600,000
314.84−0.1014−2.030316.97−289,267,200,000
316.03−0.0489−0.9232317.00−286,675,200,000
316.73−0.2417−0.0610317.03−283,996,800,000
317.54−0.14910.5946317.09−281,318,400,000
318.38−0.10531.329317.16−278,899,200,000
319.31−0.41042.469317.25−276,220,800,000
320.420.11662.957317.35−273,628,800,000
319.61−0.15302.318317.44−270,950,400,000
318.420.05520.8217317.54−268,358,400,000
316.630.2251−1.227317.63−265,680,000,000
314.830.1417−3.032317.72−263,001,600,000
315.160.5861−3.217317.79−260,409,600,000
315.940.1081−2.030317.86−257,731,200,000
316.85−0.1457−0.9232317.92−255,139,200,000
317.78−0.1347−0.0610317.98−252,460,800,000
318.40−0.22860.5946318.03−249,782,400,000
319.530.10881.329318.09−247,363,200,000
320.42−0.20292.469318.15−244,684,800,000
320.85−0.32262.957318.22−242,092,800,000
320.45−0.14622.318318.28−239,414,400,000
319.450.28810.8217318.34−236,822,400,000
317.250.0837−1.227318.39−234,144,000,000
316.110.6960−3.032318.45−231,465,600,000
315.27−0.0103−3.217318.50−228,873,600,000
316.530.0111−2.030318.55−226,195,200,000
317.53−0.1396−0.9232318.59−223,603,200,000
318.580.0045−0.0610318.64−220,924,800,000
318.92−0.34030.5946318.67−218,246,400,000
319.70−0.32371.329318.69−215,827,200,000
321.220.02052.469318.73−213,148,800,000
322.080.35672.957318.77−210,556,800,000
321.310.16632.318318.83−207,878,400,000
319.58−0.12610.8217318.88−205,286,400,000
317.61−0.1133−1.227318.95−202,608,000,000
316.050.0661−3.032319.02−199,929,600,000
315.83−0.0138−3.217319.06−197,337,600,000
316.91−0.1661−2.030319.11−194,659,200,000
318.20−0.0198−0.9232319.14−192,067,200,000

First 60 of 468 rows.

Periodogram of co2Which cycle lengths carry the most variation in the series?
View data
co2
315.42
316.31
316.50
317.56
318.13
318
316.39
314.65
313.68
313.18
314.66
315.43
316.27
316.81
317.42
318.87
319.87
319.43
318.01
315.74
314
313.68
314.84
316.03
316.73
317.54
318.38
319.31
320.42
319.61
318.42
316.63
314.83
315.16
315.94
316.85
317.78
318.40
319.53
320.42
320.85
320.45
319.45
317.25
316.11
315.27
316.53
317.53
318.58
318.92
319.70
321.22
322.08
321.31
319.58
317.61
316.05
315.83
316.91
318.20

First 60 of 468 rows.

Strength of each component

ComponentStrength (0–1)
Trend0.9997
Seasonal0.9841
  • Strength = max(0, 1 − Var(remainder) / Var(component + remainder)) (Wang, Smith & Hyndman 2006).
  • A periodic seasonal window fixes one seasonal pattern; a finite window lets it drift.
The exact R script · R R version 4.5.1 (2025-06-13)
# Seasonal decomposition
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method ts.decompose 1.0.1 · spec 450b50c8d37fe019
# Dataset: ts_co2 (version 1)
# Runs on its own: outside the app, cs_publish() writes $CS_RESULT_PATH or prints the result JSON.

# %% Setup
library(codesplashr)

# %% Data
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/ts_co2.parquet", col_select = c("co2", "month")))
n_input <- nrow(df)
df <- df[stats::complete.cases(df[c("co2", "month")]), , drop = FALSE]  # listwise deletion
df[] <- lapply(df, function(x) if (is.factor(x)) droplevels(x) else x)
n_dropped <- n_input - nrow(df)
warnings <- list()
if (n_dropped > 0) {
  warnings <- c(warnings, cs_warning("CS_W_ROWS_DROPPED", dropped = n_dropped, total = n_input))
}
if (n_input > 0 && nrow(df) == 0) cs_error("CS_E_NO_ROWS")
cs_check_finite_columns(df, c("co2", "month"))  # infinite values stop the run (registry/errors.yaml)

# %% Series
VALUE <- "co2"
TIME <- "month"
TEMPORAL <- TRUE
METHOD <- "stl"
PERIOD <- NULL
PERIODS <- as.integer(c(24, 168))
SWIN <- NULL
KIND <- "additive"
s <- cs_ts_ordered(df, VALUE, TIME, TEMPORAL)
x <- s$x
labels <- s$labels
n <- length(x)
if (s$dups > 0) warnings <- c(warnings, sprintf("%d repeated time values: the decomposition assumes evenly spaced observations.", s$dups))
# A decomposition needs two full cycles of a season at least 2 long (5 observations) and a series that varies;
# short or constant series stop with a catalog message (registry/errors.yaml), the same in Python.
cs_check_rows(n, 5, "A seasonal decomposition")
if (METHOD == "mstl") {
  periods <- sort(PERIODS[PERIODS >= 2 & PERIODS < n / 2])
  if (!length(periods)) {
    if (any(PERIODS >= 2)) cs_check_rows(n, 2 * min(PERIODS[PERIODS >= 2]) + 1, "A seasonal decomposition")
    stop("MSTL needs at least one seasonal period shorter than half the series.")
  }
  period <- periods[1]
} else {
  period <- if (!is.null(PERIOD)) as.integer(PERIOD) else if (!is.null(TIME)) cs_ts_guess_period(s$df[[TIME]], TEMPORAL) else NULL
  if (is.null(period)) stop("Set the season length: it could not be read from the time column.")
  cs_check_rows(n, 2 * period + 1, "A seasonal decomposition")  # two full cycles
}
cs_check_not_constant(x, VALUE)

# %% Decompose
values <- list(n_obs = n, method = METHOD, period = period)
if (METHOD == "stl") {
  d <- cs_ts_stl(x, period, if (is.null(SWIN)) "periodic" else as.integer(SWIN))
  seasonal <- d$seasonal
} else if (METHOD == "classical") {
  d <- cs_ts_classical_decompose(x, period, KIND)
  seasonal <- d$seasonal
  values$seasonal_range <- max(d$figure) - min(d$figure)
} else {
  d <- cs_ts_mstl(x, periods)
  seasonal <- Reduce(`+`, d$seasonals)
  for (p in names(d$seasonals)) values[[paste0("seasonal_strength_", p)]] <- cs_ts_seasonal_strength(d$seasonals[[p]], d$remainder)
}
trend <- d$trend
rem <- d$remainder
ok <- !is.na(rem)
if (METHOD == "classical" && KIND == "multiplicative") {
  tr_s <- log(trend[ok]); se_s <- log(seasonal[ok]); re_s <- log(rem[ok])
} else {
  tr_s <- trend[ok]; se_s <- seasonal[ok]; re_s <- rem[ok]
}
values$seasonal_strength <- cs_ts_seasonal_strength(se_s, re_s)
values$trend_strength <- cs_ts_trend_strength(tr_s, re_s)
values$remainder_sd <- stats::sd(re_s)
name <- switch(METHOD, stl = "STL", mstl = "MSTL", classical = sprintf("Classical (%s)", KIND))
summary <- paste0(sprintf("%s decomposition of %s (%d observations, season length %d", name, VALUE, n, period),
                  if (METHOD == "mstl") sprintf("; periods %s", paste(periods, collapse = ", ")) else "",
                  sprintf("): trend strength %.2f, seasonal strength %.2f (0 = none, 1 = all of the variation).", values$trend_strength, values$seasonal_strength))
rows <- list(list(component = "Trend", strength = values$trend_strength),
             list(component = paste0("Seasonal", if (METHOD == "mstl") " (all periods)" else ""), strength = values$seasonal_strength))
if (METHOD == "mstl") for (p in periods) rows[[length(rows) + 1]] <- list(component = sprintf("Seasonal, period %d", p), strength = values[[paste0("seasonal_strength_", p)]])
kind <- if (TEMPORAL) "temporal" else "numeric"
na_null <- function(a) lapply(a, function(v) if (is.na(v)) NULL else v)
cs_publish(list(
  method = "ts.decompose",
  methodVersion = "1.0.1",
  title = "Seasonal decomposition",
  engine = cs_engine_info("stats", "nanoparquet"),
  n = n,
  summary = summary,
  apa = sprintf("F_T = %.2f, F_S = %.2f", values$trend_strength, values$seasonal_strength),
  statistics = list(list(key = "trend_strength", label = "Trend strength", value = values$trend_strength),
                    list(key = "seasonal_strength", label = "Seasonal strength", value = values$seasonal_strength),
                    list(key = "period", label = "Season length", value = period)),
  tables = list(list(key = "strength", title = "Strength of each component",
                     columns = list(list(key = "component", label = "Component", type = "string"), list(key = "strength", label = "Strength (0–1)", type = "number")),
                     rows = rows)),
  effectSizes = list(),
  assumptions = list(),
  warnings = warnings,
  notes = list(paste0("Strength = max(0, 1 − Var(remainder) / Var(component + remainder)) (Wang, Smith & Hyndman 2006)",
                      if (KIND == "multiplicative" && METHOD == "classical") "; computed on logs for multiplicative seasonality." else "."),
               switch(METHOD, stl = "A periodic seasonal window fixes one seasonal pattern; a finite window lets it drift.",
                      classical = "The classical trend is missing for half a cycle at each end.",
                      "MSTL removes the shortest cycle first, then the longer ones, twice over.")),
  charts = list(
    cs_chart("decomposition", "stl-decomposition", sprintf("%s decomposition of %s", name, VALUE), list(
      x = cs_col(if (is.null(TIME)) "index" else TIME, labels, kind = kind), observed = cs_col(VALUE, x),
      trend = cs_col("trend", na_null(trend), kind = "numeric"), seasonal = cs_col("seasonal", na_null(seasonal), kind = "numeric"),
      remainder = cs_col("remainder", na_null(rem), kind = "numeric")),
      controls = list(multiplicative = METHOD == "classical" && KIND == "multiplicative")),
    cs_chart("periodogram", "periodogram", sprintf("Periodogram of %s", VALUE), list(y = cs_col(VALUE, x)), controls = list(period = period))),
  values = values
))
Python

F_T = 1.00, F_S = 0.98

Trend strength
0.9997
Seasonal strength
0.9841
Season length
12

To keep this page light, the plots are shown once, under the R tab.

Strength of each component

ComponentStrength (0–1)
Trend0.9997
Seasonal0.9841
  • Strength = max(0, 1 − Var(remainder) / Var(component + remainder)) (Wang, Smith & Hyndman 2006).
  • A periodic seasonal window fixes one seasonal pattern; a finite window lets it drift.
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Seasonal decomposition
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method ts.decompose 1.0.1 · spec 450b50c8d37fe019
# Dataset: ts_co2 (version 1)
# Runs on its own: outside the app, cs.publish() writes $CS_RESULT_PATH or prints the result JSON.

# %% Setup
import numpy as np
import pandas as pd

import codesplash as cs
from codesplash.errors import check_not_constant
from codesplash.stats import ts

# %% Data
df = pd.read_parquet("tests/parity/fixtures/ts_co2.parquet", columns=["co2", "month"])
n_input = len(df)
df = df.dropna(subset=["co2", "month"])  # listwise deletion over the analysis columns
n_dropped = n_input - len(df)
warnings = []
if n_dropped:
    warnings.append(cs.cs_warning("CS_W_ROWS_DROPPED", dropped=n_dropped, total=n_input))
if n_input and not len(df):
    cs.cs_error("CS_E_NO_ROWS")
cs.check_finite_columns(df, ["co2", "month"])  # infinite values stop the run (registry/errors.yaml)

# %% Series
VALUE = "co2"
TIME = "month"
TEMPORAL = True
METHOD = "stl"
PERIOD = None
PERIODS = [int(v) for v in [24, 168]]
SWIN = None
KIND = "additive"
s = ts.ordered(df, VALUE, TIME, TEMPORAL)
x, labels = s["x"], s["labels"]
n = len(x)
if s["dups"]:
    warnings.append(f"{s['dups']} repeated time values: the decomposition assumes evenly spaced observations.")
# A decomposition needs two full cycles of a season at least 2 long (5 observations) and a series that varies;
# short or constant series stop with a catalog message (registry/errors.yaml), the same in R.
cs.check_rows(n, 5, "A seasonal decomposition")
if METHOD == "mstl":
    periods = sorted(p for p in PERIODS if 2 <= p < n / 2)
    if not periods:
        if any(p >= 2 for p in PERIODS):
            cs.check_rows(n, 2 * min(p for p in PERIODS if p >= 2) + 1, "A seasonal decomposition")
        raise ValueError("MSTL needs at least one seasonal period shorter than half the series.")
    period = periods[0]
else:
    period = int(PERIOD) if PERIOD is not None else ts.guess_period(s["df"][TIME].to_numpy(), TEMPORAL) if TIME else None
    if period is None:
        raise ValueError("Set the season length: it could not be read from the time column.")
    cs.check_rows(n, 2 * period + 1, "A seasonal decomposition")  # two full cycles
check_not_constant(x, VALUE)

# %% Decompose
values = {"n_obs": n, "method": METHOD, "period": period}
if METHOD == "stl":
    d = ts.stl(x, period, "periodic" if SWIN is None else int(SWIN))
    seasonal = d["seasonal"]
elif METHOD == "classical":
    d = ts.classical_decompose(x, period, KIND)
    seasonal = d["seasonal"]
    values["seasonal_range"] = float(np.max(d["figure"]) - np.min(d["figure"]))
else:
    d = ts.mstl(x, periods)
    seasonal = sum(d["seasonals"].values())
    for p, sp in d["seasonals"].items():
        values[f"seasonal_strength_{p}"] = ts.seasonal_strength(sp, d["remainder"])
trend, rem = d["trend"], d["remainder"]
ok = ~np.isnan(rem)
if METHOD == "classical" and KIND == "multiplicative":
    tr_s, se_s, re_s = np.log(trend[ok]), np.log(seasonal[ok]), np.log(rem[ok])
else:
    tr_s, se_s, re_s = trend[ok], seasonal[ok], rem[ok]
values.update({"seasonal_strength": ts.seasonal_strength(se_s, re_s), "trend_strength": ts.trend_strength(tr_s, re_s),
               "remainder_sd": float(np.std(re_s, ddof=1))})
name = {"stl": "STL", "mstl": "MSTL", "classical": f"Classical ({KIND})"}[METHOD]
summary = (f"{name} decomposition of {VALUE} ({n} observations, season length {period}"
           + (f"; periods {', '.join(str(p) for p in periods)}" if METHOD == "mstl" else "")
           + f"): trend strength {values['trend_strength']:.2f}, seasonal strength {values['seasonal_strength']:.2f} (0 = none, 1 = all of the variation).")
rows = [{"component": "Trend", "strength": values["trend_strength"]}, {"component": "Seasonal" + (" (all periods)" if METHOD == "mstl" else ""), "strength": values["seasonal_strength"]}]
if METHOD == "mstl":
    rows += [{"component": f"Seasonal, period {p}", "strength": values[f"seasonal_strength_{p}"]} for p in periods]
kind = "temporal" if TEMPORAL else "numeric"
nan_none = lambda a: [None if np.isnan(v) else float(v) for v in a]
cs.publish({
    "method": "ts.decompose",
    "methodVersion": "1.0.1",
    "title": "Seasonal decomposition",
    "engine": cs.engine_info("pandas", "numpy", "statsmodels"),
    "n": n,
    "summary": summary,
    "apa": f"F_T = {values['trend_strength']:.2f}, F_S = {values['seasonal_strength']:.2f}",
    "statistics": [{"key": "trend_strength", "label": "Trend strength", "value": values["trend_strength"]},
                   {"key": "seasonal_strength", "label": "Seasonal strength", "value": values["seasonal_strength"]},
                   {"key": "period", "label": "Season length", "value": period}],
    "tables": [{"key": "strength", "title": "Strength of each component",
                "columns": [{"key": "component", "label": "Component", "type": "string"}, {"key": "strength", "label": "Strength (0–1)", "type": "number"}],
                "rows": rows}],
    "effectSizes": [],
    "assumptions": [],
    "warnings": warnings,
    "notes": ["Strength = max(0, 1 − Var(remainder) / Var(component + remainder)) (Wang, Smith & Hyndman 2006)" + ("; computed on logs for multiplicative seasonality." if KIND == "multiplicative" and METHOD == "classical" else "."),
              "A periodic seasonal window fixes one seasonal pattern; a finite window lets it drift." if METHOD == "stl" else "The classical trend is missing for half a cycle at each end." if METHOD == "classical" else "MSTL removes the shortest cycle first, then the longer ones, twice over."],
    "charts": [cs.chart("decomposition", "stl-decomposition", f"{name} decomposition of {VALUE}", {
                   "x": cs.col(TIME or "index", labels, kind=kind), "observed": cs.col(VALUE, x), "trend": cs.col("trend", nan_none(trend), kind="numeric"),
                   "seasonal": cs.col("seasonal", nan_none(seasonal), kind="numeric"), "remainder": cs.col("remainder", nan_none(rem), kind="numeric")},
                   controls={"multiplicative": METHOD == "classical" and KIND == "multiplicative"}),
               cs.chart("periodogram", "periodogram", f"Periodogram of {VALUE}", {"y": cs.col(VALUE, x)}, controls={"period": period})],
    "values": values,
})

Atmospheric CO2 has a seasonal strength of 0.98, a trend strength of 1.000, and a remainder SD of 0.26.

Look at the decomposition panels and the periodogram. At which frequency is the sharpest spike?

05

How strength is measured

Read

Seasonal strengthSeasonal strengthThe share of variation (after trend) that a repeating seasonal pattern explains, from 0 (none) to 1 (all) — and likewise for the trend. compares the remainder with the season plus remainder:

FS=max⁡ ⁣(0, 1−Var⁡(Rt)Var⁡(St+Rt))F_S = \max\!\left(0,\ 1 - \frac{\operatorname{Var}(R_t)}{\operatorname{Var}(S_t + R_t)}\right)

Near 1, the season dominates the noise. Near 0, there is little sign of a season. Trend strength has the same form, using Tt+RtT_t + R_t. These are descriptive numbers, not tests.

06

When seasons change

Reflect

Seasonal window decides how fast the pattern may change. Periodic forces one fixed pattern for the whole series. A number such as 13 lets it change slowly.

On UK gas consumption, with a window of 13, the seasonal strength is 0.98 and the remainder SD 23.6.

A small window can absorb real events into the seasonal part. What would you check to see if that happened?

07

More than one season

Predict

Predict first

Hourly electricity load has a daily cycle and a weekly cycle. Can a single seasonal period capture both?

Yes: STL with one period is enoughNo: you need to model two periodsOnly if weekends are removed
Reveal

No. MSTL peels off several seasonal parts in turn. Here it finds strength 0.96 at 24 hours and 0.90 at 168 hours, on 672 hours of data.

08

Check your understanding

Checkpoint

Check yourself

Var⁡(Rt)=2\operatorname{Var}(R_t) = 2 and Var⁡(St+Rt)=20\operatorname{Var}(S_t + R_t) = 20. What is the seasonal strength?

Show the answer

Answer: 0.9

1−2/20=0.91 - 2/20 = 0.9.

Check yourself

A series' seasonal swings get larger as its level rises. What's the sound approach?

Show the answer

Answer: a

Additive decomposition leaves growing swings in the remainder, where they look like noise.

Check yourself

A decomposition gives a seasonal strength of 0.95. What can you say?

Show the answer

Answer: c

It's a descriptive ratio, with no p-value and no promise about the future. It also says nothing about the trend.

09

Do it in CodeSplash

In the app

Set Series and Time. Season length comes from the dates unless you set it. Seasonal decomposition is also the Look step in the Series lab.

Python
import pandas as pd
from statsmodels.tsa.seasonal import STL

df = pd.read_csv("co2.csv")
fit = STL(df["co2"], period=12).fit()
print(fit.seasonal.head(), fit.trend.head())
R
co2_fit <- stl(co2, s.window = "periodic")
plot(co2_fit)
10

Recap

Recap
  • Decomposition describes a series as trend, season and remainder.
  • If swings grow with the level, use a multiplicative form or logs.
  • STL lets the seasonal pattern change, and MSTL handles several periods.
  • Strength values are descriptive, not tests or forecasts.

Concepts in this lesson