Repository Public
1# =============================================================================2# SP BOUCHER | SOFTWARE & RESEARCH3# ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project : Lou·Ka9# File : louka/building.py10# Module : louka11# Repository : https://git.spboucher.ai/lou-ka12# Created : 2026-08-2413# Last Modified : 2026-08-2414#15# =============================================================================16# AUTHOR & PROFESSIONAL AFFILIATION17# =============================================================================18#19# Author : Simon-Pierre Boucher20# Position : Professor of Finance21# Institution : Université du Québec en Outaouais (UQO)22# Department : Département des sciences administratives23# Organization : SP Boucher24#25# Website : https://spboucher.ai26# Git : https://git.spboucher.ai27#28# =============================================================================29# OFFICIAL CONTACT DIRECTORY30# =============================================================================31#32# General : info@spboucher.ai33# Professional : contact@spboucher.ai34# Direct : simon@spboucher.ai35# Research : research@spboucher.ai36# Development : dev@spboucher.ai37# Support : support@spboucher.ai38# Security/Admin : admin@spboucher.ai39# Notifications : notifications@spboucher.ai40#41# Preferred Contact: contact@spboucher.ai42#43# =============================================================================44# COPYRIGHT & INTELLECTUAL PROPERTY45# =============================================================================46#47# Copyright (c) 202648# Simon-Pierre Boucher49#50# All rights reserved where applicable.51#52# This file is governed by the applicable project license,53# copyright notices, institutional agreements and relevant law.54#55# Unless expressly authorized by the applicable license or56# rights holder, copying, redistribution, sublicensing,57# publication and commercial exploitation are not permitted.58#59# Existing third-party rights and notices remain unaffected.60#61# =============================================================================62# CONFIDENTIALITY & SECURITY63# =============================================================================64#65# Classification : Public66# Distribution : Public repository; use is governed by the project license67# Security Contact : admin@spboucher.ai68#69# Access to this source does not independently grant permission70# to redistribute or disclose confidential materials.71#72# Do not embed credentials, private keys, access tokens,73# certificates or confidential personal information.74#75# =============================================================================76# LICENSE & MAINTENANCE77# =============================================================================78#79# License : None specified (no license file in this repository)80# Maintainer : Simon-Pierre Boucher81# Technical Contact: dev@spboucher.ai82#83# =============================================================================84# END OF SP BOUCHER SOURCE HEADER85# =============================================================================8687# -----------------------------------------------------------------------------88# Lou-Ka — Agrégateur de logements à louer (province de Québec)89# Auteur : Simon-Pierre Boucher — contact@spboucher.ai90# building.py : « Passeport de l'immeuble » — entité persistante regroupant les91# annonces (actives ET historiques) d'un même bâtiment.92#93# Clé d'immeuble : la clé d'adresse civique de dedup._parse_address94# (« civique|rue|ville », préfixe « adr: ») — la même logique éprouvée que la95# déduplication inter-sources ; repli « geo:coord_key » (~11 m) quand l'adresse96# n'a pas de numéro civique fiable mais que l'annonce est géocodée.97#98# Tout indicateur est calculé UNIQUEMENT sur ce que Lou-Ka observe réellement99# (annonces collectées par les crawls). Un indicateur sans échantillon100# suffisant est omis ou marqué « donnees_insuffisantes » — jamais inventé.101# -----------------------------------------------------------------------------102from __future__ import annotations103104import json105import statistics106import time107108from . import db109from .dedup import CLASSIFIEDS, PORTALS, _parse_address110111VERSION = "immeuble-1.0"112113# seuils du score de rotation (annonces des 12 derniers mois / unités estimées)114ROTATION = [(0.5, "faible"), (1.0, "normale"), (2.0, "élevée")]115ROTATION_MAX = "très élevée"116MIN_OBS_DAYS = 180 # fenêtre d'observation minimale pour classer la rotation117MIN_ADS_ROTATION = 3 # nb d'annonces minimal pour classer la rotation118MIN_ADS_PRESSURE = 3 # nb minimal par fenêtre pour la pression sur les loyers119120121def building_key(address: str | None, city: str | None,122 coord_key: str | None) -> tuple[str | None, str | None]:123 """(clé d'immeuble, numéro d'unité) — adresse d'abord, géo en repli."""124 akey, unit = _parse_address(address or "", city or "")125 if akey:126 return f"adr:{akey}", unit127 if coord_key:128 return f"geo:{coord_key}", unit129 return None, unit130131132def _median(vals: list[float]) -> float | None:133 vals = [v for v in vals if v]134 return round(statistics.median(vals)) if vals else None135136137def _stats_for(members: list[dict], now: float) -> dict:138 """Statistiques d'un immeuble à partir de ses annonces (obs. Lou-Ka)."""139 d30, d90, d365, d730 = (now - 30 * 86400, now - 90 * 86400,140 now - 365 * 86400, now - 730 * 86400)141 actives = [m for m in members if m["active"]]142 first_obs = min(m["first_seen"] for m in members if m["first_seen"])143 last_obs = max(m["last_seen"] for m in members if m["last_seen"])144 obs_days = max(1, round((now - first_obs) / 86400))145146 units = {m["unit"] for m in members if m["unit"]}147 # unités estimées : numéros d'app distincts observés, plancher = annonces148 # actives en ce moment (elles existent forcément toutes en même temps)149 unites_estimees = max(len(units), len(actives), 1)150151 n_12m = sum(1 for m in members if (m["first_seen"] or 0) >= d365)152153 # loyers médians (annonces actives)154 med = _median([m["price"] for m in actives])155 par_cc: dict[str, int] = {}156 by_cc: dict[str, list[float]] = {}157 for m in actives:158 if m["price"] and m["bedrooms"] is not None:159 by_cc.setdefault(str(int(m["bedrooms"])), []).append(m["price"])160 for cc, vals in sorted(by_cc.items()):161 v = _median(vals)162 if v and len(vals) >= 2:163 par_cc[cc] = v164 vals_pi2 = [m["price"] / m["area"] for m in actives165 if m["price"] and m["area"] and m["area"] > 100]166 pi2 = round(statistics.median(vals_pi2), 2) if vals_pi2 else None167168 # pression sur les loyers : médiane des PREMIERS prix observés des annonces169 # apparues dans les 12 derniers mois vs celles des 12 mois précédents170 win_new = [m["first_price"] for m in members171 if m["first_price"] and (m["first_seen"] or 0) >= d365]172 win_old = [m["first_price"] for m in members173 if m["first_price"] and d730 <= (m["first_seen"] or 0) < d365]174 pression = None175 if len(win_new) >= MIN_ADS_PRESSURE and len(win_old) >= MIN_ADS_PRESSURE:176 m_new, m_old = statistics.median(win_new), statistics.median(win_old)177 if m_old > 0:178 pression = {179 "variation_12m": round((m_new - m_old) / m_old, 4),180 "mediane_12m": round(m_new), "mediane_12_24m": round(m_old),181 "n_12m": len(win_new), "n_12_24m": len(win_old),182 "statut": "calculated",183 }184185 # score de rotation : annonces des 12 derniers mois / unités estimées186 rotation: dict = {"statut": "donnees_insuffisantes"}187 if obs_days >= MIN_OBS_DAYS and len(members) >= MIN_ADS_ROTATION:188 ratio = n_12m / unites_estimees189 classe = ROTATION_MAX190 for seuil, nom in ROTATION:191 if ratio < seuil:192 classe = nom193 break194 rotation = {195 "classe": classe, "ratio": round(ratio, 2),196 "annonces_12m": n_12m, "unites_estimees": unites_estimees,197 "observation_jours": obs_days, "statut": "calculated",198 "methode": ("annonces observées les 12 derniers mois ÷ unités "199 "estimées (numéros d'app distincts, plancher = annonces "200 "actives simultanées). Mesure uniquement ce que Lou-Ka "201 "observe — pas un taux de roulement démographique."),202 }203204 sources: dict[str, int] = {}205 for m in members:206 sources[m["source"]] = sources.get(m["source"], 0) + 1207 gestionnaires = sorted(s for s in sources208 if s not in PORTALS and s not in CLASSIFIEDS)209210 return {211 "annonces_total": len(members),212 "annonces_actives": len(actives),213 "annonces_30j": sum(1 for m in members if (m["first_seen"] or 0) >= d30),214 "annonces_90j": sum(1 for m in members if (m["first_seen"] or 0) >= d90),215 "annonces_12m": n_12m,216 "unites_identifiees": len(units),217 "unites_estimees": unites_estimees,218 "loyer_median": med,219 "loyer_median_par_cc": par_cc or None,220 "pi2_median": pi2,221 "pression_loyers": pression,222 "rotation": rotation,223 "gestionnaires": gestionnaires,224 "sources": sources,225 "premiere_observation": first_obs,226 "derniere_observation": last_obs,227 "unites_actives": sorted(228 [{"uid": m["uid"], "unit_type": m["unit_type"],229 "price": m["price"], "bedrooms": m["bedrooms"]}230 for m in actives if not m["dup_of"]],231 key=lambda x: (x["price"] is None, x["price"] or 0))[:24],232 }233234235def rollup(con=None) -> dict:236 """Recalcule building_key de toutes les annonces + la table buildings.237238 Idempotent, recalcul complet (même philosophie que dedup.run) : les239 annonces INACTIVES participent — l'historique de l'immeuble est justement240 ce qui fait la valeur du passeport.241 """242 own = con is None243 if own:244 con = db.connect()245 now = time.time()246 rows = con.execute(247 "SELECT uid, source, address, city, coord_key, unit_type, bedrooms,"248 " price, area_sqft, first_seen, last_seen, active, dup_of, building_key"249 " FROM listings").fetchall()250251 # premier prix observé par annonce (pression sur les loyers)252 firstp = {r["uid"]: r["p"] for r in con.execute(253 "SELECT uid, (SELECT price FROM price_log p2 WHERE p2.uid=p1.uid"254 " AND p2.price IS NOT NULL ORDER BY ts LIMIT 1) p"255 " FROM (SELECT DISTINCT uid FROM price_log) p1")}256257 groups: dict[str, list[dict]] = {}258 key_updates: list[tuple[str | None, str]] = []259 for r in rows:260 bkey, unit = building_key(r["address"], r["city"], r["coord_key"])261 if bkey != r["building_key"]:262 key_updates.append((bkey, r["uid"]))263 if not bkey:264 continue265 groups.setdefault(bkey, []).append({266 "uid": r["uid"], "source": r["source"], "unit": unit,267 "unit_type": r["unit_type"], "bedrooms": r["bedrooms"],268 "price": r["price"], "area": r["area_sqft"],269 "first_seen": r["first_seen"], "last_seen": r["last_seen"],270 "active": r["active"], "dup_of": r["dup_of"],271 "first_price": firstp.get(r["uid"]) or r["price"],272 "address": r["address"], "city": r["city"],273 })274 if key_updates:275 con.executemany("UPDATE listings SET building_key=? WHERE uid=?",276 key_updates)277278 upserts = []279 for bkey, members in groups.items():280 # doublons inter-sources : un même logement publié sur 3 plateformes ne281 # compte qu'une fois dans les statistiques de l'immeuble282 uniq = [m for m in members if not m["dup_of"]]283 if not uniq:284 continue285 stats = _stats_for(uniq, now)286 # adresse d'affichage : la plus fréquente parmi les membres actifs287 addrs = [m["address"] for m in uniq if m["address"]]288 addr = max(set(addrs), key=addrs.count) if addrs else None289 cities = [m["city"] for m in uniq if m["city"]]290 city = max(set(cities), key=cities.count) if cities else None291 # position : coord de n'importe quel membre géocodé (via coord_key)292 upserts.append((bkey, addr, city,293 json.dumps(stats, ensure_ascii=False), VERSION, now))294 con.executemany(295 "INSERT INTO buildings (bkey, address, city, stats, version, computed_at)"296 " VALUES (?,?,?,?,?,?)"297 " ON CONFLICT(bkey) DO UPDATE SET address=excluded.address,"298 " city=excluded.city, stats=excluded.stats, version=excluded.version,"299 " computed_at=excluded.computed_at", upserts)300 con.commit()301 out = {"buildings": len(upserts), "listings_scanned": len(rows),302 "keys_updated": len(key_updates)}303 if own:304 con.close()305 return out306307308def fiche(bkey: str, con=None) -> dict | None:309 """Passeport d'un immeuble pour l'API (stats précalculées par rollup)."""310 own = con is None311 if own:312 con = db.connect()313 row = con.execute(314 "SELECT bkey, address, city, stats, version, computed_at FROM buildings"315 " WHERE bkey=?", (bkey,)).fetchone()316 if own and row is None:317 con.close()318 return None319 if row is None:320 return None321 out = {"bkey": row["bkey"], "address": row["address"], "city": row["city"],322 "version": row["version"], "computed_at": row["computed_at"],323 **json.loads(row["stats"] or "{}")}324 if own:325 con.close()326 return out327328329if __name__ == "__main__":330 print(rollup())331