Algorithm Search⌘K

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
Properties
deterministicexactofflineiterative
Origin
Robert B. Cleveland, William S. Cleveland, Jean E. McRae, Irma Terpenning, 1990

STL splits a time series YtY_t into three parts, Yt=Tt+St+RtY_t = T_t + S_t + R_t: a smooth trend, a seasonal part that repeats roughly every mm 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 Y1,…,YnY_1, \dots, Y_n and an integer period m≥2m \ge 2 with n≥2mn \ge 2m, find a trend TT, a seasonal component SS and a remainder RR with

Yt=Tt+St+Rt,t=1..n,Y_t = T_t + S_t + R_t, \qquad t = 1..n,

where TT varies slowly, SS is close to periodic with period mm and changes slowly from cycle to cycle, and RR is what neither explains. "Slowly" is set by three odd spans: nsn_s for LOESS along each cycle-subseries (how fast the season may change), ntn_t for the trend, and nln_l 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 y1,…,yNy_1, \dots, y_N at positions 1..N1..N, span qq and a position xx (which may lie outside 1..N1..N), let λq(x)\lambda_q(x) be the distance from xx to the farthest of the qq positions nearest xx; if q>Nq > N, use all NN positions and multiply the distance by q/Nq/N. The weight of position ii is the tricube W(u)=(1−u3)3W(u) = (1 - u^3)^3 for 0≤u<10 \le u < 1 and 0 otherwise, at u=∣i−x∣/λq(x)u = |i - x|/\lambda_q(x), times a robustness weight ρi\rho_i. The LOESS value at xx is the value at xx 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

  1. STL(Y₁..Y_n, m, n_s, n_t, n_l, n_i, n_o)
  2. 1T ← 0; ρ ← 1
  3. for pass ← 0 to n_o
  4. 2repeat n_i times
  5. 3D ← Y − T ▷ detrend
  6. 4for each cycle-subseries j = 1..m: C_j ← LOESS(D_j, n_s, ρ_j) at positions 0..len(D_j)+1
  7. ▷ C, in time order, covers times 1−m .. n+m
  8. 5L ← LOESS(MA₃(MA_m(MA_m(C))), n_l) ▷ low-pass, length n
  9. 6S ← C_{1..n} − L
  10. 7H ← Y − S ▷ deseasonalize
  11. 8T ← LOESS(H, n_t, ρ)
  12. 9R ← Y − S − T
  13. 10if pass < n_o: h ← 6 median|R_t|; ρ_t ← B(|R_t|/h), with B(u) = (1 − u²)² for u < 1, else 0
  14. 11return (S, T, R, ρ)

The cycle-subseries DjD_j holds the values at times j,j+m,j+2m,…j, j + m, j + 2m, \dots. Line L4 evaluates its LOESS fit one step beyond each end, so the series CC has n+2mn + 2m values. The three moving averages of line L5 have lengths mm, mm and 3 and shorten it by 2m2m, back to nn; they remove the seasonal pattern, and line L5's LOESS smooths what remains. Line L6 subtracts that slow part from CC, 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 BB of their remainder, as in Cleveland (1979).

Cleveland et al. (1990) give defaults: nln_l is the smallest odd integer ≥m\ge m, and ntn_t is the smallest odd integer ≥1.5m/(1−1.5/ns)\ge 1.5m/(1 - 1.5/n_s). They recommend ns≥7n_s \ge 7 and odd, chosen by looking at the seasonal-diagnostic plots. R's stl uses ni=2n_i = 2, no=0n_o = 0 without robustness and ni=1n_i = 1, no=15n_o = 15 with it. A very large nsn_s (R's "periodic") makes every cycle-subseries nearly constant, so the season repeats exactly.

Example

By hand. Take the quarterly series Y=(12,8,14,10,16,11,17,14,19,14,21,17)Y = (12, 8, 14, 10, 16, 11, 17, 14, 19, 14, 21, 17), m=4m = 4, ns=7n_s = 7. The default rules give nl=5n_l = 5 and $n_t = $ the smallest odd integer ≥6/(1−1.5/7)=7.64\ge 6/(1 - 1.5/7) = 7.64, which is 9. Use ni=2n_i = 2 and no robustness passes.

