Module contents
Lesson 22 of 31Core 110 min

Probabilistic forecasting and its evaluation

Useful forecasts describe distributions. This lesson develops sharpness subject to calibration, proper scoring rules, quantile forecasts, PIT diagnostics, rolling-origin evaluation, scaled metrics, Diebold-Mariano comparison and forecast combination.

After this lesson you can

  • Demonstrate that a scoring rule is proper and select one suited to the use: logarithmic, CRPS, pinball or intervals.
  • Calculate normal CRPS in closed form and from samples.
  • Diagnose calibration with PIT histograms and coverage, and distinguish calibration from sharpness.
  • Design a leakage-free rolling-origin evaluation with suitable baselines.
  • Compare forecasters with Diebold-Mariano and combine forecasts by averaging quantiles and estimated weights.

Before you start

How uncertain is the future?

Deciding how much inventory to buy, capacity to reserve or capital to risk requires more than a central value. The same mean can correspond to a narrow distribution or one with a considerable loss tail. A predictive distribution assigns probabilities to future outcomes conditional on information available at the forecast origin. Before evaluating it, check what information it used and for which horizon.

In the first experiment, change a predictive distribution’s bias and spread and compare its PIT histogram, coverage and scores. An overly wide interval can overcover, but that does not mean it is calibrated. Comparing a calibrated marginal distribution with a better-informed conditional distribution shows that even correct marginal calibration can coexist with low sharpness.

InteractiveDistribution, calibration and sharpness

For known covariate X = 1, compare the true density with your prediction. The chart uses that fixed value; metrics use all observations in the selected group.

  • True, X = 1
  • Predictive, X = 1

PIT histogram for the selected group: each bar covers one tenth of [0, 1]. The line marks the expected 10% per bar under uniformity.

10 %0.00.51.0

Quantile reliability: at each level τ, height is the observed proportion of Y below predictive quantile τ. The diagonal is the ideal reference; finite samples deviate even when the predictive distribution is correct.

  • Ideal reference
  • Observed frequency
Horizontal: level τ · vertical: frequency of Y ≤ qτ

We generate 2000 independent pairs: X and ε are independent standard normals, Y = X + ε. The base conditional predictive distribution is N(X, 1), and the marginal is N(0, 2), where 2 is variance. The latter ignores X: with offset 0 and scale 1 its PIT is uniform and overall coverage correct, but it is less sharp and conditionally miscalibrated. Compare mean PIT by sign of X and select each group.

The offset is added to the base mean and scale multiplies its standard deviation. A predictive distribution that is merely too wide is not automatically calibrated: it generally produces excess coverage and PIT concentrated in the center. Metrics are sample averages, not guarantees for every realization. Log loss is −log density; lower values are preferred for both it and CRPS. PIT uses a normal approximation with absolute error below 0.000000075.

Base predictive distribution
0.0
1.0
Evaluate observations
Observations evaluated2000
Central 90% coverage88.5 %
Mean CRPS0.576
Mean log loss1.443
Mean PIT for X ≥ 00.504
Mean PIT for X < 00.505
Seed2622
Compare forecasts calculated on data generated by a known model.

Scores that reward telling the truth

A proper scoring rule assigns loss S(F,y)S(F,y) to the announced distribution FF and outcome yy. It is proper if, for every true distribution GG in the class considered, EGS(G,Y)≤EGS(F,Y)E_G S(G,Y)\le E_G S(F,Y). It is strictly proper if equality implies F=GF=G. In this lesson lower values are better; other sources use the opposite convention.

Logarithmic loss −log⁡f(y)-\log f(y) is strictly proper under the necessary domination and integrability conditions: the expected loss difference is the Kullback-Leibler divergence DKL(g∥f)D_{\rm KL}(g\|f). It severely penalizes assigning very low density to the observation and requires a well-defined density. Changing scale requires transforming the density with the Jacobian.

CRPS evaluates the entire cumulative distribution function:

