Skip to main content
v2026.11,986 entries · CC-BY 4.0

STL Decomposition: Python statsmodels and R stl() Compared

How to run STL decomposition in Python and R, choose the windows, read trend, seasonal and remainder, and map each setting between statsmodels and stl().

Written and maintained by CASRAI Editorial Board

Published

On this page

STL decomposition splits a regularly sampled time series into three additive components (a trend, a repeating seasonal pattern and a remainder) using LOESS smoothing, a method published by Cleveland, Cleveland, McRae and Terpenning in 1990. In Python it is the STL class in statsmodels.tsa.seasonal; in R it is stl() in the base stats package, and the fable package wraps it as STL().

What STL decomposition is used for in research

Researchers reach for STL when a monthly, quarterly or otherwise periodic series (admissions, assay readings, citation counts, sensor output) mixes a slow-moving level with a recurring cycle, and the two need to be examined separately. The decomposition returns a trend, a seasonal component and a remainder, so you can look at the underlying movement without the cycle, check whether the cycle itself is stable, and inspect the remainder for unusual points.

Hyndman and Athanasopoulos, in section 3.6 of Forecasting: Principles and Practice (3rd edition), give the reasons STL is a common choice over the classical decomposition. It handles any type of seasonality (the X-11 and SEATS methods handle only monthly and quarterly data), the seasonal component is allowed to change over time at a rate the analyst controls, the smoothness of the trend-cycle is user-controlled, and a robust option reduces the effect of outliers on the trend and seasonal estimates. Its documented limitations are that it does not handle trading-day or calendar variation automatically and that it provides only additive decompositions.

For modelling rather than description, a decomposition is often a first step before fitting a forecasting model; see the CASRAI guides on ARIMA models for research time series, the exponential smoothing formula and the forecast package in R.

Install or access

Python (statsmodels)

The statsmodels installation page gives two official routes: python -m pip install statsmodels, or conda install -c conda-forge statsmodels. The page lists Python 3.9 as the minimum supported version. The STL class is then imported with from statsmodels.tsa.seasonal import STL.

R (stats and fable)

stl() belongs to the stats package that ships with R, so there is nothing extra to install. The forecasting-textbook workflow uses the fable package (STL() inside model()), which is installed from CRAN like any other R package.

Step-by-step: run STL on a series

Python with statsmodels

  1. Put the data in a pandas Series with a regular date index, so the period can be inferred. The statsmodels documentation states that the period is inferred when the input is a pandas object with a frequency; with a plain NumPy array you must pass period yourself.
  2. Create the model: stl = STL(series, seasonal=13). The statsmodels example notebook decomposes monthly atmospheric CO2 data (1959 to 1987, from the Cleveland et al. paper) with seasonal=13 and notes that the default seasonal=7 should also be changed in most applications.
  3. Fit it: res = stl.fit(). The result is a DecomposeResult.
  4. Plot it: fig = res.plot(), or read the components directly from res.trend, res.seasonal, res.resid and res.weights.
  5. For a series with outliers, set robust=True in the constructor. The documentation describes this as a weighted version of the procedure that is more resistant to some forms of outliers.

R with stats::stl

  1. Convert the data to a univariate ts object with frequency greater than 1 (for example ts(x, frequency = 12, start = c(1959, 1))). The R manual requires this.
  2. Call fit = stl(x, s.window = "periodic"). The argument s.window has no default; you must give either the string "periodic" or an odd span of at least 7. The manual states that "periodic" replaces the seasonal smoothing with a simple mean, so every cycle has the same seasonal values.
  3. Inspect the result: fit$time.series holds the columns seasonal, trend and remainder, and plot(fit) draws them.
  4. For outlier resistance, add robust = TRUE.

R with fable

The textbook pattern is dcmp = us_employment |> model(stl = STL(Employed)) followed by components(dcmp). To set the windows yourself, the textbook writes STL(Employed ~ trend(window = 7) + season(window = "periodic"), robust = TRUE).

Choosing the windows: a worked decision aid

The two settings that change a result most are the seasonal window and the trend window. The sources agree on the following.

Seasonal window: periodic or an odd span

A fixed (“periodic”) seasonal pattern forces the seasonal values to be identical in every year. An odd span lets the pattern drift and a smaller span lets it drift faster. Hyndman and Athanasopoulos state that in the fable defaults the seasonal window is 11, and that "periodic" makes the seasonal component identical across years. In statsmodels the seasonal value must be odd and the documentation says it should normally be at least 7.

Trend window: too rigid and the signal leaks into the remainder

In the textbook example, the default trend window (21 for monthly data) was too rigid to follow the 2008 financial crisis in US employment, so part of that movement appeared in the remainder component instead of the trend. The practical reading rule: if a clearly real change in level shows up as a run of large remainder values, widen the flexibility of the trend (a smaller trend window) before concluding the data are anomalous. In statsmodels the default trend is the smallest odd integer greater than 1.5 × period / (1 − 1.5 / seasonal), so the trend window moves with the seasonal setting unless you set it.

