Cuantifica la incertidumbre de la previsión

Unos 25 minutos de lectura, con 4 ejemplos en 7 secciones.

Edición 2026.11.11 Ejemplos verificados el 20 de nov de 2026 41 de 41 ejemplos pasan Qué ha cambiado

Traducido con IA. Verificado por personas en inglés. Cómo hacemos los libros

Traducido del libro en inglés, edición 2026.11.11. Lee el original

Este capítulo asigna un rango a cada previsión del día siguiente, para que puedas decir si una compra puede apoyarse en ella. Calibrarás intervalos de predicción con los días que van antes de los días que evalúas, medirás con qué frecuencia se cumplen y elegirás el nivel al que comprar a partir de los dos costes de un error.

Esta parte aún no está traducida, así que está en inglés.

Why one number is not enough

Último cambio en la edición 2026.11.11

The forecasts so far give one number for each client and hour, and a single number is not enough to buy on. The supplier cannot buy an expected value. It buys an amount of power a day ahead for each hour, so it needs a range around each forecast. Each kWh it buys is either used or not. Buying short means buying the rest later at a premium, and buying long means paying for power that nobody uses. The two errors cost different amounts, so the right purchase is usually not the forecast itself. Take one hour. Suppose the forecast is 100 kWh. If the reading turns out 10 kWh higher, the supplier is short and pays the short cost on those 10 kWh. If it turns out 10 kWh lower, the supplier has 10 kWh it pays for and does not use. When the short cost is three times the unused cost, a purchase above the forecast costs less on average, because it makes the expensive error less likely. How far above the forecast the purchase should sit depends on that ratio, and on how wide the errors are.

This chapter states two costs as assumptions. A kWh bought short costs 3.00 cost units, and a kWh bought and not used costs 1.00. These numbers are illustrative. They are not prices, and the book does not claim that any real supplier faces them. A later section shows how they set the purchase.

A prediction interval gives a lower and an upper bound for each hour. A prediction interval's level, such as 80 or 95, is the share of readings the bounds should contain. The share of readings the bounds contain is the coverage, and coverage belongs to many forecasts made the same way, not to one. One day's band either contains the readings or it does not. Across the 72 hours of three days, the share inside the band is a measurement. Across a year of days, it becomes a track record. A 95 percent band whose hours fall inside it 90 percent of the time has undercovered, but no single day shows it. Only the average over many hours shows it, and that average is what we measure.

Quantiles connect the bands to the costs. The lower bound of a central 80 percent interval is the 0.1 quantile of the forecast's distribution, the value that the reading falls below one time in ten. The upper bound is the 0.9 quantile. The purchase that minimises the expected cost is also a quantile, and Choose the level from the cost of error derives which one.

In the case, the range that matters is the total's, because the total is what the supplier buys. Chapter 6 forecast the thirty clients with one global model, and the total is the hourly sum of those forecasts. Each client has its own range, but the total's range cannot be read off the clients' ranges by adding them. Choose the level from the cost of error compares the two.

Working rule: Ask for a range wherever the costs of the two errors differ, and choose its level from those costs rather than from a number that looks reassuring. Report coverage as the share of hours inside the band over many windows, never as the chance that one day falls inside.

Construir intervalos a partir de residuos

Último cambio en la edición 2026.11.6

Un rango necesita límites, y los límites más simples provienen de errores pasados. Un residuo es el error de un pronóstico anterior: la lectura menos el pronóstico, e = y - f. La predicción conforme construye una banda a partir de los residuos de pronósticos hechos de la misma manera en días anteriores. Toma los residuos de un conjunto de ventanas de calibración, agrúpalos por paso de horizonte y lee los cuantiles que necesites. Un pronóstico del día siguiente hecho a las 00:00 tiene un paso de horizonte por cada hora del día, así que el grupo es solo la hora. Para un nivel L en porcentaje, los límites para un pronóstico f hecho en un paso dado son:

lower = f + Q((1 - L/100) / 2)
upper = f + Q((1 + L/100) / 2)

donde Q(p) es el cuantil empírico p de los residuos de calibración en ese paso. El método no supone ningún modelo de los errores. Solo supone que los residuos de calibración se parecen a los residuos que vendrán, lo que una sección posterior comprueba. Una ventana de calibración es un punto de corte cuyos residuos dimensionan las bandas. Siempre va antes de los puntos de corte que se pronostican, y nunca es una de las ventanas que se puntúan.

La biblioteca que hace esto para el modelo del libro es mlforecast, en la versión 1.1.0. Su clase PredictionIntervals recibe un número de ventanas, un horizonte y un método, y tiene cuatro métodos conformes: conformal_error, conformal_distribution, y sus versiones ponderadas. Los dos métodos no ponderados puntúan los residuos absolutos, |y - f|, así que sus límites son simétricos alrededor del pronóstico (mlforecast 1.1.0, mlforecast/conformal_prediction.py, función compute_conformity_scores). El predeterminado, conformal_distribution, trabaja un cliente y un paso de horizonte a la vez. Para cada cliente y paso, toma los residuos absolutos de las ventanas de calibración, construye las trayectorias del pronóstico más y menos cada uno, y lee los cuantiles de esas trayectorias. No se agrupa nada entre clientes. La biblioteca estadística, statsforecast en la versión 2.1.1, llama a su clase de intervalos ConformalIntervals, no PredictionIntervals.

