Repository Public
1#!/usr/bin/env python32# =============================================================================3# SP BOUCHER | SOFTWARE & RESEARCH4# ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5# =============================================================================6#7# PROJECT METADATA8# -----------------------------------------------------------------------------9# Project : Vrai-Prix10# File : scripts/hedonic-retrain.py11# Module : scripts12# Repository : https://git.spboucher.ai/vrai-prix13# Created : 2026-08-2214# Last Modified : 2026-08-2215#16# =============================================================================17# AUTHOR & PROFESSIONAL AFFILIATION18# =============================================================================19#20# Author : Simon-Pierre Boucher21# Position : Professor of Finance22# Institution : Université du Québec en Outaouais (UQO)23# Department : Département des sciences administratives24# Organization : SP Boucher25#26# Website : https://spboucher.ai27# Git : https://git.spboucher.ai28#29# =============================================================================30# OFFICIAL CONTACT DIRECTORY31# =============================================================================32#33# General : info@spboucher.ai34# Professional : contact@spboucher.ai35# Direct : simon@spboucher.ai36# Research : research@spboucher.ai37# Development : dev@spboucher.ai38# Support : support@spboucher.ai39# Security/Admin : admin@spboucher.ai40# Notifications : notifications@spboucher.ai41#42# Preferred Contact: contact@spboucher.ai43#44# =============================================================================45# COPYRIGHT & INTELLECTUAL PROPERTY46# =============================================================================47#48# Copyright (c) 202649# Simon-Pierre Boucher50#51# All rights reserved where applicable.52#53# This file is governed by the applicable project license,54# copyright notices, institutional agreements and relevant law.55#56# Unless expressly authorized by the applicable license or57# rights holder, copying, redistribution, sublicensing,58# publication and commercial exploitation are not permitted.59#60# Existing third-party rights and notices remain unaffected.61#62# =============================================================================63# CONFIDENTIALITY & SECURITY64# =============================================================================65#66# Classification : Public67# Distribution : Public repository; use is governed by the project license68# Security Contact : admin@spboucher.ai69#70# Access to this source does not independently grant permission71# to redistribute or disclose confidential materials.72#73# Do not embed credentials, private keys, access tokens,74# certificates or confidential personal information.75#76# =============================================================================77# LICENSE & MAINTENANCE78# =============================================================================79#80# License : None specified (no license file in this repository)81# Maintainer : Simon-Pierre Boucher82# Technical Contact: dev@spboucher.ai83#84# =============================================================================85# END OF SP BOUCHER SOURCE HEADER86# =============================================================================8788# Ré-estimation du modèle hédonique DIRECTEMENT SUR LE NŒUD.89#90# Le pipeline batch historique (laptop, hedonic.py/LightGBM) produit est_2021..91# est_2026 + p10/p90 par unité. Depuis que le connecteur ingest-jdm.mjs ajoute92# les ventes récentes en continu dans vraiprix.db, on peut ré-entraîner ici même93# (sklearn HistGradientBoostingRegressor ≈ LightGBM ; 28 cœurs / 96 Go).94#95# Deux modes :96# --eval Bench ÉQUITABLE : le modèle laptop a vu les ventes ≤ 2026-07-2797# (build 2026-08-08). On entraîne le challenger sur ce même98# périmètre, puis on compare les deux sur les ventes > 2026-07-2799# (jamais vues par aucun des deux). Rien n'est écrit.100# --apply Ré-entraîne sur TOUTES les ventes, prédit les 3,7 M d'unités101# (médiane + P10/P90 par modèles quantiles), sauvegarde les anciennes102# colonnes dans `units_est_prev`, puis met à jour units.est_2026/p10/p90.103#104# Cible : log(prix). Enrichissements vs les features brutes du rôle :105# - te_ratio : médiane locale (code_mun × unite_voisinage, replis municipalité106# puis global) de log(prix/valeur_role) — « ratio d'évaluation » local ;107# - ppm2_loc : médiane locale du prix/m² ;108# - t : date de vente en mois depuis 2021-01 (tendance de marché) ;109# - pondération de récence (demi-vie 36 mois) pour coller au marché actuel.110#111# Usage : python3 scripts/hedonic-retrain.py --eval112# python3 scripts/hedonic-retrain.py --apply113114import argparse115import sqlite3116import sys117import time118119import numpy as np120import pandas as pd121from sklearn.ensemble import HistGradientBoostingRegressor122123DB = "data/vraiprix.db"124BASELINE_CUTOFF = "2026-07-27" # dernière vente vue par le build laptop 2026-08-08125T0 = pd.Timestamp("2021-01-01")126AMOUNT_MIN, AMOUNT_MAX = 50_000, 10_000_000127128NUM_FEATS = [129 "lat", "lng", "annee_construction", "aire_etages_m2", "superficie_terrain_m2",130 "front_terrain_m", "nb_etages", "nb_logements", "nb_locaux_non_resid",131 "nb_chambres_locatives", "n_adresses", "valeur_terrain", "valeur_batiment",132 "valeur_role", "valeur_anterieure",133]134CAT_FEATS = ["type_prop", "lien_physique", "genre_construction"]135# naive_role / naive_ppm2 : « estimés naïfs » locaux donnés explicitement au GBM136# (les arbres capturent mal les relations multiplicatives rôle × ratio local).137ENG_FEATS = ["t", "log_role", "te_ratio", "ppm2_loc",138 "naive_role", "naive_ppm2", "age", "log_aire", "log_terr"]139140141def log(msg):142 print(f"[hedonic] {msg}", flush=True)143144145def load_sales(con):146 q = f"""147 SELECT t.date, t.amount,148 u.id_provinc, u.code_mun, u.unite_voisinage, u.municipalite,149 u.lat, u.lng, u.annee_construction, u.aire_etages_m2,150 u.superficie_terrain_m2, u.front_terrain_m, u.nb_etages,151 u.nb_logements, u.nb_locaux_non_resid, u.nb_chambres_locatives,152 u.n_adresses, u.valeur_terrain, u.valeur_batiment, u.valeur_role,153 u.valeur_anterieure, u.type_prop, u.lien_physique, u.genre_construction154 FROM transactions t155 JOIN units u ON u.id_provinc = t.id_provinc156 WHERE t.amount BETWEEN {AMOUNT_MIN} AND {AMOUNT_MAX}157 """158 df = pd.read_sql_query(q, con)159 df["t"] = (pd.to_datetime(df["date"]) - T0).dt.days / 30.44160 return df161162163# --- encodages locaux (calculés sur l'ENTRAÎNEMENT seulement, replis lissés) ---164class LocalEncoder:165 K = 8 # lissage : poids du repli166167 def fit(self, df):168 d = df[(df["valeur_role"] > 0)].copy()169 d["ratio"] = np.log(d["amount"] / d["valeur_role"])170 self.g_ratio = d["ratio"].median()171 m = d.groupby("municipalite")["ratio"].agg(["median", "size"])172 self.mun_ratio = ((m["median"] * m["size"] + self.g_ratio * self.K)173 / (m["size"] + self.K)).to_dict()174 d["vk"] = d["code_mun"].astype(str) + "|" + d["unite_voisinage"].astype(str)175 v = d.groupby(["vk", "municipalite"])["ratio"].agg(["median", "size"]).reset_index()176 v["fb"] = v["municipalite"].map(self.mun_ratio).fillna(self.g_ratio)177 v["val"] = (v["median"] * v["size"] + v["fb"] * self.K) / (v["size"] + self.K)178 self.vois_ratio = dict(zip(v["vk"], v["val"]))179180 p = df[(df["aire_etages_m2"] > 20)].copy()181 p["ppm2"] = p["amount"] / p["aire_etages_m2"]182 self.g_ppm2 = p["ppm2"].median()183 m2 = p.groupby("municipalite")["ppm2"].agg(["median", "size"])184 self.mun_ppm2 = ((m2["median"] * m2["size"] + self.g_ppm2 * self.K)185 / (m2["size"] + self.K)).to_dict()186 p["vk"] = p["code_mun"].astype(str) + "|" + p["unite_voisinage"].astype(str)187 v2 = p.groupby(["vk", "municipalite"])["ppm2"].agg(["median", "size"]).reset_index()188 v2["fb"] = v2["municipalite"].map(self.mun_ppm2).fillna(self.g_ppm2)189 v2["val"] = (v2["median"] * v2["size"] + v2["fb"] * self.K) / (v2["size"] + self.K)190 self.vois_ppm2 = dict(zip(v2["vk"], v2["val"]))191 return self192193 def transform(self, df):194 vk = df["code_mun"].astype(str) + "|" + df["unite_voisinage"].astype(str)195 mun_r = df["municipalite"].map(self.mun_ratio).fillna(self.g_ratio)196 df["te_ratio"] = vk.map(self.vois_ratio).fillna(mun_r)197 mun_p = df["municipalite"].map(self.mun_ppm2).fillna(self.g_ppm2)198 df["ppm2_loc"] = vk.map(self.vois_ppm2).fillna(mun_p)199 return df200201202def featurize(df, enc, cat_maps=None):203 df = enc.transform(df.copy())204 df["log_role"] = np.log1p(df["valeur_role"].clip(lower=0))205 df["naive_role"] = np.log1p((df["valeur_role"].clip(lower=0)206 * np.exp(df["te_ratio"])).clip(lower=0))207 df["naive_ppm2"] = np.log1p((df["aire_etages_m2"].clip(lower=0)208 * df["ppm2_loc"]).clip(lower=0))209 df["age"] = (2021 + df["t"] / 12.0) - df["annee_construction"]210 df["log_aire"] = np.log1p(df["aire_etages_m2"].clip(lower=0))211 df["log_terr"] = np.log1p(df["superficie_terrain_m2"].clip(lower=0))212 if cat_maps is None:213 cat_maps = {c: {v: i for i, v in enumerate(df[c].astype(str).fillna("NA").unique())}214 for c in CAT_FEATS}215 for c in CAT_FEATS:216 df[c] = df[c].astype(str).fillna("NA").map(cat_maps[c]).fillna(-1).astype(int)217 cols = NUM_FEATS + ENG_FEATS + CAT_FEATS218 X = df[cols].astype(float).to_numpy()219 return X, cols, cat_maps220221222def make_model(loss="absolute_error", quantile=None, cols=None, light=False):223 # Config volontairement SIMPLE (≈ 8 min d'entraînement) : la variante lourde224 # (2500 it / 255 feuilles, ~40 min) ne gagnait que ~1-2 pts de MdAPE sur les225 # segments remplacés — pas rentable.226 cat_mask = [c in CAT_FEATS for c in cols]227 kw = dict(228 max_iter=600 if light else 900, learning_rate=0.06, max_leaf_nodes=127,229 min_samples_leaf=40, l2_regularization=0.1, max_bins=255,230 early_stopping=True, validation_fraction=0.05, n_iter_no_change=40,231 random_state=42, categorical_features=cat_mask,232 )233 if quantile is not None:234 return HistGradientBoostingRegressor(loss="quantile", quantile=quantile, **kw)235 return HistGradientBoostingRegressor(loss=loss, **kw)236237238def recency_weights(t, t_max, half_life=24.0):239 return np.power(0.5, (t_max - t) / half_life)240241242def metrics(y_true, y_pred, label):243 ape = np.abs(y_pred - y_true) / y_true244 return {245 "label": label, "n": len(y_true),246 "MdAPE": float(np.median(ape) * 100),247 "MAPE": float(np.mean(ape) * 100),248 "±10%": float(np.mean(ape <= 0.10) * 100),249 "±20%": float(np.mean(ape <= 0.20) * 100),250 }251252253def print_metrics(rows):254 hdr = f"{'modèle':<26}{'n':>7}{'MdAPE':>8}{'MAPE':>8}{'±10%':>7}{'±20%':>7}"255 print(hdr); print("-" * len(hdr))256 for r in rows:257 print(f"{r['label']:<26}{r['n']:>7}{r['MdAPE']:>7.2f}%{r['MAPE']:>7.2f}%"258 f"{r['±10%']:>6.1f}%{r['±20%']:>6.1f}%")259260261def run_eval(con):262 df = load_sales(con)263 log(f"ventes jointes exploitables : {len(df)}")264 train = df[df["date"] <= BASELINE_CUTOFF].copy()265 test = df[df["date"] > BASELINE_CUTOFF].copy()266 log(f"train (≤ {BASELINE_CUTOFF}) : {len(train)} | test (>) : {len(test)}")267268 enc = LocalEncoder().fit(train)269 Xtr, cols, cat_maps = featurize(train, enc)270 ytr = np.log(train["amount"].to_numpy())271 w = recency_weights(train["t"].to_numpy(), train["t"].max())272273 t0 = time.time()274 model = make_model(cols=cols)275 model.fit(Xtr, ytr, sample_weight=w)276 log(f"challenger entraîné ({model.n_iter_} itérations, {time.time()-t0:.0f}s)")277278 Xte, _, _ = featurize(test, enc, cat_maps)279 pred = np.exp(model.predict(Xte))280 y = test["amount"].to_numpy()281282 # baseline : est_2026 de l'unité jointe283 base = pd.read_sql_query(284 "SELECT id_provinc, est_2026, p10, p90 FROM units", con)285 test = test.merge(base, on="id_provinc", how="left")286 mask = test["est_2026"].notna().to_numpy()287288 # mélange géométrique laptop × challenger (moyenne sur l'échelle log)289 base_est = test["est_2026"].to_numpy()290 blend = np.where(mask, np.exp(0.5 * np.log(np.where(mask, base_est, 1))291 + 0.5 * np.log(pred)), pred)292293 rows = [294 metrics(y[mask], base_est[mask], "laptop est_2026"),295 metrics(y[mask], pred[mask], "challenger (nœud)"),296 metrics(y[mask], blend[mask], "blend 50/50 (géo)"),297 ]298 print(); print(f"=== Ventes jamais vues (> {BASELINE_CUTOFF}) — {mask.sum()} obs ===")299 print_metrics(rows)300301 # par type302 print("\n--- par type de propriété (MdAPE %) ---")303 tt = test[mask].copy(); tt["pred"] = pred[mask]; tt["y"] = y[mask]304 tt["blend"] = blend[mask]305 for tp, g in tt.groupby(test[mask]["type_prop"]):306 b = np.median(np.abs(g["est_2026"] - g["y"]) / g["y"]) * 100307 c = np.median(np.abs(g["pred"] - g["y"]) / g["y"]) * 100308 bl = np.median(np.abs(g["blend"] - g["y"]) / g["y"]) * 100309 print(f" {tp:<16} n={len(g):>5} laptop {b:6.2f}% challenger {c:6.2f}% blend {bl:6.2f}%")310311 # couverture des quantiles baseline312 cov10 = float(np.mean(y[mask] < test["p10"].to_numpy()[mask]) * 100)313 cov90 = float(np.mean(y[mask] > test["p90"].to_numpy()[mask]) * 100)314 print(f"\ncouverture P10/P90 laptop sur test : {cov10:.1f}% sous P10 (cible 10) | "315 f"{cov90:.1f}% au-dessus de P90 (cible 10)")316 return rows317318319# Types dont l'estimation laptop est remplacée par le challenger (gain validé320# sur ventes jamais vues : terrain MdAPE 62→36 %, autre 79→52 %).321REPLACE_TYPES = ("terrain", "autre")322323324def quantile_calibration(con, df):325 """Facteurs d'élargissement des P10/P90 laptop, calibrés sur les ventes326 jamais vues (> BASELINE_CUTOFF), hors types remplacés. Couverture observée327 18,5 %/16,8 % hors bornes → cible 10 %/10 % de chaque côté."""328 test = df[df["date"] > BASELINE_CUTOFF].copy()329 base = pd.read_sql_query(330 "SELECT id_provinc, est_2026, p10, p90, type_prop tp FROM units", con)331 test = test.merge(base, on="id_provinc", how="inner")332 test = test[test["est_2026"].notna() & (test["est_2026"] > 0)333 & (test["p10"] > 0) & (test["p90"] > 0)334 & ~test["tp"].isin(REPLACE_TYPES)]335 z = np.log(test["amount"] / test["est_2026"])336 r_lo = np.log(test["p10"] / test["est_2026"]) # < 0337 r_hi = np.log(test["p90"] / test["est_2026"]) # > 0338 ok = (r_lo < -1e-6) & (r_hi > 1e-6)339 s_lo = (z[ok] / r_lo[ok]) # >1 ⇒ sous P10340 s_hi = (z[ok] / r_hi[ok]) # >1 ⇒ au-dessus de P90341 a_lo = float(np.quantile(s_lo, 0.90)) # P(s_lo > a_lo) = 10 %342 a_hi = float(np.quantile(s_hi, 0.90))343 a_lo, a_hi = max(1.0, a_lo), max(1.0, a_hi)344 log(f"calibration quantiles laptop (n={ok.sum()}) : alpha_lo={a_lo:.3f}, "345 f"alpha_hi={a_hi:.3f}")346 return a_lo, a_hi347348349def run_apply(con):350 df = load_sales(con)351 a_lo, a_hi = quantile_calibration(con, df)352353 log(f"ré-entraînement final sur {len(df)} ventes (tout l'historique)")354 enc = LocalEncoder().fit(df)355 X, cols, cat_maps = featurize(df, enc)356 yl = np.log(df["amount"].to_numpy())357 w = recency_weights(df["t"].to_numpy(), df["t"].max())358359 t0 = time.time()360 med = make_model(cols=cols); med.fit(X, yl, sample_weight=w)361 log(f"modèle médian : {med.n_iter_} it, {time.time()-t0:.0f}s")362 t0 = time.time()363 q10 = make_model(cols=cols, quantile=0.10, light=True); q10.fit(X, yl, sample_weight=w)364 q90 = make_model(cols=cols, quantile=0.90, light=True); q90.fit(X, yl, sample_weight=w)365 log(f"modèles quantiles P10/P90 : {time.time()-t0:.0f}s")366367 # --- unités des types remplacés, prédites à la date « maintenant » ---368 t_now = float(df["t"].max())369 ph = ",".join("?" * len(REPLACE_TYPES))370 units = pd.read_sql_query(f"""371 SELECT id_provinc, code_mun, unite_voisinage, municipalite,372 {', '.join(NUM_FEATS)}, {', '.join(CAT_FEATS)}373 FROM units WHERE type_prop IN ({ph})""", con, params=REPLACE_TYPES)374 log(f"unités à ré-estimer ({' + '.join(REPLACE_TYPES)}) : {len(units)}")375 units["t"] = t_now376 Xu, _, _ = featurize(units, enc, cat_maps)377378 log("prédiction challenger (médiane + P10/P90)…")379 est = np.exp(med.predict(Xu))380 lo = np.exp(q10.predict(Xu))381 hi = np.exp(q90.predict(Xu))382 lo2 = np.minimum.reduce([lo, est, hi]); hi2 = np.maximum.reduce([lo, est, hi])383 out = pd.DataFrame({384 "id_provinc": units["id_provinc"],385 "est": np.clip(est, 1000, None).round(-2),386 "p10": np.clip(lo2, 1000, None).round(-2),387 "p90": np.clip(hi2, 1000, None).round(-2),388 })389390 log("écriture en base (sauvegarde units_est_prev puis UPDATE)…")391 cur = con.cursor()392 cur.execute("PRAGMA busy_timeout=30000")393 cur.execute("DROP TABLE IF EXISTS units_est_prev")394 cur.execute("""CREATE TABLE units_est_prev AS395 SELECT id_provinc, est_2026, p10, p90 FROM units""")396 con.commit()397398 # 1) types remplacés → challenger399 cur.execute("DROP TABLE IF EXISTS units_est_new")400 cur.execute("""CREATE TABLE units_est_new401 (id_provinc TEXT PRIMARY KEY, est REAL, p10 REAL, p90 REAL)""")402 cur.executemany("INSERT OR REPLACE INTO units_est_new VALUES (?,?,?,?)",403 out.itertuples(index=False, name=None))404 con.commit()405 cur.execute("""UPDATE units SET406 est_2026 = (SELECT est FROM units_est_new n WHERE n.id_provinc = units.id_provinc),407 p10 = (SELECT p10 FROM units_est_new n WHERE n.id_provinc = units.id_provinc),408 p90 = (SELECT p90 FROM units_est_new n WHERE n.id_provinc = units.id_provinc)409 WHERE id_provinc IN (SELECT id_provinc FROM units_est_new)""")410 con.commit()411 cur.execute("DROP TABLE units_est_new")412 con.commit()413414 # 2) autres types → P10/P90 laptop élargis (p' = est × (p/est)^alpha)415 ph2 = ",".join("?" * len(REPLACE_TYPES))416 cur.execute(f"""UPDATE units SET417 p10 = ROUND(est_2026 * POW(p10 / est_2026, ?), -2),418 p90 = ROUND(est_2026 * POW(p90 / est_2026, ?), -2)419 WHERE type_prop NOT IN ({ph2})420 AND est_2026 > 0 AND p10 > 0 AND p90 > 0""",421 (a_lo, a_hi, *REPLACE_TYPES))422 con.commit()423 cur.execute("PRAGMA wal_checkpoint(TRUNCATE)")424 n = cur.execute(425 f"SELECT COUNT(*) FROM units WHERE type_prop IN ({ph2}) AND est_2026 IS NOT NULL",426 REPLACE_TYPES).fetchone()[0]427 log(f"terminé : {n} unités ré-estimées (challenger), P10/P90 recalibrés ailleurs "428 f"(alpha {a_lo:.3f}/{a_hi:.3f}). Ancienne version dans units_est_prev.")429430431if __name__ == "__main__":432 ap = argparse.ArgumentParser()433 ap.add_argument("--eval", action="store_true")434 ap.add_argument("--apply", action="store_true")435 ap.add_argument("--db", default=DB)436 a = ap.parse_args()437 con = sqlite3.connect(a.db)438 try:439 if a.eval:440 run_eval(con)441 elif a.apply:442 run_apply(con)443 else:444 ap.print_help(); sys.exit(1)445 finally:446 con.close()447