SPB Git

Repository Public

statsextra.py 16.6 KB 424 lines python

1# =============================================================================2#                  SP BOUCHER | SOFTWARE & RESEARCH3#             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project          : Immo·Ka9# File             : immoka/statsextra.py10# Module           : immoka11# Repository       : https://git.spboucher.ai/immo-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# Immo-Ka — Agrégateur de propriétés à vendre (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    from .public import PUBLIC217    return PUBLIC218219220def _panel_population(con: sqlite3.Connection) -> dict | None:221    qc = _ro("quartier.db")222    if qc is None:223        return None224    aw = _active_where(con)225    try:226        # aires de diffusion couvertes par au moins une annonce active227        dauids = [r[0] for r in con.execute(228            f"SELECT DISTINCT dauid FROM listings WHERE {aw} "229            "AND dauid IS NOT NULL AND dauid<>''")]230    except sqlite3.Error:231        dauids = []232    if len(dauids) < 20:233        qc.close()234        return None235    # charger le recensement des DA couvertes236    rows = []237    CH = 400238    for i in range(0, len(dauids), CH):239        chunk = dauids[i:i + CH]240        ph = ",".join("?" * len(chunk))241        rows += qc.execute(242            f"SELECT * FROM da_stats WHERE dauid IN ({ph})", chunk).fetchall()243    qc.close()244    if not rows:245        return None246247    def med(col):248        v = [r[col] for r in rows if r[col] is not None]249        return median(v) if v else None250251    pop_tot = sum(r["population"] or 0 for r in rows)252    kpis = [253        {"id": "pop_tot", "label": "Population des secteurs couverts",254         "value": round(pop_tot)},255        {"id": "pop_rev", "label": "Revenu médian des ménages (médiane)",256         "value": round(med("revenu_median")) if med("revenu_median") else None,257         "unit": "$"},258        {"id": "pop_loc", "label": "Part de locataires (médiane)",259         "value": round(med("pct_locataires")) if med("pct_locataires") is not None else None,260         "unit": "%"},261        {"id": "pop_age", "label": "Âge médian (médiane des secteurs)",262         "value": round(med("age_median")) if med("age_median") else None,263         "unit": "ans"},264        {"id": "pop_univ", "label": "Diplôme universitaire (médiane)",265         "value": round(med("pct_univ")) if med("pct_univ") is not None else None,266         "unit": "%"},267    ]268269    # répartition de la population par quintile de défavorisation matérielle270    defav = _ro("quartier.db")271    donut_items = []272    try:273        dmap = {r["dauid"]: r["quintile_materiel"] for r in defav.execute(274            "SELECT dauid, quintile_materiel FROM da_defav")}275        buckets: dict[int, float] = {}276        for r in rows:277            qv = dmap.get(r["dauid"])278            if qv:279                buckets[qv] = buckets.get(qv, 0) + (r["population"] or 0)280        labels = {1: "Très favorisé", 2: "Favorisé", 3: "Moyen",281                  4: "Défavorisé", 5: "Très défavorisé"}282        donut_items = [{"label": labels.get(k, str(k)), "value": round(v)}283                       for k, v in sorted(buckets.items())]284    except sqlite3.Error:285        pass286    finally:287        if defav:288            defav.close()289290    # tableau par ville : population, revenu médian, % locataires291    qc2 = _ro("quartier.db")292    table = None293    try:294        # villes avec le plus d'annonces actives295        top_cities = [r["city"] for r in con.execute(296            f"SELECT city, COUNT(*) n FROM listings WHERE {aw} "297            "AND city<>'' GROUP BY city ORDER BY n DESC LIMIT 15")]298        st = {r["dauid"]: r for r in qc2.execute("SELECT * FROM da_stats")}299        trows = []300        for city in top_cities:301            das = [r["dauid"] for r in con.execute(302                f"SELECT DISTINCT dauid FROM listings WHERE {aw} "303                "AND city=? AND dauid IS NOT NULL", (city,))]304            recs = [st[d] for d in das if d in st]305            if len(recs) < 3:306                continue307            pop = sum(x["population"] or 0 for x in recs)308            rev = [x["revenu_median"] for x in recs if x["revenu_median"]]309            loc = [x["pct_locataires"] for x in recs310                   if x["pct_locataires"] is not None]311            trows.append([city, f"{round(pop):,}".replace(",", " "),312                          _money(median(rev)) if rev else "—",313                          f"{round(median(loc))} %" if loc else "—"])314        if trows:315            table = {"id": "pop_villes",316                     "title": "Profil des secteurs couverts par ville",317                     "columns": ["Ville", "Population", "Revenu médian",318                                 "Locataires"],319                     "rows": trows}320    except sqlite3.Error:321        pass322    finally:323        qc2.close()324325    return {326        "id": "population",327        "title": "Population & territoire",328        "subtitle": "Portrait sociodémographique des secteurs (aires de "329                    "diffusion) où se trouvent les annonces — recensement.",330        "kpis": [k for k in kpis if k.get("value") is not None],331        "breakdowns": [{"id": "pop_defav",332                        "title": "Population par niveau de défavorisation "333                        "matérielle", "kind": "donut", "items": donut_items}]334                      if donut_items else [],335        "tables": [table] if table else [],336    }337338339# --- Panneau 3 : Prix de l'essence -------------------------------------------340def _panel_gaz() -> dict | None:341    try:342        from . import gaz343        gcon = gaz._connect()344        row = gcon.execute("SELECT v FROM meta WHERE k='maj'").fetchone()345        if row is None or time.time() - float(row["v"]) > gaz.TTL:346            try:347                gaz.refresh(gcon)348            except Exception:349                pass350        rows = gcon.execute(351            "SELECT region, prix_regulier, prix_super, prix_diesel "352            "FROM gaz_stations WHERE prix_regulier > 50").fetchall()353        gcon.close()354    except Exception:355        return None356    if len(rows) < 30:357        return None358    reg = [r["prix_regulier"] for r in rows]359    sup = [r["prix_super"] for r in rows if r["prix_super"]]360    die = [r["prix_diesel"] for r in rows if r["prix_diesel"]]361362    def c(v):363        return round(v, 1) if v is not None else None364365    kpis = [366        {"id": "gaz_n", "label": "Stations suivies", "value": len(rows)},367        {"id": "gaz_reg", "label": "Régulier médian",368         "value": c(median(reg)), "unit": "¢/L"},369        {"id": "gaz_min", "label": "Meilleur prix (régulier)",370         "value": c(min(reg)), "unit": "¢/L"},371        {"id": "gaz_sup", "label": "Super médian",372         "value": c(median(sup)) if sup else None, "unit": "¢/L"},373        {"id": "gaz_die", "label": "Diesel médian",374         "value": c(median(die)) if die else None, "unit": "¢/L"},375    ]376377    # prix régulier médian par région378    byreg: dict[str, list[float]] = {}379    for r in rows:380        if r["region"]:381            byreg.setdefault(r["region"], []).append(r["prix_regulier"])382    bars = sorted(383        ([{"label": k, "value": round(median(v), 1)}384          for k, v in byreg.items() if len(v) >= 5]),385        key=lambda x: x["value"])386    # tableau régions387    treg = sorted(([k, len(v), round(median(v), 1)]388                   for k, v in byreg.items() if len(v) >= 5),389                  key=lambda x: x[2])390    table = {"id": "gaz_regions",391             "title": "Prix de l'essence régulière par région",392             "columns": ["Région", "Stations", "Régulier médian (¢/L)"],393             "rows": [[r[0], r[1], f"{r[2]:.1f}"] for r in treg]}394395    return {396        "id": "essence",397        "title": "Prix de l'essence au Québec",398        "subtitle": "Prix courants des stations-service (gazquebec.ca), toutes "399                    "régions confondues.",400        "kpis": [k for k in kpis if k.get("value") is not None],401        "breakdowns": [{"id": "gaz_reg_bar",402                        "title": "Essence régulière — médiane par région (¢/L)",403                        "kind": "bar", "items": bars}] if bars else [],404        "tables": [table],405    }406407408def panels(con: sqlite3.Connection) -> list[dict]:409    """Retourne les panneaux « territoire » (cache 30 min). `con` = base des410    annonces (pour la jointure recensement via l'aire de diffusion)."""411    hit = _CACHE.get("panels")412    if hit and time.time() - hit[0] < _TTL:413        return hit[1]414    out = []415    for fn in (_panel_rdl, lambda: _panel_population(con), _panel_gaz):416        try:417            p = fn()418            if p and (p.get("kpis") or p.get("tables") or p.get("breakdowns")):419                out.append(p)420        except Exception:421            continue422    _CACHE["panels"] = (time.time(), out)423    return out424
Files main
Menu

Theme