Protocole amont apparie : IC diagnostiques, familles as-of, placebo et PR-AUC
This commit is contained in:
456
enrich_campaign.py
Normal file
456
enrich_campaign.py
Normal file
@@ -0,0 +1,456 @@
|
||||
"""Apport marginal des familles amont, en comparaison **strictement appariée**.
|
||||
|
||||
Protocole verrouillé :
|
||||
|
||||
- **Endpoints pré-déclarés** avant tout regard sur les enrichissements : Gazole J+14 hausse ≥3,
|
||||
Gazole J+14 hausse ≥5, E10 J+14 hausse ≥3. J+7, les autres carburants et toutes les baisses
|
||||
restent secondaires/exploratoires.
|
||||
- **Baseline appariée** : `local_matched` ré-estimée sur exactement les mêmes journées que le bras
|
||||
enrichi (même train, même validation, même test, mêmes labels). Aucune comparaison entre des
|
||||
fenêtres différentes.
|
||||
- **Une famille à la fois** : local → +EUR/USD → +raffinage → +PortWatch (Brent sauté, cf.
|
||||
`upstream_features`). Chaque famille garde son `available_at` ; aucun forward-fill ne rend une
|
||||
publication visible avant sa date.
|
||||
- **Seuils gelés** : les mêmes seuils absolus sont appliqués aux deux bras ; les quantiles suivent
|
||||
la même règle, appliquée à la fenêtre de validation antérieure, jamais au test.
|
||||
- **Apport marginal** : Brier, PR-AUC, calibration, précision/lift, couverture, amplitude et
|
||||
mouvement adverse, épisodes, origines disjointes, valeur économique par signal.
|
||||
- **Comparaison appariée** par bootstrap de blocs sur la différence jour par jour.
|
||||
- **Placebo anti-fuite** : la famille permutée par blocs de 30 jours doit faire moins bien.
|
||||
- **Aucun réglage sur 2026** : la fenêtre reste consultable en diagnostic, jamais pour choisir.
|
||||
"""
|
||||
|
||||
import json
|
||||
import math
|
||||
from datetime import date
|
||||
from pathlib import Path
|
||||
from statistics import fmean, pstdev
|
||||
|
||||
import upstream_features as up
|
||||
from clean_backtest import feature_rows, states_for
|
||||
from event_backtest import (
|
||||
KEYS,
|
||||
MIN_MATURED_LABELS,
|
||||
QUANTILES,
|
||||
SCORE_GRID,
|
||||
add,
|
||||
empty_stats,
|
||||
regime,
|
||||
risk_scores,
|
||||
)
|
||||
from event_targets import event_target
|
||||
from risk_report import (
|
||||
decision_loss,
|
||||
episode_summary,
|
||||
expected_price_value_cents_per_signal,
|
||||
non_overlapping,
|
||||
paired_block_bootstrap,
|
||||
per_day_brier,
|
||||
per_day_decision_loss,
|
||||
pr_auc,
|
||||
score_brier,
|
||||
score_threshold,
|
||||
)
|
||||
|
||||
TRAIN_END = "2023-01-01"
|
||||
VAL_END = "2025-01-01"
|
||||
TEST_END = "2026-12-31"
|
||||
ABS_THRESHOLDS = (0.20, 0.25, 0.30)
|
||||
PRIMARY = [("Gazole", 14, "up_3"), ("Gazole", 14, "up_5"), ("E10", 14, "up_3")]
|
||||
SECONDARY = [
|
||||
(fuel, horizon, "up_3")
|
||||
for fuel in ("Gazole", "SP95", "SP98", "E10", "E85", "GPLc")
|
||||
for horizon in (7, 14)
|
||||
] + [("Gazole", 14, "down_3"), ("Gazole", 14, "down_5"), ("E10", 14, "down_3")]
|
||||
STAGES = [
|
||||
("local_matched", ()),
|
||||
("+fx", ("fx",)),
|
||||
("+fx+raffinage", ("fx", "raffinage")),
|
||||
("+fx+raffinage+portwatch", ("fx", "raffinage", "portwatch")),
|
||||
]
|
||||
|
||||
|
||||
# ------------------------------------------------------------------ algèbre locale, stdlib pure
|
||||
|
||||
|
||||
def fit_logistic(matrix, labels, l2=1.0, steps=250, rate=0.8):
|
||||
"""Régression logistique par descente de gradient, normalisation ajustée sur le train seul."""
|
||||
columns = list(zip(*matrix, strict=False))
|
||||
means = [fmean(column) for column in columns]
|
||||
spreads = [pstdev(column) or 1.0 for column in columns]
|
||||
design = [
|
||||
[1.0] + [(value - mean) / spread for value, mean, spread in zip(row, means, spreads, strict=False)]
|
||||
for row in matrix
|
||||
]
|
||||
weights = [0.0] * len(design[0])
|
||||
for _ in range(steps):
|
||||
gradient = [0.0] * len(weights)
|
||||
for point, label in zip(design, labels, strict=False):
|
||||
z = max(-30.0, min(30.0, sum(w * x for w, x in zip(weights, point, strict=False))))
|
||||
error = 1.0 / (1.0 + math.exp(-z)) - label
|
||||
for j, value in enumerate(point):
|
||||
gradient[j] += error * value
|
||||
count = len(design)
|
||||
for j in range(len(weights)):
|
||||
penalty = 0.0 if j == 0 else l2 * weights[j] / count
|
||||
weights[j] -= rate * (gradient[j] / count + penalty)
|
||||
return dict(weights=weights, means=means, spreads=spreads)
|
||||
|
||||
|
||||
def predict_logistic(model, row):
|
||||
design = [1.0] + [
|
||||
(value - mean) / spread
|
||||
for value, mean, spread in zip(row, model["means"], model["spreads"], strict=False)
|
||||
]
|
||||
z = max(-30.0, min(30.0, sum(w * x for w, x in zip(model["weights"], design, strict=False))))
|
||||
return 1.0 / (1.0 + math.exp(-z))
|
||||
|
||||
|
||||
def quantile_thresholds(scores, source_from, source_to):
|
||||
"""Mêmes règles de seuils que la baseline gelée, appliquées à la validation de ce bras."""
|
||||
ordered = sorted(scores)
|
||||
out = {}
|
||||
for quantile in QUANTILES:
|
||||
rank = min(len(ordered) - 1, math.ceil(quantile * (len(ordered) - 1)))
|
||||
out[f"q{int(quantile * 100)}"] = dict(
|
||||
value=round(ordered[rank], 6),
|
||||
calibrated_as=f"quantile {quantile:.0%} des scores de validation",
|
||||
source_from=source_from,
|
||||
source_to=source_to,
|
||||
source_n=len(ordered),
|
||||
)
|
||||
for threshold in SCORE_GRID:
|
||||
out[f"score>={threshold:.2f}"] = dict(
|
||||
value=threshold,
|
||||
calibrated_as="seuil absolu prédéfini",
|
||||
source_from=source_from,
|
||||
source_to=source_to,
|
||||
source_n=len(ordered),
|
||||
)
|
||||
return out
|
||||
|
||||
|
||||
# ------------------------------------------------------------------ construction des données
|
||||
|
||||
|
||||
_STATES = {}
|
||||
|
||||
|
||||
def local_rows(fuel, horizon):
|
||||
"""Rangées locales avec le score de risque **exactement** tel que la baseline gelée le calcule."""
|
||||
if fuel not in _STATES:
|
||||
_STATES[fuel] = states_for(fuel)
|
||||
states = _STATES[fuel]
|
||||
features = feature_rows(states)
|
||||
today = date.today().isoformat()
|
||||
rows = []
|
||||
for t, feature in features.items():
|
||||
label = event_target(states, t, horizon)
|
||||
if label and label["available_at"] <= today:
|
||||
rows.append(dict(t=t, score=None, target=label, regime=regime(feature["values"])))
|
||||
stats, groups, cursor = empty_stats(), {}, 0
|
||||
for row in rows:
|
||||
while cursor < len(rows) and rows[cursor]["target"]["available_at"] < row["t"]:
|
||||
add(stats, rows[cursor])
|
||||
add(groups.setdefault(rows[cursor]["regime"], empty_stats()), rows[cursor])
|
||||
cursor += 1
|
||||
if stats["n"] < MIN_MATURED_LABELS:
|
||||
continue
|
||||
row["score"] = risk_scores(stats, groups.get(row["regime"], empty_stats()))["local_regime"]
|
||||
return [row for row in rows if row["score"]]
|
||||
|
||||
|
||||
def dataset(rows, families, cache):
|
||||
"""Journées exploitables pour une famille, avec leurs features externes — mêmes jours aux deux bras."""
|
||||
names = []
|
||||
for family in families:
|
||||
cache.setdefault(family, None)
|
||||
if cache[family] is None:
|
||||
names.append(family)
|
||||
for family in names:
|
||||
cache[family] = up.family_features(family, "2015-01-01", date.today().isoformat())
|
||||
needed = [feature for family in families for feature in FEATURE_NAMES[family]]
|
||||
out = []
|
||||
for row in rows:
|
||||
values, ok = [], True
|
||||
for family in families:
|
||||
entry = cache[family].get(row["t"], ({}, {}))[0]
|
||||
for feature in FEATURE_NAMES[family]:
|
||||
value = entry.get(feature)
|
||||
if value is None:
|
||||
ok = False
|
||||
break
|
||||
values.append(value)
|
||||
if not ok:
|
||||
break
|
||||
if ok:
|
||||
out.append((row, values))
|
||||
return out, needed
|
||||
|
||||
|
||||
FEATURE_NAMES = {
|
||||
"fx": ["fx_log_level", "fx_ret_5", "fx_ret_21", "fx_z_252"],
|
||||
"raffinage": ["margin_z_252", "margin_chg_90", "diesel_htt_z_252", "diesel_htt_ret_28"],
|
||||
"portwatch": ["portwatch_tankers_z_252", "portwatch_tankers_chg_28", "portwatch_redsea_z_252"],
|
||||
}
|
||||
|
||||
|
||||
def split(pairs):
|
||||
train = [item for item in pairs if item[0]["t"] < TRAIN_END]
|
||||
validation = [item for item in pairs if TRAIN_END <= item[0]["t"] < VAL_END]
|
||||
test = [item for item in pairs if VAL_END <= item[0]["t"] <= TEST_END]
|
||||
return train, validation, test
|
||||
|
||||
|
||||
def build_predictions(rows, scores, thresholds, key):
|
||||
return [
|
||||
dict(
|
||||
t=row["t"],
|
||||
score={name: scores[index] for name in KEYS},
|
||||
thresholds={name: thresholds for name in KEYS},
|
||||
target=row["target"],
|
||||
train_n=len(rows),
|
||||
train_start=rows[0]["t"],
|
||||
train_end=rows[-1]["t"],
|
||||
manifest=[],
|
||||
calibration_refresh="fixed-split",
|
||||
)
|
||||
for index, row in enumerate(rows)
|
||||
]
|
||||
|
||||
|
||||
def summarize(predictions, key, labels):
|
||||
out = dict(brier=score_brier(predictions, key), pr_auc=pr_auc(predictions, key), thresholds={})
|
||||
for label in labels:
|
||||
metrics = score_threshold(predictions, key, label)
|
||||
metrics["expected_price_value_cents_per_signal"] = expected_price_value_cents_per_signal(metrics)
|
||||
metrics["decision_loss"] = decision_loss(predictions, key, label)
|
||||
metrics["episodes"] = episode_summary(predictions, key, label)
|
||||
metrics["non_overlapping"] = [non_overlapping(predictions, key, label, step) for step in (7, 14)]
|
||||
out["thresholds"][label] = metrics
|
||||
return out
|
||||
|
||||
|
||||
def verdict(delta_brier, delta_ap, real_brier, placebo_brier):
|
||||
"""Règle pré-déclarée AVANT de regarder les résultats, appliquée telle quelle."""
|
||||
if delta_brier is None or placebo_brier is None or real_brier is None:
|
||||
return "indéterminé — données insuffisantes"
|
||||
if real_brier >= placebo_brier:
|
||||
return "aucun apport démontré — le placebo fait aussi bien ou mieux"
|
||||
if delta_brier["usable"] and delta_brier["high"] < 0 and (delta_ap or 0) > 0:
|
||||
return "apporte une information reproductible"
|
||||
if delta_brier["usable"] and delta_brier["low"] > 0:
|
||||
return "dégrade le modèle"
|
||||
return "aucun apport démontré"
|
||||
|
||||
|
||||
def run_endpoint(fuel, horizon, key, families, cache, with_placebo):
|
||||
rows = local_rows(fuel, horizon)
|
||||
pairs, _ = dataset(rows, families, cache)
|
||||
train, validation, test = split(pairs)
|
||||
result = dict(
|
||||
fuel=fuel,
|
||||
horizon=horizon,
|
||||
event=key,
|
||||
families=list(families),
|
||||
n_train=len(train),
|
||||
n_validation=len(validation),
|
||||
n_test=len(test),
|
||||
)
|
||||
if len(train) < 200 or len(validation) < 100 or len(test) < 50:
|
||||
result["skipped"] = "fenêtre insuffisante"
|
||||
return result
|
||||
labels_base = [1.0 if row["target"]["events"][key]["hit"] else 0.0 for row, _ in train]
|
||||
arms = {}
|
||||
for name, use_external in (("baseline_local_matched", False), ("enriched", True)):
|
||||
matrix = [[row["score"][key]] + (values if use_external else []) for row, values in train]
|
||||
model = fit_logistic(matrix, labels_base)
|
||||
val_scores = [
|
||||
predict_logistic(model, [row["score"][key]] + (values if use_external else []))
|
||||
for row, values in validation
|
||||
]
|
||||
thresholds = quantile_thresholds(val_scores, train[0][0]["t"], validation[-1][0]["t"])
|
||||
test_scores = [
|
||||
predict_logistic(model, [row["score"][key]] + (values if use_external else []))
|
||||
for row, values in test
|
||||
]
|
||||
predictions = build_predictions([row for row, _ in test], test_scores, thresholds, key)
|
||||
arms[name] = dict(
|
||||
predictions=predictions,
|
||||
summary=summarize(
|
||||
predictions,
|
||||
key,
|
||||
[f"q{int(q * 100)}" for q in QUANTILES] + [f"score>={t:.2f}" for t in SCORE_GRID],
|
||||
),
|
||||
)
|
||||
result["matched_window"] = dict(
|
||||
train=train[0][0]["t"] + " → " + train[-1][0]["t"],
|
||||
validation=validation[0][0]["t"] + " → " + validation[-1][0]["t"],
|
||||
test=test[0][0]["t"] + " → " + test[-1][0]["t"],
|
||||
)
|
||||
if with_placebo and families:
|
||||
for name, shuffle in (("placebo_blocs_30j", "blocks"), ("placebo_decalage_90j", "shift")):
|
||||
modified = up.permute_blocks(pairs) if shuffle == "blocks" else up.shift_rows(pairs)
|
||||
train_p, _, test_p = split(modified)
|
||||
matrix = [[row["score"][key]] + values for row, values in train_p]
|
||||
model = fit_logistic(
|
||||
matrix, [1.0 if row["target"]["events"][key]["hit"] else 0.0 for row, _ in train_p]
|
||||
)
|
||||
scores = [predict_logistic(model, [row["score"][key]] + values) for row, values in test_p]
|
||||
predictions = build_predictions(
|
||||
[row for row, _ in test_p], scores, arms["enriched"]["predictions"][0]["thresholds"][key], key
|
||||
)
|
||||
arms[name] = dict(predictions=predictions, summary=summarize(predictions, key, ["q90"]))
|
||||
baseline, enriched = arms["baseline_local_matched"], arms["enriched"]
|
||||
paired_brier = paired_block_bootstrap(
|
||||
per_day_brier(enriched["predictions"], key), per_day_brier(baseline["predictions"], key)
|
||||
)
|
||||
paired_loss = paired_block_bootstrap(
|
||||
per_day_decision_loss(enriched["predictions"], key, "score>=0.25"),
|
||||
per_day_decision_loss(baseline["predictions"], key, "score>=0.25"),
|
||||
)
|
||||
placebo = arms.get("placebo_blocs_30j", {}).get("summary", {}).get("brier")
|
||||
result["comparison"] = dict(
|
||||
brier_baseline=baseline["summary"]["brier"],
|
||||
brier_enriched=enriched["summary"]["brier"],
|
||||
delta_brier=paired_brier,
|
||||
pr_auc_baseline=baseline["summary"]["pr_auc"],
|
||||
pr_auc_enriched=enriched["summary"]["pr_auc"],
|
||||
delta_pr_auc=round((enriched["summary"]["pr_auc"] or 0) - (baseline["summary"]["pr_auc"] or 0), 4),
|
||||
decision_loss_baseline=baseline["summary"]["thresholds"]["score>=0.25"]["decision_loss"],
|
||||
decision_loss_enriched=enriched["summary"]["thresholds"]["score>=0.25"]["decision_loss"],
|
||||
delta_decision_loss=paired_loss,
|
||||
brier_placebo_blocks=placebo,
|
||||
brier_placebo_shift=arms.get("placebo_decalage_90j", {}).get("summary", {}).get("brier"),
|
||||
)
|
||||
result["verdict"] = verdict(
|
||||
paired_brier, result["comparison"]["delta_pr_auc"], enriched["summary"]["brier"], placebo
|
||||
)
|
||||
for name in ("baseline_local_matched", "enriched", "placebo_blocs_30j"):
|
||||
if name in arms:
|
||||
result[name.replace("baseline_local_matched", "baseline")] = arms[name]["summary"]
|
||||
return result
|
||||
|
||||
|
||||
def run():
|
||||
output = Path("reports")
|
||||
output.mkdir(exist_ok=True)
|
||||
cache = {}
|
||||
results = dict(
|
||||
protocol=dict(
|
||||
train_end=TRAIN_END,
|
||||
validation_end=VAL_END,
|
||||
test_end=TEST_END,
|
||||
absolute_thresholds=list(ABS_THRESHOLDS),
|
||||
quantiles=list(QUANTILES),
|
||||
primary=[list(item) for item in PRIMARY],
|
||||
secondary=[list(item) for item in SECONDARY],
|
||||
stages=[list(item) for item in STAGES],
|
||||
brent="sauté : aucune série quotidienne propre sans roll traité",
|
||||
production="aucun score consommé par le conseil réel",
|
||||
),
|
||||
endpoints=[],
|
||||
ablations=[],
|
||||
)
|
||||
for families in [stage[1] for stage in STAGES]:
|
||||
for fuel, horizon, key in PRIMARY:
|
||||
print(f"{fuel} J+{horizon} {key} {'+'.join(families) or 'local'} ...", flush=True)
|
||||
entry = run_endpoint(fuel, horizon, key, families, cache, with_placebo=bool(families))
|
||||
entry["stage"] = "+".join(families) or "local_matched"
|
||||
entry["scope"] = "principal"
|
||||
results["ablations"].append(entry)
|
||||
for fuel, horizon, key in SECONDARY:
|
||||
for families in [(), ("fx", "raffinage", "portwatch")]:
|
||||
print(f"[secondaire] {fuel} J+{horizon} {key} {'+'.join(families) or 'local'} ...", flush=True)
|
||||
entry = run_endpoint(fuel, horizon, key, families, cache, with_placebo=False)
|
||||
entry["stage"] = "+".join(families) or "local_matched"
|
||||
entry["scope"] = "exploratoire" if "down" in key else "secondaire"
|
||||
results["endpoints"].append(entry)
|
||||
(output / "enrich-results.json").write_text(json.dumps(results, ensure_ascii=False, indent=1))
|
||||
write_report(results, output / "enrich-report.md")
|
||||
for entry in results["ablations"]:
|
||||
print(
|
||||
entry["fuel"],
|
||||
entry["horizon"],
|
||||
entry["event"],
|
||||
entry["stage"],
|
||||
entry.get("verdict"),
|
||||
(entry.get("comparison") or {}).get("brier_baseline"),
|
||||
(entry.get("comparison") or {}).get("brier_enriched"),
|
||||
(entry.get("comparison") or {}).get("brier_placebo_blocks"),
|
||||
flush=True,
|
||||
)
|
||||
|
||||
|
||||
def write_report(results, path):
|
||||
lines = [
|
||||
"# Apport marginal des familles amont — comparaison appariée",
|
||||
"",
|
||||
"Baseline `local_matched` ré-estimée sur exactement les mêmes journées que le bras",
|
||||
"enrichi. Seuils gelés identiques, aucune sélection sur 2026. Métrique économique et",
|
||||
"intervalles par blocs avec diagnostic d'effectif temporel.",
|
||||
"",
|
||||
]
|
||||
lines.append("## Table d'ablation (endpoints principaux)")
|
||||
lines.append("")
|
||||
for entry in results["ablations"]:
|
||||
comparison = entry.get("comparison") or {}
|
||||
lines.append(f"### {entry['fuel']} J+{entry['horizon']} {entry['event']} — {entry['stage']}")
|
||||
lines.append(
|
||||
f"- fenêtre appariée : {entry.get('matched_window')} · train {entry['n_train']}"
|
||||
f" · validation {entry['n_validation']} · test {entry['n_test']}"
|
||||
)
|
||||
if entry.get("skipped"):
|
||||
lines.append(f"- **{entry['skipped']}**")
|
||||
continue
|
||||
lines.append(
|
||||
f"- Brier : baseline {comparison['brier_baseline']} → enrichi "
|
||||
f"{comparison['brier_enriched']} (placebo {comparison['brier_placebo_blocks']})"
|
||||
)
|
||||
lines.append(f"- différence appariée : {json.dumps(comparison['delta_brier'], ensure_ascii=False)}")
|
||||
lines.append(
|
||||
f"- PR-AUC : {comparison['pr_auc_baseline']} → {comparison['pr_auc_enriched']}"
|
||||
f" (Δ {comparison['delta_pr_auc']})"
|
||||
)
|
||||
lines.append(
|
||||
f"- perte de décision au seuil 0,25 : {comparison['decision_loss_baseline']} →"
|
||||
f" {comparison['decision_loss_enriched']} · {json.dumps(comparison['delta_decision_loss'], ensure_ascii=False)}"
|
||||
)
|
||||
threshold = (entry.get("enriched") or {}).get("thresholds", {}).get("q90")
|
||||
if threshold:
|
||||
lines.append(
|
||||
f"- seuil q90 : couverture observée {threshold['actual_test_coverage']},"
|
||||
f" précision {threshold['precision']} (base {threshold['base_rate']}),"
|
||||
f" lift {threshold['lift_vs_base']}, valeur attendue"
|
||||
f" {threshold['expected_price_value_cents_per_signal']} c€/signal"
|
||||
)
|
||||
lines.append(f"- **verdict : {entry['verdict']}**")
|
||||
lines.append("")
|
||||
lines.append("## Détail par endpoint et par seuil")
|
||||
lines.append("")
|
||||
for entry in results["ablations"] + results["endpoints"]:
|
||||
if entry.get("skipped"):
|
||||
continue
|
||||
for arm in ("baseline", "enriched"):
|
||||
summary = entry.get(arm)
|
||||
if not summary:
|
||||
continue
|
||||
lines.append(
|
||||
f"### {entry['fuel']} J+{entry['horizon']} {entry['event']} · "
|
||||
f"{entry['stage']} · {arm} ({entry['scope']})"
|
||||
)
|
||||
lines.append(f"Brier {summary['brier']} · PR-AUC {summary['pr_auc']}")
|
||||
for label, metrics in summary["thresholds"].items():
|
||||
lines.append(
|
||||
f"- {label} ≥ {metrics['threshold_value']} : couverture "
|
||||
f"{metrics['actual_test_coverage']} · précision {metrics['precision']} · "
|
||||
f"lift {metrics['lift_vs_base']} · valeur attendue "
|
||||
f"{metrics['expected_price_value_cents_per_signal']} c€/signal · IC "
|
||||
f"{json.dumps(metrics['precision_ci'], ensure_ascii=False)}"
|
||||
)
|
||||
lines.append("")
|
||||
(Path(path)).write_text("\n".join(lines))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
run()
|
||||
160
risk_report.py
160
risk_report.py
@@ -21,6 +21,7 @@ from statistics import fmean
|
||||
KEYS = [f"{d}_{q}" for d in ("up", "down") for q in (2, 3, 5)]
|
||||
BIN_BOUNDS = (0.0, 0.1, 0.2, 0.3, 0.4, 0.5, 1.01)
|
||||
DEFAULT_BLOCK = 28
|
||||
MIN_USABLE_BLOCKS = 8 # en dessous, un IC par blocs est étroit par construction, pas par preuve
|
||||
BOOTSTRAP_RESAMPLES = 150 # compromis coût/stabilité : 150 rééchantillonnages de blocs de 28 j
|
||||
|
||||
|
||||
@@ -113,26 +114,58 @@ def reliability(pairs):
|
||||
# ------------------------------------------------------------------ intervalles de confiance
|
||||
|
||||
|
||||
def bootstrap_ci(values, block=DEFAULT_BLOCK, resamples=BOOTSTRAP_RESAMPLES, seed=7):
|
||||
"""Bootstrap par blocs temporels : respecte l'autocorrélation des séries de prix."""
|
||||
if len(values) < 10:
|
||||
def bootstrap_ci(values, block=DEFAULT_BLOCK, resamples=BOOTSTRAP_RESAMPLES, seed=7, flags=None):
|
||||
# `values` contient un élément par jour évalué, `None` hors signal. Les blocs sont découpés
|
||||
# sur la chronologie complète : sans cela, 53 jours signalés formeraient 2 blocs de 28 jours
|
||||
# et l'intervalle serait étroit artificiellement.
|
||||
"""Bootstrap par blocs temporels : respecte l'autocorrélation des séries de prix.
|
||||
|
||||
Le diagnostic de blocs est **toujours** renvoyé avec l'intervalle. Un intervalle étroit
|
||||
n'est crédible que si plusieurs blocs indépendants portent le signal : le seuil q95
|
||||
Gazole J+14 n'a que 53 jours signalés et 11 épisodes, son IC quotidien est artificiellement
|
||||
étroit. Sans blocs suffisants, aucun intervalle et aucune significativité ne sont revendiqués.
|
||||
"""
|
||||
sample = [value for value in values if value is not None]
|
||||
if len(sample) < 10:
|
||||
return None
|
||||
flags = [True] * len(values) if flags is None else flags
|
||||
rng = random.Random(seed)
|
||||
blocks = [values[i : i + block] for i in range(0, len(values), block)]
|
||||
blocks = list(
|
||||
zip(
|
||||
[values[i : i + block] for i in range(0, len(values), block)],
|
||||
[flags[i : i + block] for i in range(0, len(flags), block)],
|
||||
strict=False,
|
||||
)
|
||||
)
|
||||
means = []
|
||||
for _ in range(resamples):
|
||||
drawn = []
|
||||
for _ in range(len(blocks)):
|
||||
drawn.extend(blocks[rng.randrange(len(blocks))])
|
||||
vals, fl = blocks[rng.randrange(len(blocks))]
|
||||
drawn.extend(v for v, f in zip(vals, fl, strict=False) if f and v is not None)
|
||||
if drawn:
|
||||
means.append(fmean(drawn))
|
||||
if not means:
|
||||
return None
|
||||
means.sort()
|
||||
return dict(
|
||||
with_signal = sum(1 for _, fl in blocks if any(fl))
|
||||
out = dict(
|
||||
low=round(means[int(0.025 * (len(means) - 1))], 4),
|
||||
high=round(means[int(0.975 * (len(means) - 1))], 4),
|
||||
block_days=block,
|
||||
resamples=resamples,
|
||||
n_blocks_total=len(blocks),
|
||||
n_blocks_with_signal=with_signal,
|
||||
n_effective_signals=with_signal,
|
||||
n_days_signaled=len(sample),
|
||||
)
|
||||
if with_signal < MIN_USABLE_BLOCKS:
|
||||
out["usable"] = False
|
||||
out["note"] = "intervalle non exploitable — effectif temporel insuffisant"
|
||||
else:
|
||||
out["usable"] = True
|
||||
out["note"] = f"{with_signal} blocs porteurs de signaux sur {len(blocks)}"
|
||||
return out
|
||||
|
||||
|
||||
# ------------------------------------------------------------------ signaux et épisodes
|
||||
@@ -176,7 +209,10 @@ def score_threshold(predictions, key, label, flags=None):
|
||||
correct = [event for event in signaled if event["hit"]]
|
||||
wrong = [event for event in signaled if not event["hit"]]
|
||||
total_hits = sum(1 for p, _flag in rows if p["target"]["events"][key]["hit"])
|
||||
hits_vector = [1 if event["hit"] else 0 for event in signaled]
|
||||
day_hits = [
|
||||
(1 if event["hit"] else 0) if flag else None
|
||||
for event, flag in zip([p["target"]["events"][key] for p, _ in rows], flags, strict=False)
|
||||
]
|
||||
precision = len(correct) / len(signaled) if signaled else None
|
||||
spec = predictions[0]["thresholds"][key][label]
|
||||
return dict(
|
||||
@@ -201,7 +237,7 @@ def score_threshold(predictions, key, label, flags=None):
|
||||
if wrong
|
||||
else None,
|
||||
mean_terminal_when_wrong_cents=round(fmean(e["terminal"] for e in wrong), 2) if wrong else None,
|
||||
precision_ci=bootstrap_ci(hits_vector) if len(signaled) >= 20 else None,
|
||||
precision_ci=bootstrap_ci(day_hits, flags=list(flags)) if len(signaled) >= 10 else None,
|
||||
)
|
||||
|
||||
|
||||
@@ -229,10 +265,116 @@ def episode_summary(predictions, key, label):
|
||||
lift_vs_base=round(precision / base, 3) if base else None,
|
||||
mean_episode_length_days=round(fmean(r["days"] for r in rows), 2),
|
||||
mean_delay_when_right_days=round(fmean(r["best"][1] for r in wins), 2) if wins else None,
|
||||
precision_ci=bootstrap_ci([1 if r["hits"] else 0 for r in rows]) if len(rows) >= 20 else None,
|
||||
precision_ci=bootstrap_ci([1 if r["hits"] else 0 for r in rows]) if len(rows) >= 10 else None,
|
||||
)
|
||||
|
||||
|
||||
def pr_auc(predictions, key):
|
||||
"""Aire sous la courbe précision-rappel : adaptée aux événements rares, appariée jour/jour."""
|
||||
rows = sorted(
|
||||
((p["score"][key], p["target"]["events"][key]["hit"]) for p in predictions), key=lambda item: -item[0]
|
||||
)
|
||||
positives = sum(1 for _, hit in rows if hit)
|
||||
if not positives:
|
||||
return None
|
||||
area, seen_pos, index = 0.0, 0, 0
|
||||
while index < len(rows):
|
||||
score = rows[index][0]
|
||||
tp = fp = 0
|
||||
while index < len(rows) and rows[index][0] == score:
|
||||
tp += 1 if rows[index][1] else 0
|
||||
fp += 0 if rows[index][1] else 1
|
||||
index += 1
|
||||
recall_delta = tp / positives
|
||||
precision_at = tp / (tp + fp) if (tp + fp) else 0.0
|
||||
area += recall_delta * precision_at
|
||||
seen_pos += tp
|
||||
if seen_pos == positives:
|
||||
break
|
||||
return round(area, 4)
|
||||
|
||||
|
||||
def score_brier(predictions, key):
|
||||
values = [
|
||||
(p["score"][key] - (1.0 if p["target"]["events"][key]["hit"] else 0.0)) ** 2 for p in predictions
|
||||
]
|
||||
return round(fmean(values), 5) if values else None
|
||||
|
||||
|
||||
def decision_loss(predictions, key, label):
|
||||
"""Perte de décision appariée : signal manqué (faux négatif) ou signal émis à tort."""
|
||||
flags = signal_flags(predictions, key, label)
|
||||
loss = [
|
||||
0
|
||||
if (
|
||||
(flag and p["target"]["events"][key]["hit"])
|
||||
or (not flag and not p["target"]["events"][key]["hit"])
|
||||
)
|
||||
else 1
|
||||
for p, flag in zip(predictions, flags, strict=False)
|
||||
]
|
||||
return round(fmean(loss), 4) if loss else None
|
||||
|
||||
|
||||
def expected_price_value_cents_per_signal(thresholds):
|
||||
"""Valeur attendue par signal : gains des vrais positifs moins pertes adverses pondérées.
|
||||
|
||||
Métrique **expérimentale** : aucun effet sur le conseil véhicule.
|
||||
"""
|
||||
precision = thresholds.get("precision")
|
||||
gain = thresholds.get("mean_opportunity_when_right_cents")
|
||||
adverse = thresholds.get("mean_adverse_when_wrong_cents")
|
||||
if precision is None or gain is None:
|
||||
return None
|
||||
return round(precision * gain - (1 - precision) * (adverse or 0.0), 2)
|
||||
|
||||
|
||||
def paired_block_bootstrap(values_a, values_b, block=DEFAULT_BLOCK, resamples=BOOTSTRAP_RESAMPLES, seed=13):
|
||||
"""Bootstrap apparié par blocs : IC de la **différence** jour par jour entre deux modèles.
|
||||
|
||||
Deux intervalles calculés séparément ne disent pas si l'écart est réel ; la différence
|
||||
appariée, elle, élimine la variance commune aux deux modèles sur les mêmes journées.
|
||||
"""
|
||||
if len(values_a) != len(values_b) or len(values_a) < 10:
|
||||
return None
|
||||
diffs = [a - b for a, b in zip(values_a, values_b, strict=False)]
|
||||
rng = random.Random(seed)
|
||||
blocks = [diffs[i : i + block] for i in range(0, len(diffs), block)]
|
||||
means = sorted(
|
||||
fmean([v for b in [rng.choice(blocks) for _ in blocks] for v in b]) for _ in range(resamples)
|
||||
)
|
||||
low, high = means[int(0.025 * (len(means) - 1))], means[int(0.975 * (len(means) - 1))]
|
||||
usable = len(blocks) >= MIN_USABLE_BLOCKS
|
||||
return dict(
|
||||
mean_difference=round(fmean(diffs), 5),
|
||||
low=round(low, 5),
|
||||
high=round(high, 5),
|
||||
n_blocks_total=len(blocks),
|
||||
block_days=block,
|
||||
resamples=resamples,
|
||||
usable=usable,
|
||||
significant=bool(usable and (low > 0 or high < 0)),
|
||||
note=None if usable else "intervalle non exploitable — effectif temporel insuffisant",
|
||||
)
|
||||
|
||||
|
||||
def per_day_brier(predictions, key):
|
||||
return [(p["score"][key] - (1.0 if p["target"]["events"][key]["hit"] else 0.0)) ** 2 for p in predictions]
|
||||
|
||||
|
||||
def per_day_decision_loss(predictions, key, label):
|
||||
flags = signal_flags(predictions, key, label)
|
||||
return [
|
||||
0
|
||||
if (
|
||||
(flag and p["target"]["events"][key]["hit"])
|
||||
or (not flag and not p["target"]["events"][key]["hit"])
|
||||
)
|
||||
else 1
|
||||
for p, flag in zip(predictions, flags, strict=False)
|
||||
]
|
||||
|
||||
|
||||
def select_on_validation(snapshot, key):
|
||||
"""Seuil absolu choisi EXCLUSIVEMENT sur les paires de validation passées."""
|
||||
pairs = snapshot["pairs"]
|
||||
|
||||
119
tests/test_enrich_protocol.py
Normal file
119
tests/test_enrich_protocol.py
Normal file
@@ -0,0 +1,119 @@
|
||||
"""Le protocole amont tient-il : appariement, disponibilité réelle, placebo, IC diagnostiqués."""
|
||||
import sqlite3
|
||||
|
||||
import pytest
|
||||
|
||||
import upstream_features as up
|
||||
from enrich_campaign import fit_logistic, predict_logistic, quantile_thresholds, verdict
|
||||
from risk_report import MIN_USABLE_BLOCKS, bootstrap_ci, paired_block_bootstrap
|
||||
|
||||
|
||||
def make_db(tmp_path):
|
||||
path = tmp_path / "synthetic.sqlite3"
|
||||
conn = sqlite3.connect(path)
|
||||
conn.execute("create table upstream_series (series text, day text, value real, unit text,"
|
||||
" source text, fetched_at text, observed_at text, published_at text)")
|
||||
conn.execute("create table chokepoint_daily (chokepoint text, day text, transit_tankers real,"
|
||||
" transit_total real, capacity_tankers real, capacity_total real, source text,"
|
||||
" fetched_at text)")
|
||||
for index in range(0, 40):
|
||||
day = f"2024-01-{index + 1:02d}" if index < 31 else f"2024-02-{index - 30:02d}"
|
||||
conn.execute("insert into upstream_series values (?,?,?,?,?,?,?,?)",
|
||||
("usd_per_eur", day, 1.10 + index / 1000, "usd", "BCE", None, day, None))
|
||||
conn.execute("insert into chokepoint_daily values (?,?,?,?,?,?,?,?)",
|
||||
("Strait of Hormuz", day, 50 + index, 90, 10, 20, "IMF PortWatch", None))
|
||||
conn.commit()
|
||||
conn.close()
|
||||
return path
|
||||
|
||||
|
||||
def test_publication_lag_hides_a_value_that_is_not_published_yet(tmp_path):
|
||||
path = make_db(tmp_path)
|
||||
points = up.load_family("portwatch", path)["portwatch_tankers"]
|
||||
observed = points[0]["day"]
|
||||
assert points[0]["lag_days"] == 10, "PortWatch décrit un jour mais publie plus tard"
|
||||
daily = up.asof_daily(points, observed, points[0]["available_at"])
|
||||
assert daily[observed] is None, "aucune ligne ne doit être visible avant sa publication"
|
||||
assert daily[points[0]["available_at"]] is not None, "elle devient visible à sa date de publication"
|
||||
|
||||
|
||||
def test_forward_fill_starts_only_after_publication(tmp_path):
|
||||
path = make_db(tmp_path)
|
||||
points = up.load_family("portwatch", path)["portwatch_tankers"]
|
||||
start, end = points[0]["day"], points[-1]["available_at"]
|
||||
daily = up.asof_daily(points, start, end)
|
||||
published = points[0]["available_at"]
|
||||
assert daily[published] == points[0]["value"]
|
||||
assert daily[start] is None
|
||||
assert all(value is not None for day, value in daily.items() if day > published)
|
||||
|
||||
|
||||
def test_external_features_never_change_when_a_future_value_changes(tmp_path):
|
||||
path = make_db(tmp_path)
|
||||
before = up.family_features("fx", "2024-01-01", "2024-02-10", path)
|
||||
snapshots = {day: dict(values) for day, (values, _) in before.items()}
|
||||
conn = sqlite3.connect(path)
|
||||
conn.execute("update upstream_series set value = value * 3 where day = '2024-02-09'")
|
||||
conn.commit()
|
||||
conn.close()
|
||||
after = up.family_features("fx", "2024-01-01", "2024-02-10", path)
|
||||
for day in ("2024-01-05", "2024-01-20", "2024-02-01"):
|
||||
assert after[day][0] == snapshots[day], "une valeur plus récente ne réécrit pas le passé"
|
||||
|
||||
|
||||
def test_placebo_keeps_the_distribution_and_breaks_the_order(tmp_path):
|
||||
rows = [(index, index * 2.0) for index in range(200)]
|
||||
shuffled = up.permute_blocks(rows, block=30, seed=5)
|
||||
assert sorted(shuffled) == sorted(rows), "la distribution marginale est conservée"
|
||||
assert shuffled != rows, "l'ordre temporel est bien cassé"
|
||||
shifted = up.shift_rows(rows, shift=90)
|
||||
assert shifted[-1] == rows[89], "décalage temporel non causal explicite"
|
||||
|
||||
|
||||
def test_paired_bootstrap_detects_a_systematic_difference():
|
||||
good = [0.1] * 600
|
||||
bad = [0.3] * 600
|
||||
same = paired_block_bootstrap(good, good)
|
||||
assert same["mean_difference"] == 0 and not same["significant"]
|
||||
worse = paired_block_bootstrap(bad, good)
|
||||
assert worse["mean_difference"] > 0 and worse["significant"], "dégradation systématique détectée"
|
||||
better = paired_block_bootstrap(good, bad)
|
||||
assert better["mean_difference"] < 0 and better["high"] < 0
|
||||
|
||||
|
||||
def test_ci_exposes_block_diagnostics_and_refuses_a_thin_effectif():
|
||||
flags = [True] * 12 + [False] * 588
|
||||
thin = bootstrap_ci([1] * 12 + [None] * 588, flags=flags)
|
||||
assert thin["n_blocks_total"] == 22
|
||||
assert thin["n_blocks_with_signal"] == 1 and thin["n_effective_signals"] == 1
|
||||
assert thin["usable"] is False
|
||||
assert "non exploitable" in thin["note"]
|
||||
wide = [True] * 300 + [False] * 300
|
||||
usable = bootstrap_ci([1, 0] * 150 + [None] * 300, flags=wide)
|
||||
assert usable["n_blocks_with_signal"] >= MIN_USABLE_BLOCKS and usable["usable"] is True
|
||||
|
||||
|
||||
def test_verdicts_are_pre_declared_and_placebo_aware():
|
||||
real = dict(usable=True, low=-0.02, high=-0.004, mean_difference=-0.01)
|
||||
assert verdict(real, 0.03, 0.20, 0.25) == "apporte une information reproductible"
|
||||
assert verdict(real, 0.03, 0.30, 0.20) == "aucun apport démontré — le placebo fait aussi bien ou mieux"
|
||||
assert verdict(dict(usable=True, low=0.002, high=0.03), -0.01, 0.30, 0.35) == "dégrade le modèle"
|
||||
assert verdict(dict(usable=False, low=-0.02, high=0.004), 0.01, 0.20, 0.25) == "aucun apport démontré"
|
||||
|
||||
|
||||
def test_thresholds_follow_the_frozen_rule_on_their_own_validation():
|
||||
scores = [0.1] * 95 + [0.5] * 5
|
||||
table = quantile_thresholds(scores, "2023-01-01", "2024-12-31")
|
||||
assert table["q95"]["value"] == pytest.approx(0.5)
|
||||
assert table["q90"]["value"] == pytest.approx(0.1)
|
||||
assert table["score>=0.25"]["value"] == 0.25
|
||||
assert table["q95"]["source_from"] == "2023-01-01"
|
||||
|
||||
|
||||
def test_logistic_is_deterministic_and_responds_to_its_feature():
|
||||
matrix = [[0.0], [0.1], [0.9], [1.0]] * 50
|
||||
labels = [0.0, 0.0, 1.0, 1.0] * 50
|
||||
first = fit_logistic(matrix, labels)
|
||||
second = fit_logistic(matrix, labels)
|
||||
assert first["weights"] == second["weights"], "aucun aléa dans l'ajustement"
|
||||
assert predict_logistic(first, [1.0]) > predict_logistic(first, [0.0])
|
||||
213
upstream_features.py
Normal file
213
upstream_features.py
Normal file
@@ -0,0 +1,213 @@
|
||||
"""Familles de données amont, lues avec leur disponibilité réelle — jamais avec leur date d'observation.
|
||||
|
||||
Chaque famille est construite en trois temps :
|
||||
|
||||
1. **Disponibilité** : `available_at` vient de la publication réelle quand elle existe, sinon d'un
|
||||
décalage **estimé par source** (`asof.PUBLICATION_LAG_DAYS`) ; un décalage supplémentaire
|
||||
conservateur est appliqué à l'EUR/USD (cotation BCE publiée en fin de journée).
|
||||
2. **Reconduction, pas interpolation** : entre deux publications, la dernière valeur **déjà
|
||||
publiée** est reconduite. Aucun forward-fill ne rend une publication visible avant sa vraie
|
||||
date, et une valeur trop ancienne (`FEATURE_MAX_AGE_DAYS`) disparaît au lieu de rester.
|
||||
3. **Dérivées tournées vers le passé** : variations et z-scores n'utilisent que des valeurs
|
||||
disponibles à la date considérée.
|
||||
|
||||
Brent est volontairement absent : la seule série quotidienne stockée est `brent_futures_usd`
|
||||
(BZ=F, contrat enchaîné) dont les rolls ne sont pas traités proprement.
|
||||
"""
|
||||
|
||||
import math
|
||||
import sqlite3
|
||||
from datetime import date, timedelta
|
||||
from pathlib import Path
|
||||
from statistics import fmean, pstdev
|
||||
|
||||
from asof import PUBLICATION_LAG_DAYS, source_family
|
||||
|
||||
DB_PATH = Path("/var/lib/fuel-advisor/fuel.sqlite3")
|
||||
FEATURE_MAX_AGE_DAYS = 45
|
||||
ZSCORE_WINDOW = 252
|
||||
ZSCORE_MIN = 120
|
||||
# Décalage supplémentaire conservateur : la BCE publie vers 16 h, après la collecte locale du matin.
|
||||
EXTRA_LAG_DAYS = {"usd_per_eur": 1}
|
||||
# Familles telles qu'elles sont empilées dans la campagne ; Brent est sauté (cf. docstring).
|
||||
FAMILY_SERIES = {
|
||||
"fx": ["usd_per_eur"],
|
||||
"raffinage": ["dgec_margin_eur_per_tonne", "eu_fr_diesel_htt"],
|
||||
"portwatch": [],
|
||||
}
|
||||
|
||||
|
||||
def connect(path=None):
|
||||
return sqlite3.connect(path or DB_PATH)
|
||||
|
||||
|
||||
def _fk_series(conn, series):
|
||||
rows = conn.execute(
|
||||
"select day, value from upstream_series where series=? and value is not null order by day",
|
||||
(series,),
|
||||
).fetchall()
|
||||
family = source_family(series)
|
||||
lag = int(PUBLICATION_LAG_DAYS.get(family, 0)) + EXTRA_LAG_DAYS.get(family, 0)
|
||||
return [
|
||||
dict(
|
||||
day=r[0][:10],
|
||||
value=float(r[1]),
|
||||
available_at=(date.fromisoformat(r[0][:10]) + timedelta(days=lag)).isoformat(),
|
||||
lag_days=lag,
|
||||
series=series,
|
||||
)
|
||||
for r in rows
|
||||
]
|
||||
|
||||
|
||||
def _chokepoint_series(conn):
|
||||
lag = int(PUBLICATION_LAG_DAYS.get("portwatch", 10))
|
||||
total, redsea = {}, {}
|
||||
for day, choke, tankers in conn.execute(
|
||||
"select day, chokepoint, transit_tankers from chokepoint_daily order by day"
|
||||
):
|
||||
if tankers is None:
|
||||
continue
|
||||
day = day[:10]
|
||||
total[day] = total.get(day, 0.0) + float(tankers)
|
||||
if choke in ("Suez Canal", "Bab el-Mandeb Strait"):
|
||||
redsea[day] = redsea.get(day, 0.0) + float(tankers)
|
||||
out = {}
|
||||
for name, series in (("portwatch_tankers", total), ("portwatch_redsea", redsea)):
|
||||
out[name] = [
|
||||
dict(
|
||||
day=day,
|
||||
value=value,
|
||||
available_at=(date.fromisoformat(day) + timedelta(days=lag)).isoformat(),
|
||||
lag_days=lag,
|
||||
series=name,
|
||||
)
|
||||
for day, value in sorted(series.items())
|
||||
]
|
||||
return out
|
||||
|
||||
|
||||
def load_family(name, path=None):
|
||||
"""Séries d'une famille, avec leur `available_at` explicite."""
|
||||
conn = connect(path)
|
||||
try:
|
||||
if name == "portwatch":
|
||||
return _chokepoint_series(conn)
|
||||
return {series: _fk_series(conn, series) for series in FAMILY_SERIES[name]}
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
|
||||
def asof_daily(points, start, end, max_age=FEATURE_MAX_AGE_DAYS):
|
||||
"""Valeur quotidienne **publiée** : reconduite après publication, absente avant et si périmée."""
|
||||
usable = sorted(points, key=lambda p: (p["available_at"], p["day"]))
|
||||
out, index = {}, 0
|
||||
last = None
|
||||
day = date.fromisoformat(start)
|
||||
stop = date.fromisoformat(end)
|
||||
while day <= stop:
|
||||
text = day.isoformat()
|
||||
while index < len(usable) and usable[index]["available_at"] <= text and usable[index]["day"] <= text:
|
||||
last = usable[index]
|
||||
index += 1
|
||||
if last is None:
|
||||
out[text] = None
|
||||
else:
|
||||
age = (day - date.fromisoformat(last["available_at"])).days
|
||||
out[text] = last["value"] if age <= max_age else None
|
||||
day += timedelta(days=1)
|
||||
return out
|
||||
|
||||
|
||||
def trailing(values, day, window):
|
||||
"""Fenêtre de valeurs strictement antérieures ou égales au jour, sans trou."""
|
||||
keys = [k for k in values if k <= day]
|
||||
keys.sort()
|
||||
window_values = [values[k] for k in keys[-window:]]
|
||||
return window_values if all(v is not None for v in window_values) else None
|
||||
|
||||
|
||||
def zscore(values, day, window=ZSCORE_WINDOW, minimum=ZSCORE_MIN):
|
||||
sample = trailing(values, day, window)
|
||||
if not sample or len(sample) < minimum:
|
||||
return None
|
||||
spread = pstdev(sample)
|
||||
if not spread:
|
||||
return None
|
||||
return (values[day] - fmean(sample)) / spread
|
||||
|
||||
|
||||
def change(values, day, days):
|
||||
earlier = (date.fromisoformat(day) - timedelta(days=days)).isoformat()
|
||||
if values.get(day) is None or values.get(earlier) is None:
|
||||
return None
|
||||
return values[day] - values[earlier]
|
||||
|
||||
|
||||
def log_return(values, day, days):
|
||||
earlier = (date.fromisoformat(day) - timedelta(days=days)).isoformat()
|
||||
if values.get(day) is None or values.get(earlier) in (None, 0):
|
||||
return None
|
||||
return math.log(values[day] / values[earlier])
|
||||
|
||||
|
||||
def family_features(name, start, end, path=None):
|
||||
"""Features quotidiennes d'une famille : dict jour → ({feature: valeur}, disponibilité)."""
|
||||
series = load_family(name, path)
|
||||
daily = {key: asof_daily(points, start, end) for key, points in series.items()}
|
||||
availability = {key: max(p["available_at"] for p in points) for key, points in series.items()}
|
||||
out = {}
|
||||
day = date.fromisoformat(start)
|
||||
stop = date.fromisoformat(end)
|
||||
while day <= stop:
|
||||
text = day.isoformat()
|
||||
values = {}
|
||||
if name == "fx":
|
||||
level = daily["usd_per_eur"].get(text)
|
||||
if level is not None and level > 0:
|
||||
values["fx_log_level"] = round(math.log(level), 6)
|
||||
values["fx_ret_5"] = log_return(daily["usd_per_eur"], text, 5)
|
||||
values["fx_ret_21"] = log_return(daily["usd_per_eur"], text, 21)
|
||||
values["fx_z_252"] = zscore(daily["usd_per_eur"], text)
|
||||
elif name == "raffinage":
|
||||
margin = daily["dgec_margin_eur_per_tonne"]
|
||||
diesel = daily["eu_fr_diesel_htt"]
|
||||
values["margin_z_252"] = zscore(margin, text)
|
||||
values["margin_chg_90"] = change(margin, text, 90)
|
||||
values["diesel_htt_z_252"] = zscore(diesel, text)
|
||||
values["diesel_htt_ret_28"] = log_return(diesel, text, 28)
|
||||
elif name == "portwatch":
|
||||
values["portwatch_tankers_z_252"] = zscore(daily["portwatch_tankers"], text)
|
||||
values["portwatch_tankers_chg_28"] = change(daily["portwatch_tankers"], text, 28)
|
||||
values["portwatch_redsea_z_252"] = zscore(daily["portwatch_redsea"], text)
|
||||
out[text] = (values, availability)
|
||||
day += timedelta(days=1)
|
||||
return out
|
||||
|
||||
|
||||
def family_start(name, path=None):
|
||||
"""Premier jour où toute la famille est exploitable (toutes dérivées calculables)."""
|
||||
series = load_family(name, path)
|
||||
firsts = [min(p["available_at"] for p in points) for points in series.values() if points]
|
||||
return max(firsts) if firsts else None
|
||||
|
||||
|
||||
def permute_blocks(rows, block=30, seed=23):
|
||||
"""Placebo : permute les features par blocs temporels de `block` jours.
|
||||
|
||||
La distribution marginale et l'autocorrélation interne aux blocs sont conservées, le lien
|
||||
temporel entre la famille externe et la cible est détruit. Si le modèle réel ne fait pas
|
||||
mieux que ce placebo, l'apport annoncé n'est pas crédible.
|
||||
"""
|
||||
import random
|
||||
|
||||
rng = random.Random(seed)
|
||||
blocks = [rows[i : i + block] for i in range(0, len(rows), block)]
|
||||
order = list(range(len(blocks)))
|
||||
rng.shuffle(order)
|
||||
return [row for index in order for row in blocks[index]]
|
||||
|
||||
|
||||
def shift_rows(rows, shift=90):
|
||||
"""Placebo non causal : décale la famille de +`shift` jours (information reçue trop tard)."""
|
||||
return rows[shift:] + rows[:shift]
|
||||
Reference in New Issue
Block a user