Repository Public
1# =============================================================================2# SP BOUCHER | SOFTWARE & RESEARCH3# ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project : Lou·Ka9# File : louka/marketstats.py10# Module : louka11# Repository : https://git.spboucher.ai/lou-ka12# Created : 2026-08-0913# Last Modified : 2026-08-0914#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# marketstats.py : agrégats du marché partagés par /api/stats/detailed (page91# Statistiques) et par le rapport PDF (pdfgen.rapport_pdf) — une seule92# source de vérité pour tous les chiffres.93# -----------------------------------------------------------------------------94from __future__ import annotations9596import json97import time9899from . import db100101# Régions administratives simplifiées (villes réellement présentes en base)102REGIONS: list[tuple[str, set[str]]] = [103 ("Québec métro", {"Québec", "Lévis", "Saint-Augustin-de-Desmaures",104 "L'Ancienne-Lorette", "Pont-Rouge", "Shannon",105 "Sainte-Brigitte-de-Laval", "Saint-Raphaël", "La Malbaie"}),106 ("Outaouais", {"Gatineau", "Chelsea", "Thurso", "Perkins", "Maniwaki",107 "Val-des-Monts"}),108 ("Estrie / Montérégie-Est", {"Sherbrooke", "Magog", "Orford", "East Angus",109 "Waterville", "Granby", "Waterloo", "Bromont",110 "Cowansville", "Richmond"}),111 ("Mauricie / Centre-du-Québec", {"Trois-Rivières", "Bécancour", "Shawinigan",112 "Drummondville", "Victoriaville", "Nicolet",113 "Notre-Dame-du-Bon-Conseil", "Wickham",114 "Saint-Léonard-d'Aston", "Louiseville",115 "Saint-Narcisse", "Saint-Nicéphore"}),116 ("Lanaudière / Laurentides", {"Joliette", "Saint-Jérôme", "Berthierville",117 "Saint-Ambroise-de-Kildare", "Charlemagne",118 "Saint-Gabriel-de-Brandon", "Lachute",119 "Brownsburg-Chatham", "Saint-Charles-Borromée",120 "Mirabel", "Sainte-Agathe-des-Monts",121 "Sainte-Thérèse", "Blainville",122 "Notre-Dame-des-Prairies"}),123 ("Bas-Saint-Laurent / Gaspésie", {"Rimouski", "Rivière-du-Loup", "Matane",124 "Saint-Ulric", "Amqui", "Le Bic",125 "New Richmond", "Carleton-sur-Mer", "Gaspé",126 "Pointe-au-Père"}),127 ("Saguenay–Lac-Saint-Jean", {"Saguenay", "Alma", "Chicoutimi", "Jonquière",128 "Chambord", "La Baie", "Laterrière"}),129 ("Abitibi-Témiscamingue", {"Rouyn-Noranda", "Val-d'Or", "Amos", "Malartic"}),130 ("Côte-Nord", {"Sept-Îles", "Port-Cartier", "Baie-Comeau", "Forestville"}),131 ("Chaudière-Appalaches", {"Saint-Georges", "Sainte-Marie", "Thetford Mines",132 "Montmagny", "Vallée-Jonction", "Scott",133 "Saint-Isidore", "La Guadeloupe",134 "Saint-Joseph-de-Beauce"}),135]136137138def region_for(city: str) -> str:139 for nom, villes in REGIONS:140 if city in villes:141 return nom142 return "Grand Montréal & environs"143144145def _median(v: list) -> float | None:146 n = len(v)147 if n == 0:148 return None149 return v[n // 2] if n % 2 else (v[n // 2 - 1] + v[n // 2]) / 2150151152def compute() -> dict:153 """Tous les agrégats du marché sur les annonces actives."""154 con = db.connect()155 rows = con.execute(156 """SELECT uid, city, source, price, unit_type, area_sqft, furnished,157 pets, availability_date, lat, details158 FROM listings WHERE active=1 AND published=1 AND dup_of IS NULL AND province='QC'""").fetchall()159 now = time.time()160161 total = len(rows)162 prix = sorted(r["price"] for r in rows163 if r["price"] and 300 <= r["price"] <= 10000)164165 # -- groupes simples ------------------------------------------------------166 def grouper(cle_fn):167 g: dict[str, dict] = {}168 for r in rows:169 k = cle_fn(r)170 if not k:171 continue172 d = g.setdefault(k, {"count": 0, "prix": [], "sources": set()})173 d["count"] += 1174 d["sources"].add(r["source"])175 if r["price"] and 300 <= r["price"] <= 10000:176 d["prix"].append(r["price"])177 out = []178 for k, d in sorted(g.items(), key=lambda kv: -kv[1]["count"]):179 p = d["prix"]180 out.append({"key": k, "count": d["count"],181 "sources": len(d["sources"]),182 "avg_price": round(sum(p) / len(p)) if p else None,183 "min_price": min(p) if p else None})184 return out185186 by_type = grouper(lambda r: r["unit_type"])187 by_city = grouper(lambda r: r["city"])188 by_source = grouper(lambda r: r["source"])189 by_region = grouper(lambda r: region_for(r["city"] or ""))190191 # -- histogramme des loyers ------------------------------------------------192 lo, hi, step = 400, 3200, 200193 hist = [{"lo": a, "hi": a + step, "count": 0} for a in range(lo, hi, step)]194 under = over = 0195 for p in prix:196 if p < lo:197 under += 1198 elif p >= hi:199 over += 1200 else:201 hist[int((p - lo) // step)]["count"] += 1202 if under:203 hist.insert(0, {"lo": 0, "hi": lo, "count": under})204 if over:205 hist.append({"lo": hi, "hi": None, "count": over})206207 # -- offre : inclusions, animaux, meublé, dispo, superficie ----------------208 def pct(n, d):209 return round(100 * n / d, 1) if d else None210211 inc_counts = {"heating": 0, "electricity": 0, "hot_water": 0, "internet": 0}212 ac = parking = balcon = 0213 with_details = 0214 for r in rows:215 try:216 det = json.loads(r["details"] or "{}")217 except ValueError:218 det = {}219 if det:220 with_details += 1221 inc = det.get("inclusions")222 if not isinstance(inc, dict):223 inc = {}224 for k in inc_counts:225 if inc.get(k):226 inc_counts[k] += 1227 if det.get("ac"):228 ac += 1229 # `parking` : dict {"available": …} ou, selon le connecteur, un simple230 # nombre de places / booléen — les deux formes comptent231 pk = det.get("parking")232 if (pk.get("available") if isinstance(pk, dict) else pk):233 parking += 1234 if det.get("balcony"):235 balcon += 1236237 pets_vals = [r["pets"] for r in rows if r["pets"]]238 furn = sum(1 for r in rows if r["furnished"])239 dispo_now = sum(1 for r in rows if r["availability_date"] == "now")240 dispo_date = sum(1 for r in rows241 if r["availability_date"] and r["availability_date"] != "now")242 aires = [r["area_sqft"] for r in rows if r["area_sqft"]]243244 # prix au pi² par taille (annonces ayant les deux)245 pi2: dict[str, list] = {}246 for r in rows:247 if (r["price"] and r["area_sqft"] and r["unit_type"]248 and 300 <= r["price"] <= 10000 and r["area_sqft"] >= 200):249 pi2.setdefault(r["unit_type"], []).append(r["price"] / r["area_sqft"])250 prix_pi2 = [{"key": k, "count": len(v),251 "val": round(sum(v) / len(v), 2)}252 for k, v in sorted(pi2.items(), key=lambda kv: -len(kv[1]))253 if len(v) >= 8][:8]254255 offre = {256 "furnished_pct": pct(furn, total),257 "pets_oui_pct": pct(sum(1 for p in pets_vals if p in ("oui", "conditions")),258 len(pets_vals)),259 "pets_connu": len(pets_vals),260 "chauffage_pct": pct(inc_counts["heating"], total),261 "electricite_pct": pct(inc_counts["electricity"], total),262 "eau_chaude_pct": pct(inc_counts["hot_water"], total),263 "internet_pct": pct(inc_counts["internet"], total),264 "clim_pct": pct(ac, total),265 "stationnement_pct": pct(parking, total),266 "balcon_pct": pct(balcon, total),267 "dispo_now": dispo_now,268 "dispo_date": dispo_date,269 "dispo_inconnue": total - dispo_now - dispo_date,270 "superficie_moyenne": round(sum(aires) / len(aires)) if aires else None,271 "superficie_connue": len(aires),272 "prix_pi2": prix_pi2,273 }274275 # -- baisses de prix récentes (30 jours) -----------------------------------276 baisses = []277 for r in con.execute(278 """SELECT p1.uid, l.title, l.city, l.price, p1.price nouveau, p1.ts279 FROM price_log p1280 JOIN listings l ON l.uid = p1.uid AND l.active=1 AND l.published=1 AND l.dup_of IS NULL281 WHERE p1.ts > ? AND p1.price IS NOT NULL282 ORDER BY p1.ts DESC LIMIT 400""", (now - 30 * 86400,)).fetchall():283 prev = con.execute(284 "SELECT price FROM price_log WHERE uid=? AND ts<? AND price IS NOT NULL"285 " ORDER BY ts DESC LIMIT 1", (r["uid"], r["ts"])).fetchone()286 if prev and prev["price"] and r["nouveau"] and r["nouveau"] < prev["price"]:287 baisses.append({"uid": r["uid"], "title": r["title"],288 "city": r["city"], "avant": prev["price"],289 "apres": r["nouveau"],290 "pct": round(100 * (r["nouveau"] - prev["price"])291 / prev["price"], 1)})292 baisses.sort(key=lambda b: b["pct"])293 baisses = baisses[:12]294295 # -- santé des sources ------------------------------------------------------296 sync24 = con.execute(297 "SELECT COUNT(DISTINCT source) c FROM sync_log WHERE ok=1 AND ts>?",298 (now - 86400,)).fetchone()["c"]299 alertes = [dict(r) for r in con.execute(300 """SELECT source, message, ts FROM sync_log301 WHERE ts > ? AND message NOT IN ('ok') ORDER BY ts DESC LIMIT 10""",302 (now - 86400,)).fetchall()]303 gps_pct = con.execute(304 "SELECT ROUND(100.0*SUM(lat IS NOT NULL)/COUNT(*),1) p"305 " FROM listings WHERE active=1 AND published=1 AND dup_of IS NULL AND province='QC'").fetchone()["p"]306307 out = {308 "totals": {309 "total": total,310 "with_price": len(prix),311 "avg": round(sum(prix) / len(prix)) if prix else None,312 "median": round(_median(prix)) if prix else None,313 "min": prix[0] if prix else None,314 "max": prix[-1] if prix else None,315 "sources": len(by_source),316 "cities": len(by_city),317 "regions": len([r for r in by_region if r["count"] > 0]),318 "gps_pct": gps_pct,319 "superficie_moyenne": offre["superficie_moyenne"],320 "dispo_now": dispo_now,321 },322 "histogram": hist,323 "by_type": by_type,324 "by_city": by_city,325 "by_source": by_source,326 "by_region": by_region,327 "offre": offre,328 "baisses": baisses,329 "sante": {"sources_sync_24h": sync24, "alertes_24h": alertes},330 }331 con.close()332 return out333