In the first pass T=0T = 0, so the first cycle-subseries is (12,16,19)(12, 16, 19) at positions 1, 2, 3. Since ns=7>3n_s = 7 > 3, all three points are used and the bandwidth is stretched by 7/37/3. At position 2 the outer points get the weight W(3/7)=(316/343)3=0.782W(3/7) = (316/343)^3 = 0.782 and the fitted line gives 12.156. The fits at positions 0 to 4 are 8.633,12.156,15.695,19.156,22.6338.633, 12.156, 15.695, 19.156, 22.633. Doing the same for the other quarters gives CC on times −3..16-3..16. The low-pass filter of line L5 gives L=(9.757,10.603,11.448,…,19.036)L = (9.757, 10.603, 11.448, \dots, 19.036), close to a line rising 0.845 per quarter, which is the growth that the subseries fits had picked up. Then S=C−LS = C - L starts (2.400,−2.603,2.395,−2.137,… )(2.400, -2.603, 2.395, -2.137, \dots), and the trend LOESS of Y−SY - S gives T=(9.703,10.577,…,19.012)T = (9.703, 10.577, \dots, 19.012).

The second pass starts from this trend. The final components, to three decimals, are:

tt 1 2 3 4 5 6 7 8 9 10 11 12
YtY_t 12 8 14 10 16 11 17 14 19 14 21 17
StS_t 2.437 −2.591-2.591 2.389 −2.156-2.156 2.565 −2.979-2.979 2.482 −1.966-1.966 2.631 −3.356-3.356 2.660 −1.852-1.852
TtT_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
RtR_t −0.120-0.120 0.027 0.173 −0.152-0.152 0.271 −0.024-0.024 −0.318-0.318 0.308 −0.135-0.135 0.020 0.174 −0.144-0.144

Each column adds up to YtY_t 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 −2.59-2.59 to −3.36-3.36, because the ns=7n_s = 7 fit lets the season change. All values are rational, and the tests compute them in exact fractions.

Exact recovery. For Yt=5+t/2+σtY_t = 5 + t/2 + \sigma_t with σ=(3,−1,−4,2)\sigma = (3, -1, -4, 2) repeating, STL with any odd ns≥3n_s \ge 3 returns St=σtS_t = \sigma_t, Tt=5+t/2T_t = 5 + t/2 and R=0R = 0 exactly, with or without robustness passes. The correctness page proves this.

Outliers. With seed 2026, simulate 120 months of a trend 50+0.2t+5sin⁡(2πt/60)50 + 0.2t + 5\sin(2\pi t/60), a fixed season 8sin⁡(2πt/12)+3cos⁡(4πt/12)8\sin(2\pi t/12) + 3\cos(4\pi t/12) and standard Gaussian noise, with ns=13n_s = 13 (nt=21n_t = 21, nl=13n_l = 13). 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 t=30,31,75t = 30, 31, 75. Without robustness (ni=2n_i = 2, no=0n_o = 0), 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 SS and TT. With ni=1n_i = 1 and no=15n_o = 15, 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 YY exactly, by line L9. Without robustness passes, the map from YY to (S,T,R)(S, T, R) is linear. The procedure reproduces its target model exactly: if YY is a line plus a periodic season that sums to 0 over a period, then SS is that season, TT is that line and R=0R = 0, 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 [0,1][0, 1] and vanish for remainders above 66 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 q≥3q \ge 3 and m≥2m \ge 2.

Lemma 1 (LOESS reproduces lines). Let yi=a+biy_i = a + bi for i=1..Ni = 1..N, let xx be any real number, let q≥3q \ge 3, and let the robustness weights be positive. Then the LOESS value at xx is a+bxa + bx.

Proof. Let PP be the set of window positions with positive weight wiw_i. If PP has two or more points, the weighted least squares line through (i,yi)(i, y_i), i∈Pi \in P, is unique because the positions are distinct, so ∑Pwi(i−xˉ)2>0\sum_P w_i(i - \bar x)^2 > 0. The line a+bia + bi fits these points with zero residuals, so it is the minimizer, and its value at xx is a+bxa + bx. In the code, yˉ=a+bxˉ\bar y = a + b\bar x and Sxy/Sxx=bS_{xy}/S_{xx} = b, so yˉ+(Sxy/Sxx)(x−xˉ)=a+bx\bar y + (S_{xy}/S_{xx})(x - \bar x) = a + bx.

Now suppose PP has one point. With positive robustness weights, position ii has positive weight exactly when ∣i−x∣<λq(x)|i - x| < \lambda_q(x). If q>Nq > N, then λq(x)=(q/N)max⁡i∣i−x∣>max⁡i∣i−x∣\lambda_q(x) = (q/N)\max_i|i - x| > \max_i|i - x|, so all N≥2N \ge 2 points are in PP. Otherwise the window is the q≥3q \ge 3 consecutive positions nearest xx, and λq(x)\lambda_q(x) is the distance to the farther end. Every position strictly between the two ends is closer than that end, so at least q−2≥1q - 2 \ge 1 interior positions are in PP, and so is the nearer end unless both ends are at distance λq(x)\lambda_q(x). So PP has one point only when q=3q = 3 and xx is the middle position, and then the code returns yx=a+bxy_x = a + bx. □\square