Robust fitting

The statsmodels example notebook reports that robust and non-robust fits differ only slightly on its series, with the difference visible around the 2008 crisis in an electrical equipment series. Treat robust as a diagnostic: fit both ways and compare the remainder, rather than assuming either is correct. The CASRAI guides on finding outliers and outliers in R cover the screening step.

Parameter cross-walk: statsmodels versus R

The same algorithm is exposed under different argument names and different defaults in Python and R, which is the usual source of results that do not match between the two. The data table below lists the settings documented for both implementations. Three differences matter most: R has no default for the seasonal window while statsmodels defaults to 7, the seasonal LOESS degree defaults to 1 in statsmodels but 0 in R, and R scales its jump values to the window (ceiling(s.window/10)) while statsmodels defaults every jump to 1.

Robust mode also differs in how it is described. In R, robust = TRUE changes the iteration counts: inner defaults to 1 and outer to 15 when robust, against 2 and 0 otherwise. In statsmodels, robust is a constructor flag and the iteration counts are arguments of fit(inner_iter, outer_iter).

The jump arguments (seasonal_jump, trend_jump, low_pass_jump in statsmodels; s.jump, t.jump, l.jump in R) evaluate the LOESS fit at every nth point and linearly interpolate between them, which reduces compute time. The statsmodels notebook reports a drop from about 342 ms to about 33 ms with jumps enabled on its example series.

Output and how to read it

Whatever the language, you get three series that add up to the original.

  • Trend: the smooth, slowly varying level after the seasonal cycle is removed.
  • Seasonal: the repeating pattern, one value per position in the cycle. With "periodic" (R) the same values repeat every cycle.
  • Remainder (statsmodels resid): what is left. Because the model is additive, trend + seasonal + remainder equals the observed value.
  • Weights: in statsmodels, res.weights holds robustness weights between 0 and 1; in R they are all 1 unless robust = TRUE. Low weights flag points the robust fit down-weighted.

Read the remainder first. A remainder that looks like random noise around zero suggests the seasonal and trend windows are adequate; a remainder with a visible cycle or a sustained level shift suggests the seasonal window is too rigid or the trend window too stiff, as in the 2008 example above. If the remainder is clearly autocorrelated, the structure left in it is a modelling task; see autocorrelation in time series data.

Multiplicative seasonality

STL is additive only. Hyndman and Athanasopoulos give two workarounds: take logarithms, decompose, then back-transform the components; or use a Box-Cox transformation with λ strictly between 0 and 1, where λ = 0 corresponds to a multiplicative decomposition and λ = 1 to an additive one. Use this when the seasonal swings grow with the level of the series.

Forecasting from an STL fit

The statsmodels class STLForecast forecasts the deseasonalised series with a model you choose (the notebook uses ARIMA(1,1,0)) and adds the seasonal component back to the forecast.

Troubleshooting

  • An error about the period (Python). A NumPy array carries no frequency, so pass period=12 (or your cycle length) explicitly. A pandas Series needs a set frequency for inference.
  • A frequency error (R). stl() needs a ts object with frequency greater than 1; a plain vector or a ts with frequency 1 will not work.
  • Missing values stop the fit (R). The default is na.action = na.fail, so any NA raises an error. Handle the gaps before decomposing rather than changing the action blindly.
  • An error about an even window. The seasonal, trend and low_pass settings in statsmodels must be odd, and low_pass must be at least 3. The degree arguments accept only 0 or 1.
  • Results differ between Python and R. Compare the cross-walk table: different seasonal-degree defaults and a required versus default seasonal window are the first things to align.
  • Calendar effects remain in the remainder. STL has no automatic trading-day or calendar handling, so such effects must be modelled separately.

Free alternatives and other implementations

Tool Function What the documentation says
R base (stats) stl() Seasonal-trend decomposition by LOESS; requires a univariate ts with frequency above 1; author B. D. Ripley, Fortran code by Cleveland et al. from netlib.
R fable model(stl = STL(y)) and components() Formula interface with trend(window) and season(window); used throughout the FPP3 textbook.
Python statsmodels STL, STLForecast Derived from the NETLIB Fortran implementation, with the original median bug in the robust weighting corrected.
Classical decomposition, X-11, SEATS (other methods) Discussed by FPP3 as alternatives; X-11 and SEATS support only monthly and quarterly data.

Frequently asked questions

What does STL stand for?

The method comes from the 1990 paper “STL: A Seasonal-Trend Decomposition Procedure Based on LOESS” by Cleveland, Cleveland, McRae and Terpenning, published in the Journal of Official Statistics, volume 6, pages 3 to 73.

Does STL work for multiplicative seasonality?

Not directly. It is additive only; decompose the logarithm of the series (or a Box-Cox transformation with λ strictly between 0 and 1) and back-transform the components.