CRPS⁡(F,y)=∫R[F(z)−1{y≤z}]2 dz.\operatorname{CRPS}(F,y)=\int_{\mathbb R} \left[F(z)-\mathbf 1\{y\le z\}\right]^2\,dz.

If X,X′X,X' are independent with law FF and have finite first moment, it is also E∣X−y∣−12E∣X−X′∣E|X-y|-\tfrac12E|X-X'|. To show propriety, take expectation under GG: EG[(F(z)−1{Y≤z})2]=(F(z)−G(z))2+G(z)(1−G(z))E_G[(F(z)-\mathbf1\{Y\le z\})^2]=(F(z)-G(z))^2+G(z)(1-G(z)). The expected loss difference is ∫(F−G)2\int(F-G)^2, zero only when the distributions coincide. In higher dimensions, the energy score replaces absolute value with Euclidean norm in the expectation representation; it is proper under moment assumptions, although it can be insensitive to certain dependence errors.

For F=N(μ,σ2)F=N(\mu,\sigma^2), σ>0\sigma>0, z=(y−μ)/σz=(y-\mu)/\sigma, standard density ϕ\phi and CDF Φ\Phi:

CRPS⁡(F,y)=σ[z(2Φ(z)−1)+2ϕ(z)−1π].\operatorname{CRPS}(F,y)=\sigma\left[z(2\Phi(z)-1)+2\phi(z)-\frac1{\sqrt\pi}\right].

The score of a central interval [l,u][l,u] at level 1−α1-\alpha adds width and penalizes observations outside it: (u−l)+2α(l−y)1{y<l}+2α(y−u)1{y>u}.(u-l)+\frac2\alpha(l-y)\mathbf1\{y<l\}+\frac2\alpha(y-u)\mathbf1\{y>u\}. It evaluates that interval, not the entire distribution. Nominal coverage alone does not demonstrate full calibration.

Quantiles and asymmetric decisions

The pinball loss of quantile qq for τ∈(0,1)\tau\in(0,1) is ρτ(y−q)=(τ−1{y<q})(y−q)\rho_\tau(y-q)=(\tau-\mathbf1\{y<q\})(y-q). Underestimation and overestimation have different costs. The expected minimum is any qq satisfying G(q−)≤τ≤G(q)G(q^-)\le\tau\le G(q); with atoms or empirical data there may be multiple minimizers.

InteractivePinball geometry

Mean loss versus q in a fixed sample of 20 uniform observations in [−2, 2]. Dots indicate ordered observations; any q in the highlighted interval minimizes loss.

  • Mean loss
  • Minima
  • Selected q

Each bar represents 2ρτ(y−qτ) at the midpoint of its τ interval. Their total area approximates the empirical distribution’s CRPS for observed y.

  • 2 × loss per quantile

Loss is ρτ(y−q)=τ(y−q) if y≥q and (τ−1)(y−q) if y<q. When 20τ is an integer, all values between the two neighboring observations minimize loss; otherwise the minimum is one sample observation.

For a distribution F with finite first moment, CRPS(F,y)=2∫₀¹ρτ(y−F⁻¹(τ)) dτ. The exact value uses the identity with distances between observations; bars use midpoint quadrature, so they may differ. Here F is the sample empirical distribution, not the generating uniform law.

50
0.00
0.65
10
1
Mean loss at q0.5544
Minimum mean loss0.4864
Optimal quantile or interval[0.608, 0.813]
Exact empirical CRPS0.3263
CRPS by quadrature0.3561
Absolute difference0.0298
Change the quantile and move the forecast; compare the empirical minimum with integrated losses.

CRPS is also 2∫01ρτ(y−F−1(τ)) dτ2\int_0^1\rho_\tau(y-F^{-1}(\tau))\,d\tau for distributions with finite first moment. Quadrature with a few quantiles only approximates it. Separately fitted quantiles can cross, contradicting their order; use a model with monotonicity constraints or rearrangement and reevaluate calibration and loss.

Diagnose before declaring victory