A constant is a line with b=0b = 0, so a LOESS of a constant sequence returns the constant at every position. The fit is a weighted average of the yiy_i with weights that depend only on the positions, xx and the robustness weights, so for fixed robustness weights it is linear in yy.

Lemma 2 (the low-pass filter). Let ct=a+bt+σtc_t = a + bt + \sigma_t for t=1−m..n+mt = 1 - m..n + m, where σt+m=σt\sigma_{t + m} = \sigma_t and ∑j=1mσj=0\sum_{j=1}^m\sigma_j = 0. Then MA3(MAm(MAm(c)))\mathrm{MA}_3(\mathrm{MA}_m(\mathrm{MA}_m(c))) has nn terms, and its tt-th term is a+bta + bt.

Proof. A moving average of length kk maps a sequence of length ℓ\ell to one of length ℓ−k+1\ell - k + 1, so the lengths are n+2m→n+m+1→n+2→nn + 2m \to n + m + 1 \to n + 2 \to n. The mean of a line over kk consecutive times is the line at the mean time, which is the first time plus (k−1)/2(k - 1)/2. The mean of σ\sigma over mm consecutive times is 1m∑j=1mσj=0\frac{1}{m}\sum_{j=1}^m\sigma_j = 0, because any mm consecutive times hit each residue class once. So the first average is the line, with its first term at time 1−m+(m−1)/21 - m + (m - 1)/2, and has no seasonal part left. The next two averages keep a line a line. The first term of the result sits at time 1−m+(m−1)/2+(m−1)/2+1=11 - m + (m - 1)/2 + (m - 1)/2 + 1 = 1, and the terms are at consecutive times, so the tt-th term is a+bta + bt. □\square

Theorem 3 (exact recovery). Let Yt=a+bt+σtY_t = a + bt + \sigma_t for t=1..nt = 1..n, with σ\sigma periodic of period mm and summing to 0 over a period, and n≥2mn \ge 2m. Then for any spans, any ni≥1n_i \ge 1 and any no≥0n_o \ge 0, STL returns St=σtS_t = \sigma_t, Tt=a+btT_t = a + bt and Rt=0R_t = 0.

