SPB Git

Repository Public

build-marche-stats.mjs 11.6 KB 287 lines javascript

1/**2 * =============================================================================3 *                  SP BOUCHER | SOFTWARE & RESEARCH4 *             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5 * =============================================================================6 *7 * Project          : Vrai-Prix8 * File             : scripts/build-marche-stats.mjs9 * Module           : scripts10 * Repository       : https://git.spboucher.ai/vrai-prix11 * Created          : 2026-09-0812 * Last Modified    : 2026-09-0813 *14 * Author           : Simon-Pierre Boucher15 * Position         : Professor of Finance16 * Institution      : Université du Québec en Outaouais (UQO)17 * Organization     : SP Boucher18 * Website          : https://spboucher.ai19 * Git              : https://git.spboucher.ai20 *21 * Preferred Contact: contact@spboucher.ai22 * Development      : dev@spboucher.ai23 * Support          : support@spboucher.ai24 * Security/Admin   : admin@spboucher.ai25 *26 * Copyright (c) 202627 * Simon-Pierre Boucher28 * All rights reserved where applicable. This file is governed by the29 * applicable project license, copyright notices and relevant law.30 * Existing third-party rights and notices remain unaffected.31 *32 * License          : None specified (no license file in this repository)33 *34 * Do not embed credentials, private keys, access tokens,35 * certificates or confidential personal information.36 *37 * =============================================================================38 * END OF SP BOUCHER SOURCE HEADER39 * =============================================================================40 */4142/**43 * scripts/build-marche-stats.mjs — fusion des shards d'évaluation Immo-Ka44 * (tmp/eval-shards/*.jsonl, produits par scripts/eval-immoka.ts) :45 *   1. écrit la table `vp_eval` dans data/immoka.db (le « merge » annonce ↔46 *      estimation Vrai-Prix, requêtable en SQL) ;47 *   2. calcule src/data/marche-stats.json — performance de la mesure face aux48 *      prix demandés du marché actif, servi par /stats/marche.49 * Données 100 % réelles — aucune valeur inventée. À relancer quand la copie50 * d'immoka.db ou le moteur change.51 */52import Database from "better-sqlite3";53import { readdirSync, readFileSync, writeFileSync } from "fs";54import path from "path";5556const IMMOKA_DB = process.env.IMMOKA_DB ?? path.join(process.cwd(), "data", "immoka.db");57const SHARD_DIR = path.join(process.cwd(), "tmp", "eval-shards");5859/* ---------------- 1. fusion des shards → table vp_eval ---------------- */60const files = readdirSync(SHARD_DIR).filter((f) => f.endsWith(".jsonl"));61if (!files.length) throw new Error(`aucun shard dans ${SHARD_DIR}`);62const rows = files.flatMap((f) =>63  readFileSync(path.join(SHARD_DIR, f), "utf8")64    .split("\n")65    .filter(Boolean)66    .map((l) => JSON.parse(l))67);68console.log(`${rows.length} évaluations lues (${files.length} shards)`);6970const db = new Database(IMMOKA_DB);71db.pragma("journal_mode = WAL");72db.exec(`73  DROP TABLE IF EXISTS vp_eval;74  CREATE TABLE vp_eval (75    uid TEXT PRIMARY KEY,          -- listings.uid (annonce Immo-Ka)76    unit_id TEXT,                  -- units.id_provinc (rôle MAMH)77    match_m REAL,                  -- distance du jumelage spatial lat/lng (m)78    price REAL,                    -- prix demandé au moment de la copie79    est REAL, low REAL, high REAL, -- estimation Vrai-Prix + P10-P9080    confidence_pct REAL, confidence TEXT,81    model_est REAL, comps_est REAL, model_weight REAL, n_comps INTEGER,82    cost_est REAL,                 -- méthode du coût calibrée (terrain + bâtiment déprécié)83    role_est REAL,                 -- méthode du rôle indexé (ratios de vente IAAO)84    ens_est REAL,                  -- ensemble : médiane (hybride, coût, rôle indexé)85    valeur_role REAL, type_prop TEXT, municipalite TEXT,86    ratio REAL,                    -- est / prix demandé87    diff REAL,                     -- prix demandé − est ($)88    evaluated_at TEXT89  );90`);91const ins = db.prepare(`92  INSERT OR REPLACE INTO vp_eval VALUES93  (@uid,@unit_id,@match_m,@price,@est,@low,@high,@cpct,@clevel,@model,@comps,@mw,@ncomps,94   @cost,@ridx,@ens,@role,@type,@muni,@ratio,@diff,@at)`);95const at = new Date().toISOString().slice(0, 10);96db.transaction(() => {97  for (const r of rows)98    ins.run({99      ...r,100      ratio: r.price > 0 && r.est > 0 ? r.est / r.price : null,101      diff: r.est > 0 ? r.price - r.est : null,102      at,103    });104})();105console.log("table vp_eval écrite dans", IMMOKA_DB);106107/* ---------------- 2. agrégats → src/data/marche-stats.json ---------------- */108const median = (xs) => {109  if (!xs.length) return null;110  const s = [...xs].sort((a, b) => a - b);111  const m = Math.floor(s.length / 2);112  return s.length % 2 ? s[m] : (s[m - 1] + s[m]) / 2;113};114const r4 = (v) => (v == null ? null : Math.round(v * 10000) / 10000);115116// univers : annonces résidentielles plausibles (≥ 50 000 $, même seuil que les117// ventes retenues par le moteur) avec estimation positive118const val = db119  .prepare(120    `SELECT e.uid, e.price, e.est, e.low, e.high, e.confidence AS lvl, e.n_comps,121            e.match_m, e.model_est, e.comps_est, e.cost_est, e.role_est, e.ens_est,122            e.valeur_role, e.type_prop, l.region, l.city,123            l.property_type, l.bedrooms124     FROM vp_eval e JOIN listings l ON l.uid = e.uid125     WHERE e.price >= 50000 AND e.est > 0`126  )127  .all();128129const totalListings = db130  .prepare(131    `SELECT COUNT(*) AS n FROM listings132     WHERE status='a-vendre' AND published=1 AND active=1 AND dup_hidden=0 AND price>0`133  )134  .get().n;135const geolocated = db136  .prepare(137    `SELECT COUNT(*) AS n FROM listings138     WHERE status='a-vendre' AND published=1 AND active=1 AND dup_hidden=0 AND price>0139       AND lat IS NOT NULL AND lng IS NOT NULL`140  )141  .get().n;142143const stats = (subset) => {144  const ratios = subset.map((r) => r.est / r.price);145  const apes = subset.map((r) => Math.abs(r.est - r.price) / r.price);146  const diffs = subset.map((r) => r.price - r.est).sort((a, b) => a - b);147  const q = (p) => (diffs.length ? diffs[Math.min(diffs.length - 1, Math.floor(p * diffs.length))] : null);148  const inRange = subset.filter((r) => r.price >= r.low && r.price <= r.high).length;149  return {150    n: subset.length,151    medianRatio: r4(median(ratios)),152    mdape: r4(median(apes)),153    within10: r4(apes.filter((a) => a <= 0.1).length / (apes.length || 1)),154    within20: r4(apes.filter((a) => a <= 0.2).length / (apes.length || 1)),155    askAbove: r4(subset.filter((r) => r.price > r.est).length / (subset.length || 1)),156    inP10P90: r4(inRange / (subset.length || 1)),157    medianAsk: median(subset.map((r) => r.price)),158    medianEst: median(subset.map((r) => r.est)),159    // écart prix demandé − estimation : la « prime d'affichage » mesurée160    medianDiff: median(diffs) == null ? null : Math.round(median(diffs)),161    medianDiffPct: r4(median(subset.map((r) => (r.price - r.est) / r.est))),162    p25Diff: q(0.25) == null ? null : Math.round(q(0.25)),163    p75Diff: q(0.75) == null ? null : Math.round(q(0.75)),164  };165};166167// clés géographiques : les sources d'Immo-Ka mélangent accents et graphies168// (« Montreal » / « Montréal ») et laissent parfois la région vide → on groupe169// sur une clé pliée (minuscules sans accents) et on affiche la graphie la plus170// fréquente ; les vides sont exclus.171const fold = (s) =>172  s173    .normalize("NFD")174    .replace(/[\u0300-\u036f]/g, "")175    .toLowerCase()176    .trim();177const groupBy = (key, { normalize = false } = {}) => {178  const m = new Map();179  for (const r of val) {180    const raw = (r[key] ?? "").toString().trim();181    if (normalize && !raw) continue;182    const k = normalize ? fold(raw) : raw || "?";183    if (!m.has(k)) m.set(k, { rows: [], labels: new Map() });184    const g = m.get(k);185    g.rows.push(r);186    g.labels.set(raw, (g.labels.get(raw) ?? 0) + 1);187  }188  return [...m.values()]189    .filter((g) => g.rows.length >= 30)190    .sort((a, b) => b.rows.length - a.rows.length)191    .map((g) => ({192      key: [...g.labels.entries()].sort((a, b) => b[1] - a[1])[0][0],193      ...stats(g.rows),194    }));195};196197// histogramme du ratio estimation / prix demandé (pas de 5 %, queues groupées)198const hist = [];199for (let lo = 0.5; lo < 1.5 - 1e-9; lo += 0.05) hist.push({ lo: r4(lo), hi: r4(lo + 0.05), n: 0 });200let below = 0,201  above = 0;202for (const r of val) {203  const q = r.est / r.price;204  if (q < 0.5) below++;205  else if (q >= 1.5) above++;206  else hist[Math.min(hist.length - 1, Math.floor((q - 0.5) / 0.05))].n++;207}208209// tranches de prix demandé210const brackets = [211  [0, 300000, "<300k"],212  [300000, 500000, "300-500k"],213  [500000, 750000, "500-750k"],214  [750000, 1000000, "750k-1M"],215  [1000000, Infinity, ">1M"],216].map(([lo, hi, label]) => ({217  key: label,218  ...stats(val.filter((r) => r.price >= lo && r.price < hi)),219}));220221// nuage prix demandé × estimation (échantillon stable pour le graphique)222const step = Math.max(1, Math.floor(val.length / 1500));223const scatter = val224  .filter((_, i) => i % step === 0)225  .map((r) => ({ p: Math.round(r.price), e: Math.round(r.est), l: r.lvl }));226227// duel des méthodes — la mesure principale reste l'hybride 65/35 ; les autres228// (hédonique pur, comparables purs, coût calibré, rôle indexé, ensemble) sont229// évaluées sur le même univers, chacune là où elle est disponible230const methodStats = (field) => {231  const sub = val.filter((r) => r[field] != null && r[field] > 0);232  const ratios = sub.map((r) => r[field] / r.price);233  const apes = sub.map((r) => Math.abs(r[field] - r.price) / r.price);234  return {235    n: sub.length,236    coverage: r4(sub.length / (val.length || 1)),237    medianRatio: r4(median(ratios)),238    mdape: r4(median(apes)),239    within10: r4(apes.filter((a) => a <= 0.1).length / (apes.length || 1)),240    within20: r4(apes.filter((a) => a <= 0.2).length / (apes.length || 1)),241    medianDiff: sub.length ? Math.round(median(sub.map((r) => r.price - r[field]))) : null,242  };243};244const methods = [245  { key: "hybride", field: "est", main: true },246  { key: "hedonique", field: "model_est", main: false },247  { key: "comparables", field: "comps_est", main: false },248  { key: "cout", field: "cost_est", main: false },249  { key: "role_indexe", field: "role_est", main: false },250  { key: "ensemble", field: "ens_est", main: false },251].map((m) => ({ key: m.key, main: m.main, ...methodStats(m.field) }));252253const out = {254  generated: new Date().toISOString(),255  source: {256    app: "annonces publiques",257    copiedAt: at,258    totalListings,259    geolocated,260    evaluated: rows.length,261    valid: val.length,262    matchMedianM: r4(median(val.map((r) => r.match_m).filter((v) => v != null))),263  },264  global: stats(val),265  methods,266  byConfidence: ["A", "B", "C", "D"].map((lvl) => ({267    key: lvl,268    ...stats(val.filter((r) => r.lvl === lvl)),269  })),270  // type côté annonce (Maison/Condo/…) : plus parlant que le type du rôle —271  // beaucoup de condos sont classés « unifamilial » dans le rôle MAMH.272  byType: groupBy("property_type", { normalize: true }).slice(0, 10),273  byRegion: groupBy("region", { normalize: true })274    .filter((g) => !/^\d+$/.test(g.key)) // certaines sources donnent le code de région, pas le nom275    .slice(0, 18),276  byCity: groupBy("city", { normalize: true }).slice(0, 15),277  byBracket: brackets,278  histogram: { below, above, bins: hist },279  scatter,280};281// Destination : src/data/marche-stats.json (instantané versionné, secours du site)282// ou MARCHE_STATS_OUT (ex. data/marche-stats.json, lu à chaud par src/lib/marche-stats.ts283// lors du rafraîchissement nocturne — évite tout rebuild et toute dérive git).284const dest = process.env.MARCHE_STATS_OUT ?? path.join(process.cwd(), "src", "data", "marche-stats.json");285writeFileSync(dest, JSON.stringify(out));286console.log(`écrit ${dest} — global :`, out.global);287
Files main
Menu

Theme