SPB Git

Repository Public

fairvalue.py 23.6 KB 568 lines python

1# =============================================================================2#                  SP BOUCHER | SOFTWARE & RESEARCH3#             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project          : Lou·Ka9# File             : louka/fairvalue.py10# Module           : louka11# Repository       : https://git.spboucher.ai/lou-ka12# Created          : 2026-08-1813# Last Modified    : 2026-08-1814#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# fairvalue.py : framework d'estimation de la JUSTE VALEUR locative (fair value)91#92#   Moteur générique Groupe-KA « estimation de juste valeur » : les93#   spécificités logement vivent dans CONFIG (segments, caractéristiques,94#   seuils) — décliner sur immo-ka (biens en vente) ou auto-ka (véhicules)95#   = fournir une autre CONFIG et une autre requête de chargement.96#97#   Trois niveaux, du plus robuste au plus fin :98#     N1  référence par segment de marché (ville[/quartier] × chambres),99#         médiane + p25/p75, volume minimal sinon repli au niveau supérieur ;100#     N2  ajustements multiplicatifs par caractéristiques (meublé, chauffage101#         inclus, stationnement…) estimés SUR LES DONNÉES elles-mêmes ;102#     N3  comparables kNN géographiques (grille spatiale, pondération103#         gaussienne par la distance).104#   Combinaison + couloir de sécurité autour du segment + indice de confiance.105#   AUCUNE donnée inventée : segment trop rare => confiance faible / pas de106#   verdict, jamais d'estimation à l'aveugle.107# -----------------------------------------------------------------------------108from __future__ import annotations109110import math111import re112import time113from statistics import median114115MODEL_VERSION = "fv-logement-1.0"116117CONFIG = {118    # volume minimal d'annonces pour qu'un segment fasse référence119    "min_segment": 8,120    # comparables (niveau 3)121    "knn_k": 12,122    "knn_min": 4,123    "knn_radius_m": 3000.0,124    "knn_bandwidth_m": 800.0,       # pondération gaussienne exp(-(d/bw)^2)125    # combinaison : poids du kNN quand il est disponible126    "knn_weight": 0.6,127    # couloir de sécurité autour de la référence du segment128    "corridor": (0.70, 1.30),        # x p25 … x p75129    # classification (écart relatif au marché)130    "seuil_sous": -0.08,131    "seuil_sur": 0.08,132    # au-delà : donnée probablement corrompue (prix à la semaine, coquille…)133    # -> pas de verdict plutôt qu'un verdict trompeur134    "verdict_dev_bounds": (-0.50, 1.00),135    # ajustement superficie : (aire/aire_type)^elasticité, borné136    "area_elasticity": 0.35,137    "area_adj_bounds": (0.80, 1.30),138    # caractéristiques ajustables (chemin json_extract dans details, ou champ)139    "features": {140        "meuble":        ("field", "furnished"),141        "chauffage":     ("details", "$.inclusions.heating"),142        "electricite":   ("details", "$.inclusions.electricity"),143        "stationnement": ("details", "$.parking.available"),144        "climatisation": ("details", "$.ac"),145        "balcon":        ("details", "$.balcony"),146        "ascenseur":     ("details", "$.elevator"),147        "piscine":       ("details", "$.pool"),148        "lave_vaisselle": ("details", "$.appliances.dishwasher"),149    },150    # bornes de sanité des coefficients appris (un coef hors bornes = bruit)151    "coef_bounds": (0.85, 1.35),152    "coef_min_pairs": 60,            # nb min d'annonces avec ET sans la carac.153}154155156# --------------------------------------------------------------- utilitaires157# location de CHAMBRE / colocation : segment à part — comparer une chambre158# au loyer d'un logement entier fabriquerait de fausses « bonnes affaires »159_CHAMBRE = re.compile(160    r"(chambre\s+(à|a)\s+louer|chambre\s+dans|chambre\s+disponible|"161    r"chambre\s+meubl|colocation|\bcoloc\b|room\s+for\s+rent|"162    r"room\s+in\b|roommate|chambre\s+(à|a)\s+partager)", re.IGNORECASE)163164# prix affiché non mensuel (semaine/jour/nuit) : l'écart serait trompeur165_NON_MENSUEL = re.compile(166    r"(/\s*sem|par\s+sem|semaine|hebdo|/\s*jour|par\s+jour|/\s*nuit|"167    r"par\s+nuit|/\s*wk|/\s*week\b|weekly|/\s*night|nightly|/\s*day\b)",168    re.IGNORECASE)169170171def _bed_group(bedrooms) -> str:172    """Groupe de chambres : 0 (studio), 1, 2, 3, 4+ — clé de segment."""173    if bedrooms is None:174        return "?"175    b = int(round(float(bedrooms)))176    return "4+" if b >= 4 else str(max(0, b))177178179def _pct(sorted_vals: list[float], q: float) -> float:180    if not sorted_vals:181        return 0.0182    i = q * (len(sorted_vals) - 1)183    lo, hi = int(math.floor(i)), int(math.ceil(i))184    return sorted_vals[lo] + (sorted_vals[hi] - sorted_vals[lo]) * (i - lo)185186187def _dist_m(lat1, lng1, lat2, lng2) -> float:188    """Distance approx. en mètres (équirectangulaire — suffisant à < 10 km)."""189    kx = 111320.0 * math.cos(math.radians((lat1 + lat2) / 2))190    return math.hypot((lat1 - lat2) * 110540.0, (lng1 - lng2) * kx)191192193def _ensure_tables(con) -> None:194    con.executescript("""195    CREATE TABLE IF NOT EXISTS fairvalue (196        uid           TEXT PRIMARY KEY,      -- listings.uid197        fv            REAL,                  -- juste valeur estimée ($/mois)198        fv_low        REAL,                  -- fourchette basse199        fv_high       REAL,                  -- fourchette haute200        deviation     REAL,                  -- (prix - fv) / fv201        verdict       TEXT,                  -- sous | marche | sur | NULL202        confidence    TEXT,                  -- fort | moyen | faible203        method        TEXT,                  -- segment | segment+ajust | knn+segment204        comps         INTEGER,               -- nb de comparables kNN retenus205        segment       TEXT,                  -- clé du segment de référence206        model_version TEXT,207        computed_at   REAL208    );209    CREATE TABLE IF NOT EXISTS fv_segments (   -- historisation des références210        ts     REAL,211        level  INTEGER,                        -- 1=ville+quartier+ch, 2=ville+ch, 3=ch, 4=global212        key    TEXT,213        n      INTEGER,214        p25    REAL, p50 REAL, p75 REAL,215        area_p50 REAL216    );217    CREATE INDEX IF NOT EXISTS idx_fv_segments_ts ON fv_segments(ts);218    """)219    con.commit()220221222# ------------------------------------------------------------- jeu de données223def _load(con) -> list[dict]:224    """Jeu de référence : annonces publiées (qualité validée), canoniques,225    au prix plausible. Les annonces en quarantaine sont EXCLUES."""226    feats = CONFIG["features"]227    cols = ", ".join(228        f"json_extract(details, '{path}') AS f_{name}"229        for name, (kind, path) in feats.items() if kind == "details")230    rows = con.execute(f"""231        SELECT uid, source, city, sector, unit_type, bedrooms, price,232               area_sqft, lat, lng, furnished, price_label, title,233               json_extract(details, '$.price_from') AS price_from, {cols}234        FROM listings235        WHERE active=1 AND published=1 AND dup_of IS NULL236          AND price IS NOT NULL AND price BETWEEN 175 AND 20000237    """).fetchall()238    out = []239    for r in rows:240        d = dict(r)241        if ((d.get("unit_type") or "").strip().lower() in ("chambre", "chambres")242                or _CHAMBRE.search(d.get("title") or "")):243            d["bed"] = "ch"          # segment « chambre / colocation »244        else:245            d["bed"] = _bed_group(d["bedrooms"])246        # prix à la semaine/nuit rangé comme mensuel : EXCLU du jeu de247        # référence (fausserait les médianes) et jamais de verdict248        d["non_monthly"] = bool(249            _NON_MENSUEL.search(d.get("price_label") or "")250            or _NON_MENSUEL.search(d.get("title") or ""))251        if not d["non_monthly"]:252            out.append(d)253    return out254255256def _feature_value(item: dict, name: str):257    kind, path = CONFIG["features"][name]258    if kind == "field":259        return item.get(path)260    return item.get(f"f_{name}")261262263# ------------------------------------------------- niveau 1 : segments marché264def _build_segments(items: list[dict]) -> dict[str, dict]:265    """Références par segment avec échelle de repli :266    L1 ville|quartier|ch → L2 ville|ch → L3 ch (province) → L4 global."""267    buckets: dict[tuple[int, str], list[dict]] = {}268    for it in items:269        keys = []270        if it["city"] and it["sector"] and it["bed"] != "?":271            keys.append((1, f"{it['city']}|{it['sector']}|{it['bed']}"))272        if it["city"] and it["bed"] != "?":273            keys.append((2, f"{it['city']}|{it['bed']}"))274        if it["bed"] != "?":275            keys.append((3, it["bed"]))276        keys.append((4, "global"))277        for k in keys:278            buckets.setdefault(k, []).append(it)279    refs: dict[str, dict] = {}280    n_min = CONFIG["min_segment"]281    for (level, key), members in buckets.items():282        if len(members) < n_min and level != 4:283            continue284        prices = sorted(m["price"] for m in members)285        areas = sorted(m["area_sqft"] for m in members if m["area_sqft"])286        refs[f"{level}|{key}"] = {287            "level": level, "key": key, "n": len(members),288            "p25": _pct(prices, 0.25), "p50": _pct(prices, 0.50),289            "p75": _pct(prices, 0.75),290            "area_p50": median(areas) if areas else None,291        }292    return refs293294295def _segment_for(it: dict, refs: dict[str, dict]) -> dict | None:296    """Référence la plus fine disponible pour une annonce (repli en échelle)."""297    candidates = []298    if it["city"] and it["sector"] and it["bed"] != "?":299        candidates.append(f"1|{it['city']}|{it['sector']}|{it['bed']}")300    if it["city"] and it["bed"] != "?":301        candidates.append(f"2|{it['city']}|{it['bed']}")302    if it["bed"] != "?":303        candidates.append(f"3|{it['bed']}")304    candidates.append("4|global")305    for c in candidates:306        if c in refs:307            return refs[c]308    return None309310311# ------------------------------------- niveau 2 : coefficients par carac.312def _learn_coefficients(items: list[dict], refs: dict) -> dict[str, float]:313    """Coefficient multiplicatif de chaque caractéristique, appris des données :314    médiane de (prix / p50 du segment) des annonces AVEC la caractéristique,315    divisée par celle des annonces SANS. Borné (coef_bounds) et ignoré si316    l'échantillon est trop mince — aucun coefficient inventé."""317    coefs: dict[str, tuple[float, float]] = {}318    lo, hi = CONFIG["coef_bounds"]319    for name in CONFIG["features"]:320        with_r, without_r = [], []321        for it in items:322            ref = _segment_for(it, refs)323            if ref is None or ref["level"] >= 4 or ref["p50"] <= 0:324                continue325            v = _feature_value(it, name)326            if v is None:327                continue328            ratio = it["price"] / ref["p50"]329            (with_r if v else without_r).append(ratio)330        if (len(with_r) >= CONFIG["coef_min_pairs"]331                and len(without_r) >= CONFIG["coef_min_pairs"]):332            c = median(with_r) / max(median(without_r), 1e-9)333            c = min(hi, max(lo, c))334            # part des annonces (au statut connu) qui ONT la caractéristique :335            # sert à centrer l'ajustement — le p50 du segment reflète déjà le336            # mélange avec/sans, appliquer c brut gonflerait toutes les337            # estimations (biais systématique vers « sous-évalué »)338            share = len(with_r) / (len(with_r) + len(without_r))339            coefs[name] = (c, share)340    return coefs341342343def _adjusted(it: dict, ref: dict, coefs: dict[str, float]) -> float:344    """Niveau 2 : référence du segment ajustée aux caractéristiques."""345    fv = ref["p50"]346    for name, (coef, share) in coefs.items():347        v = _feature_value(it, name)348        if v is None:349            continue                      # statut inconnu = effet moyen (neutre)350        norm = share * coef + (1.0 - share)   # effet moyen déjà dans le p50351        fv *= (coef if v else 1.0) / norm352    if it["area_sqft"] and ref.get("area_p50"):353        lo, hi = CONFIG["area_adj_bounds"]354        adj = (it["area_sqft"] / ref["area_p50"]) ** CONFIG["area_elasticity"]355        fv *= min(hi, max(lo, adj))356    return fv357358359# -------------------------------------------- niveau 3 : comparables kNN géo360def _build_grid(items: list[dict]) -> dict[tuple[int, int, str], list[dict]]:361    grid: dict[tuple[int, int, str], list[dict]] = {}362    for it in items:363        if it["lat"] is None or it["lng"] is None or it["bed"] == "?":364            continue365        cell = (int(it["lat"] * 50), int(it["lng"] * 50), it["bed"])  # ~2 km366        grid.setdefault(cell, []).append(it)367    return grid368369370def _knn(it: dict, grid: dict) -> tuple[float | None, int]:371    if it["lat"] is None or it["lng"] is None or it["bed"] == "?":372        return None, 0373    ci, cj = int(it["lat"] * 50), int(it["lng"] * 50)374    cands = []375    for di in (-1, 0, 1):376        for dj in (-1, 0, 1):377            cands.extend(grid.get((ci + di, cj + dj, it["bed"]), ()))378    radius, bw = CONFIG["knn_radius_m"], CONFIG["knn_bandwidth_m"]379    scored = []380    for c in cands:381        if c["uid"] == it["uid"]:382            continue383        d = _dist_m(it["lat"], it["lng"], c["lat"], c["lng"])384        if d > radius:385            continue386        w = math.exp(-((d / bw) ** 2))387        if it["unit_type"] and c["unit_type"] and it["unit_type"] == c["unit_type"]:388            w *= 1.3                       # même type d'unité = plus comparable389        scored.append((w, c["price"], d))390    if len(scored) < CONFIG["knn_min"]:391        return None, len(scored)392    scored.sort(key=lambda x: -x[0])393    top = scored[:CONFIG["knn_k"]]394    # médiane PONDÉRÉE des loyers comparables (la moyenne serait tirée vers le395    # haut par l'asymétrie des loyers)396    by_price = sorted(top, key=lambda x: x[1])397    half = sum(w for w, _, _ in top) / 2398    acc = 0.0399    fv = by_price[-1][1]400    for w, price, _ in by_price:401        acc += w402        if acc >= half:403            fv = price404            break405    return fv, len(top)406407408# --------------------------------------------------------- calcul d'ensemble409def compute_all(verbose: bool = True) -> dict:410    """(Re)calcule la fair value de toutes les annonces publiées.411412    Appelé à chaque cycle de synchronisation (ingest.watch) et via413    `python run.py fairvalue`. Historise les références de segments.414    """415    from . import db416    con = db.connect()417    _ensure_tables(con)418    t0 = time.time()419420    items = _load(con)421    refs = _build_segments(items)422    coefs = _learn_coefficients(items, refs)423    grid = _build_grid(items)424425    now = time.time()426    stats = {"annonces": len(items), "segments": len(refs), "coefs": coefs,427             "sous": 0, "marche": 0, "sur": 0, "sans_verdict": 0}428    rows = []429    for it in items:430        ref = _segment_for(it, refs)431        if ref is None:432            continue433        fv_seg = _adjusted(it, ref, coefs)434        fv_knn, n_comps = _knn(it, grid)435        if fv_knn is not None:436            w = CONFIG["knn_weight"]437            fv = w * fv_knn + (1 - w) * fv_seg438            method = "knn+segment"439        else:440            fv = fv_seg441            method = "segment+ajust" if coefs else "segment"442        # couloir de sécurité autour du segment (jamais d'estimation absurde)443        c_lo, c_hi = CONFIG["corridor"]444        fv = min(max(fv, ref["p25"] * c_lo), ref["p75"] * c_hi)445446        # fourchette : dispersion relative du segment appliquée à l'estimation447        lo = fv * (ref["p25"] / ref["p50"]) if ref["p50"] else fv * 0.85448        hi = fv * (ref["p75"] / ref["p50"]) if ref["p50"] else fv * 1.15449450        # divergence forte entre méthodes -> fourchette élargie, confiance451        # abaissée (les deux estimateurs ne racontent pas la même histoire)452        divergent = (fv_knn is not None and fv_seg > 0453                     and abs(fv_knn - fv_seg) / fv_seg > 0.25)454        if divergent:455            lo, hi = min(lo, min(fv_knn, fv_seg)), max(hi, max(fv_knn, fv_seg))456457        if (n_comps >= 8 and ref["level"] <= 2 and not divergent):458            confidence = "fort"459        elif n_comps >= CONFIG["knn_min"] or (ref["level"] <= 2 and ref["n"] >= 15):460            confidence = "moyen"461        else:462            confidence = "faible"463464        deviation = (it["price"] - fv) / fv if fv > 0 else None465        # prudence : pas de verdict si confiance faible, prix ambigu466        # (« à partir de » = plancher) ou écart hors du plausible (donnée467        # douteuse : coquille de prix, périodicité mal lue…)468        b_lo, b_hi = CONFIG["verdict_dev_bounds"]469        verdict = None470        if (deviation is not None and confidence != "faible"471                and not it["price_from"] and b_lo < deviation < b_hi):472            if deviation <= CONFIG["seuil_sous"]:473                verdict = "sous"474            elif deviation >= CONFIG["seuil_sur"]:475                verdict = "sur"476            else:477                verdict = "marche"478            stats[verdict] += 1479        else:480            stats["sans_verdict"] += 1481482        rows.append((it["uid"], round(fv), round(lo), round(hi),483                     round(deviation, 4) if deviation is not None else None,484                     verdict, confidence, method, n_comps,485                     f"{ref['level']}|{ref['key']}", MODEL_VERSION, now))486487    con.execute("DELETE FROM fairvalue")488    con.executemany(489        "INSERT INTO fairvalue (uid, fv, fv_low, fv_high, deviation, verdict,"490        " confidence, method, comps, segment, model_version, computed_at)"491        " VALUES (?,?,?,?,?,?,?,?,?,?,?,?)", rows)492    # historisation des références (évolution des loyers par segment)493    con.executemany(494        "INSERT INTO fv_segments (ts, level, key, n, p25, p50, p75, area_p50)"495        " VALUES (?,?,?,?,?,?,?,?)",496        [(now, r["level"], r["key"], r["n"], round(r["p25"]), round(r["p50"]),497          round(r["p75"]), r["area_p50"]) for r in refs.values()498         if r["level"] <= 2])499    con.commit()500    con.close()501    stats["seconds"] = round(time.time() - t0, 1)502    stats["estimees"] = len(rows)503    if verbose:504        c = {k: round(v[0], 3) for k, v in coefs.items()}505        print(f"[lou-ka] fairvalue: {stats['estimees']} estimées "506              f"({stats['segments']} segments) en {stats['seconds']}s — "507              f"sous {stats['sous']} / marché {stats['marche']} / "508              f"sur {stats['sur']} / sans verdict {stats['sans_verdict']}")509        print(f"[lou-ka] fairvalue coefs: {c}")510    return stats511512513# ------------------------------------------------- explication d'une annonce514def explain(uid: str) -> dict | None:515    """Détail d'une estimation pour la fiche (analyse de prix) : fair value,516    fourchette, confiance, distribution du segment (mini-graphique)."""517    from . import db518    con = db.connect()519    _ensure_tables(con)520    row = con.execute("SELECT * FROM fairvalue WHERE uid=?", (uid,)).fetchone()521    if row is None:522        con.close()523        return None524    d = dict(row)525    # distribution des loyers du segment de référence (pour l'histogramme)526    level, key = d["segment"].split("|", 1)527    parts = key.split("|")528    sql = ("SELECT price FROM listings WHERE active=1 AND published=1"529           " AND dup_of IS NULL AND price BETWEEN 175 AND 20000")530    args: list = []531    if level == "1":532        sql += " AND city=? AND sector=?"533        args += parts[0:2]534        bed = parts[2]535    elif level == "2":536        sql += " AND city=?"537        args.append(parts[0])538        bed = parts[1]539    else:540        bed = parts[0] if parts[0] != "global" else None541    prices = [r["price"] for r in con.execute(sql, args)]542    if bed is not None:543        beds = {r["uid"]: r["bedrooms"] for r in con.execute(544            "SELECT uid, bedrooms FROM listings WHERE active=1 AND published=1")}545        # re-filtrer par groupe de chambres via une requête directe (plus sûr)546        sql2 = sql + (" AND ((?='0' AND (bedrooms IS NOT NULL AND CAST(ROUND(bedrooms) AS INT)<=0))"547                      " OR (?='4+' AND CAST(ROUND(bedrooms) AS INT)>=4)"548                      " OR (CAST(ROUND(bedrooms) AS INT) = CAST(? AS INT) AND ? NOT IN ('0','4+')))")549        prices = [r["price"] for r in con.execute(sql2, args + [bed, bed, bed, bed])]550    con.close()551    prices.sort()552    # histogramme en 24 classes bornées p1–p99 (queues écrasées sinon)553    hist = []554    if len(prices) >= 8:555        lo, hi = _pct(prices, 0.01), _pct(prices, 0.99)556        if hi > lo:557            nbins = 24558            counts = [0] * nbins559            for p in prices:560                i = int((min(max(p, lo), hi) - lo) / (hi - lo) * (nbins - 1))561                counts[i] += 1562            hist = [{"x0": round(lo + (hi - lo) * i / nbins),563                     "x1": round(lo + (hi - lo) * (i + 1) / nbins),564                     "n": c} for i, c in enumerate(counts)]565    d["segment_n"] = len(prices)566    d["histogram"] = hist567    return d568
Files main
Menu

Theme