Para ver qué hace la biblioteca con un historial de calibración corto, ejecuta su clase con tres ventanas de calibración. Puntúa los tres puntos de corte estándar, del 29 al 31 de diciembre de 2014, cada uno a las 00:00. Son los últimos tres días de la semana reservada, y los días que este capítulo puntúa. mlforecast reajusta el modelo global en cada punto de corte y calibra cada uno con los tres anteriores.

conformal-three-windows.py Python 3.13.16 · holidays 0.110.dev20261118063242 · lightgbm 4.7.0 · mlforecast 1.1.0 · numpy 2.5.5 · pandas 2.3.3 · statsforecast 2.1.1 · utilsforecast 0.2.17 Superado
"""mlforecast's own conformal intervals, with three calibration windows, refitted at each of the three standard cutoffs.Compare the coverage at 80 and 95 with their labels, and with the highest coverage three windows allow."""import pandas as pdfrom lib.electricity import loadfrom lib.intervals import builtin_intervals, design_coverage, symmetric_ceilingfrom lib.panel import ALL30from lib.quirks import mask_clock_changesfrom lib.settings import EVAL_CUTOFFS, showraw = load(ALL30)# Every clock-change hour (four changes, 2013 and 2014) is masked as NaN. builtin_intervals keeps only rows from Oct 27, 2014 on, so no masked hour is in a window.df = mask_clock_changes(raw)[["unique_id", "ds", "y"]]# One row per client and hour. The bounds are columns named by model and level, such as LGBMRegressor-lo-80.cv = builtin_intervals(df, pd.to_datetime(EVAL_CUTOFFS))show("scored hours", len(cv))show("calibration windows per cutoff", 3)show("residuals per client and hour", 3)# Ceiling of a band of plus and minus n absolute residuals, n / (n + 1), with n = 3: at most 3 of the 4 places a new one can take.show("highest coverage three windows allow, any level", symmetric_ceiling(3), 3)for level in (80, 95):    # Simulated under exchangeable normal errors, with mlforecast's construction, to set against the measured coverage.    show(f"simulated coverage at {level}, exchangeable errors", design_coverage(level, 3, "builtin"), 3)for level in (80, 95):    lo, hi = cv[f"LGBMRegressor-lo-{level}"], cv[f"LGBMRegressor-hi-{level}"]    inside = (cv["y"] >= lo) & (cv["y"] <= hi)    show(f"coverage at {level}", inside.mean(), 3)    show(f"mean width at {level}", (hi - lo).mean())    if level == 80:        # The by-day lines are printed for the 80 level only. Each hour is grouped by its calendar day.        day = cv["ds"].dt.floor("D")        for d, share in inside.groupby(day).mean().items():            show(f"coverage at 80 on {d:%Y-%m-%d}", share, 3)        for d, err in (cv["y"] - cv["LGBMRegressor"]).abs().groupby(day).mean().items():            show(f"mean absolute error on {d:%Y-%m-%d}", err)
Salidapython conformal-three-windows.py
scored hours: 2160
calibration windows per cutoff: 3
residuals per client and hour: 3
highest coverage three windows allow, any level: 0.750
simulated coverage at 80, exchangeable errors: 0.656
simulated coverage at 95, exchangeable errors: 0.732
coverage at 80: 0.690
mean width at 80: 281.07
coverage at 80 on 2014-12-29: 0.756
coverage at 80 on 2014-12-30: 0.676
coverage at 80 on 2014-12-31: 0.637
mean absolute error on 2014-12-29: 114.62
mean absolute error on 2014-12-30: 94.42
mean absolute error on 2014-12-31: 163.37
coverage at 95: 0.750
mean width at 95: 355.39

La salida muestra el fallo antes de cualquier corrección: en las 2160 horas-cliente, las bandas al nivel 80 cubren 0.690 y al nivel 95 0.750. Ambas quedan por debajo de sus etiquetas, y las bandas al 80 tienen un ancho medio de 281.07 kWh.

El diseño fija un techo, y el resultado del 95 está en ese techo. Con tres ventanas, cada cliente y hora tiene tres residuos absolutos, y la banda no llega más allá del mayor de ellos. Para errores intercambiables, el error de prueba es el mayor de cuatro errores absolutos una de cada cuatro veces, así que la banda lo deja fuera con esa frecuencia. La cobertura más alta que permiten tres ventanas es 0.750, en cualquier nivel. Bajo ese mismo supuesto de intercambiabilidad, la cobertura esperada de la banda es 0.656 al 80 y 0.732 al 95. La simulación extrae errores normales, con la misma construcción. Las cifras medidas están un poco por encima de esos valores esperados, así que las ventanas de calibración no tuvieron errores menores que los días puntuados. Unas ventanas de calibración tranquilas empujarían la cobertura por debajo del valor esperado, no por encima. El déficit se debe a la construcción.

