591 lines
23 KiB
Python
591 lines
23 KiB
Python
"""Modèles de prévision J+0→J+21 : benchmarks simples d'abord, mesurés hors échantillon.
|
||
|
||
Aucune bibliothèque scientifique n'est disponible sur la VM (Python standard + SQLite) : la
|
||
régression, la normalisation et le voisinage sont donc écrits à la main. C'est suffisant, ces
|
||
modèles sont volontairement petits.
|
||
|
||
Règles de conception :
|
||
|
||
- **le niveau absolu du Brent futures n'est jamais une feature** : la série BZ=F est un contrat à
|
||
échéance enchaîné, et un changement de contrat (roll) ressemble à un mouvement du pétrole. On
|
||
utilisait des rendements logarithmiques : ils NE sont PAS insensibles aux rolls.
|
||
Pipeline historique invalidé ; ne pas utiliser ses résultats.
|
||
- **deux séries de brut sont conservées** (futures BZ=F et référence mensuelle DGEC) : leur valeur
|
||
prédictive se compare, elle ne se remplace pas aveuglément.
|
||
- **features as-of** : chaque valeur est prise à la première date où elle était réellement
|
||
disponible (`asof.available_at`), jamais à la date qu'elle décrit.
|
||
- **une prédiction par horizon** : la relation à J+3 n'est pas celle à J+14, chaque horizon a son
|
||
propre modèle et ses propres cibles en **centimes par litre**.
|
||
- **sélection sans fuite** : le modèle et ses hyper-paramètres sont choisis sur une fin
|
||
d'apprentissage, jamais sur la période de test.
|
||
|
||
Sortie destinée au moteur véhicule : ``mu_cents`` (variation prévue), ``interval`` (fourchette
|
||
80 %), ``p_up`` / ``p_down`` (probabilités) et ``confidence``.
|
||
"""
|
||
|
||
import math
|
||
import statistics
|
||
from datetime import date, timedelta
|
||
|
||
import asof
|
||
import series as series_module
|
||
import storage
|
||
|
||
HORIZONS = (1, 3, 7, 14, 21)
|
||
MIN_TRAIN_SAMPLES = 120
|
||
FEATURE_NAMES = (
|
||
"local_delta_1",
|
||
"local_delta_3",
|
||
"local_delta_7",
|
||
"local_delta_14",
|
||
"local_slope_7",
|
||
"local_vol_14",
|
||
"local_percentile_90",
|
||
"local_matched_7",
|
||
"brent_fut_ret_1",
|
||
"brent_fut_ret_7",
|
||
"brent_fut_ret_14",
|
||
"usd_ret_7",
|
||
"dgec_brent_change",
|
||
"dgec_margin_change",
|
||
"eu_diesel_htt_ret_14",
|
||
"eu_diesel_htt_ret_28",
|
||
"portwatch_change_14",
|
||
)
|
||
MARKET_FEATURES = (
|
||
"brent_fut_ret_1",
|
||
"brent_fut_ret_7",
|
||
"brent_fut_ret_14",
|
||
"usd_ret_7",
|
||
"dgec_brent_change",
|
||
"dgec_margin_change",
|
||
"eu_diesel_htt_ret_14",
|
||
"eu_diesel_htt_ret_28",
|
||
)
|
||
LOGISTIC_SCALE = 1.7 # approximation logistique de la fonction de répartition normale
|
||
|
||
|
||
# --------------------------------------------------------------------------- données
|
||
|
||
|
||
def _series_points(names):
|
||
"""Séries amont avec leur date de disponibilité réelle (``available_at``)."""
|
||
out = {}
|
||
with storage.connect() as db:
|
||
for name in names:
|
||
rows = db.execute(
|
||
"SELECT day, value, observed_at, published_at FROM upstream_series "
|
||
"WHERE series=? ORDER BY day",
|
||
(name,),
|
||
).fetchall()
|
||
points = []
|
||
for row in rows:
|
||
info = asof.available_at(dict(row, series=name))
|
||
if info["available_at"]:
|
||
points.append(
|
||
dict(
|
||
available_from=info["available_at"],
|
||
day=row["day"],
|
||
value=row["value"],
|
||
estimated=info["estimated"],
|
||
basis=info["basis"],
|
||
)
|
||
)
|
||
points.sort(key=lambda item: item["available_from"])
|
||
out[name] = points
|
||
return out
|
||
|
||
|
||
def _asof_value(points, day, max_age_days=60):
|
||
"""Dernière valeur disponible à ``day``, ou None si elle est trop ancienne."""
|
||
usable = [point for point in points if point["available_from"] <= day]
|
||
if not usable:
|
||
return None
|
||
newest = usable[-1]
|
||
if (date.fromisoformat(day) - date.fromisoformat(newest["available_from"])).days > max_age_days:
|
||
return None
|
||
return newest
|
||
|
||
|
||
def _log_return(points, day, window, max_age_days=60):
|
||
"""Rendement logarithmique en % sur ``window`` jours, à partir des seules valeurs disponibles."""
|
||
newest = _asof_value(points, day, max_age_days)
|
||
if not newest or not newest["value"]:
|
||
return None
|
||
target = (date.fromisoformat(newest["available_from"]) - timedelta(days=window)).isoformat()
|
||
older = _asof_value(points, target, max_age_days)
|
||
if not older or not older["value"] or older["value"] <= 0 or newest["value"] <= 0:
|
||
return None
|
||
return round(math.log(newest["value"] / older["value"]) * 100, 4)
|
||
|
||
|
||
def detect_rolls(points, threshold=4.0, revert_window=2, revert_ratio=0.5):
|
||
"""Jours suspects de **changement de contrat** sur une série continue de futures.
|
||
|
||
Yahoo ne publie pas le contrat sous-jacent : BZ=F est un enchaînement d'échéances. Un roll
|
||
apparaît comme un saut d'un jour qui **ne se prolonge pas** (le prix revient partiellement les
|
||
jours suivants), là où un vrai mouvement de marché se poursuit. On signale ces jours au lieu de
|
||
les retirer : c'est une suspicion, pas une certitude.
|
||
"""
|
||
values = [point for point in points if point.get("value")]
|
||
if len(values) < 30:
|
||
return dict(count=0, days=[], threshold_sigma=threshold, basis="série trop courte")
|
||
returns = []
|
||
for older, newer in zip(values, values[1:], strict=False):
|
||
returns.append(math.log(newer["value"] / older["value"]) if older["value"] > 0 else 0.0)
|
||
absolute = sorted(abs(value) for value in returns)
|
||
median = absolute[len(absolute) // 2]
|
||
sigma = 1.4826 * median or 1e-9
|
||
flagged = []
|
||
for index, value in enumerate(returns):
|
||
if abs(value) <= threshold * sigma:
|
||
continue
|
||
following = returns[index + 1 : index + 1 + revert_window]
|
||
if not following:
|
||
continue
|
||
reversal = -sum(following)
|
||
if value and reversal / abs(value) >= revert_ratio:
|
||
flagged.append(
|
||
dict(
|
||
day=values[index + 1]["day"],
|
||
move_pct=round(value * 100, 3),
|
||
reversal_pct=round(reversal * 100, 3),
|
||
)
|
||
)
|
||
return dict(
|
||
count=len(flagged),
|
||
days=flagged,
|
||
threshold_sigma=threshold,
|
||
robust_sigma=round(sigma, 5),
|
||
basis="saut d’un jour partiellement annulé : signature d’un roll de contrat",
|
||
)
|
||
|
||
|
||
def fuel_coverage(fuel):
|
||
"""Couverture réelle d'un carburant : premier jour exploitable, volume, stations."""
|
||
with storage.connect() as db:
|
||
row = db.execute(
|
||
"SELECT min(day) AS first, max(day) AS last, count(*) AS points, "
|
||
"count(DISTINCT station_id) AS stations FROM observations WHERE fuel=?",
|
||
(fuel,),
|
||
).fetchone()
|
||
archived = db.execute(
|
||
"SELECT count(*) FROM observations WHERE fuel=? AND origin LIKE 'archive:%'", (fuel,)
|
||
).fetchone()[0]
|
||
return dict(
|
||
fuel=fuel,
|
||
first=row["first"],
|
||
last=row["last"],
|
||
points=row["points"],
|
||
stations=row["stations"],
|
||
archived=archived,
|
||
)
|
||
|
||
|
||
def build_samples(lat, lon, radius, fuel, horizons=HORIZONS, days=4000, market=True, now=None):
|
||
"""Échantillons jour par jour : features as-of en entrée, variations en c€/L en cible."""
|
||
reconstructed = series_module.active_series(lat, lon, radius, fuel, days=days, now=now)
|
||
levels = series_module.median_series(reconstructed)
|
||
if len(levels) < MIN_TRAIN_SAMPLES:
|
||
return dict(samples=[], reason=f"seulement {len(levels)} jours de marché reconstruits")
|
||
targets = {}
|
||
for horizon in horizons:
|
||
for item in series_module.matched_variation(reconstructed, horizon=horizon):
|
||
if item["comparable"]:
|
||
targets.setdefault(horizon, {})[item["day"]] = item
|
||
upstream = (
|
||
_series_points(
|
||
(
|
||
"brent_futures_usd",
|
||
"brent_spot_usd",
|
||
"dgec_brent_usd",
|
||
"usd_per_eur",
|
||
"dgec_margin_usd_per_bbl",
|
||
"eu_fr_diesel_htt",
|
||
"portwatch",
|
||
)
|
||
)
|
||
if market
|
||
else {}
|
||
)
|
||
chokepoints = _chokepoint_points() if market else []
|
||
samples = []
|
||
for index, point in enumerate(levels):
|
||
if index < 20:
|
||
continue
|
||
day, level = point["day"], point["median"]
|
||
window = [item for item in levels[max(0, index - 30) : index + 1] if item["median"]]
|
||
deltas = [
|
||
round((later["median"] - older["median"]) * 100, 3)
|
||
for older, later in zip(window, window[1:], strict=False)
|
||
]
|
||
if len(deltas) < 14:
|
||
continue
|
||
features = dict(
|
||
local_delta_1=deltas[-1],
|
||
local_delta_3=round(sum(deltas[-3:]), 3),
|
||
local_delta_7=round(sum(deltas[-7:]), 3),
|
||
local_delta_14=round(sum(deltas[-14:]), 3),
|
||
local_slope_7=round(statistics.median(deltas[-7:]), 3),
|
||
local_vol_14=round(statistics.median(abs(value) for value in deltas[-14:]), 3),
|
||
local_percentile_90=_asof_percentile(
|
||
levels, index, [item["median"] for item in levels[max(0, index - 90) : index + 1]]
|
||
),
|
||
# Ancienne feature contaminée supprimée. Pipeline historique non validé.
|
||
local_matched_7=None,
|
||
days_since_change=point["declared_today"],
|
||
)
|
||
if market:
|
||
futures = upstream.get("brent_futures_usd") or []
|
||
spot = upstream.get("brent_spot_usd") or []
|
||
brent_series = futures or spot
|
||
features.update(
|
||
brent_fut_ret_1=_log_return(brent_series, day, 1),
|
||
brent_fut_ret_7=_log_return(brent_series, day, 7),
|
||
brent_fut_ret_14=_log_return(brent_series, day, 14),
|
||
usd_ret_7=_log_return(upstream.get("usd_per_eur") or [], day, 7),
|
||
dgec_brent_change=_log_return(upstream.get("dgec_brent_usd") or [], day, 30),
|
||
dgec_margin_change=_log_return(upstream.get("dgec_margin_usd_per_bbl") or [], day, 30),
|
||
eu_diesel_htt_ret_14=_log_return(upstream.get("eu_fr_diesel_htt") or [], day, 14),
|
||
eu_diesel_htt_ret_28=_log_return(upstream.get("eu_fr_diesel_htt") or [], day, 28),
|
||
portwatch_change_14=_chokepoint_change(chokepoints, day),
|
||
)
|
||
row = dict(
|
||
day=day,
|
||
price=level,
|
||
features=features,
|
||
targets={
|
||
horizon: (targets.get(horizon, {}).get(day) or {}).get("delta_cents") for horizon in horizons
|
||
},
|
||
target_meta={horizon: targets.get(horizon, {}).get(day) for horizon in horizons},
|
||
declared_today=point["declared_today"],
|
||
active_stations=point["stations"],
|
||
)
|
||
samples.append(row)
|
||
usable = [row for row in samples if any(value is not None for value in row["targets"].values())]
|
||
return dict(
|
||
samples=usable,
|
||
levels=levels,
|
||
reconstructed=reconstructed,
|
||
basis="features as-of, cibles en centimes par litre sur panel comparable",
|
||
)
|
||
|
||
|
||
def _asof_percentile(levels, index, window_values):
|
||
"""Percentile du niveau courant parmi les seuls jours antérieurs (aucune fuite)."""
|
||
sample = sorted(value for value in window_values if value)
|
||
if not sample:
|
||
return None
|
||
rank = sum(1 for value in sample if value <= levels[index]["median"])
|
||
return round(rank / len(sample) * 100, 2)
|
||
|
||
|
||
def _chokepoint_points():
|
||
with storage.connect() as db:
|
||
rows = db.execute(
|
||
"SELECT day, sum(transit_tankers) AS tankers FROM chokepoint_daily GROUP BY day ORDER BY day"
|
||
).fetchall()
|
||
return [
|
||
dict(
|
||
day=row["day"],
|
||
value=row["tankers"],
|
||
available_from=(
|
||
date.fromisoformat(row["day"]) + timedelta(days=asof.PUBLICATION_LAG_DAYS["portwatch"])
|
||
).isoformat(),
|
||
)
|
||
for row in rows
|
||
if row["tankers"]
|
||
]
|
||
|
||
|
||
def _chokepoint_change(points, day):
|
||
newest = _asof_value(points, day, max_age_days=21)
|
||
if not newest or not newest["value"]:
|
||
return None
|
||
target = (date.fromisoformat(newest["available_from"]) - timedelta(days=14)).isoformat()
|
||
older = _asof_value(points, target, max_age_days=21)
|
||
if not older or not older["value"]:
|
||
return None
|
||
return round((newest["value"] - older["value"]) / older["value"] * 100, 4)
|
||
|
||
|
||
# --------------------------------------------------------------------------- algèbre
|
||
|
||
|
||
def _standardise(rows, names):
|
||
columns = {name: [row[name] for row in rows] for name in names}
|
||
stats = {}
|
||
for name, values in columns.items():
|
||
clean = [value for value in values if value is not None]
|
||
mean = statistics.fmean(clean) if clean else 0.0
|
||
sigma = statistics.pstdev(clean) if len(clean) > 1 else 1.0
|
||
stats[name] = (mean, sigma or 1.0)
|
||
return stats
|
||
|
||
|
||
def _design(rows, names, stats, fill=0.0):
|
||
matrix = []
|
||
for row in rows:
|
||
line = [1.0]
|
||
for name in names:
|
||
value = row.get(name)
|
||
mean, sigma = stats[name]
|
||
line.append(fill if value is None else (value - mean) / sigma)
|
||
matrix.append(line)
|
||
return matrix
|
||
|
||
|
||
def _solve(matrix, vector):
|
||
"""Résolution d'un système linéaire (Gauss, pivot partiel) — dimension minuscule."""
|
||
size = len(matrix)
|
||
augmented = [row[:] + [vector[index]] for index, row in enumerate(matrix)]
|
||
for column in range(size):
|
||
pivot = max(range(column, size), key=lambda row: abs(augmented[row][column]))
|
||
if abs(augmented[pivot][column]) < 1e-12:
|
||
continue
|
||
augmented[column], augmented[pivot] = augmented[pivot], augmented[column]
|
||
for row in range(column + 1, size):
|
||
factor = augmented[row][column] / augmented[column][column]
|
||
if factor:
|
||
for item in range(column, size + 1):
|
||
augmented[row][item] -= factor * augmented[column][item]
|
||
solution = [0.0] * size
|
||
for row in range(size - 1, -1, -1):
|
||
if abs(augmented[row][row]) < 1e-12:
|
||
continue
|
||
total = augmented[row][size] - sum(
|
||
augmented[row][column] * solution[column] for column in range(row + 1, size)
|
||
)
|
||
solution[row] = total / augmented[row][row]
|
||
return solution
|
||
|
||
|
||
def _ridge(rows, names, targets, lam=1.0):
|
||
stats = _standardise(rows, names)
|
||
design = _design(rows, names, stats)
|
||
width = len(names) + 1
|
||
gram = [[0.0] * width for _ in range(width)]
|
||
moment = [0.0] * width
|
||
for line, target in zip(design, targets, strict=False):
|
||
for first in range(width):
|
||
moment[first] += line[first] * target
|
||
for second in range(first, width):
|
||
gram[first][second] += line[first] * line[second]
|
||
for first in range(width):
|
||
for second in range(first):
|
||
gram[first][second] = gram[second][first]
|
||
for index in range(1, width): # l'intercepte n'est pas pénalisé
|
||
gram[index][index] += lam
|
||
coefficients = _solve(gram, moment)
|
||
return dict(names=names, stats=stats, coefficients=coefficients)
|
||
|
||
|
||
def _ridge_predict(model, row):
|
||
line = [1.0] + [
|
||
0.0 if row.get(name) is None else (row[name] - model["stats"][name][0]) / model["stats"][name][1]
|
||
for name in model["names"]
|
||
]
|
||
return sum(coefficient * value for coefficient, value in zip(model["coefficients"], line, strict=False))
|
||
|
||
|
||
# --------------------------------------------------------------------------- modèles
|
||
|
||
|
||
def _fit_pairs(samples, horizon):
|
||
return [(row, row["targets"][horizon]) for row in samples if row["targets"].get(horizon) is not None]
|
||
|
||
|
||
def model_naive_unchanged(train, horizon):
|
||
"""« Le prix ne bouge pas » : la référence à battre."""
|
||
pairs = _fit_pairs(train, horizon)
|
||
values = [target for _row, target in pairs]
|
||
sigma = statistics.pstdev(values) if len(values) > 1 else 0.0
|
||
return dict(name="naive_unchanged", sigma_cents=round(sigma, 3), mean_cents=0.0, predict=lambda row: 0.0)
|
||
|
||
|
||
def model_local_trend(train, horizon):
|
||
"""Prolongation de la tendance locale récente (momentum simple)."""
|
||
pairs = _fit_pairs(train, horizon)
|
||
values = [target for _row, target in pairs]
|
||
sigma = statistics.pstdev(values) if len(values) > 1 else 0.0
|
||
|
||
def predict(row):
|
||
slope = row["features"].get("local_slope_7")
|
||
if slope is None:
|
||
return 0.0
|
||
return round(slope * horizon, 3)
|
||
|
||
residuals = [abs(predict(row) - target) for row, target in pairs]
|
||
return dict(
|
||
name="local_trend",
|
||
sigma_cents=round(sigma, 3),
|
||
residual_mae=round(statistics.fmean(residuals), 3) if residuals else None,
|
||
mean_cents=statistics.fmean([predict(row) for row, _t in pairs]) if pairs else 0.0,
|
||
predict=predict,
|
||
)
|
||
|
||
|
||
def model_autoregressive(train, horizon):
|
||
"""Autorégressif sur le seul historique pompe (5 décalages de variation quotidienne)."""
|
||
names = ("local_delta_1", "local_delta_3", "local_delta_7", "local_delta_14", "local_slope_7")
|
||
return _linear_model("ar_pump", train, horizon, names, default_lambda=0.5)
|
||
|
||
|
||
def model_ridge_market(train, horizon, names=None):
|
||
"""Ridge sur les décalages des variables de marché et du marché local."""
|
||
names = names or [name for name in FEATURE_NAMES if name in MARKET_FEATURES] + [
|
||
"local_delta_7",
|
||
"local_delta_14",
|
||
"local_slope_7",
|
||
"local_vol_14",
|
||
"local_percentile_90",
|
||
]
|
||
return _linear_model("ridge_market", train, horizon, tuple(names), default_lambda=1.0)
|
||
|
||
|
||
def _linear_model(name, train, horizon, names, default_lambda=1.0):
|
||
pairs = _fit_pairs(train, horizon)
|
||
if len(pairs) < 30:
|
||
return None
|
||
rows = [{key: row["features"].get(key) for key in names} for row, _target in pairs]
|
||
targets = [target for _row, target in pairs]
|
||
model = _ridge(rows, list(names), targets, default_lambda)
|
||
fitted = [_ridge_predict(model, row) for row in rows]
|
||
sigma = statistics.pstdev(
|
||
[predicted - actual for predicted, actual in zip(fitted, targets, strict=False)]
|
||
)
|
||
return dict(
|
||
name=name,
|
||
sigma_cents=round(sigma, 3),
|
||
names=tuple(names),
|
||
default_lambda=default_lambda,
|
||
ridge=model,
|
||
predict=lambda row: round(
|
||
_ridge_predict(model, {key: (row.get("features") or row).get(key) for key in names}), 3
|
||
),
|
||
)
|
||
|
||
|
||
def model_knn(train, horizon, neighbours=20, subset=300):
|
||
"""Voisinage : seule candidate non linéaire, coût explicitement borné.
|
||
|
||
Le sous-échantillon et la dispersion (écart-type des cibles) évitent une boucle in-sample qui
|
||
dominerait le temps de calcul sans rien apporter à la décision.
|
||
"""
|
||
pairs = _fit_pairs(train, horizon)
|
||
if len(pairs) < 60:
|
||
return None
|
||
names = (
|
||
"local_delta_7",
|
||
"local_delta_14",
|
||
"local_slope_7",
|
||
"local_vol_14",
|
||
"local_matched_7",
|
||
"brent_fut_ret_7",
|
||
"eu_diesel_htt_ret_14",
|
||
)
|
||
rows = [{key: row["features"].get(key) for key in names} for row, _target in pairs]
|
||
targets = [target for _row, target in pairs]
|
||
stats = _standardise(rows, list(names))
|
||
step = max(1, len(rows) // subset)
|
||
kept_rows, kept_targets = rows[::step], targets[::step]
|
||
|
||
def predict(row):
|
||
flat = row.get("features") or row
|
||
vector = [
|
||
0.0 if flat.get(name) is None else (flat[name] - stats[name][0]) / stats[name][1]
|
||
for name in names
|
||
]
|
||
distances = []
|
||
for index, candidate in enumerate(kept_rows):
|
||
total = 0.0
|
||
for position, name in enumerate(names):
|
||
value = candidate.get(name)
|
||
delta = vector[position] - (
|
||
0.0 if value is None else (value - stats[name][0]) / stats[name][1]
|
||
)
|
||
total += delta * delta
|
||
distances.append((total, kept_targets[index]))
|
||
distances.sort(key=lambda item: item[0])
|
||
chosen = [target for _distance, target in distances[:neighbours]]
|
||
return round(statistics.median(chosen), 3)
|
||
|
||
sigma = statistics.pstdev(targets) if len(targets) > 1 else 0.0
|
||
return dict(
|
||
name="knn",
|
||
sigma_cents=round(sigma, 3),
|
||
names=names,
|
||
neighbours=neighbours,
|
||
subset=len(kept_rows),
|
||
predict=predict,
|
||
)
|
||
|
||
|
||
CANDIDATES = (model_naive_unchanged, model_local_trend, model_autoregressive, model_ridge_market, model_knn)
|
||
|
||
|
||
def probability_up(mu_cents, sigma_cents):
|
||
"""Probabilité de hausse à partir de la variation prévue et de la dispersion observée."""
|
||
if not sigma_cents:
|
||
return 0.5 if not mu_cents else (1.0 if mu_cents > 0 else 0.0)
|
||
exponent = max(-30.0, min(30.0, LOGISTIC_SCALE * mu_cents / sigma_cents))
|
||
return round(1 / (1 + math.exp(-exponent)), 4)
|
||
|
||
|
||
def predict(fitted, row):
|
||
"""Sortie destinée au moteur véhicule : variation, fourchette, probabilités, confiance."""
|
||
mu = fitted["predict"](row) if fitted["name"] != "naive_unchanged" else 0.0
|
||
sigma = fitted.get("sigma_cents") or 0.0
|
||
up = probability_up(mu, sigma)
|
||
return dict(
|
||
mu_cents=round(mu, 3),
|
||
sigma_cents=round(sigma, 3),
|
||
interval=(round(mu - 1.28 * sigma, 3), round(mu + 1.28 * sigma, 3)),
|
||
p_up=up,
|
||
p_down=round(1 - up, 4),
|
||
confidence=round(max(up, 1 - up), 4),
|
||
direction=("up" if mu > 0 else "down" if mu < 0 else "flat"),
|
||
model=fitted["name"],
|
||
)
|
||
|
||
|
||
def select_model(train, horizon, candidates=CANDIDATES, validation_share=0.2, verbose=False):
|
||
"""Choix du modèle **sur une fin d'apprentissage**, jamais sur la période de test."""
|
||
ordered = sorted(_fit_pairs(train, horizon), key=lambda item: item[0]["day"])
|
||
if len(ordered) < 60:
|
||
return None, dict(reason=f"{len(ordered)} échantillons : trop peu pour sélectionner")
|
||
cut = max(30, int(len(ordered) * (1 - validation_share)))
|
||
inner_train = [row for row, _target in ordered[:cut]]
|
||
inner_valid = [row for row, _target in ordered[cut:]]
|
||
if len(inner_valid) < 10:
|
||
inner_valid = [row for row, _target in ordered[-10:]]
|
||
inner_train = [row for row, _target in ordered[:-10]]
|
||
scores = {}
|
||
for candidate in candidates:
|
||
fitted = candidate(inner_train, horizon)
|
||
if not fitted:
|
||
continue
|
||
errors = []
|
||
for row in inner_valid:
|
||
target = row["targets"].get(horizon)
|
||
if target is None:
|
||
continue
|
||
predicted = 0.0 if fitted["name"] == "naive_unchanged" else fitted["predict"](row)
|
||
errors.append(abs(predicted - target))
|
||
if not errors:
|
||
continue
|
||
scores[fitted["name"]] = round(statistics.fmean(errors), 4)
|
||
if not scores:
|
||
return None, dict(reason="aucun candidat évaluable")
|
||
winner = min(scores, key=scores.get)
|
||
for candidate in candidates:
|
||
fitted = candidate(train, horizon)
|
||
if fitted and fitted["name"] == winner:
|
||
return fitted, dict(
|
||
candidate_scores=scores,
|
||
winner=winner,
|
||
validation_samples=len(inner_valid),
|
||
validation="fin d’apprentissage (chronologique)",
|
||
)
|
||
return None, dict(reason="candidat retenu non réentraînable", candidate_scores=scores)
|