Module contents
Lesson 10 of 31Core 100 min

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.

InteractiveDecompose a series

Observed series and trend

Estimated trend

Estimated seasonality

Remainder: observed minus trend and seasonality

  • Observed
  • Tendencia
  • Seasonal
  • Remainder

Simulated consumption series: 120 months, period 12, trend 10 + 0.025t + 0.8 sin(2πt/84), seasonality (2 + 0.004t) sin(2πt/12) + 0.6 cos(4πt/12), and independent normal noise with deviation 0.3. Here t starts at 0. The outlier adds 10 at t = 60, observation 61.

This custom additive STL implementation uses tricube linear LOESS in each monthly subseries and trend, two inner iterations, a low-pass of moving averages 12, 12 and 3 followed by LOESS with window 13, and six outer bisquare updates when robustness is enabled. Endpoints extrapolate the local line. The displayed weight is that used in the last iteration; without robustness it is 1. Options and results may differ from statsmodels. This is retrospective decomposition: it uses future observations, not a real-time forecast.

25
7
Robustness weight at observation 611.000
Remainder at observation 616.578
Root mean squared remainder0.749
Seed2610
Adjust smoothing windows and add an outlier. Compare components with and without robust weights; the series is generated from a reproducible model.

Trend, seasonality and scale

An additive time-series decomposition writes yt=Tt+St+Rty_t=T_t+S_t+R_t: trend or slow cycle, seasonal component and remainder. In a multiplicative decomposition, yt=TtStRty_t=T_tS_tR_t; 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 y>0y>0, is

