SPB Git

Repository Public

fv_validation_report.py 7.0 KB 162 lines python

1# =============================================================================2#                  SP BOUCHER | SOFTWARE & RESEARCH3#             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project          : Lou·Ka9# File             : scripts/fv_validation_report.py10# Module           : scripts11# 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 — génère docs/FAIRVALUE-VALIDATION.md depuis la base (données réelles)89#   Usage : .venv/bin/python scripts/fv_validation_report.py90# -----------------------------------------------------------------------------91import sys92import time93from pathlib import Path9495sys.path.insert(0, str(Path(__file__).resolve().parent.parent))96from louka import db  # noqa: E4029798con = db.connect()99q = lambda sql, *a: con.execute(sql, a).fetchall()   # noqa: E731100one = lambda sql, *a: con.execute(sql, a).fetchone()  # noqa: E731101L: list[str] = []102p = L.append103104p("# Rapport de validation — juste valeur Lou-Ka (fv-logement-1.0)\n")105p(f"Généré le {time.strftime('%Y-%m-%d %H:%M')} sur le parc publié de www.lou-ka.com.\n")106107p("## 1. Distribution des classifications\n")108tot = one("SELECT COUNT(*) n FROM fairvalue")["n"]109p("| Classification | Annonces | Part | Écart moyen |")110p("|---|---|---|---|")111for r in q("SELECT COALESCE(verdict,'sans verdict (prudence)') v, COUNT(*) n,"112           " ROUND(AVG(deviation)*100,1) d FROM fairvalue"113           " GROUP BY verdict ORDER BY verdict IS NULL, verdict"):114    p(f"| {r['v']} | {r['n']:,} | {100 * r['n'] / tot:.1f} % | {r['d']} % |")115p("")116p("| Confiance | Annonces |")117p("|---|---|")118for r in q("SELECT confidence c, COUNT(*) n FROM fairvalue"119           " GROUP BY confidence ORDER BY n DESC"):120    p(f"| {r['c']} | {r['n']:,} |")121d0 = one("SELECT ROUND(AVG(deviation)*100,2) d FROM fairvalue")["d"]122p(f"\nCentrage global : écart moyen {d0} % (cible ≈ 0 : pas de biais systématique).\n")123124p("## 2. Plausibilité par segment (juste valeur vs loyers réels)\n")125p("| Segment (ville, chambres) | n | FV moyenne | Loyer moyen réel | Écart |")126p("|---|---|---|---|---|")127for r in q("""SELECT f.segment s, COUNT(*) n, ROUND(AVG(f.fv)) fv, ROUND(AVG(l.price)) pr128              FROM fairvalue f JOIN listings l USING(uid) WHERE f.segment LIKE '2|%'129              GROUP BY f.segment ORDER BY n DESC LIMIT 14"""):130    seg = r["s"].split("|", 1)[1].replace("|", ", ")131    ec = 100 * (r["fv"] - r["pr"]) / r["pr"]132    p(f"| {seg} | {r['n']} | {r['fv']:.0f} $ | {r['pr']:.0f} $ | {ec:+.1f} % |")133p("")134135p("## 3. Exemples par catégorie (confiance forte)\n")136LIB = {"sous": "Sous le marché", "marche": "Dans le marché", "sur": "Au-dessus du marché"}137for v in ("sous", "marche", "sur"):138    p(f"### {LIB[v]}")139    for r in q("""SELECT l.price pr, f.fv, ROUND(f.deviation*100) d, l.city,140                         l.unit_type u, substr(l.title,1,50) t141                  FROM fairvalue f JOIN listings l USING(uid)142                  WHERE f.verdict=? AND f.confidence='fort'143                  ORDER BY l.last_seen DESC LIMIT 3""", v):144        p(f"- {r['t']} ({r['u'] or '—'}, {r['city'] or '—'}) : {r['pr']:.0f} $ "145          f"demandé vs {r['fv']:.0f} $ estimé ({r['d']:+.0f} %)")146    p("")147148p("## 4. Calibration temporelle (à re-mesurer)\n")149for r in q("""SELECT f.verdict v, ROUND(AVG((strftime('%s','now')-l.first_seen)/86400.0),1) j,150                     COUNT(*) n151              FROM fairvalue f JOIN listings l USING(uid)152              WHERE f.verdict IS NOT NULL GROUP BY f.verdict"""):153    p(f"- {LIB[r['v']]} : {r['j']} jours en ligne en moyenne ({r['n']:,} annonces)")154p("")155p("La base d'annonces est encore jeune : la durée de présence ne discrimine pas")156p("encore les verdicts. Re-mesurer après quelques semaines d'historique et")157p("recalibrer les seuils ±8 % (procédure : docs/FAIRVALUE.md §6).")158159out = Path(__file__).resolve().parent.parent / "docs" / "FAIRVALUE-VALIDATION.md"160out.write_text("\n".join(L).replace(",", ",").replace(",", ","), encoding="utf-8")161print(f"écrit: {out}")162
Files main
Menu

Theme