Skip to content

DTime series · ts.decompose

Seasonal decomposition

How much of the series is trend, how much is a repeating seasonal pattern (one or several), and what is left over?

Splits a series into trend, seasonal and remainder by STL (loess, R's stl defaults), MSTL for several seasonal periods (hours in a day and days in a week …) or classical moving averages (additive or multiplicative), and reports the strength of the trend and of each seasonal pattern.

Verified in Python and R Python and R agree to 6 decimals Also called STL, seasonal decomposition, MSTL…

A real result

Example “Stl co2”, recorded in both engines. In the app, “Try this example” loads it into Analyze.

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.
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.

Do it in CodeSplash Run it on your own data, in Python or R, with the code to prove it.

Worked examples in the app

  • Stl co2ts_co2 · time: month · value: co2
  • Stl ukgas windowml_ukgas · time: quarter · value: gas
  • Classical multiplicativeml_airpassengers · time: month · value: passengers
  • Mstl hourlyts_hourly · time: hour · value: load
  • Degenerate constantts_co2 · time: month · value: co2
  • Degenerate n3ts_co2 · time: month · value: co2

In the guides

Where it sits in the decision guides

  • Time series (ARIMA, ETS) · DS & ML Decision Guide · Predict — forecast or classify outcomes

What you need

Seriesnumeric · 1 column
The time series to split into trend, seasonal and remainder parts.
Timetemporal / numeric · 0–1 column
Orders the rows; dates also suggest the season length.

Choices you make

hypothesis

Methoddefault stl

STL is robust and flexible; MSTL handles several seasonal periods; classical uses moving averages.

  • STL (loess)(default) — Robust to changing seasonality when the seasonal window is finite.
  • MSTL (several seasonal periods) — STL applied to each period in turn (shortest first), refined twice.
  • Classical moving average — Centered moving-average trend and an average seasonal figure (R's decompose).
Season lengthdefault —

Observations per cycle: 12 monthly, 4 quarterly, 7 daily, 24 hourly …

Seasonal periodsdefault 24,168

Every cycle length to remove, e.g. 24 and 168 for hourly data.

options

Seasonal windowdefault —

Odd number of cycles the seasonal loess spans; smaller lets the pattern evolve faster.

Seasonalitydefault additive

Additive seasonality has constant size; multiplicative grows with the level of the series.

  • Additive (constant amplitude)(default) — Seasonal swings stay the same size; pick it when amplitude doesn't change with the level.
  • Multiplicative (amplitude grows with the level) — Seasonal swings grow with the level; pick it for positive series whose amplitude scales up.

What it reports

n_obs
How many independent units the analysis used; it sets precision and power.
period
A pattern that repeats at a fixed period — daily, weekly, yearly.
seasonal_strength
The share of variation (after trend) that a repeating seasonal pattern explains, from 0 (none) to 1 (all) — and likewise for the trend.
trend_strength
The share of variation (after trend) that a repeating seasonal pattern explains, from 0 (none) to 1 (all) — and likewise for the trend.
remainder_sd
Splits a series into trend, seasonal and remainder by repeated local (loess) smoothing; MSTL handles several cycle lengths.

Per group, level or term: method, seasonal_range, seasonal_strength_<period>

Python and R

Python and R agree to 6 decimals (relative tolerance 1e-8). Python uses pandas, numpy, statsmodels, codesplash; R uses stats, nanoparquet, codesplashr.

Default traps between the two languages

  • STL: statsmodels' port of the Fortran with R's stl() defaults (seasonal degree 0, windows and jumps as stl computes them, inner 2 / outer 0); agrees with R to about 1e-13. Robust STL is not offered (the two ports' robustness weights differ near 1e-5).
  • MSTL is the same loop in both engines (seasonal windows 7 + 4i, two iterations), not forecast::mstl.
Python

The exact script CodeSplash ran for example “Stl co2” · 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,
})
R

The exact script CodeSplash ran for example “Stl co2” · 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
))

Sources

  • Cleveland, R. B., Cleveland, W. S., McRae, J. E., & Terpenning, I. (1990). STL: A seasonal-trend decomposition procedure based on loess. J. Official Statistics, 6, 3–73.
  • Bandara, K., Hyndman, R. J., & Bergmeir, C. (2021). MSTL: A seasonal-trend decomposition algorithm for time series with multiple seasonal patterns. arXiv:2107.13462.
  • Wang, X., Smith, K., & Hyndman, R. (2006). Characteristic-based clustering for time series data. Data Mining and Knowledge Discovery, 13, 335–364.

From the CodeSplash method registry · ts.decompose v1.0.1.