feat(pronostico): Fase B — Holt-Winters con gate anti-humo + pronóstico con incertidumbre
Capa 2 del bloque Ola 1 + Fase B. Pronóstico en LITROS por combustible + total con Holt-Winters aditivo de estacionalidad semanal (m=7); deriva a PESOS con propagación de incertidumbre. app/pronostico.py nuevo; reusa la serie determinista (analitica) y el agregado. - holt_winters_fit/hw_forecast: HW aditivo (nivel/tendencia/estacional semanal), params FIJOS (α=0.2 β=0.02 γ=0.3) sin tuning sobre el test -> comparación honesta. - backtest_h: walk-forward h-pasos; elegir_metodo + evaluar_gate aplican el GATE ANTI-HUMO por horizonte y por serie estación×combustible: HW entra solo donde le gana a MM28 (vara 13.1%), baseline donde no. Gate verificado: HW gana los 3 horizontes (corto 9.6% / medio 10.3% / largo 10.7% vs ~13.3% MM28) y se queda MM28 en zavaleta·Premium (HW 12.3% > MM28 11.1%). - pronosticar: por combustible + total, litros [inf,sup] y pesos [inf,sup] (solo-límites). El precio = efectivo realizado (ingreso/litros) promedio de últimos X días por horizonte + su volatilidad; se propagan volumen ⊕ precio -> banda de pesos ≥ banda de litros (en demo el precio estable la estrecha; el mecanismo es correcto). - comparativos: la proyección de cierre del día hereda banda del modelo (punto 8); verificado que el cierre determinista real cae dentro de la banda proyectada. - catálogo: 🔮 pronostico_venta (WOW) + parámetro 'dias' (1-90) en el dispatcher/tools_schema; menú auto-actualizado. "¿cuánto voy a vender mañana?". - tests/backtest_faseB.py: arnés re-ejecutable del gate (MAPE por horizonte + por serie). - aislamiento: pronostico_venta de B nunca trae datos de demo (17 funciones × 2 clientes). Verificado en caliente (PG16): gate y pronóstico reproducibles (misma serie -> mismo resultado); proyección de cierre con banda; aislamiento + backtest_faseB + backtest_pronosticos + cerebro_mock + worker_mock EXIT 0. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
1 parent
c537b73cfa
commit
326ff3664a
5 files changed
+320
-2
No files matched your search
+27
-1
@@ -29,7 +29,7 @@ import unicodedata
|
||||
from dataclasses import dataclass, field
|
||||
from typing import Callable
|
||||
|
||||
from app import comparativos, consultas
|
||||
from app import comparativos, consultas, pronostico
|
||||
|
||||
COMUNES, FUNCIONALES, WOW = "comunes", "funcionales", "wow"
|
||||
|
||||
@@ -95,6 +95,12 @@ def _comparativo_mes(conn, ctx, cid, estacion=None):
|
||||
return comparativos.comparativo_mes(ctx.reg, conn, cid, station=estacion, ahora=ctx.now)
|
||||
|
||||
|
||||
def _pronostico_venta(conn, ctx, cid, estacion=None, dias=1):
|
||||
"""Pronóstico de venta a futuro (Fase B): litros y pesos con banda, por combustible + total.
|
||||
Gate anti-humo: Holt-Winters donde le gana a MM28, baseline si no."""
|
||||
return pronostico.pronosticar(ctx.reg, conn, cid, dias=dias, station=estacion)
|
||||
|
||||
|
||||
def _comparar_estaciones(conn, ctx, cid):
|
||||
rent = sorted(consultas.rentabilidad(conn, ctx, cid), key=lambda r: -r["ingreso"])
|
||||
return {"estaciones": [{"station_id": r["station_id"], "nombre": r["nombre"],
|
||||
@@ -185,6 +191,7 @@ class Funcion:
|
||||
ejecutor: Callable
|
||||
usa_estacion: bool = False
|
||||
usa_periodo: bool = False
|
||||
usa_dias: bool = False
|
||||
# --- metadatos del MENÚ DE AYUDA (aditivos; no afectan al LLM ni a la lógica) ---
|
||||
emoji: str = "" # viñeta funcional para escanear el menú
|
||||
resumen: str = "" # qué hace, breve y natural (para el menú)
|
||||
@@ -257,6 +264,15 @@ _CATALOGO = [
|
||||
"Úsala para '¿estoy perdiendo producto hoy?', '¿hubo faltante?'.",
|
||||
_mermas, usa_estacion=True,
|
||||
emoji="💧", resumen="Mermas y faltantes de hoy", ejemplo="¿hubo merma hoy?"),
|
||||
Funcion("pronostico_venta", WOW,
|
||||
"Pronóstico de CUÁNTO se va a VENDER a futuro (litros y pesos, por combustible y total, "
|
||||
"con rango de incertidumbre). Holt-Winters con estacionalidad semanal donde le gana al "
|
||||
"baseline en backtest, baseline si no (gate anti-humo). Úsala para '¿cuánto voy a vender "
|
||||
"mañana?', '¿cuánto venderé la próxima semana?', '¿qué espero este mes?'. El parámetro "
|
||||
"'dias' fija el horizonte (1=mañana). Presenta el rango, no solo el número central.",
|
||||
_pronostico_venta, usa_estacion=True, usa_dias=True,
|
||||
emoji="🔮", resumen="Cuánto vas a vender (pronóstico con rango)",
|
||||
ejemplo="¿cuánto voy a vender mañana?"),
|
||||
# 🔴 WOW — insights de alto valor (mes cerrado)
|
||||
Funcion("costo_fugas", WOW,
|
||||
"Cuánto te costaron las fugas el MES cerrado: merma en pesos + faltantes de caja + "
|
||||
@@ -362,6 +378,11 @@ def tools_schema(ctx, cliente_id, niveles=None) -> list:
|
||||
"type": "string", "pattern": r"^\d{4}-\d{2}$",
|
||||
"description": "Mes en formato YYYY-MM; omite para el último mes cerrado.",
|
||||
}
|
||||
if f.usa_dias:
|
||||
props["dias"] = {
|
||||
"type": "integer", "minimum": 1, "maximum": 90,
|
||||
"description": "Días a futuro a pronosticar (1=mañana, 7=próxima semana, 30=mes). Default 1.",
|
||||
}
|
||||
tools.append({"name": f.nombre, "nivel": f.nivel, "description": f.descripcion,
|
||||
"parameters": {"type": "object", "properties": props, "required": []}})
|
||||
return tools
|
||||
@@ -392,6 +413,11 @@ def ejecutar(conn, ctx, cliente_id, nombre, args=None, niveles=None) -> dict:
|
||||
kwargs["estacion"] = None
|
||||
if f.usa_periodo:
|
||||
kwargs["periodo"] = args.get("periodo") or ""
|
||||
if f.usa_dias:
|
||||
try:
|
||||
kwargs["dias"] = max(1, min(90, int(args.get("dias") or 1)))
|
||||
except (TypeError, ValueError):
|
||||
kwargs["dias"] = 1
|
||||
|
||||
try:
|
||||
data = f.ejecutor(conn, ctx, cliente_id, **kwargs)
|
||||
|
||||
@@ -127,6 +127,13 @@ def proyeccion_cierre_dia(reg, conn, cliente_id, station=None, ahora=None) -> di
|
||||
confiable = frac >= UMBRAL_FRACCION_CONFIABLE and acum["ingreso"] > 0
|
||||
proy = {"ingreso": round(acum["ingreso"] / frac) if frac > 0 else None,
|
||||
"litros": round(acum["litros"] / frac, 1) if frac > 0 else None}
|
||||
# punto 8: la proyección hereda una banda del modelo de Fase B (incertidumbre a 1 día)
|
||||
if confiable and proy["ingreso"]:
|
||||
from app import pronostico
|
||||
rel = pronostico.incertidumbre_relativa_dia(reg, conn, cliente_id, station, op_day - dt.timedelta(days=1))
|
||||
if rel:
|
||||
proy["inf"] = round(proy["ingreso"] * (1 - rel))
|
||||
proy["sup"] = round(proy["ingreso"] * (1 + rel))
|
||||
# guarda de arranque/ráfaga: acumulado muy por encima de lo típico-esperado a esta altura
|
||||
alerta_arranque = False
|
||||
if tipico and tipico["ingreso"] > 0 and frac > 0:
|
||||
|
||||
@@ -0,0 +1,231 @@
|
||||
"""Pronóstico (Fase B, Roadmap analítica) — Holt-Winters con gate anti-humo.
|
||||
|
||||
Pronóstico en LITROS (no pesos) por combustible + total, con Holt-Winters aditivo de
|
||||
estacionalidad SEMANAL (m=7) — captura el patrón día-de-semana que los baselines de la Fase A
|
||||
(media móvil) ignoran. Ventana base por horizonte: corto/medio/largo miran distinta historia.
|
||||
|
||||
GATE ANTI-HUMO (la regla innegociable de la Fase A): para CADA horizonte y CADA serie
|
||||
estación×combustible, se mide el MAPE walk-forward de Holt-Winters contra el baseline MM28
|
||||
(13.1% agregado, la vara). Holt-Winters SOLO entra donde le gana; si no, se usa el baseline y se
|
||||
reporta. Parámetros HW FIJOS (sin espiar el test) -> comparación honesta.
|
||||
|
||||
Derivación a PESOS: precio efectivo realizado (ingreso/litros) promedio de los últimos X días por
|
||||
horizonte + su volatilidad. Se propagan AMBAS incertidumbres (volumen + precio): el rango de
|
||||
pesos es más ancho que el de litros. Salida = dos rangos solo-límites [inf, sup].
|
||||
|
||||
Determinista y reproducible: serie regenerada (analitica), precios deterministas, HW sin azar.
|
||||
Multi-tenant: todo scopeado por cliente_id.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import datetime as dt
|
||||
import math
|
||||
|
||||
from app import agregados, analitica
|
||||
|
||||
# Horizonte -> días a futuro (h) + ventana base de historia que mira el modelo + días de
|
||||
# precio para el promedio/volatilidad. Corto reacciona a lo reciente; largo mira más atrás.
|
||||
HORIZONTES = {
|
||||
"corto": {"h": 7, "ventana": 42, "precio_dias": 7},
|
||||
"medio": {"h": 30, "ventana": 90, "precio_dias": 14},
|
||||
"largo": {"h": 90, "ventana": 180, "precio_dias": 28},
|
||||
}
|
||||
M_SEMANA = 7 # estacionalidad semanal
|
||||
HW_ALPHA, HW_BETA, HW_GAMMA = 0.2, 0.02, 0.3 # FIJOS (sin tuning sobre el test)
|
||||
Z_BANDA = 1.28 # ~80% central para los límites de la banda
|
||||
BASELINE = "media_movil_28" # la vara (MM28, 13.1% agregado en Fase A)
|
||||
|
||||
|
||||
# --------------------------------------------------------------- Holt-Winters aditivo
|
||||
def holt_winters_fit(y: list, m: int = M_SEMANA, alpha=HW_ALPHA, beta=HW_BETA, gamma=HW_GAMMA):
|
||||
"""Ajusta HW aditivo (nivel/tendencia/estacional). Devuelve (nivel, tendencia, estacionales, n)
|
||||
o None si no hay al menos 2 estaciones completas."""
|
||||
n = len(y)
|
||||
if n < 2 * m:
|
||||
return None
|
||||
s1 = sum(y[:m]) / m
|
||||
s2 = sum(y[m:2 * m]) / m
|
||||
level = s1
|
||||
trend = (s2 - s1) / m
|
||||
seasonals = [y[i] - s1 for i in range(m)] # estacional inicial aditivo
|
||||
for t in range(n):
|
||||
val = y[t]
|
||||
sidx = t % m
|
||||
s_prev = seasonals[sidx]
|
||||
level_new = alpha * (val - s_prev) + (1 - alpha) * (level + trend)
|
||||
trend = beta * (level_new - level) + (1 - beta) * trend
|
||||
seasonals[sidx] = gamma * (val - level_new) + (1 - gamma) * s_prev
|
||||
level = level_new
|
||||
return level, trend, seasonals, n
|
||||
|
||||
|
||||
def hw_forecast(y: list, h: int, m: int = M_SEMANA, **kw):
|
||||
"""Pronóstico h pasos adelante con HW aditivo. None si la serie es muy corta."""
|
||||
fit = holt_winters_fit(y, m, **kw)
|
||||
if fit is None:
|
||||
return None
|
||||
level, trend, seasonals, n = fit
|
||||
return level + h * trend + seasonals[(n + h - 1) % m]
|
||||
|
||||
|
||||
# --------------------------------------------------------------- backtest h-pasos
|
||||
def backtest_h(valores: list, modelo, h: int, test_size: int = 28, min_train: int = 2 * M_SEMANA):
|
||||
"""Walk-forward h-pasos: para cada día t de los últimos `test_size`, entrena en
|
||||
valores[:t-h+1] (lo que el modelo SÍ vio, h días antes) y pronostica valores[t].
|
||||
Devuelve (actuales, pronosticos). `modelo(historia, h) -> float|None`."""
|
||||
n = len(valores)
|
||||
inicio = max(min_train + h, n - test_size)
|
||||
act, pron = [], []
|
||||
for t in range(inicio, n):
|
||||
hist = valores[:t - h + 1]
|
||||
if len(hist) < min_train:
|
||||
continue
|
||||
f = modelo(hist, h)
|
||||
if f is not None:
|
||||
act.append(valores[t]); pron.append(f)
|
||||
return act, pron
|
||||
|
||||
|
||||
def _modelo_hw(ventana: int):
|
||||
return lambda hist, h: hw_forecast(hist[-ventana:], h)
|
||||
|
||||
|
||||
def _modelo_baseline(hist, h): # MM28: plano, ignora h (la vara de Fase A)
|
||||
return analitica.media_movil(hist, 28)
|
||||
|
||||
|
||||
# --------------------------------------------------------------- selección por serie (gate)
|
||||
def elegir_metodo(valores: list, h: int, ventana: int, test_size: int = 28) -> dict:
|
||||
"""Gate anti-humo para UNA serie: backtest HW vs MM28 a horizonte h; gana el de menor MAPE.
|
||||
Devuelve {metodo, mape_hw, mape_baseline, residual_std, n}. residual_std del método ganador
|
||||
(para dimensionar la banda)."""
|
||||
a_hw, p_hw = backtest_h(valores, _modelo_hw(ventana), h, test_size)
|
||||
a_b, p_b = backtest_h(valores, _modelo_baseline, h, test_size)
|
||||
mape_hw = analitica.mape(a_hw, p_hw)
|
||||
mape_b = analitica.mape(a_b, p_b)
|
||||
gana_hw = mape_hw is not None and (mape_b is None or mape_hw < mape_b)
|
||||
metodo = "holt_winters" if gana_hw else BASELINE
|
||||
act, pron = (a_hw, p_hw) if gana_hw else (a_b, p_b)
|
||||
resid = [a - p for a, p in zip(act, pron)]
|
||||
std = (sum(r * r for r in resid) / len(resid)) ** 0.5 if resid else 0.0
|
||||
return {"metodo": metodo, "mape_hw": mape_hw, "mape_baseline": mape_b,
|
||||
"mape": mape_hw if gana_hw else mape_b, "residual_std": std, "n": len(act)}
|
||||
|
||||
|
||||
def evaluar_gate(serie_litros: dict, horizontes: dict | None = None) -> dict:
|
||||
"""Gate por HORIZONTE sobre todas las series estación×combustible (litros). Devuelve, por
|
||||
horizonte: MAPE agregado HW vs MM28, ganador agregado, y el detalle por serie. Para el arnés."""
|
||||
horizontes = horizontes or HORIZONTES
|
||||
out = {}
|
||||
for nombre, cfg in horizontes.items():
|
||||
por_serie, mapes_hw, mapes_b, gana_hw_n = {}, [], [], 0
|
||||
for clave, vals in serie_litros.items():
|
||||
d = elegir_metodo(vals, cfg["h"], cfg["ventana"])
|
||||
por_serie[clave] = d
|
||||
if d["mape_hw"] is not None:
|
||||
mapes_hw.append(d["mape_hw"])
|
||||
if d["mape_baseline"] is not None:
|
||||
mapes_b.append(d["mape_baseline"])
|
||||
if d["metodo"] == "holt_winters":
|
||||
gana_hw_n += 1
|
||||
agg_hw = sum(mapes_hw) / len(mapes_hw) if mapes_hw else None
|
||||
agg_b = sum(mapes_b) / len(mapes_b) if mapes_b else None
|
||||
out[nombre] = {"h": cfg["h"], "ventana": cfg["ventana"],
|
||||
"mape_hw_agregado": agg_hw, "mape_baseline_agregado": agg_b,
|
||||
"ganador_agregado": ("holt_winters" if agg_hw is not None and
|
||||
(agg_b is None or agg_hw < agg_b) else BASELINE),
|
||||
"series_gana_hw": gana_hw_n, "series_total": len(serie_litros),
|
||||
"por_serie": por_serie}
|
||||
return out
|
||||
|
||||
|
||||
# --------------------------------------------------------------- series por combustible
|
||||
def _serie_por_combustible(reg, conn, cliente_id, ventana: int, hasta=None, station=None):
|
||||
"""{fuel: [(dia, litros, ingreso)]} del cliente (suma de estaciones), ascendente."""
|
||||
serie = analitica.serie_diaria(reg, cliente_id, ventana=ventana, hasta=hasta)
|
||||
porfuel: dict = {}
|
||||
for (sid, fuel), puntos in serie.items():
|
||||
if station and sid != station:
|
||||
continue
|
||||
acc = porfuel.setdefault(fuel, {})
|
||||
for fecha, litros, ingreso in puntos:
|
||||
a = acc.setdefault(fecha, [0.0, 0.0])
|
||||
a[0] += litros; a[1] += ingreso
|
||||
return {fuel: [(d, v[0], v[1]) for d, v in sorted(acc.items())] for fuel, acc in porfuel.items()}
|
||||
|
||||
|
||||
# --------------------------------------------------------------- precio + volatilidad
|
||||
def _precio_efectivo(serie_fuel: list, dias: int) -> tuple[float, float]:
|
||||
"""Precio efectivo realizado (ingreso/litros) promedio de los últimos `dias` + su volatilidad
|
||||
(desv. estándar diaria). Devuelve (precio_medio, sigma_precio)."""
|
||||
ult = serie_fuel[-dias:]
|
||||
precios = [ing / lit for _, lit, ing in ult if lit > 0]
|
||||
if not precios:
|
||||
return 0.0, 0.0
|
||||
media = sum(precios) / len(precios)
|
||||
var = sum((p - media) ** 2 for p in precios) / len(precios) if len(precios) > 1 else 0.0
|
||||
return media, var ** 0.5
|
||||
|
||||
|
||||
# --------------------------------------------------------------- pronóstico (producción)
|
||||
def pronosticar(reg, conn, cliente_id, dias: int = 1, station=None, hasta=None) -> dict:
|
||||
"""Pronóstico de venta a `dias` (1..90) por combustible + total: litros [inf,sup] y pesos
|
||||
[inf,sup]. Por serie aplica el gate (HW donde gana, MM28 si no) y dimensiona la banda con el
|
||||
residual del método ganador. Pesos = litros × precio efectivo, propagando ambas incertidumbres
|
||||
(el rango de pesos sale más ancho que el de litros). Multi-tenant; determinista."""
|
||||
dias = max(1, min(90, int(dias)))
|
||||
horizonte = "corto" if dias <= 7 else "medio" if dias <= 30 else "largo"
|
||||
cfg = HORIZONTES[horizonte]
|
||||
serie = _serie_por_combustible(reg, conn, cliente_id, cfg["ventana"] + 30, hasta=hasta, station=station)
|
||||
if not serie:
|
||||
return {"ok": False, "motivo": "sin historia suficiente"}
|
||||
|
||||
por_comb, tot_l, var_tot_l, tot_p, var_tot_p = [], 0.0, 0.0, 0.0, 0.0
|
||||
for fuel, sfuel in serie.items():
|
||||
litros_serie = [p[1] for p in sfuel]
|
||||
sel = elegir_metodo(litros_serie, dias, cfg["ventana"])
|
||||
fc = (_modelo_hw(cfg["ventana"]) if sel["metodo"] == "holt_winters" else _modelo_baseline)(litros_serie, dias)
|
||||
if fc is None or fc <= 0:
|
||||
continue
|
||||
sigma_l = sel["residual_std"]
|
||||
precio, sigma_p = _precio_efectivo(sfuel, cfg["precio_dias"])
|
||||
rel_l = sigma_l / fc if fc else 0.0
|
||||
rel_p = sigma_p / precio if precio else 0.0
|
||||
rel_pesos = math.sqrt(rel_l ** 2 + rel_p ** 2) # propagación volumen ⊕ precio
|
||||
pesos = fc * precio
|
||||
por_comb.append({
|
||||
"combustible": fuel, "metodo": sel["metodo"], "mape": round(sel["mape"], 1) if sel["mape"] else None,
|
||||
"litros": {"esperado": round(fc, 1), "inf": round(fc * (1 - Z_BANDA * rel_l), 1),
|
||||
"sup": round(fc * (1 + Z_BANDA * rel_l), 1)},
|
||||
"pesos": {"esperado": round(pesos), "inf": round(pesos * (1 - Z_BANDA * rel_pesos)),
|
||||
"sup": round(pesos * (1 + Z_BANDA * rel_pesos))},
|
||||
"precio_efectivo": round(precio, 3),
|
||||
})
|
||||
tot_l += fc; var_tot_l += sigma_l ** 2
|
||||
tot_p += pesos; var_tot_p += (pesos * rel_pesos) ** 2
|
||||
if not por_comb:
|
||||
return {"ok": False, "motivo": "sin pronóstico (series insuficientes)"}
|
||||
|
||||
sd_tot_l, sd_tot_p = math.sqrt(var_tot_l), math.sqrt(var_tot_p) # suma de independientes
|
||||
dia_objetivo = (hasta or analitica.dia_operativo_actual(reg)) + dt.timedelta(days=dias)
|
||||
return {
|
||||
"ok": True, "dias": dias, "horizonte": horizonte, "dia_objetivo": dia_objetivo.isoformat(),
|
||||
"por_combustible": por_comb,
|
||||
"total": {
|
||||
"litros": {"esperado": round(tot_l, 1), "inf": round(tot_l - Z_BANDA * sd_tot_l, 1),
|
||||
"sup": round(tot_l + Z_BANDA * sd_tot_l, 1)},
|
||||
"pesos": {"esperado": round(tot_p), "inf": round(tot_p - Z_BANDA * sd_tot_p),
|
||||
"sup": round(tot_p + Z_BANDA * sd_tot_p)},
|
||||
},
|
||||
"nota": "rangos solo-límites (~80% central); pesos más ancho (volumen ⊕ precio)",
|
||||
}
|
||||
|
||||
|
||||
def incertidumbre_relativa_dia(reg, conn, cliente_id, station=None, hasta=None):
|
||||
"""Incertidumbre relativa (media-banda en pesos) de un pronóstico a 1 día — para que la
|
||||
proyección de cierre del día (Ola 1) herede una banda del modelo de Fase B (punto 8)."""
|
||||
pr = pronosticar(reg, conn, cliente_id, dias=1, station=station, hasta=hasta)
|
||||
if not pr.get("ok"):
|
||||
return None
|
||||
t = pr["total"]["pesos"]
|
||||
return (t["sup"] - t["esperado"]) / t["esperado"] if t["esperado"] else None
|
||||
@@ -230,7 +230,7 @@ def main() -> int:
|
||||
# y que las funciones del catálogo corren sin fugar ids/nombres ajenos
|
||||
for cid, ids_aj, nom_aj in ((CB, demo_ids | {ORPH}, demo_nombres | {"Huerfana test"}),
|
||||
("demo", {EB, ORPH}, {"Estacion B test", "Huerfana test"})):
|
||||
for fn in ("proyeccion_cierre", "comparativo_mes"):
|
||||
for fn in ("proyeccion_cierre", "comparativo_mes", "pronostico_venta"):
|
||||
r = catalogo.ejecutar(conn, ctx, cid, fn, {})
|
||||
if not r.get("ok"):
|
||||
fallos.append(f"{fn}({cid}) falló: {r.get('mensaje')}")
|
||||
|
||||
@@ -0,0 +1,54 @@
|
||||
"""Arnés re-ejecutable del GATE de Fase B (Holt-Winters vs baseline MM28).
|
||||
|
||||
Mide el MAPE walk-forward por horizonte (corto/medio/largo) y por estación×combustible, y
|
||||
reporta dónde Holt-Winters le gana al baseline y dónde se queda MM28 (gate anti-humo). Serie
|
||||
determinista anclada -> reproducible. No escribe nada (solo lee/regenera). Uso:
|
||||
PYTHONPATH=. python tests/backtest_faseB.py
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import datetime as dt
|
||||
import sys
|
||||
|
||||
from app import analitica, pronostico
|
||||
from config.registry import load_registry
|
||||
|
||||
ANCLA = dt.date(2026, 6, 13)
|
||||
VENTANA_SERIE = 300
|
||||
|
||||
|
||||
def main() -> int:
|
||||
reg = load_registry()
|
||||
serie = analitica.serie_diaria(reg, "demo", ventana=VENTANA_SERIE, hasta=ANCLA)
|
||||
serie_litros = {k: [p[1] for p in v] for k, v in serie.items()}
|
||||
n_dias = len(next(iter(serie_litros.values())))
|
||||
print(f"Gate Fase B — {len(serie_litros)} series × {n_dias} días, ancla {ANCLA}, params HW "
|
||||
f"α={pronostico.HW_ALPHA} β={pronostico.HW_BETA} γ={pronostico.HW_GAMMA} (fijos)")
|
||||
|
||||
gate = pronostico.evaluar_gate(serie_litros)
|
||||
print(f"\n{'horizonte':8} {'h':>4} {'ventana':>7} {'MAPE HW':>9} {'MAPE MM28':>10} {'GANADOR':>14} {'HW gana':>9}")
|
||||
for nombre, g in gate.items():
|
||||
hw = f"{g['mape_hw_agregado']:.1f}%" if g['mape_hw_agregado'] else "—"
|
||||
mb = f"{g['mape_baseline_agregado']:.1f}%" if g['mape_baseline_agregado'] else "—"
|
||||
print(f"{nombre:8} {g['h']:>4} {g['ventana']:>7} {hw:>9} {mb:>10} {g['ganador_agregado']:>14} "
|
||||
f"{str(g['series_gana_hw'])+'/'+str(g['series_total']):>9}")
|
||||
|
||||
print("\nDetalle por serie (horizonte corto, h=7):")
|
||||
for clave, d in sorted(gate["corto"]["por_serie"].items()):
|
||||
mh = f"{d['mape_hw']:.1f}%" if d['mape_hw'] else "—"
|
||||
mb = f"{d['mape_baseline']:.1f}%" if d['mape_baseline'] else "—"
|
||||
marca = "" if d["metodo"] == "holt_winters" else " <- se queda MM28"
|
||||
print(f" {clave[0]:12}·{clave[1]:8} HW {mh:>7} MM28 {mb:>7}{marca}")
|
||||
|
||||
# reproducibilidad
|
||||
g2 = pronostico.evaluar_gate(serie_litros)
|
||||
repro = all(gate[h]["mape_hw_agregado"] == g2[h]["mape_hw_agregado"] for h in gate)
|
||||
print(f"\nReproducibilidad (misma serie -> mismo gate): {repro}")
|
||||
|
||||
ok = all(g["mape_hw_agregado"] is not None for g in gate.values()) and repro
|
||||
print("\n✅ GATE OK" if ok else "\n❌ GATE con problemas")
|
||||
return 0 if ok else 1
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
Reference in new issue
Block a user