La cobertura por día muestra dónde se concentra el déficit. Al nivel 80 es 0.756 el 29 de diciembre, 0.676 el 30 y 0.637 el 31. Los errores de pronóstico de esos días fueron de 114.62, 94.42 y 163.37 kWh en promedio. El 31 de diciembre tiene los errores más grandes y la cobertura más baja, y tres días no bastan para separar la variación de un día a otro del diseño.

Un segundo problema viene de la calibración. Cada punto de corte calibra solo con los días anteriores a él: las bandas del 31 de diciembre usan el 28, 29 y 30. Pero el 29 y el 30 también son días puntuados. Así que las tres ventanas puntuadas no son independientes, porque la calibración de una contiene las lecturas de otra ventana puntuada. Ninguna banda usa las lecturas de su propio día, y la regla es correcta para la operación, donde esas lecturas se conocen. Para una prueba debilita el resultado. Corregirlo requeriría un ajuste de calibración separado para cada punto de corte, lo cual es más que un cambio de un argumento, así que las bandas propias del capítulo usan un conjunto de calibración fijo, como muestra Calibrar con ventanas anteriores.

Regla práctica: Construye cada banda a partir de los residuos de las ventanas que van antes de su punto de corte, y comprueba la cobertura que alcanza en ventanas que no usó antes de confiar en ella. Lee el nivel que puede alcanzar un diseño antes de leer la cobertura. Tres residuos por cliente y hora no pueden alcanzar ninguna de las dos etiquetas, así que la solución es un conjunto de calibración más grande, no una lectura distinta de la salida.

Esta parte aún no está traducida, así que está en inglés.

Calibrate on earlier windows

Último cambio en la edición 2026.11.11

The calibration windows must come before the windows you score, and they must not share a target hour with them. The book adds one more rule: a calibration window must not fall on a Portuguese public holiday, because a holiday's load follows the calendar rather than the week before it. The rule applies to the decision windows as well. The held-out evaluation calibrates on twelve ordinary days, Dec 9 to 20, 2014, which end four days before the held-out week. Both examples in this section print the holiday hours and the shared hours in their calibration, and both counts are zero.

Twelve windows with thirty clients give 360 residuals for each hour of the day. They come from twelve days, though, and the thirty clients share each day's weather and calendar. So a day-level error is still a sample of twelve. The pooled residuals have a second problem. The clients differ enormously in size. In the scored week the largest client, MT_370, averages 17499.81 kWh an hour over the three scored days. Pooled residuals in kWh are dominated by such clients, so the bands fit the large clients and misfit the small ones. The fix is to divide each client's residuals by that client's scale before pooling, and multiply the bound back by the scale of the client being forecast. The scale is the seasonal naive error on the history before the first calibration cutoff, the same kind of scale the book uses for MASE. With the scale, the thirty clients count alike.

Two choices in this design were made on the decision windows, not on the held-out evaluation. The decision windows are the four cutoffs from Nov 25 to Dec 3, 2014. Their calibration is Nov 9 to 20, 2014, twelve holiday-free days that end four days before the first decision cutoff, the same shape as the held-out design. The windows are scored on their own, and the held-out evaluation is not read. The choices are judged by the interval score and the lowest client's coverage. The interval score adds a band's width to a penalty for each reading that misses the band, the penalty growing with the distance of the miss and scaled by 2 over the miss rate (Gneiting and Raftery (2007), eq. 43). Those windows settle both choices, as the measurements below show.

