SPB Git

Repository Public

statsextra.py 16.7 KB 427 lines python

1# =============================================================================2#                  SP BOUCHER | SOFTWARE & RESEARCH3#             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project          : Lou·Ka9# File             : louka/statsextra.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# statsextra.py : panneaux « données du territoire » de l'onglet Statistiques91#   Trois blocs indépendants du marché des annonces, calculés sur nos jeux de92#   données ouverts et mis en cache :93#     · Registre des loyers (loyers réellement déclarés, data/rdl.db) ;94#     · Population & territoire (recensement des secteurs couverts,95#       quartier.db.da_stats joint aux annonces par aire de diffusion) ;96#     · Prix de l'essence (stations gazquebec.ca, data/gaz.db).97#   Chaque panneau réutilise les rendus existants du kit stats (kpis, donut/98#   barres, histogramme, tableau) — aucune donnée inventée : un bloc absent si99#   sa source ne répond pas.100# -----------------------------------------------------------------------------101from __future__ import annotations102103import sqlite3104import time105from pathlib import Path106from statistics import median107108ROOT = Path(__file__).resolve().parent.parent109DATA = ROOT / "data"110_CACHE: dict[str, tuple[float, list]] = {}111_TTL = 1800112113114def _ro(name: str) -> sqlite3.Connection | None:115    p = DATA / name116    if not p.exists():117        return None118    con = sqlite3.connect(f"file:{p}?mode=ro", uri=True)119    con.row_factory = sqlite3.Row120    return con121122123def _money(v) -> str:124    return f"{round(v):,}".replace(",", " ") + " $" if v is not None else "—"125126127def _q(vals: list[float], f: float) -> float:128    s = sorted(vals)129    if not s:130        return 0131    i = f * (len(s) - 1)132    lo = int(i)133    hi = min(lo + 1, len(s) - 1)134    return s[lo] + (s[hi] - s[lo]) * (i - lo)135136137# --- Panneau 1 : Registre des loyers -----------------------------------------138def _panel_rdl() -> dict | None:139    con = _ro("rdl.db")140    if con is None:141        return None142    try:143        rows = con.execute(144            "SELECT price, rooms, year, city FROM rdl_housings "145            "WHERE price > 100 AND price < 20000").fetchall()146    except sqlite3.Error:147        con.close()148        return None149    con.close()150    if len(rows) < 100:151        return None152    prices = [r["price"] for r in rows]153    recent = [r["price"] for r in rows if (r["year"] or 0) >= 2023]154    villes = {r["city"] for r in rows if r["city"]}155156    kpis = [157        {"id": "rdl_n", "label": "Loyers déclarés", "value": len(rows)},158        {"id": "rdl_med", "label": "Loyer médian déclaré",159         "value": round(median(prices)), "unit": "$"},160        {"id": "rdl_rec", "label": "Médiane depuis 2023",161         "value": round(median(recent)) if recent else None, "unit": "$"},162        {"id": "rdl_villes", "label": "Villes représentées", "value": len(villes)},163    ]164165    # médiane par nombre de chambres (barres)166    byr: dict[int, list[float]] = {}167    for r in rows:168        if r["rooms"] is not None and 0 <= r["rooms"] <= 6:169            byr.setdefault(r["rooms"], []).append(r["price"])170    bars = [{"label": f"{k} ch.", "value": round(median(v))}171            for k, v in sorted(byr.items()) if len(v) >= 10]172173    # histogramme des loyers déclarés (récents de préférence)174    base = recent if len(recent) >= 500 else prices175    lo, hi = round(_q(base, 0.02)), round(_q(base, 0.98))176    step = max(50, round((hi - lo) / 14 / 50) * 50)177    bins = []178    x = lo179    while x < hi:180        n = sum(1 for p in base if x <= p < x + step)181        bins.append({"label": f"{x}", "value": n})182        x += step183184    # top villes par nombre de déclarations185    vcount: dict[str, list[float]] = {}186    for r in rows:187        if r["city"]:188            vcount.setdefault(r["city"], []).append(r["price"])189    top = sorted(vcount.items(), key=lambda kv: -len(kv[1]))[:15]190    table = {"id": "rdl_villes_t",191             "title": "Loyers déclarés par ville (top 15)",192             "columns": ["Ville", "Déclarations", "Loyer médian"],193             "rows": [[v, len(p), _money(median(p))] for v, p in top]}194195    return {196        "id": "registre_loyers",197        "title": "Registre des loyers — loyers réellement payés",198        "subtitle": "Loyers déclarés volontairement par des locataires au "199                    "Registre des loyers (Vivre en ville). Données citoyennes, "200                    "indicatives.",201        "kpis": [k for k in kpis if k.get("value") is not None],202        "breakdowns": [{"id": "rdl_rooms", "title": "Loyer médian déclaré par "203                        "nombre de chambres", "kind": "bar", "items": bars}]204                      if bars else [],205        "distributions": [{"id": "rdl_hist",206                           "title": "Distribution des loyers déclarés"207                           + (" (depuis 2023)" if base is recent else ""),208                           "unit": "$", "bins": bins}] if len(bins) >= 4 else [],209        "tables": [table],210    }211212213# --- Panneau 2 : Population & territoire --------------------------------------214def _active_where(con: sqlite3.Connection) -> str:215    """Filtre « annonces actives » adapté au schéma (lou-ka a dup_of, pas immo)."""216    cols = {r[1] for r in con.execute("PRAGMA table_info(listings)")}217    w = "active=1" if "active" in cols else "1=1"218    if "dup_of" in cols:219        w += " AND dup_of IS NULL"220    return w221222223def _panel_population(con: sqlite3.Connection) -> dict | None:224    qc = _ro("quartier.db")225    if qc is None:226        return None227    aw = _active_where(con)228    try:229        # aires de diffusion couvertes par au moins une annonce active230        dauids = [r[0] for r in con.execute(231            f"SELECT DISTINCT dauid FROM listings WHERE {aw} "232            "AND dauid IS NOT NULL AND dauid<>''")]233    except sqlite3.Error:234        dauids = []235    if len(dauids) < 20:236        qc.close()237        return None238    # charger le recensement des DA couvertes239    rows = []240    CH = 400241    for i in range(0, len(dauids), CH):242        chunk = dauids[i:i + CH]243        ph = ",".join("?" * len(chunk))244        rows += qc.execute(245            f"SELECT * FROM da_stats WHERE dauid IN ({ph})", chunk).fetchall()246    qc.close()247    if not rows:248        return None249250    def med(col):251        v = [r[col] for r in rows if r[col] is not None]252        return median(v) if v else None253254    pop_tot = sum(r["population"] or 0 for r in rows)255    kpis = [256        {"id": "pop_tot", "label": "Population des secteurs couverts",257         "value": round(pop_tot)},258        {"id": "pop_rev", "label": "Revenu médian des ménages (médiane)",259         "value": round(med("revenu_median")) if med("revenu_median") else None,260         "unit": "$"},261        {"id": "pop_loc", "label": "Part de locataires (médiane)",262         "value": round(med("pct_locataires")) if med("pct_locataires") is not None else None,263         "unit": "%"},264        {"id": "pop_age", "label": "Âge médian (médiane des secteurs)",265         "value": round(med("age_median")) if med("age_median") else None,266         "unit": "ans"},267        {"id": "pop_univ", "label": "Diplôme universitaire (médiane)",268         "value": round(med("pct_univ")) if med("pct_univ") is not None else None,269         "unit": "%"},270    ]271272    # répartition de la population par quintile de défavorisation matérielle273    defav = _ro("quartier.db")274    donut_items = []275    try:276        dmap = {r["dauid"]: r["quintile_materiel"] for r in defav.execute(277            "SELECT dauid, quintile_materiel FROM da_defav")}278        buckets: dict[int, float] = {}279        for r in rows:280            qv = dmap.get(r["dauid"])281            if qv:282                buckets[qv] = buckets.get(qv, 0) + (r["population"] or 0)283        labels = {1: "Très favorisé", 2: "Favorisé", 3: "Moyen",284                  4: "Défavorisé", 5: "Très défavorisé"}285        donut_items = [{"label": labels.get(k, str(k)), "value": round(v)}286                       for k, v in sorted(buckets.items())]287    except sqlite3.Error:288        pass289    finally:290        if defav:291            defav.close()292293    # tableau par ville : population, revenu médian, % locataires294    qc2 = _ro("quartier.db")295    table = None296    try:297        # villes avec le plus d'annonces actives298        top_cities = [r["city"] for r in con.execute(299            f"SELECT city, COUNT(*) n FROM listings WHERE {aw} "300            "AND city<>'' GROUP BY city ORDER BY n DESC LIMIT 15")]301        st = {r["dauid"]: r for r in qc2.execute("SELECT * FROM da_stats")}302        trows = []303        for city in top_cities:304            das = [r["dauid"] for r in con.execute(305                f"SELECT DISTINCT dauid FROM listings WHERE {aw} "306                "AND city=? AND dauid IS NOT NULL", (city,))]307            recs = [st[d] for d in das if d in st]308            if len(recs) < 3:309                continue310            pop = sum(x["population"] or 0 for x in recs)311            rev = [x["revenu_median"] for x in recs if x["revenu_median"]]312            loc = [x["pct_locataires"] for x in recs313                   if x["pct_locataires"] is not None]314            trows.append([city, f"{round(pop):,}".replace(",", " "),315                          _money(median(rev)) if rev else "—",316                          f"{round(median(loc))} %" if loc else "—"])317        if trows:318            table = {"id": "pop_villes",319                     "title": "Profil des secteurs couverts par ville",320                     "columns": ["Ville", "Population", "Revenu médian",321                                 "Locataires"],322                     "rows": trows}323    except sqlite3.Error:324        pass325    finally:326        qc2.close()327328    return {329        "id": "population",330        "title": "Population & territoire",331        "subtitle": "Portrait sociodémographique des secteurs (aires de "332                    "diffusion) où se trouvent les annonces — recensement.",333        "kpis": [k for k in kpis if k.get("value") is not None],334        "breakdowns": [{"id": "pop_defav",335                        "title": "Population par niveau de défavorisation "336                        "matérielle", "kind": "donut", "items": donut_items}]337                      if donut_items else [],338        "tables": [table] if table else [],339    }340341342# --- Panneau 3 : Prix de l'essence -------------------------------------------343def _panel_gaz() -> dict | None:344    try:345        from . import gaz346        gcon = gaz._connect()347        row = gcon.execute("SELECT v FROM meta WHERE k='maj'").fetchone()348        if row is None or time.time() - float(row["v"]) > gaz.TTL:349            try:350                gaz.refresh(gcon)351            except Exception:352                pass353        rows = gcon.execute(354            "SELECT region, prix_regulier, prix_super, prix_diesel "355            "FROM gaz_stations WHERE prix_regulier > 50").fetchall()356        gcon.close()357    except Exception:358        return None359    if len(rows) < 30:360        return None361    reg = [r["prix_regulier"] for r in rows]362    sup = [r["prix_super"] for r in rows if r["prix_super"]]363    die = [r["prix_diesel"] for r in rows if r["prix_diesel"]]364365    def c(v):366        return round(v, 1) if v is not None else None367368    kpis = [369        {"id": "gaz_n", "label": "Stations suivies", "value": len(rows)},370        {"id": "gaz_reg", "label": "Régulier médian",371         "value": c(median(reg)), "unit": "¢/L"},372        {"id": "gaz_min", "label": "Meilleur prix (régulier)",373         "value": c(min(reg)), "unit": "¢/L"},374        {"id": "gaz_sup", "label": "Super médian",375         "value": c(median(sup)) if sup else None, "unit": "¢/L"},376        {"id": "gaz_die", "label": "Diesel médian",377         "value": c(median(die)) if die else None, "unit": "¢/L"},378    ]379380    # prix régulier médian par région381    byreg: dict[str, list[float]] = {}382    for r in rows:383        if r["region"]:384            byreg.setdefault(r["region"], []).append(r["prix_regulier"])385    bars = sorted(386        ([{"label": k, "value": round(median(v), 1)}387          for k, v in byreg.items() if len(v) >= 5]),388        key=lambda x: x["value"])389    # tableau régions390    treg = sorted(([k, len(v), round(median(v), 1)]391                   for k, v in byreg.items() if len(v) >= 5),392                  key=lambda x: x[2])393    table = {"id": "gaz_regions",394             "title": "Prix de l'essence régulière par région",395             "columns": ["Région", "Stations", "Régulier médian (¢/L)"],396             "rows": [[r[0], r[1], f"{r[2]:.1f}"] for r in treg]}397398    return {399        "id": "essence",400        "title": "Prix de l'essence au Québec",401        "subtitle": "Prix courants des stations-service (gazquebec.ca), toutes "402                    "régions confondues.",403        "kpis": [k for k in kpis if k.get("value") is not None],404        "breakdowns": [{"id": "gaz_reg_bar",405                        "title": "Essence régulière — médiane par région (¢/L)",406                        "kind": "bar", "items": bars}] if bars else [],407        "tables": [table],408    }409410411def panels(con: sqlite3.Connection) -> list[dict]:412    """Retourne les panneaux « territoire » (cache 30 min). `con` = base des413    annonces (pour la jointure recensement via l'aire de diffusion)."""414    hit = _CACHE.get("panels")415    if hit and time.time() - hit[0] < _TTL:416        return hit[1]417    out = []418    for fn in (_panel_rdl, lambda: _panel_population(con), _panel_gaz):419        try:420            p = fn()421            if p and (p.get("kpis") or p.get("tables") or p.get("breakdowns")):422                out.append(p)423        except Exception:424            continue425    _CACHE["panels"] = (time.time(), out)426    return out427
Files main
Menu

Theme