SPB Git

Repository Public

modele.py 24.2 KB 491 lines python

1# =============================================================================2#                  SP BOUCHER | SOFTWARE & RESEARCH3#             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project          : Valo-Plex9# File             : moteur/plexmoteur/modele.py10# Module           : moteur11# Repository       : https://git.spboucher.ai/valo-plex12# Project Website  : https://www.valo-plex.com13# Created          : 2026-12-0114# Last Modified    : 2026-12-0315#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"""Modèles de marché, un par marché (résidentiel à revenus, commercial).8990Trois approches estiment chaque vente sans l'avoir vue :9192- hédonique : gradient boosting sur le log du rapport prix / repère, validé93  par plis mensuels à origine glissante (chaque vente est estimée par un94  modèle qui ne l'a pas vue ni aucune vente postérieure) ;95- par comparaison : ventes comparables connues au début du mois de la vente ;96- par le revenu : revenu net normalisé ÷ taux extrait des ventes antérieures.9798Elles sont réconciliées par des poids appris sur ces estimations hors99échantillon (``reconcilier.py``). Suivent le modèle d'échelle et l'intervalle100conforme à 80 % par groupe, calés sur la valeur réconciliée.101"""102from __future__ import annotations103104import json105import time106107import joblib108import numpy as np109import pandas as pd110111from . import config, reconcilier, revenu, socle, typologie112from . import variables as V113114RES, COM = typologie.RESIDENTIEL, typologie.COMMERCIAL115NIVEAU = 0.80116N_PLIS = 30117PLIS_ECHELLE = 15            # premiers plis : leurs résidus hors échantillon apprennent l'échelle et les poids118PLIS_CALAGE = 12             # derniers plis : quantiles conformes servis119DEMI_VIE_MOIS = 24.0120SEUIL_FERME = 15.0           # erreur médiane hors échantillon (%) au-delà de laquelle un groupe n'a qu'un ordre de grandeur121GB = dict(loss="absolute_error", max_iter=500, max_leaf_nodes=31, learning_rate=0.06,122          min_samples_leaf=30, l2_regularization=1.0, early_stopping=False, random_state=config.SEED)123GB_ECHELLE = dict(loss="absolute_error", max_iter=150, max_leaf_nodes=15, learning_rate=0.08,124                  min_samples_leaf=80, early_stopping=False, random_state=config.SEED)125# marché commercial : quelques milliers de ventes seulement, donc des arbres plus petits et plus réguliers126GB_COMMERCIAL = dict(loss="absolute_error", max_iter=300, max_leaf_nodes=12, learning_rate=0.05,127                     min_samples_leaf=20, l2_regularization=2.0, early_stopping=False, random_state=config.SEED)128GB_ECHELLE_COMMERCIAL = dict(loss="absolute_error", max_iter=100, max_leaf_nodes=8, learning_rate=0.08,129                             min_samples_leaf=40, early_stopping=False, random_state=config.SEED)130REGLAGES = {131    RES: dict(prefixe="vx", gb=GB, gb_echelle=GB_ECHELLE, min_groupe=250, min_calage=1000, dimension="taille",132              meta="modele"),133    COM: dict(prefixe="vc", gb=GB_COMMERCIAL, gb_echelle=GB_ECHELLE_COMMERCIAL, min_groupe=120, min_calage=250,134              dimension="categorie", meta="modele_commercial"),135}136137SQL_VENTES = """138SELECT v.sale_id, v.id, v.date, v.jour, v.prix, v.de_marche, v.motifs, v.role_vente, v.role_ref_annee ref,139       v.repere_ratio, v.doublon, i.lat, i.lng, i.logements, i.etages, i.annee, i.aire_m2, i.terrain_m2,140       i.front_m, i.lien, i.construction, i.locaux_nr, i.chambres, i.role, i.role_terrain, i.code_mun,141       t.region_code, i.loyer_porte, i.categorie, i.cubf142FROM vente v JOIN immeuble i ON i.id = v.id LEFT JOIN territoire t ON t.code_mun = i.code_mun143WHERE v.doublon = 0 AND v.prix >= 20000 AND v.role_vente >= 10000 AND i.marche = ?144ORDER BY v.jour, v.sale_id145"""146SQL_PARC = """147SELECT i.id, i.lat, i.lng, i.logements, i.etages, i.annee, i.aire_m2, i.terrain_m2, i.front_m, i.lien,148       i.construction, i.locaux_nr, i.chambres, i.role, i.role_terrain, i.code_mun, i.role_reference,149       t.region_code, i.loyer_porte, i.categorie, i.cubf150FROM immeuble i LEFT JOIN territoire t ON t.code_mun = i.code_mun151WHERE i.marche = ?152"""153154155def _colonne_loyer(con) -> None:156    cols = [r[1] for r in con.execute("PRAGMA table_info(immeuble)")]157    if "loyer_porte" not in cols:158        con.execute("ALTER TABLE immeuble ADD COLUMN loyer_porte REAL")159160161def lire_ventes(con, marche: str = RES) -> pd.DataFrame:162    S = pd.read_sql_query(SQL_VENTES, con, params=(marche,))163    S = V.preparer(S, marche)164    S["l_role"] = np.log(S["role_vente"])165    S["lr"] = np.log(S["prix"] / S["role_vente"])166    with np.errstate(all="ignore"):167        S["lpp"] = np.log(S["prix"] / S["taille"])168    S["mois"] = (pd.to_datetime(S["jour"], unit="D").dt.year * 12169                 + pd.to_datetime(S["jour"], unit="D").dt.month - 1)170    S["e"] = np.nan171    return S172173174def lire_ventes_tous(con) -> pd.DataFrame:175    HT = pd.read_sql_query("SELECT sale_id, id, jour, lat, lng, e FROM vente_tous WHERE abs(e) < 1.1 ORDER BY jour, sale_id", con)176    HT["x"], HT["y"] = V.projeter(HT["lat"], HT["lng"])177    return HT178179180def historique_ratios(con, marche: str) -> pd.DataFrame | None:181    """Ventes dont le commercial tire son ratio prix / rôle : les ventes de182    marché des plex. ``None`` pour le résidentiel, qui se sert de ses propres183    ventes."""184    if marche != COM:185        return None186    HR = lire_ventes(con, RES)187    return HR[HR["de_marche"] == 1][["jour", "lr", "ref", "region", "code_mun"]]188189190def ajouter_revenus(B: pd.DataFrame, T: dict, marche: str) -> pd.DataFrame:191    """Pose sur ``B`` son revenu net normalisé (``rne``, ``revenu_place``) et rend le détail."""192    R = revenu.revenus(B, T, marche)193    B["rne"], B["revenu_place"] = R["rne"].to_numpy(float), R["revenu_place"].to_numpy(float)194    return R195196197def construire_variables(S: pd.DataFrame, verbose: bool = False, HT: pd.DataFrame | None = None,198                         HR: pd.DataFrame | None = None, marche: str = RES) -> pd.DataFrame:199    """Passe chronologique, mois par mois : les variables de chaque vente, ses200    comparables et sa valeur par le revenu sont calculés d'après les seules201    ventes de marché publiées avant le début de son mois. Le résidu ``e``202    (prix contre repère) d'une vente ne devient visible qu'aux mois suivants.203    ``S`` doit porter ``rne`` et ``revenu_place`` (``ajouter_revenus``) pour204    que l'approche par le revenu soit calculée (colonne ``r_l``)."""205    t0 = time.time()206    blocs = []207    marche_ = S["de_marche"].to_numpy() == 1208    avec_revenu = "rne" in S209    for mois, idx in S.groupby("mois").indices.items():210        debut = int((np.datetime64(f"{mois // 12:04d}-{mois % 12 + 1:02d}-01")211                     - np.datetime64("1970-01-01")).astype(int))212        know = debut - V.DELAI213        H = S[marche_ & (S["jour"].to_numpy() <= know)]214        C = S.iloc[idx]215        F = V.variables(C, H, know, HT, HR, marche)216        S.loc[C.index, "e"] = np.log(C["prix"].to_numpy()) - F["l_repere"].to_numpy()217        if avec_revenu:218            A, _ = revenu.approche(C, H, know, marche)219            with np.errstate(all="ignore"):220                F["r_l"] = np.log(A["valeur_revenu"].to_numpy(float))221        else:222            F["r_l"] = np.nan223        blocs.append(F)224    F = pd.concat(blocs).loc[S.index]225    if verbose:226        print(f"variables : {len(F)} ventes, {time.time() - t0:.1f} s", flush=True)227    return F228229230def approches(F: pd.DataFrame, y_hat: np.ndarray) -> np.ndarray:231    """Log des valeurs par approche (hédonique, comparaison, revenu)."""232    l_rep = F["l_repere"].to_numpy(float)233    return np.c_[l_rep + y_hat, l_rep + F["c_e"].to_numpy(float), F["r_l"].to_numpy(float)]234235236def _hgb(cols, params):237    from sklearn.ensemble import HistGradientBoostingRegressor238    return HistGradientBoostingRegressor(categorical_features=[c in V.CATEGORIELLES for c in cols], **params)239240241def ajuster(X, y, w=None, cols=V.COLONNES, params=None):242    from threadpoolctl import threadpool_limits243    params = params or GB244    X = X.copy()245    mortes = np.where(~np.isfinite(X).any(axis=0))[0]246    X[:, mortes] = 0.0247    m = _hgb(cols, params)248    with threadpool_limits(limits=config.THREADS):249        m.fit(X, y, sample_weight=w)250    return m, mortes251252253def predire(mm, X):254    from threadpoolctl import threadpool_limits255    m, mortes = mm256    X = X.copy()257    X[:, mortes] = 0.0258    with threadpool_limits(limits=config.THREADS):259        return m.predict(X)260261262def poids_age(jours, reference, demi_vie=DEMI_VIE_MOIS):263    age = np.maximum(reference - np.asarray(jours, float), 0.0) / 30.4375264    return np.power(0.5, age / demi_vie)265266267def mesures(prix, est, bas=None, haut=None) -> dict | None:268    prix, est = np.asarray(prix, float), np.asarray(est, float)269    ok = np.isfinite(prix) & np.isfinite(est) & (prix > 0)270    if ok.sum() < 20:271        return None272    err = est[ok] / prix[ok] - 1.0273    a = np.abs(err)274    out = {"n": int(ok.sum()), "erreur_mediane": round(float(np.median(a)) * 100, 2),275           "biais": round(float(np.median(err)) * 100, 2),276           "a_10": round(float((a <= 0.10).mean()) * 100, 1), "a_20": round(float((a <= 0.20).mean()) * 100, 1),277           "cod": round(float(np.mean(np.abs(1 / (1 + err) - np.median(1 / (1 + err)))) / np.median(1 / (1 + err))) * 100, 1)}278    if bas is not None:279        b, h = np.asarray(bas, float)[ok], np.asarray(haut, float)[ok]280        f = np.isfinite(b) & np.isfinite(h)281        if f.sum() >= 20:282            out["couverture"] = round(float(((prix[ok][f] >= b[f]) & (prix[ok][f] <= h[f])).mean()) * 100, 1)283            out["largeur"] = round(float(np.median((h[f] - b[f]) / est[ok][f])) * 100, 1)284    return out285286287def _quantiles(z, g, groupes, min_groupe: int) -> dict:288    """Quantiles conformes des résidus normalisés, par groupe ; un groupe trop289    mince prend ceux de l'ensemble."""290    a = (1 - NIVEAU) / 2291    q = lambda v: [float(np.quantile(v, a)), float(np.quantile(v, 1 - a))]292    tous = q(z)293    return {int(k): (q(z[g == k]) if (g == k).sum() >= min_groupe else tous) for k in groupes}294295296def _bornes(y_hat, echelle, g, Q):297    defaut = next(iter(Q.values()))298    lo = np.array([Q.get(int(k), defaut)[0] for k in g])299    hi = np.array([Q.get(int(k), defaut)[1] for k in g])300    return y_hat + lo * echelle, y_hat + hi * echelle301302303def _tables(con) -> None:304    config.script(con, """305    CREATE TABLE IF NOT EXISTS modele (version TEXT PRIMARY KEY, cree TEXT NOT NULL, actif INTEGER NOT NULL,306      derniere_vente TEXT, bilan TEXT NOT NULL, marche TEXT NOT NULL DEFAULT 'residentiel');307    CREATE TABLE IF NOT EXISTS validation (version TEXT NOT NULL, population TEXT NOT NULL,308      dimension TEXT NOT NULL, segment TEXT NOT NULL, methode TEXT NOT NULL, n INTEGER,309      erreur_mediane REAL, biais REAL, a_10 REAL, a_20 REAL, cod REAL, couverture REAL, largeur REAL,310      PRIMARY KEY (version, population, dimension, segment, methode)) WITHOUT ROWID;311    """)312    if "marche" not in [r[1] for r in con.execute("PRAGMA table_info(modele)")]:313        con.execute("ALTER TABLE modele ADD COLUMN marche TEXT NOT NULL DEFAULT 'residentiel'")314    if "marche" not in [r[1] for r in con.execute("PRAGMA table_info(vente_oos)")]:315        con.execute("DROP TABLE IF EXISTS vente_oos")316    con.execute("CREATE TABLE IF NOT EXISTS vente_oos (sale_id TEXT PRIMARY KEY, estime REAL, bas REAL, haut REAL, "317                "repere REAL, hedonique REAL, comparables REAL, revenu REAL, n_comparables INTEGER, "318                "marche TEXT NOT NULL) WITHOUT ROWID")319320321def entrainer(verbose: bool = False, n_plis: int = N_PLIS, cols=None, ecrire: bool = True, marche: str = RES) -> dict:322    t0 = time.time()323    regl = REGLAGES[marche]324    cols = tuple(cols or V.colonnes(marche))325    groupes = typologie.groupes_du_marche(marche)326    con = config.ouvrir(ecriture=True)327    _colonne_loyer(con)328    S = lire_ventes(con, marche)329    if len(S) < 500:330        con.close()331        raise RuntimeError(f"marché {marche} : {len(S)} ventes seulement, entraînement refusé")332    ajouter_revenus(S, revenu.tables_inscriptions(con), marche)333    F = construire_variables(S, verbose, lire_ventes_tous(con), historique_ratios(con, marche), marche)334    X = V.matrice(F, cols)335    l_rep = F["l_repere"].to_numpy(float)336    yl = np.log(S["prix"].to_numpy(float))337    y = yl - l_rep338    jour = S["jour"].to_numpy()339    marche_ = S["de_marche"].to_numpy() == 1340    utilisable = np.isfinite(y)341    appr = utilisable & marche_ & (jour >= V.jour_de(V.DEBUT)) & (np.abs(y) < np.log(3.0))342    mois = S["mois"].to_numpy()343    plis = sorted(set(mois[utilisable]))[-n_plis:]344345    oof = np.full(len(S), np.nan)346    for k, m in enumerate(plis):347        debut = V.jour_de(f"{m // 12:04d}-{m % 12 + 1:02d}-01")348        tr = appr & (jour < debut - V.DELAI)349        te = utilisable & (mois == m)350        mm = ajuster(X[tr], y[tr], poids_age(jour[tr], debut), cols, regl["gb"])351        oof[te] = predire(mm, X[te])352        if verbose:353            r = mesures(S["prix"].to_numpy()[te & marche_], np.exp(l_rep + oof)[te & marche_])354            print(f"pli {k + 1:2d}/{len(plis)} {m // 12}-{m % 12 + 1:02d} n={te.sum():5d} "355                  f"marché {r['erreur_mediane'] if r else '—'} %  ({time.time() - t0:.0f} s)", flush=True)356357    a_oof = np.isfinite(oof)358    pli_de = {m: k for k, m in enumerate(plis)}359    kpli = np.array([pli_de.get(m, -1) for m in mois])360    n_ech = min(PLIS_ECHELLE, max(1, len(plis) // 2))361    g = S["groupe"].to_numpy()362363    # réconciliation : poids appris sur les premiers plis, appliqués à tous (les plis suivants ne les ont pas vus)364    L = approches(F, oof)365    sage = a_oof & marche_ & (np.abs(y) < np.log(3.0))366    R_tot = reconcilier.apprendre(yl[sage & (kpli < n_ech)], L[sage & (kpli < n_ech)], g[sage & (kpli < n_ech)], groupes)367    rec, _, disp = reconcilier.appliquer(L, g, R_tot)368    Lc = reconcilier.corriger(L, g, R_tot)369370    # échelle : |résidu| hors échantillon des premiers plis ; calage : les suivants371    res = yl - rec372    a_rec = a_oof & np.isfinite(rec)373    Xe = np.c_[X, np.nan_to_num(rec - l_rep), np.nan_to_num(disp)]374    cols_e = cols + ("y_hat", "desaccord")375    ech_tr = a_rec & marche_ & (kpli < n_ech)376    me = ajuster(Xe[ech_tr], np.abs(res[ech_tr]), None, cols_e, regl["gb_echelle"])377    echelle = np.full(len(S), np.nan)378    echelle[a_rec] = np.maximum(predire(me, Xe[a_rec]), 0.02)379    z = res / echelle380381    # couverture honnête : pour chaque pli de calage, quantiles des plis de calage précédents382    bas = np.full(len(S), np.nan)383    haut = np.full(len(S), np.nan)384    for k in range(n_ech + 6, len(plis)):385        cal = a_rec & marche_ & (kpli >= n_ech) & (kpli < k)386        te = a_rec & (kpli == k)387        if cal.sum() < regl["min_calage"] or not te.any():388            continue389        Q = _quantiles(z[cal], g[cal], groupes, regl["min_groupe"])390        lo, hi = _bornes(rec[te], echelle[te], g[te], Q)391        bas[te], haut[te] = np.exp(lo), np.exp(hi)392    cal = a_rec & marche_ & (kpli >= max(n_ech, len(plis) - PLIS_CALAGE))393    Q = _quantiles(z[cal], g[cal], groupes, regl["min_groupe"])394395    # validation : douze derniers plis396    prix = S["prix"].to_numpy(float)397    est = np.exp(rec)398    rep = np.exp(l_rep)399    dern = a_oof & (kpli >= len(plis) - 12)400    lignes = []401    methodes = (("valo-plex", est, bas, haut), ("hedonique", np.exp(Lc[:, 0]), None, None),402                ("comparables", np.exp(Lc[:, 1]), None, None), ("revenu", np.exp(Lc[:, 2]), None, None),403                ("role-ratio", rep, None, None), ("role", S["role_vente"].to_numpy(float), None, None))404405    def ajoute(population, dimension, segment, masque):406        for methode, e, b, h in methodes:407            r = mesures(prix[masque], e[masque], None if b is None else b[masque], None if h is None else h[masque])408            if r:409                lignes.append({"population": population, "dimension": dimension, "segment": segment,410                               "methode": methode, **r})411412    regions = dict(con.execute("SELECT DISTINCT CAST(region_code AS INTEGER), region FROM territoire "413                               "WHERE region_code IS NOT NULL").fetchall())414    for pop, mp in (("marche", dern & marche_), ("toutes", dern)):415        ajoute(pop, "ensemble", "tous", mp)416        for k, nom in groupes.items():417            ajoute(pop, regl["dimension"], nom, mp & (g == k))418        if marche == RES:419            # le multilogement en détail : par tranche de taille, immeubles mixtes, tours420            log = S["logements"].to_numpy()421            multi = mp & (log >= 6)422            ajoute(pop, "multilogement", "tous", multi)423            tr = typologie.tranche(log)424            for nom in typologie.TRANCHES[3:]:425                ajoute(pop, "multilogement", nom, multi & (tr == nom))426            ajoute(pop, "multilogement", "mixte", multi & (S["locaux_nr"].fillna(0).to_numpy() > 0))427            ajoute(pop, "multilogement", "tour", multi & (S["etages"].fillna(0).to_numpy() >= typologie.ETAGES_TOUR))428        for code, nom in sorted(regions.items()):429            ajoute(pop, "region", nom, mp & (S["region"].to_numpy() == code))430        for m in plis[-12:]:431            ajoute(pop, "mois", f"{m // 12}-{m % 12 + 1:02d}", mp & (mois == m))432        for a, b in ((0, 300e3), (300e3, 500e3), (500e3, 750e3), (750e3, 1e6), (1e6, 1.5e6), (1.5e6, 3e6), (3e6, 1e12)):433            ajoute(pop, "prix", f"{int(a / 1000)}-{int(b / 1000) if b < 1e11 else '+'} k$", mp & (prix >= a) & (prix < b))434435    # un groupe dont l'erreur hors échantillon dépasse le seuil (ou n'a pas pu être mesurée) : ordre de grandeur436    err_groupe = {l["segment"]: l["erreur_mediane"] for l in lignes if l["population"] == "marche"437                  and l["dimension"] == regl["dimension"] and l["methode"] == "valo-plex"}438    groupes_ordre = [int(k) for k, nom in groupes.items() if err_groupe.get(nom, 1e9) > SEUIL_FERME]439440    # modèles servis : toutes les ventes de marché ; réconciliation apprise sur toutes les estimations hors échantillon441    reference = int(jour.max())442    final = ajuster(X[appr], y[appr], poids_age(jour[appr], reference), cols, regl["gb"])443    R_fin = reconcilier.apprendre(yl[sage], L[sage], g[sage], groupes)444    rec_f, _, disp_f = reconcilier.appliquer(L, g, R_fin)445    Xf = np.c_[X, np.nan_to_num(rec_f - l_rep), np.nan_to_num(disp_f)]446    ech_fin = a_oof & np.isfinite(rec_f) & marche_447    me_final = ajuster(Xf[ech_fin], np.abs(yl - rec_f)[ech_fin], None, cols_e, regl["gb_echelle"])448    version = regl["prefixe"] + "-" + time.strftime("%Y%m%d-%H%M%S")449    de = lambda methode: next((l for l in lignes if l["population"] == "marche" and l["dimension"] == "ensemble"450                               and l["methode"] == methode), {})451    bilan = {"version": version, "marche": marche, "derniere_vente": V.iso_de(reference),452             "n_apprentissage": int(appr.sum()), "n_validation": int((dern & marche_).sum()), "plis": len(plis),453             "ensemble": de("valo-plex"),454             "approches": {m: de(m) for m in ("hedonique", "comparables", "revenu", "role-ratio")},455             "reconciliation": {groupes[int(k)]: {"poids": dict(zip(reconcilier.METHODES, r["poids"])), "n": r["n"],456                                                  "propre": r["propre"]} for k, r in R_fin["groupes"].items()},457             "ordre_de_grandeur": [groupes[k] for k in groupes_ordre],458             "secondes": round(time.time() - t0, 1)}459    if ecrire:460        config.MODELES.mkdir(parents=True, exist_ok=True)461        joblib.dump({"version": version, "marche": marche, "cols": cols, "modele": final, "echelle": me_final,462                     "quantiles": Q, "reference": reference, "reconciliation": R_fin,463                     "groupes_ordre": groupes_ordre}, config.MODELES / f"{version}.joblib", compress=3)464        with config.transaction(con):465            _tables(con)466            con.execute("UPDATE modele SET actif = 0 WHERE marche = ?", (marche,))467            con.execute("INSERT INTO modele VALUES (?,datetime('now'),1,?,?,?)",468                        (version, bilan["derniere_vente"], json.dumps(bilan, ensure_ascii=False), marche))469            con.executemany(470                "INSERT INTO validation VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?)",471                [(version, l["population"], l["dimension"], l["segment"], l["methode"], l["n"], l["erreur_mediane"],472                  l["biais"], l["a_10"], l["a_20"], l["cod"], l.get("couverture"), l.get("largeur")) for l in lignes])473            # estimations hors échantillon, par approche : taux de capitalisation, audit, page de méthode474            con.execute("DELETE FROM vente_oos WHERE marche = ?", (marche,))475            f = lambda v: None if not np.isfinite(v) else float(v)476            con.executemany("INSERT OR REPLACE INTO vente_oos VALUES (?,?,?,?,?,?,?,?,?,?)", [477                (s, f(e), f(b), f(h), f(r), f(a1), f(a2), f(a3), int(cn), marche)478                for s, e, b, h, r, a1, a2, a3, cn in zip(479                    S["sale_id"][a_oof], est[a_oof], bas[a_oof], haut[a_oof], rep[a_oof], np.exp(Lc[a_oof, 0]),480                    np.exp(Lc[a_oof, 1]), np.exp(Lc[a_oof, 2]), F["c_n"].to_numpy()[a_oof])])481            socle.noter(con, regl["meta"], bilan)482    con.close()483    if verbose:484        print(json.dumps(bilan, ensure_ascii=False, indent=1))485        for l in lignes:486            if l["population"] == "marche" and l["dimension"] in ("ensemble", regl["dimension"]):487                print(f"  {l['dimension']:9s} {l['segment']:22s} {l['methode']:11s} n={l['n']:6d} "488                      f"err {l['erreur_mediane']:5.2f} %  biais {l['biais']:+5.2f} %  à10 {l['a_10']:4.1f}  "489                      f"couv {l.get('couverture', '')}  larg {l.get('largeur', '')}")490    return {"bilan": bilan, "lignes": lignes}491
Files main
Menu

Theme