Aucune famille ne survit : Brier et PR-AUC degrades sur les endpoints pre-declares, placebo par blocs ou par decalage souvent meilleur que la vraie serie. Les seuils dIC exposent desormais n_blocks_total, n_blocks_with_signal et n_effective_signals, avec refus de toute significativite sur un intervalle non exploitable.
140 lines
6.9 KiB
Python
140 lines
6.9 KiB
Python
"""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, pr_auc
|
|
|
|
|
|
def _target(hit, terminal=1.0, amplitude=3.0, delay=3):
|
|
return dict(events={"up_3": dict(hit=hit, terminal=terminal, amplitude=amplitude, delay=delay)},
|
|
available_at="2026-01-01", panel=10, future_min_delta=0.0, future_max_delta=3.0)
|
|
|
|
|
|
|
|
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_reassigns_features_instead_of_reordering_rows():
|
|
rows = [(f"j{index}", [index * 2.0]) for index in range(200)]
|
|
shuffled = up.permute_blocks(rows, block=30, seed=5)
|
|
assert [row for row, _ in shuffled] == [row for row, _ in rows], "l'ordre des journées est conservé"
|
|
assert sorted(value for _, values in shuffled for value in values) == \
|
|
sorted(value for _, values in rows for value in values), "distribution marginale conservée"
|
|
assert [values for _, values in shuffled] != [values for _, values in rows], \
|
|
"les features sont bien réassignées à d'autres journées"
|
|
shifted = up.shift_rows(rows, shift=90)
|
|
assert [row for row, _ in shifted] == [row for row, _ in rows]
|
|
assert shifted[0][1] == [rows[90][1][0]], "information d'une journée plus tardive"
|
|
|
|
|
|
def test_pr_auc_is_cumulative_and_not_inflated():
|
|
predictions = [dict(score={"up_3": score}, target=_target(hit))
|
|
for score, hit in ((0.4, True), (0.3, False), (0.2, False), (0.1, True))]
|
|
assert pr_auc(predictions, "up_3") == pytest.approx(0.75), \
|
|
"AP = (1/1 + 2/4)/2 : la précision doit être cumulative"
|
|
perfect = [dict(score={"up_3": score}, target=_target(hit))
|
|
for score, hit in ((0.9, True), (0.8, True), (0.1, False))]
|
|
assert pr_auc(perfect, "up_3") == pytest.approx(1.0)
|
|
|
|
|
|
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])
|