conformal-decision-windows.py Python 3.13.16 · holidays 0.110.dev20261118063242 · lightgbm 4.7.0 · mlforecast 1.1.0 · numpy 2.5.5 · pandas 2.3.3 · statsforecast 2.1.1 · utilsforecast 0.2.17 Superado
"""The two calibration choices, scaling each client's residuals and the finite-sample levels, decided on the four decisionwindows (Nov 25 to Dec 3, 2014), with calibration on Nov 9 to 20. Compare the lowest client's coverage and the interval scores printed for each variant;the standard cutoffs are not read."""from lib.baselines import seasonal_scalefrom lib.electricity import loadfrom lib.intervals import DECISION_CAL, bounds, calibration_facts, coverage, interval_score, paired, total_offrom lib.panel import ALL30, DECISION_CUTOFFSfrom lib.quirks import mask_clock_changesfrom lib.scoring import book_scalefrom lib.settings import showraw = load(ALL30)# Every clock-change hour (four changes, 2013 and 2014) is masked as NaN, as in every example of this chapter.df = mask_clock_changes(raw)[["unique_id", "ds", "y"]]# One row per client and hour, with the forecast f, the reading y and the residual e.cal, sc = paired(df, DECISION_CAL), paired(df, DECISION_CUTOFFS)# Each client's MASE-style scale, from the history before the first calibration cutoff.scale = seasonal_scale(book_scale(raw, DECISION_CAL[0]))for label, value in calibration_facts(df, DECISION_CUTOFFS, DECISION_CAL).items():    show(label, value)show("residuals per hour of the day", len(cal) // 24)variants = (("unscaled", None, False), ("scaled", scale, False),            ("unscaled, finite", None, True), ("scaled, finite", scale, True))for name, s, fin in variants:    for level in (80, 95):        # scale=None pools the raw kWh residuals; finite=True applies the (n + 1) quantile correction.        lo, hi = bounds(sc, cal, level, scale=s, finite=fin)        show(f"{name}, coverage at {level}", coverage(sc["y"], lo, hi), 3)        show(f"{name}, interval score at {level}", interval_score(sc["y"], lo, hi, level))    lo, hi = bounds(sc, cal, 80, scale=s, finite=fin)    # Coverage per client, then the lowest of the thirty clients.    show(f"{name}, lowest client coverage at 80", ((sc["y"] >= lo) & (sc["y"] <= hi)).groupby(sc["unique_id"]).mean().min(), 3)# One series, so no scale: the scale exists only to pool clients of different size.tcal, tsc = total_of(cal), total_of(sc)for name, fin in (("total", False), ("total, finite", True)):    lo, hi = bounds(tsc, tcal, 80, finite=fin)    show(f"{name}, coverage at 80", coverage(tsc["y"], lo, hi), 3)    show(f"{name}, interval score at 80", interval_score(tsc["y"], lo, hi, 80))
Salidapython conformal-decision-windows.py
calibration windows: 12
holiday hours in calibration: 0
calibration hours shared with scored: 0
residuals per hour of the day: 360
unscaled, coverage at 80: 0.809
unscaled, interval score at 80: 603.88
unscaled, coverage at 95: 0.957
unscaled, interval score at 95: 1950.32
unscaled, lowest client coverage at 80: 0.021
scaled, coverage at 80: 0.834
scaled, interval score at 80: 336.72
scaled, coverage at 95: 0.954
scaled, interval score at 95: 581.28
scaled, lowest client coverage at 80: 0.365
unscaled, finite, coverage at 80: 0.811
unscaled, finite, interval score at 80: 604.19
unscaled, finite, coverage at 95: 0.959
unscaled, finite, interval score at 95: 1961.48
unscaled, finite, lowest client coverage at 80: 0.021
scaled, finite, coverage at 80: 0.835
scaled, finite, interval score at 80: 337.31
scaled, finite, coverage at 95: 0.956
scaled, finite, interval score at 95: 592.35
scaled, finite, lowest client coverage at 80: 0.375
total, coverage at 80: 0.948
total, interval score at 80: 9268.36
total, finite, coverage at 80: 0.990
total, finite, interval score at 80: 10724.99

Scaling wins on the two measures the variants were judged by, and loses only on the pooled coverage at 80. The worst-covered client's coverage at 80 rises from 0.021 to 0.365, and the interval score at 80 falls from 603.88 to 336.72. It falls at 95 as well, as the output shows.

We judged the variants by these two measures because the pooled figure hides clients. We chose them after seeing the decision numbers, so the pooled figure is reported beside them. At 80 the pooled coverage is closer to its label without the scale, at 0.809 against 0.834. The scale stays.

The finite-sample levels stay out of the bands. Each new residual is one more among n + 1, so the finite-sample levels move outward a little: each quantile level moves to floor((n + 1) * a) / n for the lower bound and ceil((n + 1) * (1 - a)) / n for the upper, where n is the number of residuals and a the tail share. Their effect on the scaled coverage at 80 is small, from 0.834 to 0.835, and the interval score at 80 gets worse, from 336.72 to 337.31. It gets worse at 95 too, as the output shows. The correction widens the bands and does not help, so the bands do not use it.

The held-out evaluation applies the same design to the standard cutoffs, which are the days the rest of the chapter scores.