For a continuous predictive CDF FtF_t, the probability integral transform is Ut=Ft(Yt)U_t=F_t(Y_t). Under a correct conditional forecast, each UtU_t is uniform. A U-shaped histogram often suggests a distribution that is too narrow; central concentration suggests overdispersion. Bias can produce asymmetry. These shapes are diagnostics, not unique proofs of their cause. For discrete distributions, randomize PIT within the jump; a uniform marginal histogram does not guarantee conditional calibration, and PITs at overlapping horizons can be dependent.

A quantile reliability diagram compares each announced level τ\tau with the frequency of Yt≤qτ,tY_t\le q_{\tau,t}. The diagonal is the marginal target. This parallels classification probability calibration, although here an ordered family of thresholds is evaluated. The interactive shows this comparison alongside PIT.

Interval coverage is compared with its announced level, but an excessively wide forecast can overcover. Gneiting and Raftery propose seeking sharpness subject to calibration: among valid forecasts we prefer to concentrate the distribution as much as the available information permits. A climatological distribution ignoring a predictive covariate can be well calibrated marginally and less sharp than a correctly conditioned one.

Rolling origins and comparable scales

In rolling-origin evaluation, each model is fitted on data before the origin and evaluated on later observations. An expanding window retains the past; a sliding one discards older data. For multiple horizons record origin, horizon and target date, since errors overlap. Imputation, transformations, hyperparameter selection and combination weights must be learned without looking ahead. Reserve a later segment if using earlier origins to choose the procedure.

InteractiveWhat information was available

The series has 144 synthetic observations: a Gaussian AR(1) with coefficient 0.65, trend 0.012t, a period-12 oscillation and a jump of 1.5 from observation 111. The fixed seed determines the sample; future data are shown only to inspect the experiment.

At each origin, the window ends at the last available observation. The horizon contains the next H data points. To choose a moving average among 3, 6, 12 and 24 observations, validation uses earlier origins and ends before testing; exactly the same origins and horizons are compared in every score.

  • Available data and previous validation
  • Horizon to predict
  • Full series, inspection only
  • Forecast with window 24

Normalization: a deliberately simple model predicts zero on the centered scale. Centering on the training mean makes the inverse transform predict that mean; centering on the full-series mean uses future observations and predicts the global mean. Both MSEs use the same test dates. Leakage does not guarantee lower MSE in every sample.

Selection: the legitimate option chooses the window by MSE on earlier validation and then evaluates it on test. The leaking option selects the lowest MSE among the same windows by looking at those test dates and reports it again there. By construction, that minimum does not exceed the MSE of the earlier selected window, but it is not an independent evaluation.

MSE averages all errors across the H horizons and 70 origins; the same observation may be evaluated from several origins. Scaling and selection comparisons are separate experiments, calculated in original units on the same series.

Training window
3
Origin 72
Last available observation72
First date to predict73
Test origins70
Window chosen on validation24
Test MSE of that window3.707
MSE of training mean5.038
Seed2622
Advance the origins and examine which operations would introduce future information.

Scaled metrics compare errors with a scale calculated only on training data. For seasonal period mm, MASE divides mean absolute test error by the training mean of ∣yt−yt−m∣|y_t-y_{t-m}|; RMSSE does the same with squares and takes the square root. If that denominator is zero, the metric is undefined. MAPE is problematic with zero or near-zero values; sMAPE also does not eliminate all difficulties with small denominators.

M4 compared 61 methods on 100,000 series. Organizers highlighted that the best results mainly combined statistical methods. M5 Accuracy used a 28-day horizon and weighted RMSSE; its winner equally weighted six models with different approaches and training sets. M5 Uncertainty requested nine quantiles for 42,840 hierarchical series. Results depend on the dataset and loss: they do not imply one method wins in every application.

Comparing and combining

The Diebold-Mariano test works with loss differences dt=LA,t−LB,td_t=L_{A,t}-L_{B,t}. Under the zero-mean hypothesis and suitable stationarity, moment and weak-dependence conditions, the statistic divides dˉ\bar d by an estimate of its standard error based on long-run variance. Use a HAC estimate and declare its bandwidth: overlapping horizons create dependence, but taking h−1h-1 lags does not necessarily capture all dependence. A large p-value does not prove equality, and with few dates the normal approximation can be poor.