Which value should I use for the seasonal window?

It must be odd. statsmodels documents a default of 7 and recommends at least 7, but its own example changes it to 13 for monthly data; R requires you to choose between "periodic" and an odd span of at least 7. Try a periodic or large value first, then reduce it only if the seasonal pattern clearly changes over time.

When should I turn on robust fitting?

Use it when outliers are suspected: it down-weights them so they distort the trend and seasonal estimates less. Compare the robust and non-robust remainders before deciding.

Can STL handle missing data?

In R, stl() fails on missing values by default (na.action = na.fail). Fill or otherwise treat gaps first.

Sources

  • statsmodels, statsmodels.tsa.seasonal.STL documentation: https://www.statsmodels.org/stable/generated/statsmodels.tsa.seasonal.STL.html (read 2026-11-15)
  • statsmodels, STL Decomposition example notebook (0.15.0): https://www.statsmodels.org/stable/examples/notebooks/generated/stl_decomposition.html (read 2026-11-15)
  • statsmodels, Installing statsmodels: https://www.statsmodels.org/stable/install.html (read 2026-11-15)
  • R Core Team, stats::stl manual page: https://stat.ethz.ch/R-manual/R-devel/library/stats/html/stl.html (read 2026-11-15)
  • Hyndman, R. J. and Athanasopoulos, G., Forecasting: Principles and Practice (3rd ed.), section 3.6 STL decomposition: https://otexts.com/fpp3/stl.html (read 2026-11-15)
  • Cleveland, R. B., Cleveland, W. S., McRae, J. E. and Terpenning, I. (1990). STL: A Seasonal-Trend Decomposition Procedure Based on LOESS. Journal of Official Statistics, 6, 3-73, as cited in the statsmodels and R documentation.

Data: STL decomposition settings: statsmodels STL versus R stats::stl

Cross-walk of the documented arguments and defaults of the STL (seasonal-trend decomposition by LOESS) implementation in Python statsmodels and in base R stats::stl. Compiled from the statsmodels STL class documentation and the R stats::stl manual page, both read on 2026-11-15; rows list only settings stated in both pages.

STL decomposition settings: statsmodels STL versus R stats::stl
Settingstatsmodels STL (Python)R stats::stl
Seasonal windowseasonal=7 (odd, normally at least 7)s.window has no default; "periodic" or an odd span of at least 7
Trend windowtrend=None: smallest odd integer > 1.5*period/(1-1.5/seasonal)t.window=NULL
Low-pass windowlow_pass=None: smallest odd integer > period (at least 3)l.window=nextodd(period)
Seasonal LOESS degreeseasonal_deg=1 (0 or 1)s.degree=0
Trend LOESS degreetrend_deg=1 (0 or 1)t.degree=1
Low-pass LOESS degreelow_pass_deg=1 (0 or 1)l.degree=t.degree
Seasonal jumpseasonal_jump=1s.jump=ceiling(s.window/10)
Robust fittingrobust=False; True gives the weighted, outlier-resistant versionrobust=FALSE; inner=2, outer=0 (robust: inner=1, outer=15)
Input requirementPeriod inferred from a pandas object with frequency; NumPy arrays need periodUnivariate ts with frequency > 1

Sources

Compiled by CASRAI from the sources above. Free to reuse under CC BY 4.0 with attribution.

Follow CASRAI

Research-administration guidance, standards updates and independent tool reviews.

Ask CASRAI · full access

Ask about STL Decomposition: Python statsmodels and R stl() Compared

Full access: large monthly usage, up to 10 source passages behind each answer, and MCP and API access for Claude Code, Codex and other CLIs. Cancel any time.

An AI assistant for research: funder rules, compliance, methods and publishing. It links the sources behind its answers and labels answers that come from a web search.

Answers draw on CASRAI's guides and dictionary plus the federal and funder documents we index: Federal Register, Grants.gov, Regulations.gov and UKRI.

Works on this site and inside Claude, Cursor and the AI tools you already use.

Everything CASRAI publishes — this page, the dictionary, the guides and the news — stays open to read, with no account and no card.

Referenced across the research world

University of Cambridge logoColumbia University logoCrossref logoUniversity of Edinburgh logoHarvard University logoUniversity of Oxford logoPrinceton University logoStanford School of Medicine logoUniversity College London logoORCID logoUniversity of Cambridge logoColumbia University logoCrossref logoUniversity of Edinburgh logoHarvard University logoUniversity of Oxford logoPrinceton University logoStanford School of Medicine logoUniversity College London logoORCID logo
  • University of Cambridge logo
  • Columbia University logo
  • Crossref logo
  • University of Edinburgh logo
  • Harvard University logo
  • University of Oxford logo
  • Princeton University logo
  • Stanford School of Medicine logo
  • University College London logo
  • ORCID logo

View CASRAI adoption →