Repository Public
1# =============================================================================2# SP BOUCHER | SOFTWARE & RESEARCH3# ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project : Valo-Plex9# File : moteur/plexmoteur/index.py10# Description : Tables de service du site et des applications : recherche11# d'adresse, statistiques par territoire, séries de prix par12# porte.13# Module : moteur14# Repository : https://git.spboucher.ai/valo-plex15# Project Website : https://www.valo-plex.com16# Created : 2026-12-0117# Last Modified : 2026-12-0318#19# =============================================================================20# AUTHOR & PROFESSIONAL AFFILIATION21# =============================================================================22#23# Author : Simon-Pierre Boucher24# Position : Professor of Finance25# Institution : Université du Québec en Outaouais (UQO)26# Department : Département des sciences administratives27# Organization : SP Boucher28#29# Website : https://spboucher.ai30# Git : https://git.spboucher.ai31#32# =============================================================================33# OFFICIAL CONTACT DIRECTORY34# =============================================================================35#36# General : info@spboucher.ai37# Professional : contact@spboucher.ai38# Direct : simon@spboucher.ai39# Research : research@spboucher.ai40# Development : dev@spboucher.ai41# Support : support@spboucher.ai42# Security/Admin : admin@spboucher.ai43# Notifications : notifications@spboucher.ai44#45# Preferred Contact: contact@spboucher.ai46#47# =============================================================================48# COPYRIGHT & INTELLECTUAL PROPERTY49# =============================================================================50#51# Copyright (c) 202652# Simon-Pierre Boucher53#54# All rights reserved where applicable.55#56# This file is governed by the applicable project license,57# copyright notices, institutional agreements and relevant law.58#59# Unless expressly authorized by the applicable license or60# rights holder, copying, redistribution, sublicensing,61# publication and commercial exploitation are not permitted.62#63# Existing third-party rights and notices remain unaffected.64#65# =============================================================================66# CONFIDENTIALITY & SECURITY67# =============================================================================68#69# Classification : Public70# Distribution : Public repository; use is governed by the project license71# Security Contact : admin@spboucher.ai72#73# Access to this source does not independently grant permission74# to redistribute or disclose confidential materials.75#76# Do not embed credentials, private keys, access tokens,77# certificates or confidential personal information.78#79# =============================================================================80# LICENSE & MAINTENANCE81# =============================================================================82#83# License : None specified (no license file in this repository)84# Maintainer : Simon-Pierre Boucher85# Technical Contact: dev@spboucher.ai86#87# =============================================================================88# END OF SP BOUCHER SOURCE HEADER89# =============================================================================9091"""Tables de service du site et des applications : recherche d'adresse,92statistiques par territoire, séries de prix par porte."""93from __future__ import annotations9495import json96import re97import unicodedata9899import numpy as np100import pandas as pd101102from . import config, socle103from . import variables as V104105MIN_TRIMESTRE = 8106107108def slug(texte: str) -> str:109 t = unicodedata.normalize("NFKD", texte or "").encode("ascii", "ignore").decode().lower()110 return re.sub(r"[^a-z0-9]+", "-", t).strip("-")111112113def _recherche(con) -> int:114 config.script(con, """115 DROP TABLE IF EXISTS recherche;116 CREATE VIRTUAL TABLE recherche USING fts5(adresse, municipalite, id UNINDEXED,117 tokenize = "unicode61 remove_diacritics 2");118 INSERT INTO recherche (adresse, municipalite, id)119 SELECT adresse, municipalite, id FROM immeuble WHERE adresse IS NOT NULL;120 INSERT INTO recherche (recherche) VALUES ('optimize');121 """)122 return con.execute("SELECT COUNT(*) FROM recherche").fetchone()[0]123124125def _resume(tout: pd.DataFrame) -> dict:126 """Chiffres d'un territoire. Les totaux et médianes « par porte » décrivent127 le résidentiel à revenus ; ``classes`` détaille aussi chaque catégorie128 commerciale (médiane par mètre carré)."""129 g = tout[tout["marche"] == "residentiel"]130 v = g["valeur"].dropna()131 par_classe = {}132 for c, h in g.groupby("classe"):133 hv = h["valeur"].dropna()134 par_classe[c] = {"n": int(len(h)), "valeur_mediane": float(hv.median()) if len(hv) else None,135 "porte_mediane": float((hv / h.loc[hv.index, "logements"]).median()) if len(hv) else None}136 com = tout[tout["marche"] == "commercial"]137 for c, h in com.groupby("classe"):138 hv = h["valeur"].dropna()139 m2 = h["par_m2"].dropna()140 par_classe[c] = {"n": int(len(h)), "valeur_mediane": float(hv.median()) if len(hv) else None,141 "m2_mediane": float(m2.median()) if len(m2) else None, "commercial": True}142 cv = com["valeur"].dropna()143 return {"commerciaux": int(len(com)), "valeur_commerciale": float(cv.sum()),144 "immeubles": int(len(g)), "portes": int(g["logements"].sum()),145 "valeur_totale": float(v.sum()), "valeur_mediane": float(v.median()) if len(v) else None,146 "porte_mediane": float((v / g.loc[v.index, "logements"]).median()) if len(v) else None,147 "loyer_median": float(g["loyer_porte"].median()) if g["loyer_porte"].notna().any() else None,148 "tga_median": float(g["tga_i"].median()) if g["tga_i"].notna().any() else None,149 "mrb_median": float(g["mrb_i"].median()) if g["mrb_i"].notna().any() else None,150 "classes": json.dumps(par_classe, ensure_ascii=False)}151152153def _territoires(con) -> int:154 P = pd.read_sql_query("""155 SELECT i.id, i.code_mun, i.arrond, i.classe, i.logements, i.loyer_porte, v.valeur, v.rne, v.revenu_place,156 t.municipalite, t.region_code, t.region, i.marche, v.par_m2157 FROM immeuble i JOIN valeur v ON v.id = i.id LEFT JOIN territoire t ON t.code_mun = i.code_mun""", con)158 P["tga_i"] = P["rne"] / P["valeur"]159 P["mrb_i"] = P["valeur"] / P["revenu_place"]160 S = pd.read_sql_query("""161 SELECT i.code_mun, i.arrond, t.region_code, v.jour, v.prix, i.logements162 FROM vente v JOIN immeuble i ON i.id = v.id LEFT JOIN territoire t ON t.code_mun = i.code_mun163 WHERE v.de_marche = 1 AND v.doublon = 0 AND i.marche = 'residentiel'""", con)164 S["pp"] = S["prix"] / S["logements"]165 fin = int(S["jour"].max())166 S12 = S[S["jour"] > fin - 365]167 d = pd.to_datetime(S["jour"], unit="D")168 S["trimestre"] = d.dt.year.astype(str) + "-T" + d.dt.quarter.astype(str)169 arr = dict(con.execute("SELECT code, nom FROM arrondissement").fetchall())170 lignes, series = [], []171172 def ajoute(niveau, code, nom, parent, g, s12, s):173 r = _resume(g)174 lignes.append((niveau, str(code), nom, slug(nom), parent, r["immeubles"], r["portes"], r["valeur_totale"],175 r["valeur_mediane"], r["porte_mediane"], r["loyer_median"], r["tga_median"], r["mrb_median"],176 int(len(s12)), float(s12["pp"].median()) if len(s12) >= 5 else None,177 float(s12["prix"].median()) if len(s12) >= 5 else None, r["classes"],178 r["commerciaux"], r["valeur_commerciale"]))179 q = s.groupby("trimestre").agg(n=("pp", "size"), pp=("pp", "median"), prix=("prix", "median"))180 for tri, x in q[q["n"] >= MIN_TRIMESTRE].iterrows():181 series.append((niveau, str(code), tri, int(x["n"]), float(x["pp"]), float(x["prix"])))182183 ajoute("province", "qc", "Québec", None, P, S12, S)184 for (code, nom), g in P.dropna(subset=["region_code"]).groupby(["region_code", "region"]):185 ajoute("region", code, nom, "qc", g, S12[S12["region_code"] == code], S[S["region_code"] == code])186 s12m, sm = dict(tuple(S12.groupby("code_mun"))), dict(tuple(S.groupby("code_mun")))187 vide = S.iloc[0:0]188 for (code, nom, reg), g in P.dropna(subset=["municipalite"]).groupby(["code_mun", "municipalite", "region_code"]):189 if len(g) >= 20:190 ajoute("municipalite", code, nom, reg, g, s12m.get(code, vide), sm.get(code, vide))191 for (mun, a), g in P.dropna(subset=["arrond"]).groupby(["code_mun", "arrond"]):192 if len(g) >= 20 and a in arr:193 ajoute("arrondissement", a, arr[a], mun, g, S12[(S12["code_mun"] == mun) & (S12["arrond"] == a)],194 S[(S["code_mun"] == mun) & (S["arrond"] == a)])195 config.script(con, """196 DROP TABLE IF EXISTS stats_territoire;197 CREATE TABLE stats_territoire (niveau TEXT NOT NULL, code TEXT NOT NULL, nom TEXT NOT NULL, slug TEXT NOT NULL,198 parent TEXT, immeubles INTEGER, portes INTEGER, valeur_totale REAL, valeur_mediane REAL, porte_mediane REAL,199 loyer_median REAL, tga_median REAL, mrb_median REAL, ventes_12m INTEGER, prix_porte_12m REAL,200 prix_median_12m REAL, classes TEXT, commerciaux INTEGER, valeur_commerciale REAL,201 PRIMARY KEY (niveau, code)) WITHOUT ROWID;202 CREATE INDEX stats_territoire_slug ON stats_territoire (niveau, slug);203 DROP TABLE IF EXISTS serie_prix;204 CREATE TABLE serie_prix (niveau TEXT NOT NULL, code TEXT NOT NULL, trimestre TEXT NOT NULL, n INTEGER,205 prix_porte REAL, prix REAL, PRIMARY KEY (niveau, code, trimestre)) WITHOUT ROWID;206 """)207 con.executemany("INSERT OR REPLACE INTO stats_territoire VALUES (" + ",".join("?" * 19) + ")", lignes)208 con.executemany("INSERT OR REPLACE INTO serie_prix VALUES (?,?,?,?,?,?)", series)209 return len(lignes)210211212NIVEAUX_GRILLE = range(7, 17) # tuiles « slippy » : du Québec entier (7) au pâté de maisons (16)213214215def _grille(con) -> int:216 """Agrégats de la carte : pour chaque niveau de tuile, le nombre d'immeubles,217 de portes et la valeur médiane par porte de chaque case. Au-delà du niveau218 16 la carte montre les immeubles un à un."""219 import math220 P = pd.read_sql_query("""221 SELECT i.id, i.lat, i.lng, i.logements, v.valeur, s.id IS NOT NULL vendre, i.marche222 FROM immeuble i JOIN valeur v ON v.id = i.id223 LEFT JOIN a_vendre s ON s.id = i.id224 WHERE v.valeur IS NOT NULL""", con)225 with np.errstate(all="ignore"):226 P["pp"] = np.where(P["marche"] == "residentiel", P["valeur"] / P["logements"], np.nan)227 latr = np.radians(P["lat"].to_numpy())228 merc = (1 - np.log(np.tan(latr) + 1 / np.cos(latr)) / math.pi) / 2229 fx = (P["lng"].to_numpy() + 180.0) / 360.0230 config.script(con, """231 DROP TABLE IF EXISTS grille;232 CREATE TABLE grille (z INTEGER NOT NULL, x INTEGER NOT NULL, y INTEGER NOT NULL, n INTEGER NOT NULL,233 portes INTEGER NOT NULL, a_vendre INTEGER NOT NULL, porte_mediane REAL, lat REAL, lng REAL,234 PRIMARY KEY (z, x, y)) WITHOUT ROWID;235 """)236 # case de niveau 16 de chaque immeuble : la carte filtrée (par type) s'agrège à la volée par décalage de bits237 cols = [r[1] for r in con.execute("PRAGMA table_info(immeuble)")]238 for c in ("x16", "y16"):239 if c not in cols:240 con.execute(f"ALTER TABLE immeuble ADD COLUMN {c} INTEGER")241 k16 = 2 ** 16242 con.executemany("UPDATE immeuble SET x16 = ?, y16 = ? WHERE id = ?",243 zip(np.floor(fx * k16).astype(int).tolist(), np.floor(merc * k16).astype(int).tolist(), P["id"]))244 # la grille précalculée décrit le résidentiel (valeur par porte) ; le commercial, filtré par catégorie,245 # s'agrège à la volée par la case de niveau 16 de chaque immeuble246 total = 0247 res = (P["marche"] == "residentiel").to_numpy()248 fx, merc, P = fx[res], merc[res], P[res].copy()249 for z in NIVEAUX_GRILLE:250 k = 2 ** z251 P["x"] = np.floor(fx * k).astype(int)252 P["y"] = np.floor(merc * k).astype(int)253 g = P.groupby(["x", "y"]).agg(n=("pp", "size"), portes=("logements", "sum"), vendre=("vendre", "sum"),254 pp=("pp", "median"), lat=("lat", "mean"), lng=("lng", "mean")).reset_index()255 con.executemany("INSERT INTO grille VALUES (?,?,?,?,?,?,?,?,?)",256 [(z, int(r.x), int(r.y), int(r.n), int(r.portes), int(r.vendre), float(r.pp),257 float(r.lat), float(r.lng)) for r in g.itertuples()])258 total += len(g)259 return total260261262def _a_vendre(con) -> int:263 """Un prix demandé par immeuble à vendre (le plus bas des inscriptions actives rattachées)."""264 config.script(con, """265 DROP TABLE IF EXISTS a_vendre;266 CREATE TABLE a_vendre (id TEXT PRIMARY KEY, prix REAL NOT NULL, uid TEXT NOT NULL) WITHOUT ROWID;267 INSERT INTO a_vendre268 SELECT a.id, MIN(a.prix), a.uid FROM annonce a JOIN immeuble i ON i.id = a.id JOIN valeur v ON v.id = a.id269 WHERE a.active = 1 AND a.lien_niveau = 'unite' AND v.valeur IS NOT NULL270 AND (a.logements IS NULL OR a.logements = i.logements) AND a.prix BETWEEN 0.55 * v.valeur AND 2.5 * v.valeur271 AND COALESCE(a.statut, 'a-vendre') = 'a-vendre'272 GROUP BY a.id;273 """)274 return con.execute("SELECT COUNT(*) FROM a_vendre").fetchone()[0]275276277def construire(con) -> dict:278 with config.transaction(con):279 n_vendre = _a_vendre(con)280 bilan = {"recherche": _recherche(con), "territoires": _territoires(con), "grille": _grille(con), "a_vendre": n_vendre}281 socle.noter(con, "index", bilan)282 return bilan283