Time series decomposition and exponential smoothing
Before parametric models, separate trend, seasonality and remainder. Study variance-stabilizing transformations such as Box-Cox, moving-average filters, classical decomposition and STL, forecasting baselines and exponential smoothing methods including simple, Holt and Holt-Winters, with their modern innovations state-space formulation as ETS models for likelihoods and prediction intervals.
After this lesson you can
- Choose and apply a Box-Cox transformation and invert it with bias correction.
- Decompose a series using centered moving averages and STL and assess trend and seasonal strength.
- Implement naive, seasonal-naive and drift forecasting baselines and use them as references.
- Implement simple exponential smoothing, damped Holt and Holt-Winters, estimating parameters by minimizing one-step error.
- Formulate ETS as an innovations state-space model, write its likelihood and select variants using AICc.
Before you start
Before forecasting, separate what changes
Electricity demand has peak hours, weekdays and seasons of the year. Website traffic can grow for months and fall on weekends. Summarizing the whole series with one mean and variance mixes level changes, predictable cycles and variation not yet explained.
Separating components helps formulate questions but does not automatically identify causes. A decomposition often uses observations on both sides of each time: its central components help explore the past and must not leak into training as if available in real time.
In the previous lesson you studied weak stationarity and autocorrelation. Now use those ideas to examine a decomposition’s remainder, and maximum likelihood to estimate models producing intervals.
Trend, seasonality and scale
An additive time-series decomposition writes : trend or slow cycle, seasonal component and remainder. In a multiplicative decomposition, ; if components are positive, taking logarithms converts the product to a sum. Roughly constant seasonal amplitude suggests an additive representation; if it grows proportionally to level, a multiplicative form or an additive form on the log scale may be more suitable.
The choice depends on the objective and data. Before fitting a monthly pattern, consider the number of days in each month, holidays, inflation and population changes. A total and a per-capita rate answer different questions. Known adjustments should be applied without using future information unavailable at forecast time.
The Box-Cox transformation, for , is
The limit as is the logarithm. The transformation requires an explicit decision when zeros or negative values occur; adding a constant changes the model and does not itself fix missing data. Guerrero selects to make variation more homogeneous across seasonal subseries; it does not guarantee normality or stationarity. The discussion of transformations and adjustments shows how this choice depends on the series.
If has predicted mean and variance , inverting the transformation at does not generally give . The second-order Taylor approximation is
For this gives ; if is normal, the exact mean is and is the median. For , the correction term is , provided the approximation operates in the valid domain. Variance must correspond to the forecast horizon; local correction does not replace a full predictive distribution. See Forecasting: Principles and Practice.
Moving averages and classical decomposition
A moving-average filter averages nearby observations. For a monthly series, a window of length 12 falls between two months; averaging two consecutive such averages centers the result. The filter has weights at its endpoints and at the eleven intermediate points. Exact period-12 seasonality summing to zero disappears under this filter. Observations are missing at the ends, so the centered average is undefined without extrapolation.
Classical additive decomposition first estimates centered trend, calculates residuals , averages by phase and normalizes the twelve phases to sum to zero. The remainder is . The multiplicative variant divides by trend, averages ratios by phase and normalizes to mean one; it requires positive data and trend. One mean per phase imposes a constant seasonal pattern. Outliers can contaminate both trend and seasonality.
STL decomposition replaces those rigid averages with LOESS smoothers. Each inner iteration smooths subseries of the same phase, applies a low-pass filter to separate slow and seasonal components, subtracts seasonality and smooths trend. The robust outer iteration reduces the weight of large residuals and repeats the fit. Windows determine how much trend and seasonality may change; robustness can reduce isolated-value influence but does not guarantee identification or automatically detect regime changes. STL in statsmodels documents its parameters and iterations.
With multiple periods, such as day and week in hourly data, one seasonal component may be insufficient. MSTL estimates several components by alternating smoothers; attribution can be ambiguous when patterns overlap. Neither STL nor MSTL alone supplies a predictive distribution: components must be modeled and projected.
Forecasts as references
Baselines are forecasts a new method should beat in an appropriate evaluation. At origin and horizon :
Seasonal naive repeats the last observed cycle: for period , take . Drift requires and uses the slope between endpoints, not regression over all points. Evaluate on later observations, keep the test period untouched during selection, and compare the same metric and horizon. At a rolling origin, each fit may use only data available through that origin. A centered moving average computed over the entire series would break this rule.
The memory of exponential smoothing
Simple exponential smoothing updates the level with
For , expanding the recurrence gives
Weights of observations and initial state sum to one. A large reacts more to recent changes and filters less noise; a small one retains more memory. The forecast is flat: it invents no trend or seasonality. Parameters and initialization can be estimated by minimizing one-step training forecast errors, without looking at the test set.
Holt adds a slope ; with damping , the forecast without seasonality is
The damped factor approaches as horizon grows. For updating, and . Without damping, and the slope term is .
Holt-Winters adds a seasonal component. An additive parameterization for period , with , is
The forecast adds the latest state for each phase to level and damped slope. In the multiplicative variant replace with and with , and multiply the forecast by the seasonal index. Positivity and division require care. In the additive version, some sources use with a seasonal update based on ; the forms are related through . Do not compare parameters without checking the convention. The formulas are detailed in Holt-Winters.
ETS: a distribution, not just a curve
An ETS innovations state-space model specifies error, trend and seasonality. ETS(A,N,N) has additive error, no trend and no seasonality:
One innovation appears in both observation and state update. Conditional on initial level, the Gaussian log-likelihood is . For given and initial state, maximizing over gives mean squared innovations. If the initial state is also estimated, count that parameter; with seasonality, initial states must be identified and their normalization respected.
In multiplicative ETS, error scale depends on the prediction and likelihood contains the corresponding scale change; minimizing squared absolute residuals is not enough. Selection by requires counting parameters, including states and variance when estimated, and . Compare likelihoods on the same observations and verify that models were fitted. Do not interchange AIC values computed on different transformed scales without the Jacobian.
Intervals depend on the error model and horizon; they can be obtained by formulas or path simulation. Equality of a recurrence and a point forecast does not make their distributions equivalent. Under suitable conditions, ETS(A,N,N) has an ARIMA(0,1,1) representation with MA parameter related to ; initial states and sign conventions matter. Undamped multiplicative trends can produce explosive paths and are especially delicate at long horizons.
Lab: decompose, fit and check
Work with AirPassengers: monthly totals of international passengers in thousands, from January 1949 through December 1960. The reproduced series allows the lab to run offline. Reserve the final two years for evaluation; no estimation uses those values.
import numpy as np
from scipy.optimize import minimize
y = np.array([112,118,132,129,121,135,148,148,136,119,104,118,115,126,141,135,125,149,170,170,158,133,114,140,145,150,178,163,172,178,199,199,184,162,146,166,171,180,193,181,183,218,230,242,209,191,172,194,196,196,236,235,229,243,264,272,237,211,180,201,204,188,235,227,234,264,302,293,259,229,203,229,242,233,267,269,270,315,364,347,312,274,237,278,284,277,317,313,318,374,413,405,355,306,271,306,315,301,356,348,355,422,465,467,404,347,305,336,340,318,362,348,363,435,491,505,404,359,310,337,360,342,406,396,420,472,548,559,463,407,362,405,417,391,419,461,472,535,622,606,508,461,390,432], dtype=float)
train, test = y[:120], y[120:]
print("meses entrenamiento y prueba:", len(train), len(test))
print("primer y último mes observados:", y[0], y[-1])Now calculate Guerrero on the ten training blocks and verify the inverse. The lognormal experiment uses a known model to compare the exact mean with the median and Taylor approximation; it is not a measurement of AirPassengers uncertainty.
from scipy.optimize import minimize_scalar
from scipy.special import boxcox, inv_boxcox
bloques = train.reshape(-1, 12)
medias = bloques.mean(axis=1)
desv = bloques.std(axis=1, ddof=1)
def criterio_guerrero(lam):
razones = desv/medias**(1-lam)
return razones.std(ddof=1)/razones.mean()
opt_lambda = minimize_scalar(criterio_guerrero, bounds=(-1,2), method="bounded")
lam = opt_lambda.x
transformada = boxcox(train, lam)
print("lambda Guerrero y criterio:", lam, criterio_guerrero(lam))
print("error de ida y vuelta:", np.max(abs(inv_boxcox(transformada, lam)-train)))
mu, var = 2., .25
rng = np.random.default_rng(201)
muestra = np.exp(rng.normal(mu, np.sqrt(var), size=100000))
print("mediana, media exacta, Taylor y media simulada:",
np.exp(mu), np.exp(mu+var/2), np.exp(mu)*(1+var/2), muestra.mean())Classical decomposition leaves six values without trend at each end: do not replace them with estimates calculated using the future. For STL compare components, trend strength and seasonal strength , bounded below by zero. These are descriptive summaries, not probabilities.
from statsmodels.tsa.seasonal import STL, seasonal_decompose
def clasica_aditiva(x, m=12):
x = np.asarray(x, dtype=float)
if m % 2 or len(x) < 2*m:
raise ValueError("se requieren periodo par y al menos dos ciclos")
pesos = np.r_[0.5, np.ones(m-1), 0.5]/m
trend = np.full(len(x), np.nan)
trend[m//2:len(x)-m//2] = np.convolve(x, pesos, mode="valid")
des = x-trend
fases = np.array([np.nanmean(des[j::m]) for j in range(m)])
fases -= fases.mean()
seasonal = fases[np.arange(len(x)) % m]
return trend, seasonal, x-trend-seasonal
tc, sc, rc = clasica_aditiva(train)
ref = seasonal_decompose(train, model="additive", period=12)
stl = STL(train, period=12, seasonal=13, robust=True).fit()
fuerza_s = max(0., 1-np.var(stl.resid)/np.var(stl.seasonal+stl.resid))
fuerza_t = max(0., 1-np.var(stl.resid)/np.var(stl.trend+stl.resid))
print("error máximo de tendencia y estacionalidad clásicas:",
np.nanmax(abs(tc-ref.trend)), np.max(abs(sc-ref.seasonal)))
print("fuerza descriptiva de tendencia y estacionalidad STL:", fuerza_t, fuerza_s)
print("reconstrucción máxima STL:", np.max(abs(train-stl.trend-stl.seasonal-stl.resid)))The next cells compare baseline forecasts with smoothers estimated only on training data. A comparison at this single split does not prove a method wins on other series or dates.
def baselines(x, h, m=12):
if len(x) < max(2, m) or h <= 0:
raise ValueError("se requiere historial suficiente y horizonte positivo")
pasos = np.arange(1, h+1)
return {
"media": np.repeat(np.mean(x), h),
"ingenua": np.repeat(x[-1], h),
"estacional": x[-m:][np.arange(h) % m],
"deriva": x[-1] + pasos*(x[-1]-x[0])/(len(x)-1),
}
def rmse(verdad, prediccion):
return np.sqrt(np.mean((np.asarray(verdad)-prediccion)**2))
pred_base = baselines(train, len(test))
for nombre, prediccion in pred_base.items():
print(nombre, "RMSE:", rmse(test, prediccion))To avoid introducing test information, use the first 24 training months to construct initial states and fit parameters on the following 96 months. Comparison with the library fixes exactly those same states and parameters; this checks recurrences without confounding them with initialization or optimization differences.
from statsmodels.tsa.holtwinters import ExponentialSmoothing
def estados_iniciales(x, tipo, m=12):
primero, segundo = x[:m], x[m:2*m]
pendiente = (np.mean(segundo)-np.mean(primero))/m
nivel = np.mean(segundo)+0.5*(m-1)*pendiente
nivel_segundo = np.mean(segundo)+(np.arange(m)-(m-1)/2)*pendiente
estacion = segundo-nivel_segundo if tipo == "add" else segundo/nivel_segundo
if tipo == "add":
estacion -= np.mean(estacion)
else:
estacion /= np.mean(estacion)
return nivel, pendiente, estacion
def hw(x, inicial, parametros, tipo, h=24):
alpha, beta, gamma = parametros
nivel, pendiente, est = inicial
est = np.array(est, dtype=float).copy()
ajustados = np.empty(len(x))
for i, valor in enumerate(x):
j = i % len(est)
base = nivel+pendiente
if tipo == "mul":
if base <= 0 or est[j] <= 0:
raise ValueError("estado no positivo")
ajustados[i] = base*est[j]
nuevo = alpha*valor/est[j]+(1-alpha)*base
nueva_est = gamma*valor/base+(1-gamma)*est[j]
else:
ajustados[i] = base+est[j]
nuevo = alpha*(valor-est[j])+(1-alpha)*base
nueva_est = gamma*(valor-base)+(1-gamma)*est[j]
pendiente = beta*(nuevo-nivel)+(1-beta)*pendiente
nivel = nuevo
est[j] = nueva_est
siguiente = len(x) % len(est)
fase = est[(siguiente+np.arange(h)) % len(est)]
tendencia = nivel+np.arange(1, h+1)*pendiente
pred = tendencia*fase if tipo == "mul" else tendencia+fase
return ajustados, pred
def ajustar_hw(x, inicial, tipo):
def objetivo(v):
alpha, beta, gamma = v[0], v[0]*v[1], (1-v[0])*v[2]
try:
ajuste, _ = hw(x, inicial, (alpha,beta,gamma), tipo)
return np.mean((x-ajuste)**2)
except ValueError:
return 1e30
opt = minimize(objetivo, [.3,.3,.3], method="L-BFGS-B",
bounds=[(.01,.99),(0,1),(0,1)],
options={"maxiter": 120, "ftol": 1e-9})
alpha = opt.x[0]
return opt, (alpha, alpha*opt.x[1], (1-alpha)*opt.x[2])
ajuste_x = train[24:]
for tipo in ("add", "mul"):
inicial = estados_iniciales(train[:24], tipo)
opt, parametros = ajustar_hw(ajuste_x, inicial, tipo)
fitted, pred = hw(ajuste_x, inicial, parametros, tipo)
nivel, pendiente, temporada = inicial
ref_hw = ExponentialSmoothing(
ajuste_x, trend="add", seasonal=tipo, seasonal_periods=12,
initialization_method="known", initial_level=nivel,
initial_trend=pendiente, initial_seasonal=temporada
).fit(smoothing_level=parametros[0], smoothing_trend=parametros[1],
smoothing_seasonal=parametros[2], optimized=False)
print(tipo, "convergencia:", opt.success, "parámetros:", np.round(parametros, 4))
ref_pred = np.asarray(ref_hw.forecast(24))
print("diferencia ajuste, primeros 11 horizontes y 24 horizontes:",
np.max(abs(fitted-ref_hw.fittedvalues)),
np.max(abs(pred[:11]-ref_pred[:11])),
np.max(abs(pred-ref_pred)))
print("horizontes con discrepancia:",
np.flatnonzero(abs(pred-ref_pred) > 1e-6)+1)
print("RMSE prueba:", rmse(test, pred))The preceding optimization minimizes one-step squared error with fixed initial states. For additive Gaussian errors, this is equivalent to maximizing profile likelihood over conditional on those states. In the model with multiplicative seasonality here, error remains additive; multiplicative error changes the objective.
In this run, fitted values and the first eleven horizons agree, but the cell shows discrepancies at horizons 12 and 24. The custom implementation reuses the twelve updated seasonal states as the recurrence prescribes; the library version available in this environment returns a different value for that phase. This is a reproducible warning about this particular comparison, not a claim about all versions. Check the final phase before trusting a long forecast.
Simple level and damped Holt can be fitted by the same criterion. Fix initial states using the first 24 months and estimate parameters using the remaining 96. Initial slope is the change between the means of the first two years divided by 12.
def suavizar(x, nivel, pendiente, alpha, beta=None, phi=1.):
pred = []
for valor in x:
base = nivel if beta is None else nivel+phi*pendiente
pred.append(base)
nuevo = alpha*valor+(1-alpha)*base
if beta is not None:
pendiente = beta*(nuevo-nivel)+(1-beta)*phi*pendiente
nivel = nuevo
return np.array(pred), nivel, pendiente
inicial_nivel = np.mean(train[12:24])
inicial_pendiente = (np.mean(train[12:24])-np.mean(train[:12]))/12
def mse_ses(v):
pred, _, _ = suavizar(ajuste_x, inicial_nivel, 0., v[0])
return np.mean((ajuste_x-pred)**2)
def mse_holt(v):
pred, _, _ = suavizar(ajuste_x, inicial_nivel, inicial_pendiente,
v[0], v[1], v[2])
return np.mean((ajuste_x-pred)**2)
ses_opt = minimize(mse_ses, [.3], method="L-BFGS-B", bounds=[(.001,.999)])
holt_opt = minimize(mse_holt, [.3,.1,.9], method="L-BFGS-B",
bounds=[(.001,.999),(.001,.999),(.8,.999)])
_, nivel_ses, _ = suavizar(ajuste_x, inicial_nivel, 0., ses_opt.x[0])
_, nivel_holt, pendiente_holt = suavizar(
ajuste_x, inicial_nivel, inicial_pendiente, *holt_opt.x)
h = np.arange(1, len(test)+1)
pred_holt = nivel_holt + pendiente_holt*np.cumsum(holt_opt.x[2]**h)
print("convergencia SES y Holt:", ses_opt.success, holt_opt.success)
print("parámetros SES y Holt:", ses_opt.x, holt_opt.x)
print("RMSE SES y Holt amortiguado:",
rmse(test, np.repeat(nivel_ses, len(test))), rmse(test, pred_holt))from statsmodels.tsa.exponential_smoothing.ets import ETSModel
ets0 = ETSModel(ajuste_x, error="add", trend=None,
seasonal=None, initialization_method="estimated").fit(disp=False)
ets1 = ETSModel(ajuste_x, error="add", trend="add",
seasonal=None, initialization_method="estimated").fit(disp=False)
inicial_add = estados_iniciales(train[:24], "add")
ets2 = ETSModel(ajuste_x, error="add", trend="add", seasonal="add",
seasonal_periods=12, initialization_method="known",
initial_level=inicial_add[0], initial_trend=inicial_add[1],
initial_seasonal=inicial_add[2]).fit(disp=False, maxiter=150)
for nombre, modelo in (("ETS(A,N,N)", ets0), ("ETS(A,A,N)", ets1),
("ETS(A,A,A), estados fijados", ets2)):
print(nombre, "log-verosimilitud:", modelo.llf, "AICc:", modelo.aicc,
"RMSE prueba:", rmse(test, modelo.forecast(24)))All three ETS models use the same 96 observations and original scale without using the test set. The seasonal model conditions on states calculated from the preceding 24 months, while the other two estimate their initial states from the fitting sample itself. Conditional AICc does not count fixed states as though estimated from those 96 observations: interpret this comparison cautiously and always validate with out-of-sample forecasts.
For ETS(A,N,N), conditional on the final state and known parameters, predictive variance at horizon is . The innovation at the forecast time directly affects the observation and the earlier future innovations affect the level. The following Gaussian interval uses estimated parameters as if known: it excludes uncertainty in their estimation.
from scipy.stats import norm
horizontes = np.arange(1, 25)
alpha = ets0.params[0]
media = np.asarray(ets0.forecast(24))
error = np.sqrt(ets0.scale*(1+alpha**2*(horizontes-1)))
limite = norm.ppf(.975)*error
print("intervalo 95 % en h=1:", media[0]-limite[0], media[0]+limite[0])
print("intervalo 95 % en h=24:", media[-1]-limite[-1], media[-1]+limite[-1])
print("ancho h=24 / ancho h=1:", limite[-1]/limite[0])
rng = np.random.default_rng(310)
innovaciones = rng.normal(0., np.sqrt(ets0.scale), size=(5000, 24))
error_simulado = innovaciones[:, -1]+alpha*innovaciones[:, :-1].sum(axis=1)
print("desviación simulada y teórica en h=24:", error_simulado.std(ddof=1), error[-1])
print("cobertura simulada en h=24:", np.mean(abs(error_simulado) <= limite[-1]))Exercises
Step 1 of 3. What is E[yₜ₊₁ | Fₜ]?
import numpy as np
def seasonal_naive(x, h, m):
pass
def drift(x, h):
pass
def rolling_mae(x, min_train, h, m):
passimport numpy as np
def filtro_centrado(x, m):
passDecomposition reveals slow and periodic patterns. Exponential smoothing assigns explicit weights to the past; ETS adds an innovation law for estimation, comparison and uncertainty quantification. Temporal evaluation against baselines remains essential.