Repository Public
1# =============================================================================2# SP BOUCHER | SOFTWARE & RESEARCH3# ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project : Lou·Ka9# File : louka/statsdash.py10# Module : louka11# Repository : https://git.spboucher.ai/lou-ka12# Created : 2026-08-1713# 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# statsdash.py : tableau de bord statistique — contrat commun Groupe KA v291# (voir frontend/src/ka/stats/SPEC.md). Construit le JSON du dashboard à92# partir de requêtes SQL agrégées (listings, sync_log, price_log) avec un93# cache mémoire de 5 minutes par clé de période. AUCUNE stat inventée :94# une section sans donnée réelle est simplement absente du JSON.95# v2 (2026-08-19) : sparklines KPI, jauges de couverture, série des loyers96# (area), multi-courbes loyer médian par taille, barres empilées par source,97# distribution des loyers, heatmap horaire 7×24, tableaux « loyers par98# taille » et « baisses de loyer », records enrichis.99# -----------------------------------------------------------------------------100from __future__ import annotations101102import json103import threading104import time105from datetime import date, datetime, timedelta106from pathlib import Path107from zoneinfo import ZoneInfo108109from . import db110111TZ = ZoneInfo("America/Toronto")112ROOT = Path(__file__).resolve().parent.parent113SOURCES_PATH = ROOT / "data" / "sources.json"114115CACHE_TTL = 300 # secondes116_cache: dict[str, tuple[float, dict]] = {}117_cache_lock = threading.Lock()118119# bornes de plausibilité des loyers résidentiels : au-delà, presque toujours120# des erreurs de lecture à la source — exclues des agrégats de prix.121PRIX_MIN, PRIX_MAX = 300, 15000122123PERIODS = {124 "auj": ("Aujourd'hui", 0),125 "7j": ("7 jours", 6),126 "30j": ("30 jours", 29),127 "3m": ("3 mois", 89),128 "6m": ("6 mois", 179),129 "12m": ("12 mois", 364),130}131132DOW_FR = ["lundi", "mardi", "mercredi", "jeudi", "vendredi", "samedi", "dimanche"]133134135# ---------------------------------------------------------------- utilitaires136def _day_start_ts(d: date) -> float:137 return datetime(d.year, d.month, d.day, tzinfo=TZ).timestamp()138139140def _coverage(con) -> tuple[date | None, date | None]:141 """Première et dernière date observées dans la base (first/last_seen)."""142 row = con.execute(143 "SELECT MIN(first_seen) a, MAX(last_seen) b FROM listings"144 " WHERE dup_of IS NULL"145 ).fetchone()146 if row["a"] is None:147 return None, None148 return (datetime.fromtimestamp(row["a"], TZ).date(),149 datetime.fromtimestamp(row["b"], TZ).date())150151152def resolve_period(period: str, from_: str | None, to_: str | None,153 cov_min: date, today: date) -> tuple[date, date, str]:154 """Bornes [from, to] (dates locales incluses) + libellé humain."""155 if from_ and to_:156 try:157 a = date.fromisoformat(from_)158 b = date.fromisoformat(to_)159 if a > b:160 a, b = b, a161 return max(a, cov_min), min(b, today), f"{a} → {b}"162 except ValueError:163 pass164 if period == "tout":165 return cov_min, today, "Toute la période"166 if period == "annee":167 return max(date(today.year, 1, 1), cov_min), today, "Année en cours"168 label, back = PERIODS.get(period, PERIODS["30j"])169 return max(today - timedelta(days=back), cov_min), today, label170171172def _pct(cur: float, prev: float) -> float | None:173 if not prev:174 return None175 return round(100.0 * (cur - prev) / prev, 1)176177178def _days(a: date, b: date) -> list[date]:179 return [a + timedelta(days=i) for i in range((b - a).days + 1)]180181182def _fr_int(n: float) -> str:183 return f"{int(round(n)):,}".replace(",", " ")184185186def _fr_money(n: float) -> str:187 return _fr_int(n) + " $"188189190def _spark(pts: list[dict], cap: int = 30) -> list[dict] | None:191 """Sous-échantillonne une série pour la sparkline d'un KPI (≤ cap points)."""192 if len(pts) < 2:193 return None194 if len(pts) <= cap:195 return pts196 step = max(1, len(pts) // cap)197 out = pts[::step]198 if out[-1] is not pts[-1]:199 out.append(pts[-1])200 return out201202203def _source_names() -> dict[str, str]:204 try:205 reg = json.loads(SOURCES_PATH.read_text(encoding="utf-8"))["sources"]206 return {s["id"]: s.get("name") or s["id"] for s in reg}207 except (OSError, ValueError, KeyError):208 return {}209210211def _pctile(sorted_vals: list[float], frac: float) -> float | None:212 if not sorted_vals:213 return None214 i = min(len(sorted_vals) - 1, int(len(sorted_vals) * frac))215 return sorted_vals[i]216217218# ------------------------------------------------------------------- dashboard219def compute(period: str = "30j", from_: str | None = None,220 to_: str | None = None) -> dict:221 key = f"{period}|{from_ or ''}|{to_ or ''}"222 now = time.time()223 with _cache_lock:224 hit = _cache.get(key)225 if hit and hit[0] > now:226 return hit[1]227 data = _compute(period, from_, to_)228 with _cache_lock:229 _cache[key] = (now + CACHE_TTL, data)230 return data231232233def _compute(period: str, from_: str | None, to_: str | None) -> dict:234 con = db.connect()235 try:236 return _build(con, period, from_, to_)237 finally:238 con.close()239240241# requête réutilisée : premier loyer observé de chaque annonce (journal de242# prix) — c'est le loyer demandé à l'entrée sur le marché, borné plausible.243_FIRST_PRICE_CTE = """244 WITH fp AS (245 SELECT p.uid uid, p.ts ts, p.price price246 FROM price_log p247 JOIN (SELECT uid, MIN(ts) t0 FROM price_log248 WHERE price IS NOT NULL GROUP BY uid) f249 ON f.uid = p.uid AND p.ts = f.t0250 WHERE p.price BETWEEN ? AND ?251 )252"""253254255def _build(con, period: str, from_: str | None, to_: str | None) -> dict:256 today = datetime.now(TZ).date()257 cov_min, _cov_max = _coverage(con)258 if cov_min is None: # base vide259 return {"updated": datetime.now(TZ).isoformat(),260 "period": {"from": None, "to": None, "label": "—"},261 "kpis": [], "series": [], "breakdowns": [], "tables": [],262 "records": []}263264 d_from, d_to, label = resolve_period(period, from_, to_, cov_min, today)265 ts_from = _day_start_ts(d_from)266 ts_to = _day_start_ts(d_to + timedelta(days=1)) # borne exclusive267268 # ---- histogrammes journaliers (2 balayages agrégés, réutilisés partout)269 starts = {r["d"]: r["n"] for r in con.execute(270 "SELECT date(first_seen,'unixepoch','localtime') d, COUNT(*) n"271 " FROM listings WHERE dup_of IS NULL GROUP BY d")}272 ends = {r["d"]: r["n"] for r in con.execute(273 "SELECT date(last_seen,'unixepoch','localtime') d, COUNT(*) n"274 " FROM listings WHERE dup_of IS NULL AND active=0 GROUP BY d")}275276 def actives_at(d: date) -> int:277 """Reconstruction : cum(first_seen<=d) − cum(retraits<=d−1)."""278 iso = d.isoformat()279 prev = (d - timedelta(days=1)).isoformat()280 s = sum(n for dd, n in starts.items() if dd <= iso)281 e = sum(n for dd, n in ends.items() if dd <= prev)282 return s - e283284 # ---- KPI ------------------------------------------------------------285 actives_now = con.execute(286 "SELECT COUNT(*) n FROM listings WHERE active=1 AND dup_of IS NULL"287 ).fetchone()["n"]288 new_in = sum(n for d, n in starts.items()289 if d_from.isoformat() <= d <= d_to.isoformat())290 removed_in = sum(n for d, n in ends.items()291 if d_from.isoformat() <= d <= d_to.isoformat())292293 # période précédente de même longueur (uniquement si couverte par la base)294 span = (d_to - d_from).days + 1295 p_from, p_to = d_from - timedelta(days=span), d_from - timedelta(days=1)296 prev_ok = p_from >= cov_min297 pts_prev_from = _day_start_ts(p_from)298 pts_prev_to = _day_start_ts(p_to + timedelta(days=1))299 new_prev = removed_prev = None300 if prev_ok:301 new_prev = sum(n for d, n in starts.items()302 if p_from.isoformat() <= d <= p_to.isoformat())303 removed_prev = sum(n for d, n in ends.items()304 if p_from.isoformat() <= d <= p_to.isoformat())305306 actives_prev = actives_at(p_to) if d_from - timedelta(days=1) >= cov_min else None307308 row = con.execute(309 "SELECT AVG(price) avg_p, COUNT(price) n_p FROM listings"310 " WHERE active=1 AND dup_of IS NULL AND price BETWEEN ? AND ?",311 (PRIX_MIN, PRIX_MAX)).fetchone()312 avg_price, n_priced = row["avg_p"], row["n_p"]313 median_price = None314 if n_priced:315 median_price = con.execute(316 "SELECT price FROM listings WHERE active=1 AND dup_of IS NULL"317 " AND price BETWEEN ? AND ? ORDER BY price LIMIT 1 OFFSET ?",318 (PRIX_MIN, PRIX_MAX, n_priced // 2)).fetchone()["price"]319320 connectors = con.execute(321 "SELECT COUNT(DISTINCT source) n FROM sync_log"322 " WHERE ok=1 AND ts>=? AND ts<?", (ts_from, ts_to)).fetchone()["n"]323 cities_n = con.execute(324 "SELECT COUNT(DISTINCT city) n FROM listings"325 " WHERE active=1 AND dup_of IS NULL AND city<>''").fetchone()["n"]326327 # séries journalières (réutilisées : séries, sparklines)328 days = _days(d_from, d_to)329 pts_act = [{"t": d.isoformat(), "v": actives_at(d)} for d in days]330 pts_new = [{"t": d.isoformat(), "v": starts.get(d.isoformat(), 0)}331 for d in days]332 pts_rem = [{"t": d.isoformat(), "v": ends.get(d.isoformat(), 0)}333 for d in days]334335 # loyer moyen des nouvelles annonces par jour (premier prix observé)336 fp_daily = con.execute(337 _FIRST_PRICE_CTE +338 "SELECT date(ts,'unixepoch','localtime') d, AVG(price) a, COUNT(*) n"339 " FROM fp WHERE ts>=? AND ts<? GROUP BY d ORDER BY d",340 (PRIX_MIN, PRIX_MAX, ts_from, ts_to)).fetchall()341 pts_rent = [{"t": r["d"], "v": round(r["a"])} for r in fp_daily342 if r["n"] >= 5]343344 kpis = [345 {"id": "actives", "label": "Annonces actives", "value": actives_now,346 "delta_pct": _pct(actives_now, actives_prev) if actives_prev else None,347 "direction": "up" if (actives_prev and actives_now >= actives_prev) else348 ("down" if actives_prev else None),349 "spark": _spark(pts_act)},350 {"id": "nouvelles", "label": "Nouvelles annonces (période)",351 "value": new_in,352 "delta_pct": _pct(new_in, new_prev) if prev_ok else None,353 "direction": ("up" if new_in >= (new_prev or 0) else "down") if prev_ok else None,354 "spark": _spark(pts_new)},355 {"id": "retirees", "label": "Annonces retirées (période)",356 "value": removed_in,357 "delta_pct": _pct(removed_in, removed_prev) if prev_ok else None,358 "direction": ("down" if removed_in >= (removed_prev or 0) else "up") if prev_ok else None,359 "spark": _spark(pts_rem)},360 ]361 if avg_price:362 kpis.append({"id": "loyer_moyen", "label": "Loyer moyen (actives)",363 "value": round(avg_price), "unit": "$",364 "spark": _spark(pts_rent)})365 if median_price:366 kpis.append({"id": "loyer_median", "label": "Loyer médian (actives)",367 "value": round(median_price), "unit": "$"})368 # qualité des données (quality.py) : quarantaine369 qual = con.execute(370 "SELECT ROUND(AVG(completeness),1) c, SUM(published=0) q"371 " FROM listings WHERE active=1 AND dup_of IS NULL").fetchone()372 if qual["c"] is not None:373 kpis.append({"id": "quarantaine",374 "label": "Annonces en quarantaine (qualité)",375 "value": qual["q"] or 0})376 # juste valeur (fair value) : répartition des classifications377 fv_ok = True378 try:379 fv = con.execute(380 """SELECT SUM(f.verdict='sous') sous, SUM(f.verdict='marche') marche,381 SUM(f.verdict='sur') sur, COUNT(*) n,382 ROUND(AVG(f.deviation)*100, 1) dev383 FROM fairvalue f JOIN listings l USING (uid)384 WHERE l.active=1 AND l.published=1 AND l.dup_of IS NULL385 AND f.verdict IS NOT NULL""").fetchone()386 except Exception:387 fv_ok = False388 fv = None389 if fv_ok and fv and fv["n"]:390 kpis.append({"id": "sous_marche", "label": "Annonces sous le marché",391 "value": fv["sous"] or 0})392 kpis.append({"id": "connecteurs", "label": "Connecteurs actifs (période)",393 "value": connectors})394 kpis.append({"id": "villes", "label": "Villes couvertes", "value": cities_n})395 kpis = [{k: v for k, v in kpi.items() if v is not None} for kpi in kpis]396397 # ---- jauges de couverture / complétude ---------------------------------398 cov = con.execute(399 """SELECT COUNT(*) n,400 SUM(lat IS NOT NULL AND lng IS NOT NULL) geo,401 SUM(price BETWEEN ? AND ?) prix,402 SUM(images IS NOT NULL AND images NOT IN ('', '[]')) img,403 SUM(published=1) pub404 FROM listings WHERE active=1 AND dup_of IS NULL""",405 (PRIX_MIN, PRIX_MAX)).fetchone()406 gauges = []407 if cov["n"]:408 n_act = cov["n"]409410 def _gauge(gid, lab, num, help_=None):411 g = {"id": gid, "label": lab,412 "value": round(100.0 * (num or 0) / n_act, 1),413 "max": 100, "unit": "%"}414 if help_:415 g["help"] = help_416 return g417418 gauges = [419 _gauge("geo", "Annonces géolocalisées", cov["geo"]),420 _gauge("prix", "Annonces avec loyer affiché", cov["prix"]),421 _gauge("photos", "Annonces avec photos", cov["img"]),422 _gauge("publiees", "Annonces publiées (qualité OK)", cov["pub"],423 "Le reste est en quarantaine qualité"),424 ]425 if qual["c"] is not None:426 gauges.append({"id": "completude",427 "label": "Complétude moyenne des fiches",428 "value": qual["c"], "max": 100, "unit": "%"})429430 # ---- séries temporelles ----------------------------------------------431 series = []432 if len(days) >= 2:433 s_act = {"id": "actives_jour", "title": "Annonces actives par jour",434 "unit": "annonces", "kind": "line", "points": pts_act}435 s_new = {"id": "nouvelles_jour", "title": "Nouvelles annonces par jour",436 "unit": "annonces", "kind": "bar", "points": pts_new}437 s_rem = {"id": "retraits_jour", "title": "Annonces retirées par jour",438 "unit": "annonces", "kind": "line", "points": pts_rem}439 if prev_ok:440 pdays = _days(p_from, p_to)441 s_act["compare"] = [{"t": d.isoformat(), "v": actives_at(d)}442 for d in pdays]443 s_rem["compare"] = [{"t": d.isoformat(),444 "v": ends.get(d.isoformat(), 0)}445 for d in pdays]446 series = [s_act, s_new, s_rem]447 if len(pts_rent) >= 2:448 series.append({"id": "loyer_entree_jour",449 "title": "Loyer moyen des nouvelles annonces par jour",450 "unit": "$", "kind": "area", "points": pts_rent})451452 # ---- multi-courbes : loyer médian d'entrée par taille -------------------453 multiseries = []454 if len(days) >= 2:455 top_types = [r["t"] for r in con.execute(456 _FIRST_PRICE_CTE +457 """SELECT l.unit_type t, COUNT(*) n FROM fp458 JOIN listings l ON l.uid=fp.uid AND l.dup_of IS NULL459 WHERE fp.ts>=? AND fp.ts<? AND l.unit_type<>''460 GROUP BY t ORDER BY n DESC LIMIT 4""",461 (PRIX_MIN, PRIX_MAX, ts_from, ts_to)).fetchall()]462 if top_types:463 ph = ",".join("?" * len(top_types))464 rows = con.execute(465 _FIRST_PRICE_CTE +466 f"""SELECT date(fp.ts,'unixepoch','localtime') d,467 l.unit_type t, fp.price p FROM fp468 JOIN listings l ON l.uid=fp.uid AND l.dup_of IS NULL469 WHERE fp.ts>=? AND fp.ts<? AND l.unit_type IN ({ph})""",470 (PRIX_MIN, PRIX_MAX, ts_from, ts_to, *top_types)).fetchall()471 per: dict[str, dict[str, list[float]]] = {t: {} for t in top_types}472 for r in rows:473 per[r["t"]].setdefault(r["d"], []).append(r["p"])474 # axe commun : jours où chaque taille a au moins 3 observations475 common = [d.isoformat() for d in days476 if all(len(per[t].get(d.isoformat(), [])) >= 3477 for t in top_types)]478 if len(common) >= 2:479 ms_series = []480 for t in top_types:481 pts = []482 for d in common:483 vals = sorted(per[t][d])484 pts.append({"t": d, "v": round(vals[len(vals) // 2])})485 ms_series.append({"label": t, "points": pts})486 multiseries.append({487 "id": "loyer_taille",488 "title": "Loyer médian des nouvelles annonces par taille",489 "unit": "$", "series": ms_series})490491 # ---- barres empilées : ajouts par jour et par source --------------------492 names = _source_names()493 stacked = []494 if len(days) >= 2:495 src_tot = con.execute(496 """SELECT source s, COUNT(*) n FROM listings497 WHERE dup_of IS NULL AND first_seen>=? AND first_seen<?498 GROUP BY s ORDER BY n DESC""", (ts_from, ts_to)).fetchall()499 if src_tot:500 top_src = [r["s"] for r in src_tot[:3]]501 others = [r["s"] for r in src_tot[3:]]502 daily_src: dict[str, dict[str, int]] = {}503 for r in con.execute(504 """SELECT date(first_seen,'unixepoch','localtime') d,505 source s, COUNT(*) n FROM listings506 WHERE dup_of IS NULL AND first_seen>=? AND first_seen<?507 GROUP BY d, s""", (ts_from, ts_to)):508 daily_src.setdefault(r["d"], {})[r["s"]] = r["n"]509 keys = [names.get(s, s) for s in top_src] + (510 ["Autres"] if others else [])511 pts = []512 for d in days:513 by = daily_src.get(d.isoformat(), {})514 vals = [by.get(s, 0) for s in top_src]515 if others:516 vals.append(sum(by.get(s, 0) for s in others))517 pts.append({"t": d.isoformat(), "values": vals})518 if any(sum(p["values"]) for p in pts):519 stacked.append({"id": "ajouts_source",520 "title": "Nouvelles annonces par jour et par source",521 "unit": "ajouts", "keys": keys, "points": pts})522523 # ---- répartitions ------------------------------------------------------524 types = [{"label": r["t"] or "Non précisé", "value": r["n"]}525 for r in con.execute(526 "SELECT unit_type t, COUNT(*) n FROM listings"527 " WHERE active=1 AND dup_of IS NULL GROUP BY unit_type"528 " ORDER BY n DESC LIMIT 8")]529 by_source = [{"label": names.get(r["s"], r["s"]), "value": r["n"]}530 for r in con.execute(531 "SELECT source s, COUNT(*) n FROM listings"532 " WHERE active=1 AND dup_of IS NULL GROUP BY source"533 " ORDER BY n DESC LIMIT 12")]534 breakdowns = []535 if fv_ok and fv and fv["n"]:536 breakdowns.append({"id": "fairvalue",537 "title": "Position des loyers vs juste valeur estimée",538 "kind": "donut", "items": [539 {"label": "Sous le marché", "value": fv["sous"] or 0},540 {"label": "Dans le marché", "value": fv["marche"] or 0},541 {"label": "Au-dessus du marché", "value": fv["sur"] or 0}]})542 if types:543 breakdowns.append({"id": "types", "title": "Annonces actives par taille",544 "kind": "donut", "items": types})545 # nouvelles annonces par taille (période) — deltas vs période précédente546 new_types = con.execute(547 """SELECT COALESCE(NULLIF(unit_type,''),'Non précisé') t, COUNT(*) n548 FROM listings WHERE dup_of IS NULL AND first_seen>=? AND first_seen<?549 GROUP BY t ORDER BY n DESC LIMIT 8""", (ts_from, ts_to)).fetchall()550 if new_types:551 prev_types = {}552 if prev_ok:553 prev_types = {r["t"]: r["n"] for r in con.execute(554 """SELECT COALESCE(NULLIF(unit_type,''),'Non précisé') t,555 COUNT(*) n FROM listings556 WHERE dup_of IS NULL AND first_seen>=? AND first_seen<?557 GROUP BY t""", (pts_prev_from, pts_prev_to))}558 items = []559 for r in new_types:560 it = {"label": r["t"], "value": r["n"]}561 if prev_ok:562 it["delta_pct"] = _pct(r["n"], prev_types.get(r["t"], 0))563 items.append(it)564 breakdowns.append({"id": "nouvelles_taille",565 "title": "Nouvelles annonces par taille (période)",566 "kind": "bars", "items": items})567 if by_source:568 breakdowns.append({"id": "sources", "title": "Top sources (annonces actives)",569 "kind": "bars", "items": by_source})570571 # ---- distribution des loyers (annonces actives, tranches de 200 $) ------572 distributions = []573 bins_rows = con.execute(574 """SELECT CAST(price/200 AS INT) b, COUNT(*) n FROM listings575 WHERE active=1 AND dup_of IS NULL AND price BETWEEN ? AND ?576 GROUP BY b ORDER BY b""", (PRIX_MIN, PRIX_MAX)).fetchall()577 if bins_rows:578 LO, HI = 2, 16 # < 400 $ … 3 200 $ et +579 agg: dict[int, int] = {}580 for r in bins_rows:581 b = min(max(r["b"], LO - 1), HI)582 agg[b] = agg.get(b, 0) + r["n"]583 bins = []584 for b in sorted(agg):585 if b == LO - 1:586 lab = f"< {LO * 200} $"587 elif b == HI:588 lab = f"{_fr_int(HI * 200)} $ +"589 else:590 lab = f"{_fr_int(b * 200)}–{_fr_int((b + 1) * 200 - 1)} $"591 bins.append({"label": lab, "value": agg[b]})592 distributions.append({"id": "loyers",593 "title": "Distribution des loyers (annonces actives)",594 "unit": "annonces", "bins": bins})595596 # ---- géographie --------------------------------------------------------597 geo_items = [{"label": r["c"], "value": r["n"]} for r in con.execute(598 "SELECT city c, COUNT(*) n FROM listings"599 " WHERE active=1 AND dup_of IS NULL AND city<>''"600 " GROUP BY city ORDER BY n DESC LIMIT 14")]601 geo = ({"title": "Top villes (annonces actives)", "items": geo_items}602 if geo_items else None)603604 # ---- calendrier de chaleur : 26 dernières semaines d'ajouts --------------605 heat_from = max(cov_min, today - timedelta(days=181))606 heat_cells = [{"date": d, "value": n} for d, n in sorted(starts.items())607 if d >= heat_from.isoformat()]608 heatmap = ({"title": "Nouvelles annonces par jour (26 dernières semaines)",609 "cells": heat_cells} if heat_cells else None)610611 # ---- heatmap horaire 7×24 : heure d'observation des ajouts ---------------612 hourly = None613 hour_rows = con.execute(614 """SELECT CAST(strftime('%w', first_seen,'unixepoch','localtime') AS INT) w,615 CAST(strftime('%H', first_seen,'unixepoch','localtime') AS INT) h,616 COUNT(*) n617 FROM listings WHERE dup_of IS NULL AND first_seen>=? AND first_seen<?618 GROUP BY w, h""", (ts_from, ts_to)).fetchall()619 if hour_rows:620 cells = [{"dow": (r["w"] + 6) % 7, "hour": r["h"], "value": r["n"]}621 for r in hour_rows] # %w : 0=dim → contrat : 0=lun622 hourly = {"title": "Ajouts d'annonces par heure (période)",623 "cells": cells}624625 # ---- tableaux ----------------------------------------------------------626 tables = []627 top_villes = con.execute(628 """SELECT city, COUNT(*) n, AVG(CASE WHEN price BETWEEN ? AND ? THEN price END) avg_p,629 SUM(CASE WHEN first_seen>=? AND first_seen<? THEN 1 ELSE 0 END) new_n630 FROM listings WHERE active=1 AND dup_of IS NULL AND city<>''631 GROUP BY city ORDER BY n DESC LIMIT 50""",632 (PRIX_MIN, PRIX_MAX, ts_from, ts_to)).fetchall()633 removed_by_city = {r["city"]: r["n"] for r in con.execute(634 """SELECT city, COUNT(*) n FROM listings635 WHERE active=0 AND dup_of IS NULL AND city<>''636 AND last_seen>=? AND last_seen<? GROUP BY city""",637 (ts_from, ts_to)).fetchall()}638639 def _city_median(city: str) -> float | None:640 r = con.execute(641 "SELECT COUNT(*) n FROM listings WHERE active=1 AND dup_of IS NULL"642 " AND city=? AND price BETWEEN ? AND ?",643 (city, PRIX_MIN, PRIX_MAX)).fetchone()644 if not r["n"]:645 return None646 return con.execute(647 "SELECT price FROM listings WHERE active=1 AND dup_of IS NULL"648 " AND city=? AND price BETWEEN ? AND ? ORDER BY price"649 " LIMIT 1 OFFSET ?",650 (city, PRIX_MIN, PRIX_MAX, r["n"] // 2)).fetchone()["price"]651652 city_medians: dict[str, float] = {}653 if top_villes:654 rows = []655 for r in top_villes:656 med = _city_median(r["city"])657 if med is not None:658 city_medians[r["city"]] = med659 net = r["new_n"] - removed_by_city.get(r["city"], 0)660 rows.append([661 r["city"], r["n"],662 _fr_money(r["avg_p"]) if r["avg_p"] else "—",663 _fr_money(med) if med is not None else "—",664 r["new_n"], f"{'+' if net >= 0 else ''}{net}"])665 tables.append({"id": "top_villes", "title": "Top villes",666 "columns": ["Ville", "Annonces actives", "Loyer moyen",667 "Loyer médian", "Nouvelles (période)",668 "Δ net (période)"],669 "rows": rows})670671 # loyers par taille de logement (moyenne, médiane, P10–P90)672 type_rows = con.execute(673 """SELECT COALESCE(NULLIF(unit_type,''),'Non précisé') t, COUNT(*) n,674 AVG(price) avg_p FROM listings675 WHERE active=1 AND dup_of IS NULL AND price BETWEEN ? AND ?676 GROUP BY t ORDER BY n DESC LIMIT 12""",677 (PRIX_MIN, PRIX_MAX)).fetchall()678 if type_rows:679 rows = []680 for r in type_rows:681 prices = sorted(x["price"] for x in con.execute(682 """SELECT price FROM listings WHERE active=1 AND dup_of IS NULL683 AND COALESCE(NULLIF(unit_type,''),'Non précisé')=?684 AND price BETWEEN ? AND ?""",685 (r["t"], PRIX_MIN, PRIX_MAX)))686 med = _pctile(prices, 0.5)687 p10 = _pctile(prices, 0.10)688 p90 = _pctile(prices, 0.90)689 rows.append([690 r["t"], r["n"], _fr_money(r["avg_p"]),691 _fr_money(med) if med is not None else "—",692 f"{_fr_money(p10)} – {_fr_money(p90)}"693 if p10 is not None and p90 is not None else "—"])694 tables.append({"id": "loyers_taille",695 "title": "Loyers par taille de logement (actives)",696 "columns": ["Taille", "Annonces avec loyer",697 "Loyer moyen", "Loyer médian",698 "Fourchette P10–P90"],699 "rows": rows})700701 top_srcs = con.execute(702 """SELECT source s, COUNT(*) n, AVG(CASE WHEN price BETWEEN ? AND ? THEN price END) avg_p,703 SUM(CASE WHEN first_seen>=? AND first_seen<? THEN 1 ELSE 0 END) new_n,704 ROUND(AVG(completeness),0) comp, SUM(published=0) quar705 FROM listings WHERE active=1 AND dup_of IS NULL706 GROUP BY source ORDER BY n DESC LIMIT 50""",707 (PRIX_MIN, PRIX_MAX, ts_from, ts_to)).fetchall()708 last_sync = {r["source"]: r["ts"] for r in con.execute(709 "SELECT source, MAX(ts) ts FROM sync_log WHERE ok=1 GROUP BY source")}710 if top_srcs:711 rows = []712 for r in top_srcs:713 ls = last_sync.get(r["s"])714 rows.append([715 names.get(r["s"], r["s"]), r["n"],716 _fr_money(r["avg_p"]) if r["avg_p"] else "—",717 r["new_n"],718 f"{r['comp']:.0f} %" if r["comp"] is not None else "—",719 r["quar"] or 0,720 datetime.fromtimestamp(ls, TZ).strftime("%Y-%m-%d %H:%M") if ls else "—"])721 tables.append({"id": "top_gestionnaires",722 "title": "Top gestionnaires & sources",723 "columns": ["Gestionnaire / source", "Annonces actives",724 "Loyer moyen", "Nouvelles (période)",725 "Complétude", "Quarantaine",726 "Dernière synchro"],727 "rows": rows})728729 # écart moyen au marché par ville (villes à volume suffisant)730 if fv_ok:731 fv_villes = con.execute(732 """SELECT l.city, COUNT(*) n, ROUND(AVG(f.deviation)*100,1) dev,733 SUM(f.verdict='sous') sous734 FROM fairvalue f JOIN listings l USING (uid)735 WHERE l.active=1 AND l.published=1 AND l.dup_of IS NULL736 AND f.verdict IS NOT NULL AND l.city<>''737 GROUP BY l.city HAVING n>=50 ORDER BY n DESC LIMIT 25""").fetchall()738 if fv_villes:739 tables.append({740 "id": "fv_villes", "title": "Écart au marché par ville (fair value)",741 "columns": ["Ville", "Annonces évaluées", "Écart moyen",742 "Sous le marché"],743 "rows": [[r["city"], r["n"],744 f"{'+' if r['dev'] >= 0 else ''}{r['dev']} %",745 r["sous"] or 0] for r in fv_villes]})746747 # baisses de loyer observées dans la période (journal de prix, plausibles)748 drops = con.execute(749 """SELECT a.uid uid, MAX(a.price-b.price) dp, a.price p0, b.price p1,750 b.ts ts1751 FROM price_log a JOIN price_log b752 ON a.uid=b.uid AND b.ts>a.ts753 AND a.price BETWEEN ? AND ? AND b.price BETWEEN ? AND ?754 AND b.price<a.price AND b.price>=a.price*0.5755 WHERE a.ts>=? AND b.ts<?756 GROUP BY a.uid ORDER BY dp DESC LIMIT 15""",757 (PRIX_MIN, PRIX_MAX, PRIX_MIN, PRIX_MAX, ts_from, ts_to)).fetchall()758 if drops:759 rows = []760 for r in drops:761 li = con.execute(762 "SELECT city, unit_type FROM listings WHERE uid=?",763 (r["uid"],)).fetchone()764 what = " · ".join(x for x in [li["unit_type"], li["city"]]765 if x) if li else r["uid"]766 rows.append([767 what or r["uid"], _fr_money(r["p0"]), _fr_money(r["p1"]),768 f"−{_fr_money(r['dp'])}",769 f"{round(100.0 * r['dp'] / r['p0'], 1)} %",770 datetime.fromtimestamp(r["ts1"], TZ).date().isoformat()])771 tables.append({"id": "baisses_loyer",772 "title": "Plus fortes baisses de loyer (période)",773 "columns": ["Logement", "Ancien loyer", "Nouveau loyer",774 "Baisse", "Baisse %", "Observée le"],775 "rows": rows})776777 # ---- records & faits marquants -----------------------------------------778 records = []779 in_period = {d: n for d, n in starts.items()780 if d_from.isoformat() <= d <= d_to.isoformat()}781 if in_period:782 best = max(in_period, key=in_period.get)783 records.append({"label": "Jour record d'ajouts",784 "value": _fr_int(in_period[best]) + " annonces",785 "date": best})786 rem_period = {d: n for d, n in ends.items()787 if d_from.isoformat() <= d <= d_to.isoformat()}788 if rem_period:789 worst = max(rem_period, key=rem_period.get)790 records.append({"label": "Jour record de retraits",791 "value": _fr_int(rem_period[worst]) + " annonces",792 "date": worst})793 if top_villes:794 ville = max(top_villes, key=lambda r: r["new_n"])795 if ville["new_n"]:796 records.append({"label": "Ville la plus dynamique (nouvelles annonces)",797 "value": f"{ville['city']} — {ville['new_n']}"})798 # villes la plus chère / la plus abordable (loyer médian, volume suffisant)799 big_meds = {c: m for c, m in city_medians.items()800 if next((r["n"] for r in top_villes if r["city"] == c), 0) >= 100}801 if big_meds:802 chere = max(big_meds, key=big_meds.get)803 abordable = min(big_meds, key=big_meds.get)804 records.append({"label": "Ville la plus chère (loyer médian, ≥ 100 annonces)",805 "value": f"{chere} — {_fr_money(big_meds[chere])}"})806 if abordable != chere:807 records.append({"label": "Ville la plus abordable (loyer médian, ≥ 100 annonces)",808 "value": f"{abordable} — {_fr_money(big_meds[abordable])}"})809 if types and types[0]["label"] != "Non précisé":810 records.append({"label": "Taille la plus offerte",811 "value": f"{types[0]['label']} — "812 f"{_fr_int(types[0]['value'])} annonces"})813 # plus forte baisse de loyer observée dans la période (journal de prix)814 if drops:815 d0 = drops[0]816 li = con.execute("SELECT city, unit_type FROM listings WHERE uid=?",817 (d0["uid"],)).fetchone()818 where = " · ".join(x for x in [li["unit_type"], li["city"]] if x) if li else ""819 records.append({820 "label": "Plus forte baisse de loyer observée"821 + (f" ({where})" if where else ""),822 "value": f"−{_fr_money(d0['dp'])}"823 f" ({_fr_money(d0['p0'])} → {_fr_money(d0['p1'])})",824 "date": datetime.fromtimestamp(d0["ts1"], TZ).date().isoformat()})825 # plus forte hausse de loyer observée (plausible : ≤ ×2)826 hike = con.execute(827 """SELECT a.uid uid, MAX(b.price-a.price) dp, a.price p0, b.price p1,828 b.ts ts1829 FROM price_log a JOIN price_log b830 ON a.uid=b.uid AND b.ts>a.ts831 AND a.price BETWEEN ? AND ? AND b.price BETWEEN ? AND ?832 AND b.price>a.price AND b.price<=a.price*2833 WHERE a.ts>=? AND b.ts<? LIMIT 1""",834 (PRIX_MIN, PRIX_MAX, PRIX_MIN, PRIX_MAX, ts_from, ts_to)).fetchone()835 if hike and hike["dp"]:836 li = con.execute("SELECT city, unit_type FROM listings WHERE uid=?",837 (hike["uid"],)).fetchone()838 where = " · ".join(x for x in [li["unit_type"], li["city"]] if x) if li else ""839 records.append({840 "label": "Plus forte hausse de loyer observée"841 + (f" ({where})" if where else ""),842 "value": f"+{_fr_money(hike['dp'])}"843 f" ({_fr_money(hike['p0'])} → {_fr_money(hike['p1'])})",844 "date": datetime.fromtimestamp(hike["ts1"], TZ).date().isoformat()})845 if hourly:846 peak = max(hourly["cells"], key=lambda c: c["value"])847 records.append({"label": "Heure de pointe des ajouts (période)",848 "value": f"{DOW_FR[peak['dow']]} {peak['hour']} h — "849 f"{_fr_int(peak['value'])} annonces"})850 if top_srcs:851 src = max(top_srcs, key=lambda r: r["new_n"])852 if src["new_n"]:853 records.append({"label": "Source la plus active (nouvelles annonces)",854 "value": f"{names.get(src['s'], src['s'])} — {src['new_n']}"})855856 out = {857 "updated": datetime.now(TZ).isoformat(),858 "period": {"from": d_from.isoformat(), "to": d_to.isoformat(),859 "label": label},860 "kpis": kpis,861 "series": series,862 "breakdowns": breakdowns,863 "tables": tables,864 "records": records,865 }866 if gauges:867 out["gauges"] = gauges868 if multiseries:869 out["multiseries"] = multiseries870 if stacked:871 out["stacked"] = stacked872 if distributions:873 out["distributions"] = distributions874 if geo:875 out["geo"] = geo876 if heatmap:877 out["heatmap"] = heatmap878 if hourly:879 out["hourly"] = hourly880 try:881 from . import statsextra, statsfiche882 pnls = statsfiche.panels(con) + statsextra.panels(con)883 if pnls:884 out["panels"] = pnls885 except Exception:886 pass887 return out888