conformal-earlier-windows.py Python 3.13.16 · holidays 0.110.dev20261118063242 · lightgbm 4.7.0 · mlforecast 1.1.0 · numpy 2.5.5 · pandas 2.3.3 · statsforecast 2.1.1 · utilsforecast 0.2.17 Superado
"""Conformal bands for every client, calibrated on twelve holiday-free days before the scored week, with each client'sresiduals scaled first. Read the coverage and interval score at 80 and 95 first; the unscaled, three-day andfinite-sample lines are printed for comparison."""import pandas as pdfrom lib.baselines import seasonal_scalefrom lib.electricity import loadfrom lib.intervals import CAL_CUTOFFS, bounds, calibration_facts, coverage, interval_score, pairedfrom lib.panel import ALL30from lib.quirks import mask_clock_changesfrom lib.scoring import book_scalefrom lib.settings import EVAL_CUTOFFS, showraw = load(ALL30)df = mask_clock_changes(raw)[["unique_id", "ds", "y"]]scored_cutoffs = pd.to_datetime(EVAL_CUTOFFS)cal, sc = paired(df, CAL_CUTOFFS), paired(df, scored_cutoffs)# The scale is read from the history before the first calibration cutoff, as the book's MASE scale is.scale = seasonal_scale(book_scale(raw, CAL_CUTOFFS[0]))# The largest client is the one with the highest mean reading over the scored windows.big = sc.groupby("unique_id")["y"].mean().idxmax()for label, value in calibration_facts(df, scored_cutoffs).items():    show(label, value)show("calibration residuals per hour of the day", len(cal) // 24)show("largest client", big)show("mean hourly load of the largest client", sc.groupby("unique_id")["y"].mean().max())for level in (80, 95):    lo, hi = bounds(sc, cal, level, scale=scale)    show(f"coverage at {level}", coverage(sc["y"], lo, hi), 3)    show(f"mean width at {level}", (hi - lo).mean())    show(f"interval score at {level}", interval_score(sc["y"], lo, hi, level))lo, hi = bounds(sc, cal, 80, scale=scale)per_client = ((sc["y"] >= lo) & (sc["y"] <= hi)).groupby(sc["unique_id"]).mean()show("lowest client coverage at 80", per_client.min(), 3)# No scale here: the pooled residuals stay in kWh, which is what lets the large clients set the bands.lo, hi = bounds(sc, cal, 80)unscaled = ((sc["y"] >= lo) & (sc["y"] <= hi)).groupby(sc["unique_id"]).mean()show("largest client coverage at 80, unscaled residuals", unscaled[big], 3)# The three calibration days nearest the scored week: Dec 18, 19 and 20, 2014.recent = cal[cal["cutoff"] >= "2014-12-18"]lo, hi = bounds(sc, recent, 80, scale=scale)show("coverage at 80 from three calibration days", coverage(sc["y"], lo, hi), 3)lo, hi = bounds(sc, cal, 80, scale=scale, finite=True)show("coverage at 80 with finite-sample levels", coverage(sc["y"], lo, hi), 3)
Salidapython conformal-earlier-windows.py
calibration windows: 12
holiday hours in calibration: 0
calibration hours shared with scored: 0
calibration residuals per hour of the day: 360
largest client: MT_370
mean hourly load of the largest client: 17499.81
coverage at 80: 0.739
mean width at 80: 267.62
interval score at 80: 673.89
coverage at 95: 0.902
mean width at 95: 532.00
interval score at 95: 1326.80
lowest client coverage at 80: 0.472
largest client coverage at 80, unscaled residuals: 0.000
coverage at 80 from three calibration days: 0.711
coverage at 80 with finite-sample levels: 0.741

The scaled bands still fall short of both labels on the standard cutoffs: they cover 0.739 of client-hours at 80 and 0.902 at 95. Their mean widths are 267.62 kWh and 532.00 kWh.

The scores are 673.89 at 80 and 1326.80 at 95. They are in kWh, so the large clients dominate them. Lower is better, and the score rewards a band that is both narrow and right.

The pooled bands still have to be read per client. The lowest client coverage at 80 is 0.472, for the client the scaled bands fit least well. With unscaled residuals, the largest client is covered in 0.000 of its hours at 80. The pooled kWh bands were set by the large clients, and they miss the largest client entirely.

Two more checks on the standard cutoffs test the design. Calibrating on only the three days nearest the scored week, Dec 18 to 20, gives 0.711 at 80, against 0.739 with all twelve. Three days are a smaller sample, and the coverage is a little lower. The finite-sample levels give 0.741 at 80, a small change that agrees with the decision windows: the correction does little for the client bands.

Working rule: Calibrate on windows that come before the scored ones, with no holiday in them, and scale each client before pooling its residuals. Make each design choice on windows that are not the ones you report. Report how many windows and residuals went into the bands and the coverage they gave on the scored days, even when that coverage falls short of the level.

Medir la cobertura en días no usados para la calibración

Último cambio en la edición 2026.11.6

La cobertura se mide en días que la calibración nunca usó. Los cortes estándar dan tres días, y cada día da 24 horas por cliente, así que las 2160 horas-cliente no son tantas observaciones independientes. Los treinta clientes comparten el calendario y el clima, por lo que las horas de un mismo día concuerdan entre sí. Para los errores a nivel de día la muestra son tres días, lo cual no permite medir un nivel de cobertura. Tres días pueden mostrar que una banda se quedó corta en esos días, pero no dicen cuánto se queda corta una banda durante un periodo más largo.

El proveedor compra el total, así que la cobertura del total es la que más importa. Sus bandas se construyen con sus propios residuos sobre los mismos doce días, con los cuantiles leídos directamente, y se ofrecen solo al 80, porque doce residuos no pueden sostener el 95. Con límites con signo, la banda que va desde el residuo más pequeño hasta el más grande cubre como máximo el 0.846 de las veces, si los residuos son intercambiables, y una banda del 95 o del 90 exige más.

Las bandas del total cubren el 0.667 de sus 72 horas evaluadas al 80. Para errores intercambiables, la misma construcción cubre el 0.682, así que la mayor parte de la brecha respecto al 80 proviene de la muestra de doce residuos. La sección sobre el costo pone estas bandas en uso.