Combining CDFs as a mixture and averaging quantiles are different operations. Nonnegative weights summing to one produce a valid CDF in the first case and preserve quantile ordering in the second. Fitting weights on evaluation data leaks the future; use an earlier validation window and retain a later test.

The same available-information principle appears in walk-forward strategy validation, where costs and execution rules must also be incorporated. Adaptive conformal inference addresses intervals under temporal dependence with its own conditions and guarantees: coverage is not guaranteed for every dependent series. Practical significance reminds us that a statistically detectable difference may be too small to justify an operational change.

Lab: scores from scratch

The empirical CRPS formula uses every pair from a sample of size mm. Sorting first reduces cost to O(mlog⁡m)O(m\log m): if x(1)≤⋯≤x(m)x_{(1)}\le\cdots\le x_{(m)}, half the mean pairwise distance is ∑i(2i−m−1)x(i)/m2\sum_i(2i-m-1)x_{(i)}/m^2. This is the exact score of the empirical distribution, with denominator m2m^2; replacing it by m(m−1)m(m-1) constructs another Monte Carlo estimator.

[ ]CRPS, pinball and diagnosticsBrowser
import numpy as np
from scipy.special import ndtr
from scipy.stats import norm

def crps_normal(mu, sigma, y):
    mu,sigma,y=np.broadcast_arrays(mu,sigma,y)
    if np.any(~np.isfinite(mu)) or np.any(~np.isfinite(sigma)) or np.any(~np.isfinite(y)) or np.any(sigma<=0):
        raise ValueError("parámetros finitos y sigma positiva")
    z=(y-mu)/sigma
    phi=np.exp(-z*z/2)/np.sqrt(2*np.pi)
    return sigma*(z*(2*ndtr(z)-1)+2*phi-1/np.sqrt(np.pi))

def crps_muestra(samples,y):
    x=np.sort(np.asarray(samples,dtype=float))
    if x.ndim!=1 or not len(x) or not np.all(np.isfinite(x)) or not np.isfinite(y):
        raise ValueError("muestra unidimensional no vacía y datos finitos")
    m=len(x); pesos=2*np.arange(1,m+1)-m-1
    return np.mean(np.abs(x-y))-np.dot(pesos,x-x[0])/(m*m)

def pinball(y,q,tau):
    e=np.asarray(y)-np.asarray(q)
    return np.maximum(tau*e,(tau-1)*e)

rng=np.random.default_rng(2622)
observaciones=rng.normal(size=1000)
pit=ndtr(observaciones)
print("PIT por décimas:",np.histogram(pit,bins=np.linspace(0,1,11))[0])
print("cobertura nominal 90 % y CRPS medio:",
      np.mean(np.abs(observaciones)<=norm.ppf(.95)),
      crps_normal(0,1,observaciones).mean())
muestra=rng.normal(size=4000)
rejilla=np.array([-2.,-1.5,-.5,0.,.5,1.5,2.])
print("CRPS normal en una rejilla de observaciones:",list(map(float,crps_normal(0,1,rejilla))))
print("aproximación empírica en y=0.5:",crps_muestra(muestra,.5))
desplazada=muestra[:999]+1e14
print("error de invariancia al centrar los datos:",
      abs(crps_muestra(desplazada,1e14)-crps_muestra(desplazada-desplazada[0],1e14-desplazada[0])))
print("cuantiles empíricos y pérdidas medias:",
      [(t,np.quantile(observaciones,t),pinball(observaciones,np.quantile(observaciones,t),t).mean()) for t in (.1,.5,.9)])

To distinguish lack of calibration from lack of information, let X,εX,\varepsilon be independent standard normals and Y=X+εY=X+\varepsilon. The forecast conditional on XX is N(X,1)N(X,1); if we ignore XX, the correct marginal is N(0,2)N(0,2), where the second parameter is variance. Both are calibrated given their respective information, but the second discards a useful signal. If N(X,4)N(X,4) is announced instead, central coverage is excessive and its PIT is not uniform.