Proof. We show that one inner pass (lines L3 to L8) started from any linear trend Tt=a′+b′tT_t = a' + b't (including T=0T = 0 of line L1), with all robustness weights equal to 1, returns S=σS = \sigma and Tt=a+btT_t = a + bt. Line L3 gives Dt=(a−a′)+(b−b′)t+σtD_t = (a - a') + (b - b')t + \sigma_t. On the cycle-subseries jj, the kk-th value (k=1,2,…k = 1, 2, \dots) is at time t=j+(k−1)mt = j + (k - 1)m, so it equals (a−a′)+(b−b′)(j+(k−1)m)+σj(a - a') + (b - b')(j + (k - 1)m) + \sigma_j, a line in kk. By Lemma 1, line L4 returns the same line at k=0..Nj+1k = 0..N_j + 1, so Ct=(a−a′)+(b−b′)t+σtC_t = (a - a') + (b - b')t + \sigma_t for all t=1−m..n+mt = 1 - m..n + m (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 (a−a′)+(b−b′)t(a - a') + (b - b')t on t=1..nt = 1..n, and by Lemma 1 the LOESS of line L5 leaves it unchanged. Line L6 gives St=Ct−Lt=σtS_t = C_t - L_t = \sigma_t. Line L7 gives Ht=a+btH_t = a + bt, and by Lemma 1 line L8 gives Tt=a+btT_t = a + bt.

By induction over the inner passes, every pass starts from a linear trend and ends with S=σS = \sigma and T=a+btT = a + bt. Line L9 then gives R=0R = 0. If no>0n_o > 0, line L10 sees R=0R = 0; then h=0h = 0 and the implementation sets every weight to 1, so the next outer pass repeats the same computation. □\square

Proposition 4 (additivity, linearity, equivariance). (a) St+Tt+Rt=YtS_t + T_t + R_t = Y_t for all tt. (b) With no=0n_o = 0, the map Y↦(S,T,R)Y \mapsto (S, T, R) is linear. (c) For any non_o and any c≠0c \neq 0, STL applied to cYcY returns (cS,cT,cR)(cS, cT, cR) 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 1..n1..n; each is linear, and so is their composition, starting from the linear T=0T = 0. Line L9 is linear. (c) By induction over the steps: if every input to a step is multiplied by cc and the robustness weights are the same, every LOESS, moving average and difference is multiplied by cc. So RR is multiplied by cc, the median of ∣R∣|R| by ∣c∣|c|, and ∣cRt∣/(6 median∣cR∣)=∣Rt∣/(6 median∣R∣)|cR_t|/(6\,\mathrm{median}|cR|) = |R_t|/(6\,\mathrm{median}|R|), so line L10 gives the same weights. □\square

Lemma 5 (robustness weights). The weights of line L10 satisfy 0≤ρt≤10 \le \rho_t \le 1, ρt=1\rho_t = 1 exactly when Rt=0R_t = 0 (if h>0h > 0), ρt\rho_t decreases in ∣Rt∣|R_t|, and ρt=0\rho_t = 0 exactly when ∣Rt∣≥6 median∣R∣|R_t| \ge 6\,\mathrm{median}|R|.

Proof. For 0≤u<10 \le u < 1, B(u)=(1−u2)2∈(0,1]B(u) = (1 - u^2)^2 \in (0, 1], with B(0)=1B(0) = 1, and BB is strictly decreasing there because 1−u21 - u^2 is decreasing and positive. For u≥1u \ge 1, B(u)=0B(u) = 0. Apply this with u=∣Rt∣/hu = |R_t|/h. □\square

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 0..N+10..N + 1, Lemma 2, Theorem 3 for two spans with and without robustness passes, Proposition 4(a), and Lemma 5.

Termination. The outer loop runs no+1n_o + 1 times and the inner loop nin_i times per outer pass. Each inner pass computes a fixed number of LOESS values, each from at most max⁡(q,N)\max(q, N) points, and three moving averages, and line L10 sorts nn numbers. So STL stops after finitely many operations, Θ(ni(no+1)n(ns+nt+nl)+nonlog⁡n)\Theta(n_i(n_o + 1)n(n_s + n_t + n_l) + n_on\log n) as counted on the main page.

Complexity

On a real RAM, the LOESS value at one position costs Θ(q)\Theta(q) for span qq. Line L4 fits mm subseries of about n/m+2n/m + 2 points each, so it costs Θ(n ns)\Theta(n\,n_s) when nsn_s is at most the subseries length. Line L5 costs Θ(n)\Theta(n) for the moving averages with running sums (the reference implementation sums each window again, Θ(nm)\Theta(nm), which is no more than the Θ(n nl)\Theta(n\,n_l) of the LOESS), and line L8 costs Θ(n nt)\Theta(n\,n_t). One inner pass is Θ(n(ns+nt+nl))\Theta(n(n_s + n_t + n_l)), and line L10 needs a median, Θ(nlog⁡n)\Theta(n \log n) by sorting or Θ(n)\Theta(n) by selection. With the default spans, ntn_t and nln_l are about 1.5m1.5m and mm, so a pass costs Θ(n(ns+m))\Theta(n(n_s + m)). The extra space is Θ(n)\Theta(n). Cleveland's Fortran code evaluates each LOESS only at every jj-th position and interpolates linearly in between (the "jump" parameters), which divides the time by about jj.

Numerical stability. Each LOESS fit is a weighted least squares line on at most qq 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 q=3q = 3 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. S+T+R=YS + T + R = Y exactly at every tt.
  • Linear without robustness. With no=0n_o = 0, each step is a linear filter, so SS, TT and RR are fixed linear functions of YY. The robust version is not linear, but it is scale equivariant: multiplying YY by c≠0c \neq 0 multiplies every component by cc and leaves the weights unchanged.
  • Exact on its model. A line plus a zero-sum periodic season is split exactly.
  • Changing seasons. The span nsn_s controls how fast the seasonal pattern may evolve. A large nsn_s 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 RR.
  • Local. Each output depends only on data within the spans, so a change in YtY_t affects the components only near tt (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 CC, but the seasonal values in one period sum to 0 only approximately.

Variants and improvements

  • Periodic season. Set nsn_s 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 jj-th position and interpolate, for long series.
  • Multiplicative seasons. Apply STL to log⁡Y\log Y 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 Y−SY - S 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 nsn_s. A small nsn_s 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 RR; take logs first.
  • End effects. At the ends of the series the fits extrapolate, so the last values of TT and SS change when new data arrive.
  • Remainder is not white noise. RR 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 hh 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.

stl_decomposition.pyI0RawGitHub
# 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

  1. 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
  2. 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
  3. 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.

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of time.best
  • a full proof of time.worst
  • a full proof of space.extra
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW2 basic
  • a scene preset for the example