Repository Public
1# =============================================================================2# SP BOUCHER | SOFTWARE & RESEARCH3# ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project : Valo-Plex9# File : moteur/plexmoteur/loyers.py10# Description : Loyers de marché : gradient boosting sur le log des loyers11# DEMANDÉS observés par Lou-Ka (appartements à louer), puis12# loyer de marché estimé de chaque plex du parc, par taille13# de logement.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"""Loyers de marché : gradient boosting sur le log des loyers DEMANDÉS observés93par Lou-Ka (appartements à louer), puis loyer de marché estimé de chaque plex94du parc, par taille de logement.9596Un loyer demandé est le loyer d'un logement offert aujourd'hui, pas le loyer97payé par un locataire en place : l'écart entre les deux est mesuré à part98(``revenu.py``) sur les inscriptions qui publient leurs revenus.99"""100from __future__ import annotations101102import json103import math104import time105106import joblib107import numpy as np108import pandas as pd109110from . import config, socle111from . import variables as V112113COLS = ("x", "y", "rot1", "rot2", "chambres", "aire", "chauffe", "eclaire", "meuble", "maison")114GB = dict(loss="absolute_error", max_iter=400, max_leaf_nodes=31, learning_rate=0.06,115 min_samples_leaf=25, l2_regularization=1.0, early_stopping=False, random_state=config.SEED)116PI2_PAR_M2 = 10.7639117PART_HABITABLE = 0.80 # aire d'étages du rôle (murs, escaliers, communs) → aire louable118TAILLES = {"3": 1, "4": 2, "5": 3} # 3½, 4½, 5½ → chambres119120121def chambres_typiques(aire_pi2: np.ndarray) -> np.ndarray:122 """Nombre de chambres le plus courant pour une aire louable donnée."""123 a = np.asarray(aire_pi2, float)124 return np.select([a < 480, a < 720, a < 1000, a < 1300], [0.0, 1.0, 2.0, 3.0], 4.0)125126127def _matrice(d: pd.DataFrame) -> np.ndarray:128 x, y = V.projeter(d["lat"], d["lng"])129 return np.c_[x, y, (x + y) / math.sqrt(2), (x - y) / math.sqrt(2), d["chambres"].astype(float),130 d["aire"].astype(float), d["chauffe"].astype(float), d["eclaire"].astype(float),131 d["meuble"].astype(float), d["maison"].astype(float)]132133134def entrainer(verbose: bool = False) -> dict:135 from sklearn.ensemble import HistGradientBoostingRegressor136 from sklearn.model_selection import GroupKFold137 from threadpoolctl import threadpool_limits138 t0 = time.time()139 con = config.ouvrir(ecriture=True)140 L = pd.read_sql_query(141 "SELECT lat, lng, genre, chambres, aire_pi2 aire, loyer, COALESCE(chauffe,0) chauffe, "142 "COALESCE(eclaire,0) eclaire, COALESCE(meuble,0) meuble, COALESCE(immeuble_cle, uid) cle FROM loyer "143 "WHERE genre IN ('appartement','studio','maison','condo') AND chambres IS NOT NULL "144 "AND loyer BETWEEN 400 AND 8000", con)145 L.loc[~L["aire"].between(150, 4000), "aire"] = np.nan146 L["maison"] = (L["genre"] == "maison").astype(float)147 X, y = _matrice(L), np.log(L["loyer"].to_numpy(float))148 # validation croisée par immeuble : les logements d'un même immeuble ne se valident pas entre eux149 oof = np.full(len(L), np.nan)150 with threadpool_limits(limits=config.THREADS):151 for tr, te in GroupKFold(n_splits=5).split(X, y, L["cle"]):152 oof[te] = HistGradientBoostingRegressor(**GB).fit(X[tr], y[tr]).predict(X[te])153 m = HistGradientBoostingRegressor(**GB).fit(X, y)154 err = np.abs(np.exp(oof - y) - 1)155 bilan = {"n": int(len(L)), "erreur_mediane": round(float(np.median(err)) * 100, 2),156 "a_10": round(float((err <= 0.10).mean()) * 100, 1),157 "biais": round(float(np.median(np.exp(oof - y) - 1)) * 100, 2)}158159 # parc : loyer de marché d'un logement type de chaque immeuble, non chauffé, non meublé160 P = pd.read_sql_query("SELECT id, lat, lng, logements, aire_m2 FROM immeuble WHERE marche = 'residentiel'", con)161 aire = (P["aire_m2"] / P["logements"] * PI2_PAR_M2 * PART_HABITABLE).clip(300, 1800)162 base = pd.DataFrame({"lat": P["lat"], "lng": P["lng"], "aire": aire, "chauffe": 0.0, "eclaire": 0.0,163 "meuble": 0.0, "maison": 0.0})164 with threadpool_limits(limits=config.THREADS):165 typ = base.assign(chambres=np.where(aire.notna(), chambres_typiques(aire.fillna(800)), 2.0))166 P["loyer_porte"] = np.exp(m.predict(_matrice(typ)))167 for nom, ch in TAILLES.items():168 P[f"loyer_{nom}"] = np.exp(m.predict(_matrice(base.assign(chambres=float(ch), aire=np.nan))))169 cols = [r[1] for r in con.execute("PRAGMA table_info(immeuble)")]170 with config.transaction(con):171 for c in ("loyer_porte", "loyer_3", "loyer_4", "loyer_5"):172 if c not in cols:173 con.execute(f"ALTER TABLE immeuble ADD COLUMN {c} REAL")174 con.executemany("UPDATE immeuble SET loyer_porte=?, loyer_3=?, loyer_4=?, loyer_5=? WHERE id=?",175 [(round(a), round(b), round(c), round(d), i) for a, b, c, d, i in176 zip(P["loyer_porte"], P["loyer_3"], P["loyer_4"], P["loyer_5"], P["id"])])177 bilan["secondes"] = round(time.time() - t0, 1)178 bilan["loyer_median_parc"] = float(np.median(P["loyer_porte"]))179 socle.noter(con, "modele_loyers", bilan)180 config.MODELES.mkdir(parents=True, exist_ok=True)181 joblib.dump({"modele": m, "cols": COLS}, config.MODELES / "loyers.joblib", compress=3)182 con.close()183 if verbose:184 print(json.dumps(bilan, ensure_ascii=False, indent=1))185 return bilan186