[ ]Marginal calibration and signalBrowser
x=rng.normal(size=4000); y_sim=x+rng.normal(size=4000)
for nombre,mu,sigma in [("condicional",x,1.),("marginal",np.zeros_like(x),np.sqrt(2)),("demasiado ancha",x,2.)]:
    u=ndtr((y_sim-mu)/sigma)
    cobertura=np.mean(np.abs(y_sim-mu)<=norm.ppf(.95)*sigma)
    logscore=np.mean(-norm.logpdf(y_sim,loc=mu,scale=sigma))
    print(nombre,"cobertura, CRPS, log-score, PIT por cuartiles:",
          cobertura,crps_normal(mu,sigma,y_sim).mean(),logscore,np.histogram(u,bins=np.linspace(0,1,5))[0])
niveles=np.arange(1,10)/10
frecuencias=[np.mean(y_sim<=x+norm.ppf(t)) for t in niveles]
print("fiabilidad condicional, nivel y frecuencia:",list(zip(niveles,frecuencias)))

Evaluating forecasts across series

We reuse the monthly AirPassengers series from the SARIMA lesson and quarterly real GDP from the statsmodels macroeconomic dataset. These are examples to run the protocol, not a representative competition. Each origin uses only its past, and horizons are evaluated on the original scale.

We define two origins per series with horizon three. Models and hyperparameters are fixed for this example before evaluation. The seasonal naive forecast uses the last cycle as its mean and spread based on training seasonal differences. For ETS we use a normal approximation with constant residual deviation, not an exact ETS interval. SARIMA and the structural model use predictive variance supplied by their state-space representation. In every case the bands are conditional on the fitted model and omit some parameter uncertainty.

[ ]Two series and the seasonal baselineBrowser
import statsmodels.api as sm
import warnings
from statsmodels.tools.sm_exceptions import ConvergenceWarning
warnings.filterwarnings("ignore",category=ConvergenceWarning)

pasajeros = 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)
macro = np.asarray(sm.datasets.macrodata.load_pandas().data["realgdp"],dtype=float)
series = {"pasajeros":(pasajeros,12), "pib":(macro,4)}
origenes = {nombre:(len(v)-6,len(v)-3) for nombre,(v,m) in series.items()}
resultados = []
def registrar(nombre, metodo, origen, media, sigma):
    serie,m=series[nombre]; train=serie[:origen]
    real=serie[origen:origen+len(media)]
    dif=train[m:]-train[:-m]
    escala=np.mean(np.abs(dif)); escala2=np.mean(dif*dif)
    for h,(pred,sd,obs) in enumerate(zip(media,sigma,real),1):
        resultados.append((nombre,metodo,origen,h,float(obs),float(pred),float(sd),float(escala),float(escala2)))

for nombre,(serie,m) in series.items():
    for origen in origenes[nombre]:
        train=serie[:origen]; dif=train[m:]-train[:-m]
        media=train[-m:][:3]; sigma=np.repeat(np.std(dif,ddof=1),3)
        registrar(nombre,"ingenuo",origen,media,sigma)
print("nombres, longitudes y orígenes:",
      [(k,len(v),origenes[k]) for k,(v,m) in series.items()])
print("primeras predicciones ingenuas:",resultados[:3])
[ ]Additive ETS at each originBrowser
from statsmodels.tsa.holtwinters import ExponentialSmoothing
convergencia_ets=[]
for nombre,(serie,m) in series.items():
    for origen in origenes[nombre]:
        train=serie[:origen]
        fit=ExponentialSmoothing(train,trend="add",seasonal="add",seasonal_periods=m,
                                 initialization_method="estimated").fit(optimized=True)
        media=np.asarray(fit.forecast(3))
        sigma=np.repeat(np.std(fit.resid,ddof=1),3)
        registrar(nombre,"ETS",origen,media,sigma)
        convergencia_ets.append(bool(fit.mle_retvals.get("success",False)))
