SPB Git

Repository Public

store.py 17.7 KB 423 lines python

1# =============================================================================2#                  SP BOUCHER | SOFTWARE & RESEARCH3#             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project          : Immo·Ka9# File             : immoka/mortgage/store.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# mortgage/store.py : persistance des taux hypothécaires (data/mortgage.db).91#   Historisation par périodes de validité : une ligne « courante » par produit92#   (valid_to IS NULL) ; un changement de taux ferme la ligne et en ouvre une93#   nouvelle. Aucune donnée n'est jamais écrasée — l'historique complet se94#   reconstruit par produit. Santé des providers dans provider_runs.95# -----------------------------------------------------------------------------96from __future__ import annotations9798import hashlib99import json100import sqlite3101import statistics102import time103from pathlib import Path104105DB_PATH = Path(__file__).resolve().parent.parent.parent / "data" / "mortgage.db"106107# Un taux « courant » plus vieux que STALE_H heures est signalé périmé.108STALE_H = 24109# Rejet des sauts aberrants : variation > JUMP_MAX points en < JUMP_WINDOW_H h.110JUMP_MAX = 2.5111JUMP_WINDOW_H = 48112113_SCHEMA = """114CREATE TABLE IF NOT EXISTS rate_observations (115    id             INTEGER PRIMARY KEY AUTOINCREMENT,116    provider       TEXT NOT NULL,117    institution    TEXT NOT NULL,118    product_key    TEXT NOT NULL,      -- empreinte identité produit119    product_name   TEXT,120    rate_type      TEXT NOT NULL,      -- fixed|variable|adjustable|other121    term_months    INTEGER NOT NULL,122    kind           TEXT NOT NULL,      -- posted|special123    rate           REAL NOT NULL,      -- taux contractuel en % (ex. 4.19)124    apr            REAL,125    insured_status TEXT DEFAULT 'unknown',  -- insured|insurable|uninsured|unknown126    purpose        TEXT DEFAULT 'purchase', -- purchase|renewal|refinance|unknown127    amortization_max_years INTEGER,128    conditions     TEXT,129    source_url     TEXT,130    confidence     REAL DEFAULT 1.0,131    raw            TEXT,               -- JSON : observation brute (audit)132    valid_from     REAL NOT NULL,133    valid_to       REAL,               -- NULL = taux courant134    last_checked   REAL NOT NULL135);136CREATE INDEX IF NOT EXISTS idx_rateobs_current137    ON rate_observations(provider, product_key, valid_to);138CREATE INDEX IF NOT EXISTS idx_rateobs_lookup139    ON rate_observations(rate_type, term_months, valid_to);140141CREATE TABLE IF NOT EXISTS provider_runs (142    id          INTEGER PRIMARY KEY AUTOINCREMENT,143    provider    TEXT NOT NULL,144    ts          REAL NOT NULL,145    ok          INTEGER,146    status      TEXT,     -- success|http_error|parser_error|validation_error|empty147    products    INTEGER,148    changed     INTEGER,149    rejected    INTEGER,150    duration_ms INTEGER,151    message     TEXT152);153CREATE INDEX IF NOT EXISTS idx_provider_runs ON provider_runs(provider, ts);154155-- Préparé pour les notifications futures (« alerte-moi si le 5 ans fixe156-- passe sous 3,99 % » / « si le paiement de cette propriété passe sous X $ »).157CREATE TABLE IF NOT EXISTS rate_alerts (158    id        INTEGER PRIMARY KEY AUTOINCREMENT,159    created   REAL NOT NULL,160    kind      TEXT NOT NULL,   -- rate_below|payment_below161    params    TEXT,            -- JSON : {rate_type, term_months, uid, down…}162    threshold REAL NOT NULL,163    contact   TEXT,164    active    INTEGER DEFAULT 1,165    fired_at  REAL166);167"""168169_SCHEMA_READY = False170171172def connect() -> sqlite3.Connection:173    global _SCHEMA_READY174    DB_PATH.parent.mkdir(parents=True, exist_ok=True)175    con = sqlite3.connect(DB_PATH, timeout=60)176    con.row_factory = sqlite3.Row177    con.execute("PRAGMA journal_mode=WAL")178    con.execute("PRAGMA synchronous=NORMAL")179    con.execute("PRAGMA busy_timeout=120000")180    if not _SCHEMA_READY:181        con.executescript(_SCHEMA)182        con.commit()183        _SCHEMA_READY = True184    return con185186187def product_key(p: dict) -> str:188    """Identité stable d'un produit : institution + type + terme + nature du189    taux + assurabilité + objet + nom. Deux produits incompatibles ne190    partagent jamais la même clé (règle : ne jamais comparer l'incomparable)."""191    ident = "|".join([192        p["provider"], p["rate_type"], str(p["term_months"]), p["kind"],193        p.get("insured_status") or "unknown", p.get("purpose") or "purchase",194        (p.get("product_name") or "").strip().lower(),195    ])196    return hashlib.sha1(ident.encode()).hexdigest()[:16]197198199def record_observations(con: sqlite3.Connection, provider: str,200                        products: list[dict]) -> dict:201    """Enregistre une passe de collecte validée.202203    Pour chaque produit : si le taux courant est identique → simple mise à204    jour de last_checked ; s'il a changé → fermeture de la période et205    insertion d'une nouvelle ligne. Rejette les sauts aberrants (> JUMP_MAX206    points en < JUMP_WINDOW_H h) sans écraser la bonne donnée précédente.207    Retourne {seen, changed, rejected, rejected_details}."""208    now = time.time()209    changed = 0210    rejected: list[str] = []211    for p in products:212        pk = product_key(p)213        cur = con.execute(214            "SELECT id, rate, last_checked FROM rate_observations "215            "WHERE provider=? AND product_key=? AND valid_to IS NULL",216            (provider, pk)).fetchone()217        if cur is not None:218            if abs(cur["rate"] - p["rate"]) < 1e-9:219                con.execute(220                    "UPDATE rate_observations SET last_checked=?, apr=?, "221                    "conditions=?, source_url=? WHERE id=?",222                    (now, p.get("apr"), p.get("conditions"),223                     p.get("source_url"), cur["id"]))224                continue225            # Garde-fou anti-aberration : ne jamais écraser une donnée saine226            # par un saut manifestement impossible.227            age_h = (now - (cur["last_checked"] or now)) / 3600.0228            if abs(cur["rate"] - p["rate"]) > JUMP_MAX and age_h < JUMP_WINDOW_H:229                rejected.append(230                    f"{p.get('product_name') or pk}: {cur['rate']} -> "231                    f"{p['rate']} (saut aberrant)")232                continue233            con.execute("UPDATE rate_observations SET valid_to=? WHERE id=?",234                        (now, cur["id"]))235            changed += 1236        con.execute(237            "INSERT INTO rate_observations (provider, institution, "238            "product_key, product_name, rate_type, term_months, kind, rate, "239            "apr, insured_status, purpose, amortization_max_years, "240            "conditions, source_url, confidence, raw, valid_from, "241            "valid_to, last_checked) "242            "VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,NULL,?)",243            (provider, p["institution"], pk, p.get("product_name"),244             p["rate_type"], p["term_months"], p["kind"], p["rate"],245             p.get("apr"), p.get("insured_status") or "unknown",246             p.get("purpose") or "purchase", p.get("amortization_max_years"),247             p.get("conditions"), p.get("source_url"),248             p.get("confidence", 1.0),249             json.dumps(p.get("raw"), ensure_ascii=False) if p.get("raw") else None,250             now, now))251    con.commit()252    return {"seen": len(products), "changed": changed,253            "rejected": len(rejected), "rejected_details": rejected}254255256def _row(r: sqlite3.Row) -> dict:257    d = dict(r)258    d.pop("raw", None)259    now = time.time()260    d["age_minutes"] = round((now - (d.get("last_checked") or now)) / 60)261    d["stale"] = d["age_minutes"] > STALE_H * 60262    return d263264265def current_rates(con: sqlite3.Connection, rate_type: str | None = None,266                  term_months: int | None = None, kind: str | None = None,267                  insured_status: str | None = None,268                  purpose: str | None = None,269                  provider: str | None = None) -> list[dict]:270    """Taux courants (dernière donnée valide par produit), filtrables."""271    q = ("SELECT * FROM rate_observations WHERE valid_to IS NULL")272    args: list = []273    for col, val in (("rate_type", rate_type), ("term_months", term_months),274                     ("kind", kind), ("provider", provider),275                     ("purpose", purpose)):276        if val is not None:277            q += f" AND {col}=?"278            args.append(val)279    if insured_status is not None:280        q += " AND insured_status IN (?, 'unknown')"281        args.append(insured_status)282    q += " ORDER BY provider, term_months, rate"283    return [_row(r) for r in con.execute(q, args).fetchall()]284285286def best_rate(con: sqlite3.Connection, rate_type: str = "fixed",287              term_months: int = 60, insured_status: str | None = None,288              purpose: str = "purchase") -> dict | None:289    """Meilleur taux courant pour un produit comparable (privilégie les taux290    « special », sinon posted). Retourne la ligne complète + contexte."""291    rows = current_rates(con, rate_type=rate_type, term_months=term_months,292                         insured_status=insured_status, purpose=purpose)293    if not rows:294        return None295    # Un seul candidat par institution : special prioritaire, sinon posted.296    by_inst: dict[str, dict] = {}297    for r in rows:298        cur = by_inst.get(r["provider"])299        if cur is None:300            by_inst[r["provider"]] = r301        elif r["kind"] == "special" and cur["kind"] == "posted":302            by_inst[r["provider"]] = r303        elif r["kind"] == cur["kind"] and r["rate"] < cur["rate"]:304            by_inst[r["provider"]] = r305    candidates = sorted(by_inst.values(), key=lambda r: r["rate"])306    best = candidates[0]307    rates = [r["rate"] for r in candidates]308    return {309        **best,310        "median_rate": round(statistics.median(rates), 2) if rates else None,311        "institutions_count": len(candidates),312        "per_institution": candidates,313    }314315316def history(con: sqlite3.Connection, rate_type: str, term_months: int,317            provider: str | None = None, kind: str | None = None,318            days: int = 365) -> list[dict]:319    """Historique : périodes de validité (valid_from/valid_to) par produit."""320    since = time.time() - days * 86400321    q = ("SELECT provider, institution, product_name, kind, rate, "322         "insured_status, valid_from, valid_to, last_checked, source_url "323         "FROM rate_observations WHERE rate_type=? AND term_months=? "324         "AND (valid_to IS NULL OR valid_to >= ?)")325    args: list = [rate_type, term_months, since]326    if provider:327        q += " AND provider=?"328        args.append(provider)329    if kind:330        q += " AND kind=?"331        args.append(kind)332    q += " ORDER BY provider, valid_from"333    return [dict(r) for r in con.execute(q, args).fetchall()]334335336def rate_at(con: sqlite3.Connection, rate_type: str, term_months: int,337            ts: float, kind: str = "special") -> float | None:338    """Meilleur taux observé (toutes institutions) à un instant donné."""339    rows = con.execute(340        "SELECT MIN(rate) AS r FROM rate_observations "341        "WHERE rate_type=? AND term_months=? AND kind=? AND valid_from<=? "342        "AND (valid_to IS NULL OR valid_to>?) AND last_checked>=?",343        (rate_type, term_months, kind, ts, ts, ts - 14 * 86400)).fetchone()344    if rows is None or rows["r"] is None:345        # repli : posted si aucun special à cette date346        rows = con.execute(347            "SELECT MIN(rate) AS r FROM rate_observations "348            "WHERE rate_type=? AND term_months=? AND valid_from<=? "349            "AND (valid_to IS NULL OR valid_to>?)",350            (rate_type, term_months, ts, ts)).fetchone()351    return rows["r"] if rows else None352353354def market_stats(con: sqlite3.Connection, rate_type: str = "fixed",355                 term_months: int = 60) -> dict | None:356    """Métriques Mortgage Intelligence : meilleur, médian, spread,357    variations 7/30/90 jours, plus bas observé 6 mois."""358    best = best_rate(con, rate_type=rate_type, term_months=term_months)359    if best is None:360        return None361    now = time.time()362    out = {363        "rate_type": rate_type,364        "term_months": term_months,365        "best": best["rate"],366        "best_provider": best["provider"],367        "best_institution": best["institution"],368        "best_kind": best["kind"],369        "median": best["median_rate"],370        "spread": (round(best["median_rate"] - best["rate"], 2)371                   if best["median_rate"] is not None else None),372        "institutions_count": best["institutions_count"],373    }374    for label, days in (("var_7d", 7), ("var_30d", 30), ("var_90d", 90)):375        past = rate_at(con, rate_type, term_months, now - days * 86400)376        out[label] = round(best["rate"] - past, 2) if past is not None else None377    low = con.execute(378        "SELECT MIN(rate) AS r FROM rate_observations "379        "WHERE rate_type=? AND term_months=? AND kind='special' "380        "AND last_checked >= ?",381        (rate_type, term_months, now - 182 * 86400)).fetchone()382    out["lowest_6m"] = low["r"] if low and low["r"] is not None else None383    return out384385386def log_run(con: sqlite3.Connection, provider: str, ok: bool, status: str,387            products: int = 0, changed: int = 0, rejected: int = 0,388            duration_ms: int = 0, message: str = "") -> None:389    con.execute(390        "INSERT INTO provider_runs (provider, ts, ok, status, products, "391        "changed, rejected, duration_ms, message) VALUES (?,?,?,?,?,?,?,?,?)",392        (provider, time.time(), 1 if ok else 0, status, products, changed,393         rejected, duration_ms, message[:500]))394    con.commit()395396397def provider_health(con: sqlite3.Connection) -> list[dict]:398    """Dernier état de chaque provider : OK / WARNING / ERROR + fraîcheur."""399    rows = con.execute(400        "SELECT p.* FROM provider_runs p JOIN (SELECT provider, MAX(ts) AS m "401        "FROM provider_runs GROUP BY provider) x "402        "ON p.provider=x.provider AND p.ts=x.m ORDER BY p.provider").fetchall()403    now = time.time()404    out = []405    for r in rows:406        d = dict(r)407        n_current = con.execute(408            "SELECT COUNT(*) AS n, MAX(last_checked) AS mc "409            "FROM rate_observations WHERE provider=? AND valid_to IS NULL",410            (r["provider"],)).fetchone()411        age_min = round((now - r["ts"]) / 60)412        if r["ok"] and n_current["n"] > 0:413            level = "WARNING" if age_min > STALE_H * 60 or r["rejected"] else "OK"414        elif n_current["n"] > 0:415            level = "WARNING"   # échec récent mais données valides conservées416        else:417            level = "ERROR"418        d.update({"level": level, "age_minutes": age_min,419                  "current_products": n_current["n"],420                  "last_data_at": n_current["mc"]})421        out.append(d)422    return out423
Files main
Menu

Theme