Conseil simule aligne sur le moteur reel et validation par regimes
Le conseiller du backtest raisonne desormais comme le moteur de decision : besoin d abord, anticipation seulement si le gain depasse le seuil du vehicule, et plancher d appoint qui interdit de repasser a la pompe pour quelques litres. La campagne precedente le montrait : sans ce plancher, la strategie multipliait les passages quotidiens et le verdict la refusait a juste titre. Ajout de la validation par regimes : chaque periode atypique est evaluee avec un apprentissage arrete la veille de son debut, plus l experience ou la crise actuelle reste entierement hors entrainement.
This commit is contained in:
391
models.py
391
models.py
@@ -21,6 +21,7 @@ Règles de conception :
|
||||
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
|
||||
@@ -32,45 +33,75 @@ 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',
|
||||
"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
|
||||
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()
|
||||
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'])
|
||||
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]
|
||||
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:
|
||||
if (date.fromisoformat(day) - date.fromisoformat(newest["available_from"])).days > max_age_days:
|
||||
return None
|
||||
return newest
|
||||
|
||||
@@ -78,13 +109,13 @@ def _asof_value(points, day, max_age_days=60):
|
||||
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']:
|
||||
if not newest or not newest["value"]:
|
||||
return None
|
||||
target = (date.fromisoformat(newest['available_from']) - timedelta(days=window)).isoformat()
|
||||
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:
|
||||
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)
|
||||
return round(math.log(newest["value"] / older["value"]) * 100, 4)
|
||||
|
||||
|
||||
def detect_rolls(points, threshold=4.0, revert_window=2, revert_ratio=0.5):
|
||||
@@ -95,12 +126,12 @@ def detect_rolls(points, threshold=4.0, revert_window=2, revert_ratio=0.5):
|
||||
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')]
|
||||
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')
|
||||
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)
|
||||
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
|
||||
@@ -108,28 +139,46 @@ def detect_rolls(points, threshold=4.0, revert_window=2, revert_ratio=0.5):
|
||||
for index, value in enumerate(returns):
|
||||
if abs(value) <= threshold * sigma:
|
||||
continue
|
||||
following = returns[index + 1:index + 1 + revert_window]
|
||||
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')
|
||||
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)
|
||||
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):
|
||||
@@ -141,20 +190,34 @@ def build_samples(lat, lon, radius, fuel, horizons=HORIZONS, days=4000, market=T
|
||||
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 {}
|
||||
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)]
|
||||
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(
|
||||
@@ -164,36 +227,47 @@ def build_samples(lat, lon, radius, fuel, horizons=HORIZONS, days=4000, market=T
|
||||
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]]),
|
||||
local_percentile_90=_asof_percentile(
|
||||
levels, index, [item["median"] for item in levels[max(0, index - 90) : index + 1]]
|
||||
),
|
||||
# Déjà calculée une seule fois avant la boucle : la recalculer ici serait un O(n²).
|
||||
local_matched_7=(targets.get(7, {}).get(day) or {}).get('delta_cents'),
|
||||
days_since_change=point['declared_today'],
|
||||
local_matched_7=(targets.get(7, {}).get(day) or {}).get("delta_cents"),
|
||||
days_since_change=point["declared_today"],
|
||||
)
|
||||
if market:
|
||||
futures = upstream.get('brent_futures_usd') or []
|
||||
spot = upstream.get('brent_spot_usd') or []
|
||||
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),
|
||||
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'])
|
||||
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')
|
||||
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):
|
||||
@@ -201,33 +275,42 @@ def _asof_percentile(levels, index, window_values):
|
||||
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'])
|
||||
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']]
|
||||
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']:
|
||||
if not newest or not newest["value"]:
|
||||
return None
|
||||
target = (date.fromisoformat(newest['available_from']) - timedelta(days=14)).isoformat()
|
||||
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']:
|
||||
if not older or not older["value"]:
|
||||
return None
|
||||
return round((newest['value'] - older['value']) / older['value'] * 100, 4)
|
||||
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 = {}
|
||||
@@ -269,8 +352,9 @@ def _solve(matrix, vector):
|
||||
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))
|
||||
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
|
||||
|
||||
@@ -289,25 +373,25 @@ def _ridge(rows, names, targets, lam=1.0):
|
||||
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é
|
||||
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))
|
||||
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]
|
||||
return [(row, row["targets"][horizon]) for row in samples if row["targets"].get(horizon) is not None]
|
||||
|
||||
|
||||
def model_naive_unchanged(train, horizon):
|
||||
@@ -315,8 +399,7 @@ def model_naive_unchanged(train, horizon):
|
||||
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)
|
||||
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):
|
||||
@@ -326,45 +409,60 @@ def model_local_trend(train, horizon):
|
||||
sigma = statistics.pstdev(values) if len(values) > 1 else 0.0
|
||||
|
||||
def predict(row):
|
||||
slope = row['features'].get('local_slope_7')
|
||||
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)
|
||||
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)
|
||||
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)
|
||||
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]
|
||||
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))
|
||||
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):
|
||||
@@ -376,25 +474,35 @@ def model_knn(train, horizon, neighbours=20, subset=300):
|
||||
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]
|
||||
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]
|
||||
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])
|
||||
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])
|
||||
@@ -402,12 +510,17 @@ def model_knn(train, horizon, neighbours=20, subset=300):
|
||||
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)
|
||||
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)
|
||||
CANDIDATES = (model_naive_unchanged, model_local_trend, model_autoregressive, model_ridge_market, model_knn)
|
||||
|
||||
|
||||
def probability_up(mu_cents, sigma_cents):
|
||||
@@ -420,21 +533,26 @@ def probability_up(mu_cents, sigma_cents):
|
||||
|
||||
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
|
||||
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'])
|
||||
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'])
|
||||
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')
|
||||
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:]]
|
||||
@@ -448,21 +566,24 @@ def select_model(train, horizon, candidates=CANDIDATES, validation_share=0.2, ve
|
||||
continue
|
||||
errors = []
|
||||
for row in inner_valid:
|
||||
target = row['targets'].get(horizon)
|
||||
target = row["targets"].get(horizon)
|
||||
if target is None:
|
||||
continue
|
||||
predicted = 0.0 if fitted['name'] == 'naive_unchanged' else fitted['predict'](row)
|
||||
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)
|
||||
scores[fitted["name"]] = round(statistics.fmean(errors), 4)
|
||||
if not scores:
|
||||
return None, dict(reason='aucun candidat évaluable')
|
||||
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)
|
||||
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)
|
||||
|
||||
Reference in New Issue
Block a user