w=gλ(y)={log⁡y,λ=0,(yλ−1)/λ,λ≠0.gλ−1(w)={ew,λ=0,(1+λw)1/λ,λ≠0, 1+λw>0.w=g_\lambda(y)=\begin{cases}\log y,&\lambda=0,\\ (y^\lambda-1)/\lambda,&\lambda\ne0.\end{cases} \qquad g_\lambda^{-1}(w)=\begin{cases}e^w,&\lambda=0,\\ (1+\lambda w)^{1/\lambda},&\lambda\ne0,\ 1+\lambda w>0.\end{cases}

The limit as λ→0\lambda\to0 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 λ\lambda 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.

InteractiveFind a stable scale

Transformed monthly series: λ = 0 uses the logarithm; λ = 1 gives the original series minus 1.

Sample standard deviation of each year’s 12 months after transformation. Magenta years form the window used to estimate λ.

  • All years
  • Estimation window

The generated series is positive: trend 40 exp(0.012 t), seasonal factor exp(0.28 sin(2πt/12)), and noise factor exp(0.12 Z − 0.12²/2), with independent normal Z and t starting at 0. Trend raises scale; annual deviation mixes seasonality, within-year trend and noise, not residual variance alone.

Guerrero divides the original series into full years. For each year j it calculates mean mⱼ and sample deviation sⱼ; it seeks λ minimizing the coefficient of variation of sⱼ / mⱼ^(1−λ). Here the grid is [−1, 2] in steps of 0.01. This approximate criterion differs from CV of deviations after transformation. Source: Guerrero implementation in forecast.

Percentiles summarize 80 new simulations of the same model and window; they describe between-sample variation under this model, not a general confidence interval. Box–Cox needs strictly positive data: with zero or negative values this version cannot be applied without revisiting the model or justifying another transform.

1.00
8
1
1
Years used by Guerrero1 to 8
Guerrero λ, grid 0.010.01
Guerrero criterion at selected λ0.401
CV of transformed deviations in the window0.401
λ in 80 new series: 10th and 90th percentiles−0.27 to 0.21
Compare the transformed series and dispersion in complete-season blocks. Guerrero's choice comes from the same simulated data, not a preset value.

If WW has predicted mean μ\mu and variance vv, inverting the transformation at μ\mu does not generally give E[gλ−1(W)]\mathbb E[g_\lambda^{-1}(W)]. The second-order Taylor approximation is

E[Y]≈gλ−1(μ)+v2(gλ−1)′′(μ).\mathbb E[Y]\approx g_\lambda^{-1}(\mu)+\frac v2 (g_\lambda^{-1})''(\mu).

For λ=0\lambda=0 this gives eμ(1+v/2)e^\mu(1+v/2); if WW is normal, the exact mean is eμ+v/2e^{\mu+v/2} and eμe^\mu is the median. For λ≠0\lambda\ne0, the correction term is v2(1−λ)(1+λμ)1/λ−2\tfrac v2(1-\lambda)(1+\lambda\mu)^{1/\lambda-2}, 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 2×122\times12 filter has weights 1/241/24 at its endpoints and 1/121/12 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 yt−T^ty_t-\hat T_t, averages by phase and normalizes the twelve phases to sum to zero. The remainder is yt−T^t−S^ty_t-\hat T_t-\hat S_t. 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 TT and horizon hh:

y^T+h∣Tmedia=yˉ1:T,y^T+h∣Tingenua=yT,y^T+h∣Tderiva=yT+hyT−y1T−1.\hat y^{\rm media}_{T+h|T}=\bar y_{1:T},\quad \hat y^{\rm ingenua}_{T+h|T}=y_T,\quad \hat y^{\rm deriva}_{T+h|T}=y_T+h\frac{y_T-y_1}{T-1}.

Seasonal naive repeats the last observed cycle: for period mm, take yT−m+1+((h−1) mod m)y_{T-m+1+((h-1)\bmod m)}. Drift requires T≥2T\ge2 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

ℓt=αyt+(1−α)ℓt−1,y^t+h∣t=ℓt(h≥1).\ell_t=\alpha y_t+(1-\alpha)\ell_{t-1},\qquad \hat y_{t+h|t}=\ell_t\quad(h\ge1).

For 0<α≤10<\alpha\le1, expanding the recurrence gives

ℓt=(1−α)tℓ0+α∑j=0t−1(1−α)jyt−j.\ell_t=(1-\alpha)^t\ell_0+ \alpha\sum_{j=0}^{t-1}(1-\alpha)^j y_{t-j}.

Weights of observations and initial state sum to one. A large α\alpha 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.

InteractiveWeights and adaptation

The sample model has level 3 through t=20 and level 7 from t=21; independent normal noise with standard deviation 0.8 is added to each value. The fixed initial level is ℓ₀=3. Only observations available through t are shown.

Observations and one-step forecast

Time t

Weights in forecast for t+1

Age: 0 is the most recent observation
  • Observations
  • One-step forecast
  • Model level
  • Initial-level weight

The recursion ℓₜ=αyₜ+(1−α)ℓₜ₋₁ produces forecast ℓₜ for t+1. The weight of yₜ₋ₖ is α(1−α)ᵏ for k=0,…,t−1, and that of ℓ₀ is (1−α)ᵗ. All weights are included and sum to one. The open circle indicates the next forecast; each prior curve point uses only data available before that time.

A high α gives more weight to recent data: it usually follows a level jump sooner but also transfers more noise to the forecast. At α=1 the next forecast is the latest observation; at α=0 it always remains at the initial value. One path does not determine the best α: compare them on later data not used to fit them.

0.20
30
Forecast for t+16.492
Weight of latest observation20.0 %
Initial-level weight0.12 %
Sum of all weights1.000000
Noise seed2610
Change α to compare each observation's weight and the response to a level shift. The path is generated with a fixed seed.

Holt adds a slope btb_t; with damping 0<ϕ<10<\phi<1, the forecast without seasonality is

y^t+h∣t=ℓt+(ϕ+ϕ2+⋯+ϕh)bt.\hat y_{t+h|t}=\ell_t+(\phi+\phi^2+\cdots+\phi^h)b_t.

The damped factor approaches ϕ/(1−ϕ)\phi/(1-\phi) as horizon grows. For updating, ℓt=αyt+(1−α)(ℓt−1+ϕbt−1)\ell_t=\alpha y_t+(1-\alpha)(\ell_{t-1}+\phi b_{t-1}) and bt=β∗(ℓt−ℓt−1)+(1−β∗)ϕbt−1b_t=\beta^*(\ell_t-\ell_{t-1})+(1-\beta^*)\phi b_{t-1}. Without damping, ϕ=1\phi=1 and the slope term is hbthb_t.

Holt-Winters adds a seasonal component. An additive parameterization for period mm, with dt=ℓt−1+ϕbt−1d_t=\ell_{t-1}+\phi b_{t-1}, is

ℓt=α(yt−st−m)+(1−α)dt,bt=β∗(ℓt−ℓt−1)+(1−β∗)ϕbt−1,st=γ(yt−dt)+(1−γ)st−m.\begin{aligned} \ell_t&=\alpha(y_t-s_{t-m})+(1-\alpha)d_t,\\ b_t&=\beta^*(\ell_t-\ell_{t-1})+(1-\beta^*)\phi b_{t-1},\\ s_t&=\gamma(y_t-d_t)+(1-\gamma)s_{t-m}. \end{aligned}

The forecast adds the latest state for each phase to level and damped slope. In the multiplicative variant replace yt−st−my_t-s_{t-m} with yt/st−my_t/s_{t-m} and yt−dty_t-d_t with yt/dty_t/d_t, and multiply the forecast by the seasonal index. Positivity and division require care. In the additive version, some sources use γ∗\gamma^* with a seasonal update based on yt−ℓty_t-\ell_t; the forms are related through γ=(1−α)γ∗\gamma=(1-\alpha)\gamma^*. 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:

yt=ℓt−1+εt,ℓt=ℓt−1+αεt,εt∼iidN(0,σ2).y_t=\ell_{t-1}+\varepsilon_t,\qquad \ell_t=\ell_{t-1}+\alpha\varepsilon_t,\qquad \varepsilon_t\overset{\rm iid}{\sim}N(0,\sigma^2).

One innovation appears in both observation and state update. Conditional on initial level, the Gaussian log-likelihood is −n2log⁡(2πσ2)−12σ2∑t(yt−ℓt−1)2-\tfrac n2\log(2\pi\sigma^2)-\tfrac1{2\sigma^2}\sum_t(y_t-\ell_{t-1})^2. For given α\alpha and initial state, maximizing over σ2\sigma^2 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 AICc=AIC+2k(k+1)/(n−k−1)\mathrm{AICc}=\mathrm{AIC}+2k(k+1)/(n-k-1) requires counting parameters, including states and variance when estimated, and n>k+1n>k+1. 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 α\alpha; 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.

[ ]Real data and time splitBrowser
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.

[ ]Guerrero and bias-corrected inversionBrowser
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 1−Var⁡(R)/Var⁡(S+R)1-\operatorname{Var}(R)/\operatorname{Var}(S+R), bounded below by zero. These are descriptive summaries, not probabilities.

[ ]Classical decomposition from scratch and STLBrowser
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.

[ ]Baselines with a 24-month horizonBrowser
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.

[ ]Additive and multiplicative Holt-Winters from scratchBrowser
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 σ2\sigma^2 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.

[ ]Simple smoothing and damped HoltBrowser
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))
[ ]Additive ETS: likelihood and AICcBrowser
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 hh is σ2[1+α2(h−1)]\sigma^2[1+\alpha^2(h-1)]. The innovation at the forecast time directly affects the observation and the h−1h-1 earlier future innovations affect the level. The following Gaussian interval uses estimated parameters as if known: it excludes uncertainty in their estimation.