print("pronósticos ETS registrados y convergencia:",
      sum(r[1]=="ETS" for r in resultados),convergencia_ets)
[ ]SARIMA at each originBrowser
from statsmodels.tsa.statespace.sarimax import SARIMAX
convergencia_sarima=[]
for nombre,(serie,m) in series.items():
    for origen in origenes[nombre]:
        train=serie[:origen]
        fit=SARIMAX(train,order=(0,1,1),seasonal_order=(0,1,1,m),
                    trend="n",enforce_stationarity=False,enforce_invertibility=False).fit(disp=False,maxiter=40)
        pred=fit.get_forecast(3)
        registrar(nombre,"SARIMA",origen,np.asarray(pred.predicted_mean),
                  np.sqrt(np.maximum(np.asarray(pred.var_pred_mean),1e-12)))
        convergencia_sarima.append(bool(fit.mle_retvals.get("converged",False)))
print("convergencia SARIMA por origen:",convergencia_sarima)
[ ]Structural model at each originBrowser
from statsmodels.tsa.statespace.structural import UnobservedComponents
convergencia_estructural=[]
for nombre,(serie,m) in series.items():
    for origen in origenes[nombre]:
        train=serie[:origen]
        fit=UnobservedComponents(train,level="local linear trend",seasonal=m).fit(disp=False,maxiter=40)
        pred=fit.get_forecast(3)
        registrar(nombre,"estructural",origen,np.asarray(pred.predicted_mean),
                  np.sqrt(np.maximum(np.asarray(pred.var_pred_mean),1e-12)))
        convergencia_estructural.append(bool(fit.mle_retvals.get("converged",False)))
print("convergencia estructural por origen:",convergencia_estructural)

A convergence warning is part of the result, not a detail to hide. If the optimizer does not converge, increase iterations, examine identification and scale, or discard that fit before drawing conclusions. This lab uses few origins so you can run it in the browser.

We calculate MASE and RMSSE with scales corresponding to each origin, normal CRPS and coverage. A zero scale is explicitly excluded as undefined. To avoid mixing errors in different units, we summarize each series separately.

[ ]Scores by series and methodBrowser
for nombre in series:
    for metodo in ("ingenuo","ETS","SARIMA","estructural"):
        filas=[r for r in resultados if r[0]==nombre and r[1]==metodo]
        obs=np.array([r[4] for r in filas]); mu=np.array([r[5] for r in filas])
        sd=np.array([r[6] for r in filas]); esc=np.array([r[7] for r in filas])
        esc2=np.array([r[8] for r in filas])
        mase=np.mean(np.abs(obs-mu)/esc) if np.all(esc>0) else np.nan
        rmsse=np.sqrt(np.mean((obs-mu)**2/esc2)) if np.all(esc2>0) else np.nan
        cobertura=np.mean(np.abs(obs-mu)<=norm.ppf(.95)*sd)
        print(nombre,metodo,"MASE, RMSSE, CRPS, cobertura:",
              mase,rmsse,np.mean(crps_normal(mu,sd,obs)),cobertura)

To compare dependent losses we estimate long-run variance with Bartlett weights. The implementation uses divisor nn for each autocovariance and an explicit bandwidth. Besides a simulation, we compare the seasonal naive forecast with the average of the two previous cycles on AirPassengers, at a one-step horizon and with each origin’s own training scale. Methods and period are fixed before evaluation. The small sample and test assumptions limit interpretation of the p-value.

[ ]Diebold-Mariano with HACBrowser
def diebold_mariano(d, lag):
    d=np.asarray(d,dtype=float); n=len(d)
    if n<3 or not 0<=lag<n:
        raise ValueError("n y ancho de banda inválidos")
    centrado=d-d.mean()
    var=np.dot(centrado,centrado)/n
    for k in range(1,lag+1):
        gamma=np.dot(centrado[k:],centrado[:-k])/n
        var+=2*(1-k/(lag+1))*gamma
    if var<=0:
        raise ValueError("varianza de largo plazo no positiva")
    estadistico=d.mean()/np.sqrt(var/n)
    return estadistico,2*norm.sf(abs(estadistico)),var

