SPB Git

Repository Public

estimer.py 16.0 KB 306 lines python

1# =============================================================================2#                  SP BOUCHER | SOFTWARE & RESEARCH3#             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project          : Valo-Plex9# File             : moteur/plexmoteur/estimer.py10# Description      : Estimation du parc entier : valeur de marché de chaque11#                    plex (modèle appris sur les ventes réelles), intervalle à12#                    80 %, statut, puis le second avis de l'approche par le13#                    revenu.14# Module           : moteur15# Repository       : https://git.spboucher.ai/valo-plex16# Project Website  : https://www.valo-plex.com17# Created          : 2026-12-0118# Last Modified    : 2026-12-0319#20# =============================================================================21# AUTHOR & PROFESSIONAL AFFILIATION22# =============================================================================23#24# Author           : Simon-Pierre Boucher25# Position         : Professor of Finance26# Institution      : Université du Québec en Outaouais (UQO)27# Department       : Département des sciences administratives28# Organization     : SP Boucher29#30# Website          : https://spboucher.ai31# Git              : https://git.spboucher.ai32#33# =============================================================================34# OFFICIAL CONTACT DIRECTORY35# =============================================================================36#37# General          : info@spboucher.ai38# Professional     : contact@spboucher.ai39# Direct           : simon@spboucher.ai40# Research         : research@spboucher.ai41# Development      : dev@spboucher.ai42# Support          : support@spboucher.ai43# Security/Admin   : admin@spboucher.ai44# Notifications    : notifications@spboucher.ai45#46# Preferred Contact: contact@spboucher.ai47#48# =============================================================================49# COPYRIGHT & INTELLECTUAL PROPERTY50# =============================================================================51#52# Copyright (c) 202653# Simon-Pierre Boucher54#55# All rights reserved where applicable.56#57# This file is governed by the applicable project license,58# copyright notices, institutional agreements and relevant law.59#60# Unless expressly authorized by the applicable license or61# rights holder, copying, redistribution, sublicensing,62# publication and commercial exploitation are not permitted.63#64# Existing third-party rights and notices remain unaffected.65#66# =============================================================================67# CONFIDENTIALITY & SECURITY68# =============================================================================69#70# Classification   : Public71# Distribution     : Public repository; use is governed by the project license72# Security Contact : admin@spboucher.ai73#74# Access to this source does not independently grant permission75# to redistribute or disclose confidential materials.76#77# Do not embed credentials, private keys, access tokens,78# certificates or confidential personal information.79#80# =============================================================================81# LICENSE & MAINTENANCE82# =============================================================================83#84# License          : None specified (no license file in this repository)85# Maintainer       : Simon-Pierre Boucher86# Technical Contact: dev@spboucher.ai87#88# =============================================================================89# END OF SP BOUCHER SOURCE HEADER90# =============================================================================9192"""Estimation du parc entier, marché par marché (résidentiel à revenus, puis93commercial). Chaque immeuble reçoit trois valeurs — hédonique, par94comparaison, par le revenu — réconciliées en une seule par les poids appris95hors échantillon, avec son intervalle à 80 % et son statut. Écrit la table96``valeur``.97"""98from __future__ import annotations99100import json101import time102103import joblib104import numpy as np105import pandas as pd106107from . import config, modele, reconcilier, revenu, socle, typologie108from . import variables as V109110RES, COM = typologie.RESIDENTIEL, typologie.COMMERCIAL111LARGEUR_ORDRE = 0.75         # intervalle plus large : ordre de grandeur seulement112LARGEUR_HAUTE = 0.35113LARGEUR_MOYENNE = 0.50114GROUPE_12_PLUS = 4115DOMAINE_VENTES = 0.99        # centile des prix payés au-delà duquel une valeur est une extrapolation116117COLONNES_VALEUR = (118    "id", "statut", "motif", "confiance", "valeur", "bas", "haut", "largeur", "repere", "par_porte", "rbp_marche",119    "revenu_place", "rapport_place", "taxes", "depenses", "rne", "tga", "mrb", "valeur_revenu", "valeur_mrb",120    "n_voisines", "n_voisines_1km", "voisines_ecart", "quartier_ecart", "precedente_ecart", "tendance_ecart",121    "ratio_n", "ratio", "vente_date", "vente_prix", "vente_marche",122    "marche", "valeur_hedonique", "valeur_comparables", "n_comparables", "poids_hedonique", "poids_comparables",123    "poids_revenu", "desaccord", "par_m2")124125126def _arrondi(x: np.ndarray) -> np.ndarray:127    x = np.asarray(x, float)128    pas = np.where(x >= 2e6, 10000.0, np.where(x >= 5e5, 5000.0, 1000.0))129    return np.round(x / pas) * pas130131132def _f(a) -> list:133    a = np.asarray(a, float)134    return [None if not np.isfinite(v) else float(v) for v in a]135136137def _marche(con, marche: str, know: int | None, T: dict, HT: pd.DataFrame) -> dict | None:138    """Lignes de ``valeur`` d'un marché ; ``None`` si aucun modèle n'est actif pour lui."""139    ligne = con.execute("SELECT version FROM modele WHERE actif = 1 AND marche = ?", (marche,)).fetchone()140    if not ligne:141        return None142    art = joblib.load(config.MODELES / f"{ligne[0]}.joblib")143    HR = modele.historique_ratios(con, marche)144    S = modele.lire_ventes(con, marche)145    modele.ajouter_revenus(S, T, marche)146    modele.construire_variables(S, HR=HR, marche=marche)        # pose le résidu « e » de chaque vente147    know = int(S["jour"].max()) if know is None else know148    H = S[S["de_marche"] == 1]149    P = V.preparer(pd.read_sql_query(modele.SQL_PARC, con, params=(marche,)), marche)150    P["jour"] = know151    P["l_role"] = np.log(P["role"])152    P["ref"] = pd.to_numeric(P["role_reference"].str[:4], errors="coerce")153    R = modele.ajouter_revenus(P, T, marche)154    F = V.variables(P, H, know, HT, HR, marche)155    A, M = revenu.approche(P, H, know, marche)156    with np.errstate(all="ignore"):157        F["r_l"] = np.log(A["valeur_revenu"].to_numpy(float))158    X = V.matrice(F, art["cols"])159    l_rep = F["l_repere"].to_numpy(float)160    y_hat = modele.predire(art["modele"], X)161    g = P["groupe"].to_numpy()162    L = modele.approches(F, y_hat)163    rec, poids, disp = reconcilier.appliquer(L, g, art["reconciliation"])164    Lc = reconcilier.corriger(L, g, art["reconciliation"])165    ech = np.maximum(modele.predire(art["echelle"], np.c_[X, np.nan_to_num(rec - l_rep), np.nan_to_num(disp)]), 0.02)166    Q = {int(k): v for k, v in art["quantiles"].items()}167    lo, hi = modele._bornes(rec, ech, g, Q)168    valeur, bas, haut = np.exp(rec), np.exp(lo), np.exp(hi)169    largeur = (haut - bas) / valeur170171    ok = np.isfinite(valeur)172    ordre_g = np.isin(g, art.get("groupes_ordre", []))173    # au-delà du 99e centile des prix payés sur ce marché, aucune vente n'appuie la valeur : le modèle extrapole174    plafond = float(np.quantile(H["prix"].to_numpy(float), DOMAINE_VENTES)) if len(H) >= 100 else np.inf175    hors = ok & (valeur > plafond)176    statut = np.where(~ok, "abstention", np.where((largeur > LARGEUR_ORDRE) | ordre_g | hors, "ordre", "ferme"))177    motif_groupe = np.where((g == GROUPE_12_PLUS) & (marche == RES), "12-logements-et-plus", "peu-de-ventes")178    motif = np.where(~ok, "sans-repere", np.where(hors, "au-dela-des-ventes", np.where(ordre_g, motif_groupe,179                     np.where(largeur > LARGEUR_ORDRE, "intervalle-large", ""))))180    confiance = np.where(statut != "ferme", "faible", np.where(largeur <= LARGEUR_HAUTE, "haute",181                         np.where(largeur <= LARGEUR_MOYENNE, "moyenne", "faible")))182    dern = V.derniere_vente(S[S["jour"] <= know])[["date", "prix", "de_marche"]]183    dj = P[["id"]].join(dern, on="id")184185    v_arr, b_arr, h_arr = _arrondi(valeur), _arrondi(bas), _arrondi(haut)186    n = len(P)187    vide = np.full(n, np.nan)188    col = lambda nom: R[nom].to_numpy(float) if nom in R else vide189    aire = pd.to_numeric(P["aire_m2"], errors="coerce").to_numpy(float)190    with np.errstate(all="ignore"):191        par_porte = np.round(v_arr / P["logements"].to_numpy(float)) if marche == RES else vide192        par_m2 = np.where(aire > 0, np.round(v_arr / aire), np.nan)193    lignes = list(zip(194        P["id"], statut, motif, confiance, _f(v_arr), _f(b_arr), _f(h_arr), _f(np.round(largeur, 4)),195        _f(np.round(np.exp(l_rep))), _f(par_porte),196        _f(np.round(col("rbp_marche"))), _f(np.round(col("revenu_place"))), _f(np.round(col("rapport_place"), 3)),197        _f(np.round(col("taxes"))), _f(np.round(col("depenses"))), _f(np.round(col("rne"))),198        _f(np.round(A["tga"], 5)), _f(np.round(A["mrb"], 2)), _f(_arrondi(np.exp(Lc[:, 2]))),199        _f(_arrondi(A["valeur_mrb"])), _f(np.round(F["v_n"])), _f(np.round(F["v_n1km"])),200        _f(np.round(F["v_e"], 4)), _f(np.round(F["q_e"], 4)), _f(np.round(F["p_e"], 4)), _f(np.round(F["reg_e"], 4)),201        _f(np.round(F["ratio_n"])), _f(np.round(np.exp(l_rep - np.log(P["role"].to_numpy(float))), 4)),202        [None if pd.isna(d) else d for d in dj["date"]], _f(dj["prix"]),203        [None if pd.isna(d) else int(d) for d in dj["de_marche"]],204        [marche] * n, _f(_arrondi(np.exp(Lc[:, 0]))), _f(_arrondi(np.exp(Lc[:, 1]))), _f(F["c_n"]),205        _f(np.round(poids[:, 0], 3)), _f(np.round(poids[:, 1], 3)), _f(np.round(poids[:, 2], 3)),206        _f(np.round(disp, 4)), _f(par_m2)))207    comp = _grille_comparables(P, S, H, F, know, marche) if marche == RES else []208    return {"lignes": lignes, "taux": M, "version": art["version"], "know": know, "plafond_ventes": plafond,209            "comparables": comp,210            "largeur_mediane": float(np.nanmedian(largeur)) if ok.any() else None}211212213MIN_LOGEMENTS_GRILLE = 6     # la grille des comparables retenus est gardée pour les multilogements214215216def _grille_comparables(P, S, H, F, know: int, marche: str) -> list:217    """Comparables réellement retenus par l'approche par comparaison, pour218    chaque multilogement : la grille d'ajustement d'un évaluateur. Chaque219    comparable porte son poids, son rapport prix / repère et la valeur qu'il220    donne à la cible (repère de la cible × ce rapport)."""221    sel = (P["logements"].to_numpy() >= MIN_LOGEMENTS_GRILLE) & np.isfinite(F["l_repere"].to_numpy(float))222    if not sel.any():223        return []224    Ps = P[sel]225    D = V.comparables(Ps, H, know, V.PROFILS[marche], detail=True, marche=marche)226    if "_sale" not in D:227        return []228    n, k = D["_sale"].shape229    garde = (D["_poids"] > 0) & (D["c_n"] >= V.COMP_MIN)[:, None]230    li, ki = np.nonzero(garde)                      # par cible, puis par poids décroissant231    rang = (np.cumsum(garde, axis=1))[li, ki]232    ventes = S.drop_duplicates("sale_id").set_index("sale_id")[["id", "date", "prix", "logements"]]233    v = ventes.reindex(D["_sale"][li, ki])234    e = D["_e"][li, ki]235    l_rep = F["l_repere"].to_numpy(float)[sel][li]236    prix, log = v["prix"].to_numpy(float), v["logements"].to_numpy(float)237    return list(zip(238        Ps["id"].to_numpy()[li].tolist(), rang.tolist(), D["_sale"][li, ki].tolist(), v["id"].tolist(),239        v["date"].tolist(), prix.tolist(), (prix / log).tolist(), log.astype(int).tolist(),240        np.round(D["_d"][li, ki], 3).tolist(), np.round(D["_poids"][li, ki], 4).tolist(),241        np.round(np.exp(e), 4).tolist(), np.round(np.exp(l_rep + e), -3).tolist(),242        D["_meme"][li, ki].astype(int).tolist()))243244245def estimer(verbose: bool = False) -> dict:246    t0 = time.time()247    con = config.ouvrir(ecriture=True)248    if not con.execute("SELECT 1 FROM modele WHERE actif = 1 AND marche = ?", (RES,)).fetchone():249        raise RuntimeError("aucun modèle actif : lancer « vx entrainer »")250    T = revenu.tables_inscriptions(con)251    HT = modele.lire_ventes_tous(con)252    res = _marche(con, RES, None, T, HT)253    # même date de valeur pour les deux marchés : la dernière vente résidentielle254    com = _marche(con, COM, res["know"], T, HT) if COM in typologie.marches_actifs() else None255    marches = {RES: res, **({COM: com} if com else {})}256    lignes = [l for m in marches.values() for l in m["lignes"]]257    with config.transaction(con):258        config.script(con, """259        DROP TABLE IF EXISTS valeur;260        CREATE TABLE valeur (261          id TEXT PRIMARY KEY, statut TEXT NOT NULL, motif TEXT, confiance TEXT, valeur REAL, bas REAL, haut REAL,262          largeur REAL, repere REAL, par_porte REAL, rbp_marche REAL, revenu_place REAL, rapport_place REAL,263          taxes REAL, depenses REAL, rne REAL, tga REAL, mrb REAL, valeur_revenu REAL, valeur_mrb REAL,264          n_voisines REAL, n_voisines_1km REAL, voisines_ecart REAL, quartier_ecart REAL, precedente_ecart REAL,265          tendance_ecart REAL, ratio_n REAL, ratio REAL, vente_date TEXT, vente_prix REAL, vente_marche INTEGER,266          marche TEXT NOT NULL DEFAULT 'residentiel', valeur_hedonique REAL, valeur_comparables REAL,267          n_comparables REAL, poids_hedonique REAL, poids_comparables REAL, poids_revenu REAL, desaccord REAL,268          par_m2 REAL269        ) WITHOUT ROWID;270        """)271        con.executemany("INSERT INTO valeur VALUES (" + ",".join("?" * len(COLONNES_VALEUR)) + ")", lignes)272        config.script(con, """273        DROP TABLE IF EXISTS comparable;274        CREATE TABLE comparable (id TEXT NOT NULL, rang INTEGER NOT NULL, sale_id TEXT NOT NULL, c_id TEXT NOT NULL,275          date TEXT, prix REAL, par_porte REAL, logements INTEGER, distance_km REAL, poids REAL, rapport REAL,276          valeur_ajustee REAL, meme_groupe INTEGER, PRIMARY KEY (id, rang)) WITHOUT ROWID;277        """)278        con.executemany("INSERT INTO comparable VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?)", res["comparables"])279        revenu.ecrire_marche(con, {m: d["taux"] for m, d in marches.items()}, T)280        par_marche = {}281        for m, d in marches.items():282            stat = {r[0]: r[1] for r in con.execute("SELECT statut, COUNT(*) FROM valeur WHERE marche = ? GROUP BY 1", (m,))}283            tot = con.execute("SELECT SUM(valeur), COUNT(valeur), SUM(i.logements) FROM valeur v JOIN immeuble i "284                              "USING(id) WHERE v.marche = ? AND valeur IS NOT NULL", (m,)).fetchone()285            med = con.execute("SELECT valeur FROM valeur WHERE marche = ? AND valeur IS NOT NULL ORDER BY valeur "286                              "LIMIT 1 OFFSET (SELECT COUNT(valeur) / 2 FROM valeur WHERE marche = ?)", (m, m)).fetchone()287            par_marche[m] = {"version": d["version"], "immeubles": len(d["lignes"]), "statuts": stat,288                             "valeur_totale": float(tot[0] or 0), "portes": int(tot[2] or 0),289                             "valeur_mediane": float(med[0]) if med else None, "largeur_mediane": d["largeur_mediane"],290                             "plafond_ventes": None if not np.isfinite(d["plafond_ventes"]) else round(d["plafond_ventes"])}291        r = par_marche[RES]292        # les clés de premier niveau décrivent le résidentiel, comme avant ; « marches » porte le détail293        bilan = {"version": r["version"], "date_valeur": V.iso_de(res["know"]), "immeubles": r["immeubles"],294                 "statuts": r["statuts"], "valeur_totale": r["valeur_totale"], "portes": r["portes"],295                 "valeur_mediane": r["valeur_mediane"], "largeur_mediane": r["largeur_mediane"],296                 "marches": par_marche, "immeubles_tous": len(lignes), "grille_comparables": len(res["comparables"]),297                 "valeur_totale_tous": float(sum(p["valeur_totale"] for p in par_marche.values())),298                 "secondes": round(time.time() - t0, 1)}299        socle.noter(con, "estimation", bilan)300    from . import index301    bilan["index"] = index.construire(con)302    con.close()303    if verbose:304        print(json.dumps(bilan, ensure_ascii=False, indent=1))305    return bilan306
Files main
Menu

Theme