[ ]ETS(A,N,N) prediction intervalsBrowser
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

ProofWhy the level is an optimal forecast
Prove: In ETS(A,N,N), with known initial level and centered iid innovations of finite variance, prove that ℓₜ minimizes squared error among predictors measurable with information available through t.
0
Start with the conditional expectation of the next observation.

Step 1 of 3. What is E[yₜ₊₁ | Fₜ]?

NumericDamped Holt at three steps
A state has level 100, slope 2 and damping φ=0.9. Calculate the Holt forecast for h=3 without seasonality.
QuizScale and seasonality
A positive series has seasonal fluctuations growing approximately in proportion to level. Which approach best describes that evidence?
CodeBaselines at rolling origins
Implement seasonal_naive(x, h, m), drift(x, h), and rolling_mae(x, min_train, h, m). Each origin uses only x[:t]; rolling_mae returns mean absolute errors for both forecasts over all available windows x[t:t+h]. Require positive h and m, at least m observations for seasonal naive, and at least two for drift; require min_train ≥ max(m,2) and at least one evaluation window.
import numpy as np

def seasonal_naive(x, h, m):
  pass

def drift(x, h):
  pass

def rolling_mae(x, min_train, h, m):
  pass
Shift+Enter to run
CodeCentered filter for even periods
Generalize the filter: implement filtro_centrado(x, m) for a positive even period m. Return an array of the same length with the centered 2 × m moving average and NaN at the boundaries. Reject odd m or m less than 2 and series shorter than m+1 values. In particular, check that 2 × 12 removes period-12 seasonality summing to zero without altering a linear trend.
import numpy as np

def filtro_centrado(x, m):
  pass
Shift+Enter to run
Key idea

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