Los errores del total varían según el día. El error absoluto medio del total fue de 2415.51 kWh en las ventanas de calibración y de 2985.88 kWh en los días evaluados. El 31 de diciembre explica la mayor parte de la brecha entre los días evaluados y las ventanas de calibración.

Día evaluado Error del total, kWh Cobertura al 80
29 de diciembre de 2014 2448.53 0.625
30 de diciembre de 2014 2149.78 0.708
31 de diciembre de 2014 4359.32 0.667

La cobertura no sigue a los errores. El 29 de diciembre tiene la cobertura más baja con un error intermedio, y el 31 de diciembre tiene el error más grande con una cobertura intermedia. Cada día tiene 24 horas, y tres días son muy pocos para distinguir ambas cosas.

Los niveles de muestra finita cambiarían la cifra del total. En los días evaluados dan 0.736 al 80. La elección se hizo sobre las ventanas de decisión, donde la corrección ensanchó las bandas del total y empeoró su puntuación de intervalo, así que las bandas no la usan. Las ventanas de decisión también muestran que la dirección de la brecha no es fija. Allí, las bandas al 80 del total cubrieron el 0.948 de las horas, más que su etiqueta, y los niveles finitos llevaron esa cifra a 0.990.

Angelopoulos y Bates (2022) muestran que la predicción conforme dividida cubre el punto de prueba con probabilidad de al menos 1 - alpha cuando los puntos de calibración y de prueba son independientes e idénticamente distribuidos, o, de forma más general, intercambiables. También señalan que los puntos adyacentes en una serie temporal no son intercambiables, y usan como ejemplo una serie de temperatura. Lo mismo ocurre con la carga horaria: cada hora arrastra la anterior, y las horas de un día comparten el clima y el calendario. Barber y coautores (2023) llaman brecha de cobertura a la pérdida de cobertura cuando falla la intercambiabilidad. Su cota no supone una distribución conjunta concreta. Es pequeña cuando los puntos de calibración recientes se ponderan de una forma que coincide con la distribución del punto de prueba, como en una deriva lenta. Ese resultado es teórico, y este capítulo no lo pone a prueba. Un preprint de 2026, una revisión de métodos conformes para series dependientes, afirma que la dependencia temporal viola el supuesto de intercambiabilidad. No ha sido revisado por pares, y lo citamos solo para ese punto.

Por tanto, el libro no promete nada sobre la cobertura que no mida. La cobertura de este capítulo es lo que mostraron tres días, bajo la calibración descrita en Calibrar sobre ventanas anteriores.

Regla práctica: Informa la cobertura sobre ventanas que la calibración nunca usó, con el número de ventanas y la cobertura de cada una. Mantén la misma medida en un registro continuo una vez que el pronóstico se ejecute cada día, como hace el Capítulo 10. Lee tres días evaluados como una advertencia, no como una medida del nivel que se te prometió.

Esta parte aún no está traducida, así que está en inglés.

Choose the level from the cost of error

Último cambio en la edición 2026.11.11

The supplier buys one amount for each hour, and the costs of the two errors set that amount. Let cu be the cost of one kWh bought short and co the cost of one kWh bought and not used. Let F be the distribution of demand. Differentiating the expected cost with respect to the purchase q gives co F(q) - cu (1 - F(q)), which is zero where F(q) = cu / (cu + co), the smallest expected cost. The level cu / (cu + co) is the critical fractile of the newsvendor model. The HKUST IEEM 101 notes on the newsvendor model give the same proof, writing the cost of excess as c0. This chapter writes it co. The purchase is therefore the quantile at level tau = cu / (cu + co).

With the illustrative costs from Why one number is not enough, tau is 0.75. The rule says to buy the quantile of the demand at that level, for each hour. The quantile at level tau is the purchase that minimises the quantile loss at that level, as Gneiting and Raftery (2007) show. The quantile loss is tau * (y - q) when the reading y is at or above the purchase q, and (1 - tau) * (q - y) when it is below. The quantile loss is not a cost in kWh or in money. It is the rule that the quantile minimises, and it has the same shape as the supplier's cost. Multiplying it by cu + co gives the cost exactly, which the example prints beside the mean cost.

Does buying at the critical fractile cost less than buying at the median or higher, on days the bands never saw? Below, the purchase is set for each hour from these costs, and the scored days answer the question. The level 0.95 is not offered, as Measure coverage on held-out days explains.

