Algorithmcore
STL decomposition
Also called seasonal-trend decomposition using LOESS.
Cleveland's decomposition of a series into trend, seasonal and remainder parts by alternating LOESS smoothers in an inner and a robust outer loop.
- Time
- Θ(k (r + 1) n (s + u + l) + r n log n) worst · best
- Space
- Θ(n) extra
- Where
- k = the number of inner passes n_i; l = the low-pass span n_l; m = the seasonal period; n = the length of the series; r = the number of robustness passes n_o; s = the seasonal span n_s, counted up to the number of cycles; u = the trend span n_t
- Model
- Real RAM
- Properties
- deterministicexactofflineiterative
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Robert B. Cleveland, William S. Cleveland, Jean E. McRae, Irma Terpenning, 1990
STL splits a time series into three parts, : a smooth trend, a seasonal part that repeats roughly every steps but may change slowly, and a remainder. It does this with nothing but LOESS, a local weighted least squares line fit, applied in a fixed pattern. An inner loop smooths each "cycle-subseries" (all Januaries, all Februaries, and so on) to get the season, takes out the slow part of that season with moving averages, then smooths the deseasonalized series to get the trend. An optional outer loop gives small weights to points with large remainders and repeats, which makes the result robust to outliers. STL handles any period, lets the season change over the years at a rate the user picks, and is the default decomposition in many statistics packages.
In plain words
Monthly sales rise over the years and also swing with the month of the year. To separate the two, look at all the Januaries together and draw a smooth curve through them, then do the same for every other month. Put these curves back in time order: that is a first guess at the seasonal pattern, but it may also contain some of the slow growth, so smooth it heavily and subtract that slow part. Take the season away from the data and draw a smooth curve through what is left: that is the trend. Repeat this a couple of times. What is left after taking away both trend and season is the remainder. If a few points are wild, give them less say and do it again.
The problem
Given and an integer period with , find a trend , a seasonal component and a remainder with
where varies slowly, is close to periodic with period and changes slowly from cycle to cycle, and is what neither explains. "Slowly" is set by three odd spans: for LOESS along each cycle-subseries (how fast the season may change), for the trend, and for the low-pass filter. The decomposition is not unique, so STL is defined by its procedure, not by an objective function.
LOESS. For data at positions , span and a position (which may lie outside ), let be the distance from to the farthest of the positions nearest ; if , use all positions and multiply the distance by . The weight of position is the tricube for and 0 otherwise, at , times a robustness weight . The LOESS value at is the value at of the weighted least squares line through these points (Cleveland 1979). This is local polynomial regression of degree 1 with a nearest-neighbor bandwidth.
The algorithm
STL(Y₁..Y_n, m, n_s, n_t, n_l, n_i, n_o)- 1
T ← 0; ρ ← 1 for pass ← 0 to n_o- 2
repeat n_i times - 3
D ← Y − T ▷ detrend - 4
for each cycle-subseries j = 1..m: C_j ← LOESS(D_j, n_s, ρ_j) at positions 0..len(D_j)+1 ▷ C, in time order, covers times 1−m .. n+m- 5
L ← LOESS(MA₃(MA_m(MA_m(C))), n_l) ▷ low-pass, length n - 6
S ← C_{1..n} − L - 7
H ← Y − S ▷ deseasonalize - 8
T ← LOESS(H, n_t, ρ) - 9
R ← Y − S − T - 10
if pass < n_o: h ← 6 median|R_t|; ρ_t ← B(|R_t|/h), with B(u) = (1 − u²)² for u < 1, else 0 - 11
return (S, T, R, ρ)
The cycle-subseries holds the values at times . Line L4 evaluates its LOESS fit one step beyond each end, so the series has values. The three moving averages of line L5 have lengths , and 3 and shorten it by , back to ; they remove the seasonal pattern, and line L5's LOESS smooths what remains. Line L6 subtracts that slow part from , so the trend is not counted twice. Lines L3 to L8 form the inner loop. Lines L9 and L10 form the outer loop, which reweights points by the bisquare of their remainder, as in Cleveland (1979).
Cleveland et al. (1990) give defaults: is the smallest odd integer , and is the smallest odd integer . They recommend and odd, chosen by looking at the seasonal-diagnostic plots. R's stl uses , without robustness and , with it. A very large (R's "periodic") makes every cycle-subseries nearly constant, so the season repeats exactly.
Example
By hand. Take the quarterly series , , . The default rules give and $n_t = $ the smallest odd integer , which is 9. Use and no robustness passes.
In the first pass , so the first cycle-subseries is at positions 1, 2, 3. Since , all three points are used and the bandwidth is stretched by . At position 2 the outer points get the weight and the fitted line gives 12.156. The fits at positions 0 to 4 are . Doing the same for the other quarters gives on times . The low-pass filter of line L5 gives , close to a line rising 0.845 per quarter, which is the growth that the subseries fits had picked up. Then starts , and the trend LOESS of gives .
The second pass starts from this trend. The final components, to three decimals, are:
| 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
| 12 | 8 | 14 | 10 | 16 | 11 | 17 | 14 | 19 | 14 | 21 | 17 | |
| 2.437 | 2.389 | 2.565 | 2.482 | 2.631 | 2.660 | |||||||
| 9.683 | 10.564 | 11.438 | 12.308 | 13.164 | 14.003 | 14.836 | 15.658 | 16.504 | 17.336 | 18.166 | 18.996 | |
| 0.027 | 0.173 | 0.271 | 0.308 | 0.020 | 0.174 |
Each column adds up to exactly. The season is not forced to sum to 0 over a year: the first four values sum to 0.078. The second quarter's seasonal value drifts from to , because the fit lets the season change. All values are rational, and the tests compute them in exact fractions.
Exact recovery. For with repeating, STL with any odd returns , and exactly, with or without robustness passes. The correctness page proves this.
Outliers. With seed 2026, simulate 120 months of a trend , a fixed season and standard Gaussian noise, with (, ). The root mean square errors against the true components are 0.489 for the season and 0.453 for the trend. Add 25 to the points at . Without robustness (, ), the errors grow to 1.557 and 1.291, and the outliers' remainders are only 17 to 20, because part of each outlier has leaked into and . With and , the errors are 0.506 and 0.654, the three points get weight 0, and their remainders are about 25. These numbers are measured on one sample.
Correctness
STL is defined by its steps, so "correct" here means three provable facts, shown on the correctness page. The components add up to exactly, by line L9. Without robustness passes, the map from to is linear. The procedure reproduces its target model exactly: if is a line plus a periodic season that sums to 0 over a period, then is that season, is that line and , for any spans, any number of passes, and from any linear starting trend. The proof uses two lemmas: LOESS of degree 1 reproduces a line at every position, including the extrapolated end points, and the three moving averages map a line plus a zero-sum season to the line, shifted to the right times. The robustness weights lie in and vanish for remainders above times the median absolute remainder. Statistical properties, such as the bias and variance of each component or the frequency response of the filters in Cleveland et al. (1990), are not proved here.
Proof: STL's components add up, the map is linear without robustness, and a line plus a zero-sum periodic season is decomposed exactlyfull
STL is defined by its steps, so we prove the properties that pin down what it computes. Lemma 1: LOESS of degree 1 reproduces a line at every position, inside or outside the data. Lemma 2: the moving averages of line L5 map a line plus a zero-sum season to the line, at the right times. Theorem 3: a line plus a zero-sum periodic season is split exactly. Proposition 4: the components add up, the map is linear without robustness passes, and the robust map is scale equivariant. Lemma 5: the robustness weights. We do not prove any statistical property, such as the bias, the variance or the frequency response of the filters (Cleveland et al. 1990, Section 5 onward, study these by computation). Throughout, spans are odd integers and .
Lemma 1 (LOESS reproduces lines). Let for , let be any real number, let , and let the robustness weights be positive. Then the LOESS value at is .
Proof. Let be the set of window positions with positive weight . If has two or more points, the weighted least squares line through , , is unique because the positions are distinct, so . The line fits these points with zero residuals, so it is the minimizer, and its value at is . In the code, and , so .
Now suppose has one point. With positive robustness weights, position has positive weight exactly when . If , then , so all points are in . Otherwise the window is the consecutive positions nearest , and is the distance to the farther end. Every position strictly between the two ends is closer than that end, so at least interior positions are in , and so is the nearer end unless both ends are at distance . So has one point only when and is the middle position, and then the code returns .
A constant is a line with , so a LOESS of a constant sequence returns the constant at every position. The fit is a weighted average of the with weights that depend only on the positions, and the robustness weights, so for fixed robustness weights it is linear in .
Lemma 2 (the low-pass filter). Let for , where and . Then has terms, and its -th term is .
Proof. A moving average of length maps a sequence of length to one of length , so the lengths are . The mean of a line over consecutive times is the line at the mean time, which is the first time plus . The mean of over consecutive times is , because any consecutive times hit each residue class once. So the first average is the line, with its first term at time , and has no seasonal part left. The next two averages keep a line a line. The first term of the result sits at time , and the terms are at consecutive times, so the -th term is .
Theorem 3 (exact recovery). Let for , with periodic of period and summing to 0 over a period, and . Then for any spans, any and any , STL returns , and .
Proof. We show that one inner pass (lines L3 to L8) started from any linear trend (including of line L1), with all robustness weights equal to 1, returns and . Line L3 gives . On the cycle-subseries , the -th value () is at time , so it equals , a line in . By Lemma 1, line L4 returns the same line at , so for all (each time in this range is in exactly one subseries at exactly one of these positions). By Lemma 2 the moving averages give the line on , and by Lemma 1 the LOESS of line L5 leaves it unchanged. Line L6 gives . Line L7 gives , and by Lemma 1 line L8 gives .
By induction over the inner passes, every pass starts from a linear trend and ends with and . Line L9 then gives . If , line L10 sees ; then and the implementation sets every weight to 1, so the next outer pass repeats the same computation.
Proposition 4 (additivity, linearity, equivariance). (a) for all . (b) With , the map is linear. (c) For any and any , STL applied to returns and the same weights.
Proof. (a) is line L9. (b) Every line of the inner loop is a subtraction, a LOESS with weights that depend only on positions (Lemma 1, last remark), a moving average, or a restriction to times ; each is linear, and so is their composition, starting from the linear . Line L9 is linear. (c) By induction over the steps: if every input to a step is multiplied by and the robustness weights are the same, every LOESS, moving average and difference is multiplied by . So is multiplied by , the median of by , and , so line L10 gives the same weights.
Lemma 5 (robustness weights). The weights of line L10 satisfy , exactly when (if ), decreases in , and exactly when .
Proof. For , , with , and is strictly decreasing there because is decreasing and positive. For , . Apply this with .
So a point whose remainder is at least six times the typical size has no influence on the next pass, and the outer loop is an iteratively reweighted fit in the sense of Cleveland (1979). Whether the weights converge is not proved; the method runs a fixed number of passes.
Exact arithmetic. Every step uses additions, multiplications, divisions, comparisons and a median, and the tricube and bisquare functions are polynomials. With rational data the outputs are rational, and the implementation computes them exactly when given Fractions. The tests check Lemma 1 against a direct rational computation at positions , Lemma 2, Theorem 3 for two spans with and without robustness passes, Proposition 4(a), and Lemma 5.
Termination. The outer loop runs times and the inner loop times per outer pass. Each inner pass computes a fixed number of LOESS values, each from at most points, and three moving averages, and line L10 sorts numbers. So STL stops after finitely many operations, as counted on the main page.
Complexity
On a real RAM, the LOESS value at one position costs for span . Line L4 fits subseries of about points each, so it costs when is at most the subseries length. Line L5 costs for the moving averages with running sums (the reference implementation sums each window again, , which is no more than the of the LOESS), and line L8 costs . One inner pass is , and line L10 needs a median, by sorting or by selection. With the default spans, and are about and , so a pass costs . The extra space is . Cleveland's Fortran code evaluates each LOESS only at every -th position and interpolates linearly in between (the "jump" parameters), which divides the time by about .
Numerical stability. Each LOESS fit is a weighted least squares line on at most consecutive positions. Centering the positions at their weighted mean, as the code does, keeps the normal equations well conditioned. If only one point has positive weight, which happens for at an interior position, the fit is that point's value. Robustness weights can make all weights in a window 0; the implementation then keeps the nearest observation, while other codes leave the value missing.
Properties
- Additive by construction. exactly at every .
- Linear without robustness. With , each step is a linear filter, so , and are fixed linear functions of . The robust version is not linear, but it is scale equivariant: multiplying by multiplies every component by and leaves the weights unchanged.
- Exact on its model. A line plus a zero-sum periodic season is split exactly.
- Changing seasons. The span controls how fast the seasonal pattern may evolve. A large gives a nearly fixed season; a small one lets it follow the data.
- Robust option. Bisquare weights from the remainder downweight outliers and level shifts in single points, so they stay in .
- Local. Each output depends only on data within the spans, so a change in affects the components only near (and, through the subseries fits, at the same season in nearby years).
- Season does not sum exactly to 0. The low-pass step removes the slow part from , but the seasonal values in one period sum to 0 only approximately.
Variants and improvements
- Periodic season. Set very large, or replace line L4 by the subseries mean, to force an identical season every year.
- Degree. Cleveland et al. allow local constants or lines in each of the three LOESS steps. Local quadratics for the trend follow peaks better.
- Jumps. Evaluate each LOESS at every -th position and interpolate, for long series.
- Multiplicative seasons. Apply STL to when the seasonal swing grows with the level.
- Several periods. MSTL (Bandara, Hyndman and Bergmeir 2021) applies STL repeatedly, one period at a time, for hourly or daily data with daily, weekly and yearly cycles.
- Forecasting. Forecast the seasonally adjusted series with any method (for example Holt's method or an ARIMA model) and add back the last year's season.
- Robust regression. The outer loop is an iteratively reweighted fit with bisquare weights, the same idea as IRLS for M-estimators.
When to use it
Use STL to look at a seasonal series: to see the trend without the season, to see whether the season changes over the years, and to find outliers in the remainder. It suits any integer period, monthly, weekly or other, and long series. Use the robust version whenever outliers are possible. Use it as a first step before forecasting the seasonally adjusted series. For official seasonal adjustment with trading-day and holiday effects, use X-13ARIMA-SEATS. For forecasting a short series with a stable season, a seasonal ARIMA model or the Holt-Winters method is simpler.
Pitfalls
- Choosing . A small lets the season soak up noise, and a large one forces a fixed season onto a changing pattern. Look at the cycle-subseries plots before choosing it.
- Non-integer or several periods. STL needs one integer period. Weekly data with a 52.18-week year, or hourly data with daily and weekly cycles, need special handling.
- Multiplicative seasons. STL is additive. A season that grows with the level shows up as structure in ; take logs first.
- End effects. At the ends of the series the fits extrapolate, so the last values of and change when new data arrive.
- Remainder is not white noise. is what is left, not an estimate of an independent error; it is usually autocorrelated, and tests that assume independence do not apply to it directly.
- Not unique. Different spans give different, equally valid decompositions. Report the spans used.
- Zero median remainder. If more than half of the remainders are 0, the scale of line L10 is 0. The implementation then gives weight 1 to zero remainders and 0 to the rest; other codes add a small constant.
Implementations
Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/stl-decomposition/. The authors are listed in prov/GHRJ1G.jsonl.
"""STL: seasonal-trend decomposition by LOESS (Cleveland, Cleveland, McRae and
Terpenning 1990).
Y_t = T_t + S_t + R_t. The inner loop alternates a seasonal smoother (LOESS on
each cycle-subseries, then removal of its low-frequency part) and a trend
smoother (LOESS on the deseasonalized series). The outer loop computes
bisquare robustness weights from the remainder and repeats the inner loop
with them. All arithmetic is generic: Fraction input gives Fraction output.
"""
def tricube(u):
return (1 - u * u * u) ** 3 if u < 1 else 0 * u
def bisquare(u):
return (1 - u * u) ** 2 if u < 1 else 0 * u
def loess_at(y, x, q, degree=1, rob=None):
"""LOESS fit at position x (a number, maybe outside 1..n) of y at positions 1..n.
Uses the q nearest positions (all n if q > n, with the bandwidth stretched
by q/n), tricube weights times the robustness weights rob, and a weighted
least squares fit of a line (degree 1) or a constant (degree 0)."""
n = len(y)
one = y[0] * 0 + 1
if q >= n:
lo, hi = 1, n
else:
lo = min(max(1, int(x) - (q - 1) // 2), n - q + 1)
if x < 1:
lo = 1
# slide the window so that it holds the q positions nearest to x
while lo + q <= n and abs(lo + q - x) < abs(x - lo):
lo += 1
while lo > 1 and abs(x - (lo - 1)) < abs(lo + q - 1 - x):
lo -= 1
hi = lo + q - 1
lam = max(abs(x - lo), abs(hi - x)) * one
if q > n:
lam = lam * q / n
w = []
for i in range(lo, hi + 1):
wi = tricube(abs(i - x) * one / lam) if lam > 0 else one
if rob is not None:
wi = wi * rob[i - 1]
w.append(wi)
sw = sum(w)
if sw <= 0:
return None
idx = list(range(lo, hi + 1))
xbar = sum(wi * i for wi, i in zip(w, idx)) / sw
ybar = sum(wi * y[i - 1] for wi, i in zip(w, idx)) / sw
if degree == 0:
return ybar
sxx = sum(wi * (i - xbar) ** 2 for wi, i in zip(w, idx))
if sxx <= 0:
return ybar
sxy = sum(wi * (i - xbar) * y[i - 1] for wi, i in zip(w, idx))
return ybar + sxy / sxx * (x - xbar)
def loess(y, q, degree=1, rob=None, extend=False):
"""LOESS at positions 1..n, or 0..n+1 when extend is True."""
n = len(y)
xs = range(0, n + 2) if extend else range(1, n + 1)
out = []
for x in xs:
v = loess_at(y, x, q, degree, rob)
if v is None: # all weights zero: keep the nearest observation
v = y[min(max(x, 1), n) - 1]
out.append(v)
return out
def moving_average(y, k):
"""Means of each run of k consecutive values; length len(y) - k + 1."""
return [sum(y[i:i + k]) / k for i in range(len(y) - k + 1)]
def next_odd(v):
"""The smallest odd integer >= v."""
k = int(v)
if k < v:
k += 1
return k if k % 2 == 1 else k + 1
def default_spans(period, seasonal):
"""Cleveland's defaults: n_l = next odd >= period; n_t = next odd >= 1.5 period / (1 - 1.5 / n_s)."""
return next_odd(period), next_odd(1.5 * period / (1.0 - 1.5 / seasonal))
def inner_loop(y, period, n_s, n_l, n_t, trend, rob, degrees=(1, 1, 1)):
"""One pass of the inner loop. Returns (seasonal, trend)."""
n = len(y)
detr = [a - b for a, b in zip(y, trend)] # @line L3
c = [None] * (n + 2 * period)
for j in range(period): # cycle-subseries smoothing
pos = list(range(j, n, period))
sub = [detr[t] for t in pos]
rsub = [rob[t] for t in pos] if rob is not None else None
sm = loess(sub, n_s, degrees[0], rsub, extend=True) # @line L4
for k, v in enumerate(sm): # k = 0 is one period before pos[0]
c[j + k * period] = v
low = moving_average(moving_average(moving_average(c, period), period), 3) # @line L5
low = loess(low, n_l, degrees[1])
seasonal = [c[t + period] - low[t] for t in range(n)] # @line L6
deseason = [a - b for a, b in zip(y, seasonal)] # @line L7
trend = loess(deseason, n_t, degrees[2], rob) # @line L8
return seasonal, trend
def robustness_weights(resid):
"""Bisquare weights B(|R_t| / h) with h = 6 median |R_t|."""
a = sorted(abs(r) for r in resid)
n = len(a)
med = a[n // 2] if n % 2 else (a[n // 2 - 1] + a[n // 2]) / 2
h = 6 * med
if h == 0:
return [1 if r == 0 else 0 for r in resid]
return [bisquare(abs(r) / h) for r in resid]
def stl(y, period, seasonal=7, trend=None, low_pass=None, inner=None, outer=0, degrees=(1, 1, 1)):
"""Decompose y into (seasonal, trend, remainder, weights).
seasonal is the cycle-subseries span n_s (odd, >= 7 recommended). trend and
low_pass default to Cleveland's rules. inner defaults to 2 without and 1
with robustness iterations; outer is the number of robustness passes."""
n = len(y)
if period < 2 or n < 2 * period:
raise ValueError("need a period >= 2 and at least two full periods")
if seasonal < 3 or seasonal % 2 == 0:
raise ValueError("the seasonal span must be odd and at least 3")
d_l, d_t = default_spans(period, seasonal)
n_l = low_pass or d_l
n_t = trend or d_t
if inner is None:
inner = 1 if outer > 0 else 2
zero = y[0] * 0
tr = [zero] * n # @line L1
rob = None
for o in range(outer + 1):
for _ in range(inner): # @line L2
seas, tr = inner_loop(y, period, seasonal, n_l, n_t, tr, rob, degrees)
resid = [a - b - c for a, b, c in zip(y, seas, tr)] # @line L9
if o < outer:
rob = robustness_weights(resid) # @line L10
weights = rob if rob is not None else [zero + 1] * n
return {"seasonal": seas, "trend": tr, "remainder": resid, "weights": weights, # @line L11
"spans": {"seasonal": seasonal, "trend": n_t, "low_pass": n_l}}
test_stl_decomposition.py 119 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/stl-decomposition/. The authors are listed in prov/GHRJ1G.jsonl.
import math
import random
from fractions import Fraction
import pytest
from stl_decomposition import default_spans, loess, loess_at, moving_average, robustness_weights, stl
QUARTERLY = [12, 8, 14, 10, 16, 11, 17, 14, 19, 14, 21, 17]
def brute_loess(y, x, q, degree):
"""Direct definition in rationals: the q nearest positions, tricube weights, weighted least squares."""
n = len(y)
pos = sorted(range(1, n + 1), key=lambda i: (abs(i - x), i))[:min(q, n)]
lam = Fraction(max(abs(i - x) for i in pos))
if q > n:
lam = lam * q / n
w = {i: (1 - (Fraction(abs(i - x)) / lam) ** 3) ** 3 if abs(i - x) < lam else Fraction(0) for i in pos}
sw = sum(w.values())
xb = sum(w[i] * i for i in pos) / sw
yb = sum(w[i] * y[i - 1] for i in pos) / sw
if degree == 0:
return yb
sxx = sum(w[i] * (i - xb) ** 2 for i in pos)
if sxx == 0: # only one point has positive weight (q = 3 at an interior x): a local constant
return yb
sxy = sum(w[i] * (i - xb) * y[i - 1] for i in pos)
return yb + sxy / sxx * (x - xb)
@pytest.mark.parametrize("q", [3, 5, 7, 15])
@pytest.mark.parametrize("degree", [0, 1])
def test_loess_matches_definition(q, degree) -> None:
rng = random.Random(q * 10 + degree)
y = [Fraction(rng.randint(-10, 10)) for _ in range(11)]
for x in range(0, 13): # includes the extrapolated positions 0 and n + 1
assert loess_at(y, x, q, degree) == brute_loess(y, x, q, degree)
def test_loess_reproduces_lines() -> None:
y = [Fraction(3) - Fraction(2, 7) * i for i in range(1, 10)]
for q in (3, 5, 9, 13):
out = loess(y, q, 1, extend=True)
assert out == [Fraction(3) - Fraction(2, 7) * x for x in range(0, 11)]
assert loess([Fraction(4)] * 6, 3, 0) == [4] * 6
def test_low_pass_of_line_plus_season() -> None:
# Moving averages of lengths m, m and 3, then LOESS, map a line plus a zero-sum
# season on times 1-m..N+m to the line on times 1..N exactly.
m, big_n = 4, 12
s = [Fraction(3), Fraction(-1), Fraction(-4), Fraction(2)]
c = [Fraction(5) + Fraction(1, 2) * t + s[t % m] for t in range(1 - m, big_n + m + 1)]
low = moving_average(moving_average(moving_average(c, m), m), 3)
assert len(low) == big_n
assert loess(low, 5, 1) == [Fraction(5) + Fraction(1, 2) * t for t in range(1, big_n + 1)]
@pytest.mark.parametrize("outer", [0, 2])
@pytest.mark.parametrize("n_s", [7, 11])
def test_exact_recovery_of_line_plus_season(outer, n_s) -> None:
s = [Fraction(3), Fraction(-1), Fraction(-4), Fraction(2)]
y = [Fraction(5) + Fraction(1, 2) * t + s[(t - 1) % 4] for t in range(1, 21)]
r = stl(y, 4, n_s, outer=outer)
assert r["seasonal"] == [s[i % 4] for i in range(20)]
assert r["trend"] == [Fraction(5) + Fraction(1, 2) * t for t in range(1, 21)]
assert all(v == 0 for v in r["remainder"])
def test_components_add_up_and_worked_example() -> None:
y = [Fraction(v) for v in QUARTERLY]
r = stl(y, 4, 7)
assert r["spans"] == {"seasonal": 7, "trend": 9, "low_pass": 5}
assert all(a + b + c == v for a, b, c, v in zip(r["seasonal"], r["trend"], r["remainder"], y))
want_s = [2.437, -2.591, 2.389, -2.156, 2.565, -2.979, 2.482, -1.966, 2.631, -3.356, 2.660, -1.852]
want_t = [9.683, 10.564, 11.438, 12.308, 13.164, 14.003, 14.836, 15.658, 16.504, 17.336, 18.166, 18.996]
assert all(abs(float(a) - b) < 5e-4 for a, b in zip(r["seasonal"], want_s))
assert all(abs(float(a) - b) < 5e-4 for a, b in zip(r["trend"], want_t))
def test_default_spans() -> None:
assert default_spans(12, 13) == (13, 21) # 1.5 * 12 / (1 - 1.5 / 13) = 20.35
assert default_spans(4, 7) == (5, 9) # 7.64
assert default_spans(7, 7) == (7, 15) # 13.36
def test_robustness_weights() -> None:
w = robustness_weights([Fraction(v) for v in (1, -1, 2, -2, 0, 30)])
# median |R| = 1.5, h = 9: B(1/9) = (1 - 1/81)^2, B(30/9) = 0
assert w[0] == (1 - Fraction(1, 81)) ** 2 and w[5] == 0 and w[4] == 1
def test_robust_iterations_isolate_outliers() -> None:
rng = random.Random(2026)
m, n = 12, 120
season = [8 * math.sin(2 * math.pi * i / m) + 3 * math.cos(4 * math.pi * i / m) for i in range(m)]
trend = [50 + 0.2 * t + 5 * math.sin(2 * math.pi * t / 60) for t in range(n)]
y = [trend[t] + season[t % m] + rng.gauss(0, 1) for t in range(n)]
for t in (30, 31, 75):
y[t] += 25
def rmse_s(r):
return math.sqrt(sum((r["seasonal"][t] - season[t % m]) ** 2 for t in range(n)) / n)
plain, robust = stl(y, m, 13), stl(y, m, 13, outer=15)
assert all(robust["weights"][t] == 0 for t in (30, 31, 75))
assert all(robust["remainder"][t] > 20 for t in (30, 31, 75))
assert rmse_s(robust) < 0.7 < 1.2 < rmse_s(plain)
def test_bad_input() -> None:
with pytest.raises(ValueError):
stl([1.0] * 10, 12, 7)
with pytest.raises(ValueError):
stl([1.0] * 30, 4, 8)
History
Seasonal adjustment by moving averages goes back to the 1920s. The U.S. Census Bureau's X-11 program of the 1960s combined many fixed moving averages with rules for outliers. Cleveland (1979) introduced robust locally weighted regression (LOWESS), with tricube weights and bisquare robustness iterations. Robert B. Cleveland, William S. Cleveland, Jean E. McRae and Irma Terpenning (1990) built STL from it, aiming at a method that was simple, fast, robust, able to handle any period and missing values, and easy to explain. STL was added to S and then R, and later to Python's statsmodels. Bandara, Hyndman and Bergmeir (2021) extended it to several seasonal periods as MSTL.
References
- Robert B. Cleveland, William S. Cleveland, Jean E. McRae and Irma Terpenning, STL, a seasonal-trend decomposition procedure based on loess, Journal of Official Statistics 6(1) (1990), pages 3 to 73, the inner and outer loops, the low-pass filter, the default spans and the robustness weights
- William S. Cleveland, Robust locally weighted regression and smoothing scatterplots, Journal of the American Statistical Association 74(368) (1979), pages 829 to 836, the tricube weights, the local line fit and the bisquare robustness iterations
- William S. Cleveland and Susan J. Devlin, Locally weighted regression, an approach to regression analysis by local fitting, Journal of the American Statistical Association 83(403) (1988), pages 596 to 610, LOESS with local lines and quadratics, its operator form and its degrees of freedom
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag GHRJ1G Edit this page History Report an error Markdown