SPB Git

Repository Public

statsfiche.py 20.8 KB 493 lines python

1# =============================================================================2#                  SP BOUCHER | SOFTWARE & RESEARCH3#             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project          : Immo·Ka9# File             : immoka/statsfiche.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 maisons à vendre (province de Québec)89# Auteur : Simon-Pierre Boucher — contact@spboucher.ai90# statsfiche.py : panneaux « enrichissements de la fiche » de l'onglet91#   Statistiques — tout ce qu'Immo-Ka ajoute par-dessus l'annonce brute :92#     · couverture des enrichissements (géocodage, quartier, Vrai-Prix,93#       caractéristiques, audit photos) + couches de données branchées ;94#     · Vrai-Prix (écarts prix demandé vs estimation, verdicts, villes) ;95#     · Historique des prix (baisses/hausses) ;96#     · Taux hypothécaires (meilleurs taux réels multibanques) ;97#     · Annuaires (déménageurs et inspecteurs en bâtiment).98#   Même contrat de rendu que statsextra.py (kpis/breakdowns/distributions/99#   tables, rendu générique du kit stats) — un panneau absent si sa source100#   ne répond pas. Cache 30 min.101# -----------------------------------------------------------------------------102from __future__ import annotations103104import json105import sqlite3106import time107from pathlib import Path108from statistics import median109110ROOT = Path(__file__).resolve().parent.parent111DATA = ROOT / "data"112_CACHE: dict[str, tuple[float, list]] = {}113_TTL = 1800114115116def _ro(name: str) -> sqlite3.Connection | None:117    p = DATA / name118    if not p.exists():119        return None120    con = sqlite3.connect(f"file:{p}?mode=ro", uri=True)121    con.row_factory = sqlite3.Row122    return con123124125def _active_where(con) -> str:126    from .public import PUBLIC127    return PUBLIC128129130def _n1(con, sql: str, args: tuple = ()) -> int:131    return con.execute(sql, args).fetchone()[0] or 0132133134def _fr(n: float) -> str:135    return f"{round(n):,}".replace(",", " ")136137138def _pctof(part: int, tot: int) -> float:139    return round(100.0 * part / tot, 1) if tot else 0.0140141142# --- Panneau : couverture des enrichissements ---------------------------------143def _panel_enrichissement(con) -> dict | None:144    W = _active_where(con)145    tot = _n1(con, f"SELECT COUNT(*) FROM listings WHERE {W}")146    if tot < 100:147        return None148    geo = _n1(con, f"SELECT COUNT(*) FROM listings WHERE {W}"149                   " AND lat IS NOT NULL AND lng IS NOT NULL")150    quart = _n1(con, f"SELECT COUNT(*) FROM listings WHERE {W}"151                     " AND dauid IS NOT NULL AND dauid<>''")152    vp = _n1(con, f"SELECT COUNT(*) FROM listings WHERE {W}"153                  " AND vraiprix LIKE '%estimation%'")154    annee = _n1(con, f"SELECT COUNT(*) FROM listings WHERE {W}"155                     " AND year_built IS NOT NULL AND year_built > 1600")156    sqft = _n1(con, f"SELECT COUNT(*) FROM listings WHERE {W}"157                    " AND area_sqft IS NOT NULL AND area_sqft > 0")158    desc = _n1(con, f"SELECT COUNT(*) FROM listings WHERE {W}"159                    " AND description IS NOT NULL AND LENGTH(description) > 80")160161    kpis = [162        {"id": "enr_tot", "label": "Fiches actives", "value": tot},163        {"id": "enr_vp", "label": "Avec estimation Vrai-Prix",164         "value": _pctof(vp, tot), "unit": "%"},165        {"id": "enr_img", "label": "Photos auditées (cumul)",166         "value": _n1(con, "SELECT COUNT(*) FROM image_audit")},167        {"id": "enr_px", "label": "Points de prix consignés",168         "value": _n1(con, "SELECT COUNT(*) FROM price_log")},169    ]170    bars = [171        {"label": "Géolocalisation", "value": _pctof(geo, tot)},172        {"label": "Quartier (recensement)", "value": _pctof(quart, tot)},173        {"label": "Estimation Vrai-Prix", "value": _pctof(vp, tot)},174        {"label": "Année de construction", "value": _pctof(annee, tot)},175        {"label": "Superficie habitable", "value": _pctof(sqft, tot)},176        {"label": "Description détaillée", "value": _pctof(desc, tot)},177    ]178179    layers: list[list] = []180181    def layer(nom: str, count_fn, desc_: str) -> None:182        try:183            n = count_fn()184            if n:185                layers.append([nom, _fr(n), desc_])186        except Exception:187            pass188189    def _side(db: str, sql: str) -> int:190        c = _ro(db)191        if c is None:192            return 0193        try:194            return c.execute(sql).fetchone()[0] or 0195        finally:196            c.close()197198    layer("Vrai-Prix", lambda: vp, "estimations de valeur marchande sur les fiches actives")199    layer("Historique des prix", lambda: _n1(con, "SELECT COUNT(*) FROM price_log"),200          "points de prix consignés depuis la première capture")201    layer("Audit des photos", lambda: _n1(con, "SELECT COUNT(*) FROM image_audit"),202          "images vérifiées (dimension, poids, disponibilité)")203    layer("Taux hypothécaires", lambda: _side("mortgage.db",204          "SELECT COUNT(*) FROM rate_observations"),205          "produits hypothécaires suivis en continu (multibanques)")206    layer("Qualité de l'air", lambda: _side("air.db",207          "SELECT COUNT(DISTINCT station) FROM air_stats"),208          "stations de mesure (RSQAQ) rattachées aux fiches")209    layer("Zones inondables", lambda: _side("inondation.db", "SELECT COUNT(*) FROM zi"),210          "polygones officiels vérifiés au survol de chaque fiche")211    layer("Commerces à proximité", lambda: _side("commerces.db",212          "SELECT COUNT(*) FROM commerces_cache"),213          "cellules de commerces essentiels en cache")214    layer("Hydro-Québec", lambda: _side("hydro.db", "SELECT COUNT(*) FROM hydro_cache"),215          "estimations de coût d'électricité par adresse")216    layer("Registre des loyers", lambda: _side("rdl.db",217          "SELECT COUNT(*) FROM rdl_housings"),218          "loyers déclarés (contexte locatif des plex)")219220    def _annuaire(f: str) -> int:221        p = DATA / f222        return len(json.loads(p.read_text(encoding="utf-8")).get("movers", [])) if p.exists() else 0223224    layer("Annuaire des déménageurs", lambda: _annuaire("demenageurs.json"),225          "entreprises de déménagement répertoriées (/demenageurs)")226    layer("Annuaire des inspecteurs", lambda: _annuaire("inspecteurs.json"),227          "inspecteurs en bâtiment répertoriés (/inspecteurs)")228229    table = {"id": "enr_couches",230             "title": "Couches de données branchées sur chaque fiche",231             "columns": ["Couche", "Volume", "Description"],232             "rows": layers}233234    return {235        "id": "enrichissement",236        "title": "Enrichissement des fiches — ce qu'Immo-Ka ajoute à l'annonce",237        "subtitle": "Chaque propriété agrégée est enrichie automatiquement : "238                    "géocodage, quartier de recensement, estimation Vrai-Prix, "239                    "audit des photos et couches du territoire.",240        "kpis": [k for k in kpis if k.get("value") is not None],241        "breakdowns": [{"id": "enr_couv",242                        "title": "Couverture des enrichissements (% des fiches actives)",243                        "kind": "bar", "items": bars}],244        "tables": [table] if layers else [],245    }246247248# --- Panneau : Vrai-Prix ---------------------------------------------------------249def _panel_vraiprix(con) -> dict | None:250    W = _active_where(con)251    from . import public, villes252    rows = con.execute(253        f"SELECT price, {public.VP_VALUE_SQL} vp, {public.VP_LOW_SQL} lo,"254        f" {public.VP_HIGH_SQL} hi, city"255        f" FROM listings WHERE {W} AND vraiprix LIKE '%estimation%'"256        f" AND price > 10000").fetchall()257    # même règle que le verdict des fiches (immoka/public.py)258    deltas: list[tuple[float, str]] = []259    for r in rows:260        d = public.deviation(r["price"], r["vp"], r["lo"], r["hi"])261        if d is not None:262            deltas.append((d, villes.label(r["city"])))263    if len(deltas) < 100:264        return None265    ds = [d for d, _ in deltas]266    sur = sum(1 for d in ds if d >= public.VP_SUR)267    sous = sum(1 for d in ds if d <= public.VP_SOUS)268    juste = len(ds) - sur - sous269    s_sur, s_sous = f"{public.VP_SUR:+g}".replace("-", "−"), f"{public.VP_SOUS:+g}".replace("-", "−")270271    kpis = [272        {"id": "vp_n", "label": "Propriétés avec estimation", "value": len(ds)},273        {"id": "vp_med", "label": "Écart médian demandé vs estimé",274         "value": round(median(ds), 1), "unit": "%"},275        {"id": "vp_sur", "label": f"Au-dessus de l'estimation (≥ {s_sur} %)",276         "value": _pctof(sur, len(ds)), "unit": "%"},277        {"id": "vp_juste", "label": f"Au prix du marché ({s_sous} % à {s_sur} %)",278         "value": _pctof(juste, len(ds)), "unit": "%"},279        {"id": "vp_sous", "label": f"Sous l'estimation (≤ {s_sous} %)",280         "value": _pctof(sous, len(ds)), "unit": "%"},281    ]282    donut = [{"label": f"Au-dessus (≥ {s_sur} %)", "value": sur},283             {"label": f"Au prix du marché ({s_sous} à {s_sur} %)", "value": juste},284             {"label": f"Sous l'estimation (≤ {s_sous} %)", "value": sous}]285286    bins = []287    lo = -40288    while lo < 80:289        n = sum(1 for d in ds if lo <= d < lo + 10)290        bins.append({"label": f"{lo}", "value": n})291        lo += 10292293    byc: dict[str, list[float]] = {}294    for d, c in deltas:295        if c:296            byc.setdefault(c, []).append(d)297    top = sorted(((c, v) for c, v in byc.items() if len(v) >= 50),298                 key=lambda kv: -median(kv[1]))[:12]299    table = {"id": "vp_villes",300             "title": "Villes où les prix demandés dépassent le plus "301                      "l'estimation (min. 50 fiches)",302             "columns": ["Ville", "Fiches estimées", "Écart médian"],303             "rows": [[c, len(v), f"{median(v):+.1f} %"] for c, v in top]}304305    return {306        "id": "vraiprix",307        "title": "Vrai-Prix — le prix demandé est-il le bon prix ?",308        "subtitle": "Chaque propriété est comparée à son estimation Vrai-Prix "309                    "(modèle d'évaluation Vrai-Prix).",310        "kpis": kpis,311        "breakdowns": [{"id": "vp_verdicts",312                        "title": "Prix demandé vs estimation Vrai-Prix",313                        "kind": "donut", "items": donut}],314        "distributions": [{"id": "vp_hist",315                           "title": "Distribution des écarts demandé vs estimé (%)",316                           "unit": "%", "bins": bins}],317        "tables": [table] if top else [],318    }319320321# --- Panneau : historique des prix -----------------------------------------------322def _panel_historique(con) -> dict | None:323    rows = con.execute(324        "SELECT uid, ts, price FROM price_log ORDER BY uid, ts").fetchall()325    if len(rows) < 200:326        return None327    drops: list[float] = []328    hikes: list[float] = []329    changed: set[str] = set()330    drops_abs: list[float] = []331    prev_uid, prev_price = None, None332    for r in rows:333        if r["uid"] == prev_uid and prev_price and r["price"] and r["price"] != prev_price:334            pct = (r["price"] - prev_price) / prev_price * 100.0335            if -60.0 <= pct <= 120.0:336                (drops if pct < 0 else hikes).append(pct)337                if pct < 0:338                    drops_abs.append(prev_price - r["price"])339                changed.add(r["uid"])340        prev_uid, prev_price = r["uid"], r["price"]341342    kpis = [343        {"id": "px_pts", "label": "Points de prix consignés", "value": len(rows)},344        {"id": "px_chg", "label": "Propriétés avec changement de prix",345         "value": len(changed)},346        {"id": "px_drop", "label": "Baisses de prix détectées", "value": len(drops)},347        {"id": "px_dmed", "label": "Baisse médiane",348         "value": round(median(drops_abs)) if drops_abs else None, "unit": "$"},349    ]350    donut = [{"label": "Baisses", "value": len(drops)},351             {"label": "Hausses", "value": len(hikes)}]352    return {353        "id": "historique_prix",354        "title": "Historique des prix — chaque propriété est suivie dans le temps",355        "subtitle": "Immo-Ka consigne le prix demandé à chaque synchronisation : "356                    "les baisses et hausses apparaissent sur la fiche.",357        "kpis": [k for k in kpis if k.get("value") is not None],358        "breakdowns": [{"id": "px_sens", "title": "Changements de prix détectés",359                        "kind": "donut", "items": donut}],360    }361362363# --- Panneau : taux hypothécaires -------------------------------------------------364def _panel_hypotheques() -> dict | None:365    con = _ro("mortgage.db")366    if con is None:367        return None368    try:369        rows = con.execute(370            "SELECT institution, product_name, rate_type, term_months, kind,"371            " rate FROM rate_observations WHERE rate IS NOT NULL"372            " AND (valid_to IS NULL OR valid_to = '')").fetchall()373        if not rows:374            rows = con.execute(375                "SELECT institution, product_name, rate_type, term_months,"376                " kind, rate FROM rate_observations"377                " WHERE rate IS NOT NULL").fetchall()378    finally:379        con.close()380    if len(rows) < 20:381        return None382383    inst = {r["institution"] for r in rows}384    f5 = [r for r in rows if r["rate_type"] == "fixed" and r["term_months"] == 60]385    v5 = [r for r in rows if r["rate_type"] in ("variable", "adjustable")386          and r["term_months"] == 60]387    best_f5 = min(f5, key=lambda r: r["rate"]) if f5 else None388    best_v5 = min(v5, key=lambda r: r["rate"]) if v5 else None389390    kpis = [391        {"id": "mt_prod", "label": "Produits hypothécaires suivis", "value": len(rows)},392        {"id": "mt_inst", "label": "Institutions financières", "value": len(inst)},393        {"id": "mt_f5", "label": "Meilleur 5 ans fixe",394         "value": round(best_f5["rate"], 2) if best_f5 else None, "unit": "%"},395        {"id": "mt_v5", "label": "Meilleur 5 ans variable",396         "value": round(best_v5["rate"], 2) if best_v5 else None, "unit": "%"},397    ]398399    best_by_inst: dict[str, float] = {}400    for r in f5:401        cur = best_by_inst.get(r["institution"])402        if cur is None or r["rate"] < cur:403            best_by_inst[r["institution"]] = r["rate"]404    bars = sorted(({"label": k, "value": round(v, 2)}405                   for k, v in best_by_inst.items()),406                  key=lambda x: x["value"])[:12]407408    byterm: dict[int, list[float]] = {}409    for r in rows:410        if r["rate_type"] == "fixed" and r["term_months"] in (12, 24, 36, 48, 60, 84, 120):411            byterm.setdefault(r["term_months"], []).append(r["rate"])412    tbars = [{"label": f"{t // 12} an{'s' if t >= 24 else ''}",413              "value": round(min(v), 2)}414             for t, v in sorted(byterm.items())]415416    return {417        "id": "hypotheques",418        "title": "Taux hypothécaires — collecte réelle multibanques",419        "subtitle": "Les taux publiés par les institutions sont collectés en "420                    "continu et alimentent le calculateur des fiches "421                    "(/taux-hypothecaires).",422        "kpis": [k for k in kpis if k.get("value") is not None],423        "breakdowns": ([{"id": "mt_inst_bar",424                         "title": "Meilleur taux fixe 5 ans par institution (%)",425                         "kind": "bar", "items": bars}] if bars else [])426                      + ([{"id": "mt_terms",427                           "title": "Meilleur taux fixe par terme (%)",428                           "kind": "bar", "items": tbars}] if tbars else []),429    }430431432# --- Panneau : annuaires (déménageurs + inspecteurs) ------------------------------433def _panel_annuaires() -> dict | None:434    def _load(f: str) -> list[dict]:435        p = DATA / f436        if not p.exists():437            return []438        return json.loads(p.read_text(encoding="utf-8")).get("movers", [])439440    dem = _load("demenageurs.json")441    insp = _load("inspecteurs.json")442    if len(dem) + len(insp) < 50:443        return None444445    def _note(entries: list[dict]) -> float | None:446        rated = [m["rating"] for m in entries if m.get("rating")]447        return round(median(rated), 1) if len(rated) >= 30 else None448449    kpis = [450        {"id": "ann_dem", "label": "Déménageurs répertoriés", "value": len(dem) or None},451        {"id": "ann_insp", "label": "Inspecteurs en bâtiment", "value": len(insp) or None},452        {"id": "ann_dnote", "label": "Note médiane — déménageurs",453         "value": _note(dem), "unit": "/5"},454        {"id": "ann_inote", "label": "Note médiane — inspecteurs",455         "value": _note(insp), "unit": "/5"},456    ]457    byreg: dict[str, int] = {}458    for m in insp:459        byreg[m["region"]] = byreg.get(m["region"], 0) + 1460    bars = sorted(({"label": k, "value": v} for k, v in byreg.items()),461                  key=lambda x: -x["value"])[:12]462    return {463        "id": "annuaires",464        "title": "Annuaires — déménageurs et inspecteurs en bâtiment",465        "subtitle": "Deux annuaires provinciaux compilés par Immo-Ka "466                    "pour accompagner l'achat : /demenageurs et /inspecteurs.",467        "kpis": [k for k in kpis if k.get("value") is not None],468        "breakdowns": [{"id": "ann_insp_reg",469                        "title": "Inspecteurs en bâtiment par région (top 12)",470                        "kind": "bar", "items": bars}] if bars else [],471    }472473474def panels(con: sqlite3.Connection) -> list[dict]:475    """Panneaux « enrichissements de la fiche » (cache 30 min)."""476    hit = _CACHE.get("panels")477    if hit and time.time() - hit[0] < _TTL:478        return hit[1]479    out = []480    for fn in (lambda: _panel_enrichissement(con),481               lambda: _panel_vraiprix(con),482               lambda: _panel_historique(con),483               _panel_hypotheques,484               _panel_annuaires):485        try:486            p = fn()487            if p and (p.get("kpis") or p.get("tables") or p.get("breakdowns")):488                out.append(p)489        except Exception:490            continue491    _CACHE["panels"] = (time.time(), out)492    return out493
Files main
Menu

Theme