innovaciones=rng.normal(size=180)
d=np.zeros(len(innovaciones))
for t in range(1,len(d)):
    d[t]=.55*d[t-1]+innovaciones[t]
print("DM, p bilateral y varianza HAC de la simulación:",diebold_mariano(d,4))
perdidas_a=[]; perdidas_b=[]
for origen in range(108,len(pasajeros)):
    train=pasajeros[:origen]
    escala=np.mean((train[12:]-train[:-12])**2)
    real=pasajeros[origen]
    a=train[-12]
    b=(train[-12]+train[-24])/2
    perdidas_a.append((real-a)**2/escala)
    perdidas_b.append((real-b)**2/escala)
d_real=np.array(perdidas_a)-np.array(perdidas_b)
print("orígenes reales, diferencia media de pérdidas y DM HAC:",
      len(d_real),d_real.mean(),diebold_mariano(d_real,4))

Finally, we combine ETS and SARIMA quantiles. The first origin chooses a weight from a small grid by minimizing mean pinball loss for three quantiles; the second is reserved to evaluate that weight. This demonstrates temporal separation, not reliable selection with so few observations.

[ ]Combine quantiles without looking at the second originBrowser
taus=np.array([.1,.5,.9])
for nombre in series:
    primero,segundo=origenes[nombre]
    def bloques(metodo,origen):
        return sorted([r for r in resultados if r[0]==nombre and r[1]==metodo and r[2]==origen],key=lambda r:r[3])
    def combinados(origen,peso):
        a,b=bloques("ETS",origen),bloques("SARIMA",origen)
        obs=np.array([r[4] for r in a])
        qa=np.array([r[5]+r[6]*norm.ppf(taus) for r in a])
        qb=np.array([r[5]+r[6]*norm.ppf(taus) for r in b])
        return obs,peso*qa+(1-peso)*qb
    candidatos=np.linspace(0,1,5)
    perdidas=[]
    for peso in candidatos:
        obs,q=combinados(primero,peso)
        perdidas.append(pinball(obs[:,None],q,taus).mean())
    peso=candidatos[np.argmin(perdidas)]
    obs,q=combinados(segundo,peso)
    print(nombre,"peso ETS validado, pérdida en siguiente origen:",
          peso,pinball(obs[:,None],q,taus).mean())

Exercises

ProofThe pinball minimum
Prove: Show that expected pinball loss is minimized at a τ quantile, even with atoms.
0
Let G be the outcome distribution and q the forecast.

Step 1 of 2. Which expressions give the one-sided derivatives of expected loss with respect to q?

ProofWhy CRPS is strictly proper
Prove: For distributions with finite first moment, show strict propriety of CRPS and its distance representation.
0
Let X and X' be independent with law F, and Y have true law G.

Step 1 of 3. What difference in expected losses under G remains when the score of G is subtracted from that of F?

NumericNormal score
A forecast is N(0,1) and y=1 is observed. Calculate its CRPS and round to four decimal places.
QuizA U-shaped PIT
A PIT histogram shows excess values near zero and one. What is a plausible explanation and how do you check it?
CodeEmpirical CRPS without a pair matrix
Implement crps_samples(samples,y), the CRPS of the one-dimensional empirical distribution. Sort the sample and avoid constructing the matrix of all pairs. Reject empty or nonfinite inputs.
import numpy as np

def crps_samples(samples, y):
  pass
Shift+Enter to run
Key idea

A probabilistic forecast is judged by calibration, sharpness and decision usefulness, using appropriate scores and data not involved in its construction.

The last cell lets you check the numerical exercise calculation after attempting it.

[ ]Numerical checkBrowser
print("CRPS de N(0,1) en y=1:",float(crps_normal(0,1,1)))