SPB Git

Repository Public

coutreel.py 12.5 KB 283 lines python

1# =============================================================================2#                  SP BOUCHER | SOFTWARE & RESEARCH3#             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project          : Lou·Ka9# File             : louka/coutreel.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# coutreel.py : « Coût réel mensuel Lou-Ka » — loyer + frais non inclus,91#               ligne par ligne, chaque poste étiqueté :92#   included  : explicitement inclus dans le bail (details.inclusions)93#   observed  : montant affiché par la source (ex. prix du stationnement)94#   estimated : estimation sourcée (Hydro-Québec via hydro.py, médiane Internet)95#   unknown   : ni inclus ni estimable — dit explicitement, jamais inventé96#97# + prix au pi² avec percentile RÉELLEMENT calculé sur les comparables98#   (même ville + même nombre de chambres, et rayon ~2 km si géocodée).99# -----------------------------------------------------------------------------100from __future__ import annotations101102import json103104from . import db105106# Internet résidentiel : médiane des forfaits de base au Québec (ordre de107# grandeur public CRTC/fournisseurs). Estimation générique, PAS une donnée108# de l'adresse — toujours présentée comme telle.109INTERNET_ESTIME = 60.0110111VERSION = "cout-reel-1.0"112113114def _pctile(values: list[float], x: float) -> int:115    below = sum(1 for v in values if v < x)116    return round(100 * below / len(values))117118119def pi2(con, l: dict) -> dict | None:120    """Prix au pi² + percentile parmi les comparables (calcul réel)."""121    price, area = l.get("price"), l.get("area_sqft")122    if not price or not area or area < 100:123        return None124    val = price / area125    out: dict = {"valeur": round(val, 2), "statut": "calculated"}126127    base = ("SELECT price, area_sqft, lat, lng FROM listings"128            " WHERE active=1 AND published=1 AND dup_of IS NULL"129            " AND price IS NOT NULL AND area_sqft > 100 AND uid<>?")130    args: list = [l["uid"]]131    if l.get("city"):132        base += " AND city=?"; args.append(l["city"])133    if l.get("bedrooms") is not None:134        base += " AND bedrooms=?"; args.append(l["bedrooms"])135    elif l.get("unit_type"):136        base += " AND unit_type=?"; args.append(l["unit_type"])137    rows = con.execute(base, args).fetchall()138    ville = [r["price"] / r["area_sqft"] for r in rows]139    if len(ville) >= 12:140        out["percentile_ville"] = _pctile(ville, val)141        out["n_ville"] = len(ville)142        out["portee_ville"] = (f"{l.get('city')}, "143                               + (f"{int(l['bedrooms'])} ch."144                                  if l.get("bedrooms") is not None145                                  else l.get("unit_type") or "tous types"))146    lat, lng = l.get("lat"), l.get("lng")147    if lat is not None and lng is not None:148        secteur = [r["price"] / r["area_sqft"] for r in rows149                   if r["lat"] is not None150                   and abs(r["lat"] - lat) < 0.018 and abs(r["lng"] - lng) < 0.025]151        if len(secteur) >= 12:152            out["percentile_secteur"] = _pctile(secteur, val)153            out["n_secteur"] = len(secteur)154    if "percentile_ville" not in out and "percentile_secteur" not in out:155        out["percentile_note"] = "comparables insuffisants pour un percentile"156    return out157158159def compute(uid: str, con=None) -> dict | None:160    """Coût réel mensuel d'une annonce — module « Coût réel Lou-Ka »."""161    own = con is None162    if own:163        con = db.connect()164    try:165        row = con.execute(166            "SELECT uid, price, area_sqft, city, bedrooms, unit_type, lat, lng,"167            " details, address FROM listings WHERE uid=?", (uid,)).fetchone()168        if row is None:169            return None170        l = dict(row)171        try:172            details = json.loads(l.get("details") or "{}") or {}173        except (ValueError, TypeError):174            details = {}175        inc = details.get("inclusions") or {}176        price = l.get("price")177178        lignes: list[dict] = []179        lignes.append({"poste": "Loyer affiché", "statut": "observed",180                       "montant": price, "source": "annonce"})181182        # --- électricité + chauffage (souvent le même compteur au Québec) ----183        hydro_est = None184        if not inc.get("electricity"):185            from . import hydro186            h = hydro.estimate(uid=uid, adresse=l.get("address"),187                               lat=l.get("lat"), lng=l.get("lng"), solve=False)188            if h.get("disponible") and h.get("cout_mensuel"):189                hydro_est = round(float(h["cout_mensuel"]))190        if inc.get("electricity"):191            lignes.append({"poste": "Électricité", "statut": "included",192                           "montant": 0, "source": "annonce (incluse)"})193        elif inc.get("electricity") is False:194            lignes.append({"poste": "Électricité",195                           "statut": "estimated" if hydro_est else "unknown",196                           "montant": hydro_est,197                           "source": ("outil public d'estimation Hydro-Québec"198                                      if hydro_est else None),199                           "note": None if hydro_est else200                                   "explicitement à la charge du locataire, "201                                   "montant non estimable pour cette adresse"})202        else:203            lignes.append({"poste": "Électricité",204                           "statut": "estimated" if hydro_est else "unknown",205                           "montant": hydro_est,206                           "source": ("outil public d'estimation Hydro-Québec"207                                      if hydro_est else None),208                           "note": None if hydro_est else209                                   "l'annonce ne précise pas si elle est incluse"})210211        if inc.get("heating"):212            lignes.append({"poste": "Chauffage", "statut": "included",213                           "montant": 0, "source": "annonce (inclus)"})214        elif hydro_est:215            lignes.append({"poste": "Chauffage", "statut": "estimated",216                           "montant": None,217                           "note": "chauffage électrique répandu au Québec — "218                                   "déjà compté dans l'estimation d'électricité"})219        else:220            lignes.append({"poste": "Chauffage", "statut": "unknown",221                           "montant": None,222                           "note": "ni inclus ni estimable avec les données "223                                   "disponibles"})224225        if inc.get("hot_water"):226            lignes.append({"poste": "Eau chaude", "statut": "included",227                           "montant": 0, "source": "annonce (incluse)"})228        else:229            lignes.append({"poste": "Eau chaude", "statut": "unknown",230                           "montant": None,231                           "note": "l'annonce ne précise pas si elle est incluse"})232233        if inc.get("internet"):234            lignes.append({"poste": "Internet", "statut": "included",235                           "montant": 0, "source": "annonce (inclus)"})236        else:237            lignes.append({"poste": "Internet", "statut": "estimated",238                           "montant": INTERNET_ESTIME,239                           "source": "médiane des forfaits résidentiels de base "240                                     "au Québec (estimation générique)"})241242        parking = details.get("parking") or {}243        if parking.get("available"):244            if parking.get("included"):245                lignes.append({"poste": "Stationnement", "statut": "included",246                               "montant": 0, "source": "annonce (inclus)"})247            elif parking.get("price"):248                lignes.append({"poste": "Stationnement", "statut": "observed",249                               "montant": float(parking["price"]),250                               "source": "annonce (prix affiché)"})251            else:252                lignes.append({"poste": "Stationnement", "statut": "unknown",253                               "montant": None,254                               "note": "disponible, prix non précisé par la source"})255256        # --- totaux : jamais de montant inventé ------------------------------257        total = None258        if price:259            total = float(price) + sum(260                (li["montant"] or 0) for li in lignes[1:]261                if li["statut"] in ("observed", "estimated")262                and li["montant"] is not None)263        inconnues = [li["poste"] for li in lignes if li["statut"] == "unknown"]264265        out = {266            "uid": uid, "version": VERSION,267            "loyer": price,268            "lignes": lignes,269            "total_estime": round(total) if total else None,270            "annuel_estime": round(total * 12) if total else None,271            "postes_inconnus": inconnues,272            "pi2": pi2(con, l),273            "methode": ("loyer affiché + frais non inclus connus (observés) ou "274                        "estimés avec source ; les postes inconnus sont listés "275                        "tels quels, jamais chiffrés arbitrairement"),276        }277        if total and l.get("area_sqft") and l["area_sqft"] > 100:278            out["total_pi2"] = round(total / l["area_sqft"], 2)279        return out280    finally:281        if own:282            con.close()283
Files main
Menu

Theme