buy-ahead-level-by-cost.py Python 3.13.16 · holidays 0.110.dev20261118063242 · lightgbm 4.7.0 · mlforecast 1.1.0 · numpy 2.5.5 · pandas 2.3.3 · statsforecast 2.1.1 · utilsforecast 0.2.17 Superado
"""The buy level for the total, set from the two costs: the critical fractile, cu / (cu + co), is the quantile that minimisesthe expected cost. Compare the mean cost and the hours short at each level; the costs are illustrative, not prices."""import pandas as pdfrom lib.electricity import loadfrom lib.intervals import CAL_CUTOFFS, COST_EXCESS, COST_SHORT, buy_report, critical_fractile, pairedfrom lib.panel import ALL30from lib.quirks import mask_clock_changesfrom lib.settings import EVAL_CUTOFFS, showraw = load(ALL30)# Every clock-change hour (four changes, 2013 and 2014) is masked as NaN, as in every example of this chapter.df = mask_clock_changes(raw)[["unique_id", "ds", "y"]]# Calibration on Dec 9 to 20, 2014; scored on the three standard cutoffs.pairs_cal, pairs_sc = paired(df, CAL_CUTOFFS), paired(df, pd.to_datetime(EVAL_CUTOFFS))show("cost of a kWh short", COST_SHORT)show("cost of a kWh unused", COST_EXCESS)# The quantile level cu / (cu + co), from the two costs printed above.show("critical fractile", critical_fractile())# buy_report returns the printed rows as (label, value, decimal places).for label, value, digits in buy_report(pairs_cal, pairs_sc):    show(label, value, digits)
Salidapython buy-ahead-level-by-cost.py
cost of a kWh short: 3.00
cost of a kWh unused: 1.00
critical fractile: 0.75
scored hours: 72
residuals per hour for the total: 12
highest coverage the total's residuals allow: 0.846
simulated coverage at 80, exchangeable errors: 0.682
mean absolute error of the total, calibration days: 2415.51
mean absolute error of the total, scored days: 2985.88
total coverage at 80: 0.667
total coverage at 80 with finite-sample levels, not used: 0.736
total coverage at 80 on 2014-12-29: 0.625
total coverage at 80 on 2014-12-30: 0.708
total coverage at 80 on 2014-12-31: 0.667
total mean absolute error on 2014-12-29: 2448.53
total mean absolute error on 2014-12-30: 2149.78
total mean absolute error on 2014-12-31: 4359.32
mean cost at 0.50: 5087.95
hours short at 0.50: 0.528
mean cost at 0.75: 3843.61
hours short at 0.75: 0.403
mean cost at 0.90: 3667.43
hours short at 0.90: 0.222
quantile loss at critical fractile, times both costs: 3843.61
mean hourly total bound from the total: 31983.95
mean hourly total bound from the sum of client bounds: 32388.77
hours short at critical fractile, sum of client bounds: 0.306
mean cost at critical fractile, sum of client bounds: 3729.17

The identity holds: multiplied by the sum of the two costs, the quantile loss at the critical fractile is 3843.61, the same as the mean cost at that level, 3843.61. The rule is correct as arithmetic.

Level Mean cost Hours short
0.50 5087.95 0.528
0.75, the critical fractile 3843.61 0.403
0.90 3667.43 0.222

The result on the scored days is less comfortable. The rule chose the critical fractile, and on these three days 0.90 cost less, at 3667.43 against 3843.61. At the critical fractile the purchase was short in 0.403 of the hours, where a calibrated level would fall short in one hour in four. That is the coverage shortfall from Measure coverage on held-out days seen as money. We do not move the level to 0.90. The three scored days are the test, and a level chosen because it wins on them has been chosen on the test. The honest reading is that the bands were too narrow here, so the purchase was too low, and that the level is right only when the bands are.

Should the purchase follow the clients' bounds instead? Summing each client's bound at the critical fractile gives a bound of 32388.77 kWh an hour, against 31983.95 from the total's own residuals. Summed quantiles equal the total's quantile when the errors move together perfectly. For an upper quantile, with errors that partly cancel, the sum usually sits above it, as it does here.

On the scored days the summed bound did better, with hours short at 0.306 against 0.403, and a mean cost of 3729.17 against 3843.61. That advantage comes from its higher level, not from a better calibration, and the scored days cannot show that it holds in general. We keep the total's own bound, because the purchase is made against the total's residuals, and we do not switch to the bound that did better here.

Working rule: Set the buy level from the two costs, as tau = cu / (cu + co), fix it before you score the days, and calibrate the total's bands on the total's own residuals. Show the realised cost at other levels as a check, but never move the level to whichever one would have won on the days you score.

Qué sale mal en producción

Último cambio en la edición 2026.11.5
  • La temporada de calibración no es la temporada evaluada. Los días festivos se excluyen de la calibración, lo que mantiene honesta la prueba, pero los errores del total varían de una ventana a otra, y pueden ser mayores en los días evaluados que en las ventanas de calibración. Una banda calibrada en un periodo tranquilo no cubre uno más difícil. Detéctalo comparando la cobertura con el nivel nominal cada día y observando el promedio acumulado. Una cobertura que cae por debajo de su etiqueta durante una semana es la señal, y los errores de esa semana son el primer lugar donde debes mirar.
  • Las bandas agrupadas ocultan a los clientes. Las bandas agrupadas en kWh quedan determinadas por los clientes más grandes. Con residuos sin escalar, las bandas del cliente más grande cubren 0.000 de sus horas al 80. Con residuos escalados, la cobertura mínima por cliente al 80 es 0.472, así que incluso el grupo escalado oculta a un cliente que no alcanza la cobertura. Lee la cobertura por cliente, no solo la cifra agrupada.
  • Tres días dicen poco. Una cifra de cobertura de tres días evaluados puede parecer un hallazgo, pero son tres observaciones del error a nivel diario. Usa la cobertura sobre muchas ventanas y trata una serie corta como un motivo para revisar, no como un resultado.
  • La dependencia rompe la garantía simple. La carga horaria tiene autocorrelación, y los residuos de calibración de horas vecinas no son independientes. Las bandas no tienen la garantía del teorema de los libros de texto. Su cobertura puede desviarse cuando cambian el clima o el calendario, y solo la cobertura medida te indica cuándo ocurre. Un tramo de días cuyos errores comparten signo es el patrón a vigilar, y el registro de seguimiento es donde aparece.
  • El total tiene pocos residuos por hora. Una ventana de calibración da un residuo para el total en cada hora, así que doce ventanas dan doce. Con residuos con signo, la cobertura más alta que permiten doce residuos es 0.846, por lo que las bandas del total se detienen en 80, y conviene hacer una comprobación de nivel antes de ofrecer cualquier banda. Más ventanas de calibración darían al total una muestra mayor, pero cada una debe ser un día corriente anterior a la semana evaluada.
  • La calibración móvil puede usar los días que evalúas. La regla integrada en Construir intervalos a partir de residuos calibra cada corte con los tres cortes anteriores. En operación eso está bien, porque esas lecturas son conocidas. En una prueba, hace que las ventanas evaluadas dependan unas de otras. Mantén fijo el conjunto de calibración y anterior a cada ventana evaluada.

Decisiones que tomó este capítulo

Último cambio en la edición 2026.11.5
  • Ventanas de calibración. Doce días ordinarios, del 9 al 20 de diciembre de 2014, antes de la semana retenida (held-out). Se excluyen los festivos, y ninguna hora de calibración se puntúa. Las ventanas de decisión también usan doce días, del 9 al 20 de noviembre de 2014. La longitud es una elección, no un resultado: los datos no muestran que doce días sea la mejor longitud.
  • Escala antes de agrupar. Los residuos de cada cliente se dividen por su error de referencia estacional (seasonal naive) sobre el historial anterior al primer punto de corte de calibración, la misma escala que el libro usa para MASE. Las ventanas de decisión lo establecieron, y el total no necesita escala.
  • Sin corrección de muestra finita en las bandas. La corrección se probó en las ventanas de decisión, para los clientes y para el total, y no mejoró la puntuación del intervalo. Solo se usa para determinar qué niveles puede sostener un conjunto de residuos.
  • Residuos con signo. Las bandas y el cuantil de compra usan residuos con signo, por lo que los límites inferior y superior no tienen por qué ser simétricos. Los métodos conformales de mlforecast usan residuos absolutos y dan bandas simétricas. La ejecución integrada en Construir intervalos a partir de residuos sirve para comparar.
  • La compra es para el total. El nivel de compra y su cuantil se fijan con los residuos del total. Las bandas de los clientes sirven para leer los pronósticos, no para comprar.
  • Los costos son supuestos. Los costos de 3.00 y 1.00 se indican en Por qué un solo número no basta, como juicio, y no se miden.
  • La clase de intervalos de la biblioteca estadística. La clase de statsforecast es ConformalIntervals. Su nombre difiere del PredictionIntervals de mlforecast, y este capítulo usa cada nombre para su propia biblioteca.
  • Un tercer ejemplo. La decisión de compra necesitaba su propia medición, así que se añadió buy-ahead-level-by-cost, junto con conformal-decision-windows, que toma las decisiones de diseño sobre ventanas que la evaluación reservada no usa.
  • No se afirma cobertura de festivos. El 25 de diciembre de 2014 está en la semana reservada, pero fuera de las ventanas de calibración y de puntuación. El libro no informa nada sobre cómo cubren las bandas el festivo en sí.
  • Bandas antes que niveles. Un nivel de compra es tan bueno como la banda que tiene debajo, y una banda solo es tan buena como las ventanas que la establecen.

Este capítulo, en esta edición

Edición 2026.11.11Ejemplos verificados el 20 de nov de 2026Superan la prueba 4 de 4 ejemplos ejemplos de este capítulo

Traducido del libro en inglés, edición 2026.11.11.

Cita esta sección

Formato

Cada formato cita el libro en inglés, que esta traducción sigue.

Cada formato nombra esta edición. Su enlace abre la edición actual, donde el encabezado de cada sección indica cuándo cambió su texto por última vez. Las fechas de acceso y de recuperación son el día en que lo abres.

En esta página

Capítulo 8 de 10: Cuantifica la incertidumbre de la previsión

  1. Why one number is not enough
  2. Construir intervalos a partir de residuos
  3. Calibrate on earlier windows
  4. Medir la cobertura en días no usados para la calibración
  5. Choose the level from the cost of error
  6. Qué sale mal en producción
  7. Decisiones que tomó este capítulo

Volver arribaTodos los capítulos