SPB Git

Repository Public

estimator.ts 13.5 KB 442 lines typescript

1/**2 * =============================================================================3 *                  SP BOUCHER | SOFTWARE & RESEARCH4 *             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5 * =============================================================================6 *7 * Project          : Vrai-Prix8 * File             : src/lib/estimator.ts9 * Module           : lib10 * Repository       : https://git.spboucher.ai/vrai-prix11 * Created          : 2026-08-0912 * 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// Auteur : Simon-Pierre Boucher — contact@spboucher.ai43// Service d'estimation : relie la base SQLite au moteur (engine.ts).44import {45  getCandidates,46  getMarketIndex,47  getUnit,48  municipalityCenter,49  municipalityPercentile,50  type TxRow,51  type UnitRow,52} from "./db";53import {54  estimate,55  haversineM,56  type CompInput,57  type EstimateResult,58  type Subject,59} from "./engine";6061export interface UnitSpecs {62  cubf: number | null;63  cubfLibelle: string | null;64  anneeEstimee: string | null;65  frontTerrainM: number | null;66  nbEtages: number | null;67  nbLocauxNonResid: number | null;68  nbChambresLocatives: number | null;69  lienPhysique: string | null;70  genreConstruction: string | null;71  matricule: string | null;72  uniteVoisinage: string | null;73  nAdresses: number | null;74  datCondMarche: string | null;75  valeurTerrain: number | null;76  valeurBatiment: number | null;77  valeurAnterieure: number | null;78  arrond: string | null;79  apt: string | null;80}8182/** Ventes réelles des 12 derniers mois autour du sujet (rayon adaptatif). */83export interface SectorStats {84  nSales12m: number;85  medianPrice: number | null;86  medianPpm2: number | null;87  radiusKm: number;88}8990/** Contexte marché affiché avec l'estimation — même transparence que le calcul. */91export interface MarketContext {92  /** Type de propriété du sujet (clé i18n). */93  typeProp: string;94  /** Indice de marché mensuel du type (1.0 = niveau courant). */95  index: { month: string; idx: number }[];96  index12mPct: number | null;97  indexSince2021Pct: number | null;98  sector: SectorStats | null;99  /** % des propriétés de la municipalité valant moins que le sujet. */100  muniPercentile: number | null;101  muniTotal: number | null;102}103104export interface UnitEstimate {105  unit: {106    id: string;107    adresse: string | null;108    municipalite: string | null;109    typeProp: string;110    cubfLibelle: string | null;111    anneeConstruction: number | null;112    aireEtagesM2: number | null;113    superficieTerrainM2: number | null;114    nbLogements: number | null;115    valeurRole: number | null;116    lat: number;117    lng: number;118    history: { year: number; value: number | null }[];119    specs: UnitSpecs;120  } | null;121  result: EstimateResult;122  context?: MarketContext;123}124125/** Type de comparable attendu pour le type de tx du marché de l'indice. */126export function indexType(typeProp: string): string {127  if (typeProp === "condo_ou_multi") return "condo";128  if (typeProp === "plex") return "plex";129  return "unifamilial";130}131132export function toComps(rows: TxRow[]): CompInput[] {133  return rows.map((r) => ({134    id: r.id,135    date: r.date,136    amount: r.amount,137    lat: r.lat,138    lng: r.lng,139    propertyType: r.property_type,140    yearBuilt: r.year_built,141    floorArea: r.floor_area,142    street: r.street,143    city: r.city,144  }));145}146147function nowISO(): string {148  return new Date().toISOString().slice(0, 10);149}150151function since(months: number): string {152  const d = new Date();153  d.setMonth(d.getMonth() - months);154  return d.toISOString().slice(0, 10);155}156157export function candidatesAround(lat: number, lng: number): TxRow[] {158  // ~2,2 km puis élargit à ~11 km si marché mince159  for (const halfDeg of [0.02, 0.1]) {160    const rows = getCandidates(lat, lng, halfDeg, since(30), 600);161    if (rows.length >= 30) return rows;162  }163  return getCandidates(lat, lng, 0.25, since(36), 600);164}165166function median(xs: number[]): number | null {167  if (!xs.length) return null;168  const s = [...xs].sort((a, b) => a - b);169  const m = Math.floor(s.length / 2);170  return s.length % 2 ? s[m] : (s[m - 1] + s[m]) / 2;171}172173/** Stats du secteur à partir des candidats déjà chargés (aucune requête en plus). */174function sectorStats(lat: number, lng: number, rows: TxRow[]): SectorStats | null {175  const cutoff = since(12);176  const recent = rows.filter((r) => r.date >= cutoff);177  for (const radiusKm of [2, 5, 10]) {178    const within = recent.filter(179      (r) => haversineM(lat, lng, r.lat, r.lng) <= radiusKm * 1000180    );181    if (within.length >= 8 || radiusKm === 10) {182      if (within.length === 0) return null;183      return {184        nSales12m: within.length,185        medianPrice: median(within.map((r) => r.amount)),186        medianPpm2: median(187          within188            .filter((r) => r.floor_area != null && r.floor_area > 20)189            .map((r) => r.amount / r.floor_area!)190        ),191        radiusKm,192      };193    }194  }195  return null;196}197198function buildContext(199  typeProp: string,200  lat: number,201  lng: number,202  candidates: TxRow[],203  index: { month: string; idx: number }[],204  municipalite: string | null,205  estimateValue: number206): MarketContext {207  const last = index.length ? index[index.length - 1].idx : null;208  const yearAgo = index.length >= 13 ? index[index.length - 13].idx : null;209  const first = index.length >= 2 ? index[0].idx : null;210  const pr =211    municipalite && Number.isFinite(estimateValue) && estimateValue > 0212      ? municipalityPercentile(municipalite, estimateValue)213      : null;214  return {215    typeProp,216    index,217    index12mPct:218      last != null && yearAgo != null && yearAgo > 0219        ? (last / yearAgo - 1) * 100220        : null,221    indexSince2021Pct:222      last != null && first != null && first > 0 ? (last / first - 1) * 100 : null,223    sector: sectorStats(lat, lng, candidates),224    muniPercentile: pr ? (pr.below / pr.total) * 100 : null,225    muniTotal: pr ? pr.total : null,226  };227}228229export function estimateByUnitId(id: string): UnitEstimate | null {230  const u = getUnit(id);231  if (!u) return null;232  const subject: Subject = {233    lat: u.lat,234    lng: u.lng,235    typeProp: u.type_prop,236    floorArea: u.aire_etages_m2,237    yearBuilt: u.annee_construction,238    landArea: u.superficie_terrain_m2,239    modelEstimate: u.est_2026,240    modelP10: u.p10,241    modelP90: u.p90,242  };243  const candidates = candidatesAround(u.lat, u.lng);244  const index = getMarketIndex(indexType(u.type_prop));245  const result = estimate(subject, toComps(candidates), index, nowISO());246  const context = buildContext(247    u.type_prop,248    u.lat,249    u.lng,250    candidates,251    index,252    u.municipalite,253    result.estimate254  );255  return {256    context,257    unit: {258      id: u.id_provinc,259      adresse: u.adresse,260      municipalite: u.municipalite,261      typeProp: u.type_prop,262      cubfLibelle: u.cubf_libelle,263      anneeConstruction: u.annee_construction,264      aireEtagesM2: u.aire_etages_m2,265      superficieTerrainM2: u.superficie_terrain_m2,266      nbLogements: u.nb_logements,267      valeurRole: u.valeur_role,268      lat: u.lat,269      lng: u.lng,270      history: ([2021, 2022, 2023, 2024, 2025, 2026] as const).map((y) => ({271        year: y,272        value: u[`est_${y}` as keyof UnitRow] as number | null,273      })),274      specs: {275        cubf: u.cubf,276        cubfLibelle: u.cubf_libelle,277        anneeEstimee: u.annee_estimee,278        frontTerrainM: u.front_terrain_m,279        nbEtages: u.nb_etages,280        nbLocauxNonResid: u.nb_locaux_non_resid,281        nbChambresLocatives: u.nb_chambres_locatives,282        lienPhysique: u.lien_physique,283        genreConstruction: u.genre_construction,284        matricule: u.matricule,285        uniteVoisinage: u.unite_voisinage,286        nAdresses: u.n_adresses,287        datCondMarche: u.dat_cond_marche,288        valeurTerrain: u.valeur_terrain,289        valeurBatiment: u.valeur_batiment,290        valeurAnterieure: u.valeur_anterieure,291        arrond: u.arrond,292        apt: u.apt,293      },294    },295    result,296  };297}298299export interface PortfolioAggregates {300  count: number;301  totalEstimate: number;302  totalLow: number;303  totalHigh: number;304  totalRole: number;305  ecartRolePct: number | null;306  confidencePct: number; // moyenne pondérée par valeur307  confidenceLevel: "A" | "B" | "C" | "D";308  totalFloorArea: number;309  totalLandArea: number;310  totalDwellings: number;311  avgYearBuilt: number | null;312  municipalities: { name: string; count: number; total: number }[];313  types: { type: string; count: number; total: number }[];314  history: { year: number; total: number; nCovered: number }[];315  growthPct: number | null; // croissance du parc 2021→2026 (unités couvertes)316}317318export interface PortfolioResult {319  items: UnitEstimate[];320  aggregates: PortfolioAggregates;321}322323export function estimatePortfolio(ids: string[]): PortfolioResult {324  const items = ids325    .slice(0, 40)326    .map((id) => estimateByUnitId(id))327    .filter((x): x is UnitEstimate => x !== null && x.unit !== null);328329  const val = (n: number | null | undefined) => n ?? 0;330  const totalEstimate = items.reduce((s, i) => s + val(i.result.estimate), 0);331  const totalRole = items.reduce((s, i) => s + val(i.unit!.valeurRole), 0);332  const wConf =333    totalEstimate > 0334      ? items.reduce((s, i) => s + i.result.confidencePct * val(i.result.estimate), 0) /335        totalEstimate336      : 0;337  const level = wConf >= 75 ? "A" : wConf >= 60 ? "B" : wConf >= 45 ? "C" : "D";338339  const byKey = (key: (i: UnitEstimate) => string) => {340    const m = new Map<string, { count: number; total: number }>();341    for (const i of items) {342      const k = key(i);343      const e = m.get(k) ?? { count: 0, total: 0 };344      e.count += 1;345      e.total += val(i.result.estimate);346      m.set(k, e);347    }348    return [...m.entries()]349      .map(([name, v]) => ({ name, ...v }))350      .sort((a, b) => b.total - a.total);351  };352353  const years = [2021, 2022, 2023, 2024, 2025, 2026] as const;354  const history = years.map((y) => {355    let total = 0;356    let n = 0;357    for (const i of items) {358      const h = i.unit!.history.find((hh) => hh.year === y);359      if (h?.value != null) {360        total += h.value;361        n += 1;362      }363    }364    return { year: y, total, nCovered: n };365  });366  // croissance : somme 2026 vs 2021 sur les unités couvertes aux deux bornes367  let g21 = 0;368  let g26 = 0;369  for (const i of items) {370    const a = i.unit!.history.find((h) => h.year === 2021)?.value;371    const b = i.unit!.history.find((h) => h.year === 2026)?.value;372    if (a != null && b != null) {373      g21 += a;374      g26 += b;375    }376  }377378  const yb = items379    .map((i) => i.unit!.anneeConstruction)380    .filter((v): v is number => v != null && v > 1600);381382  return {383    items,384    aggregates: {385      count: items.length,386      totalEstimate,387      totalLow: items.reduce((s, i) => s + val(i.result.low), 0),388      totalHigh: items.reduce((s, i) => s + val(i.result.high), 0),389      totalRole,390      ecartRolePct: totalRole > 0 ? (totalEstimate / totalRole - 1) * 100 : null,391      confidencePct: Math.round(wConf),392      confidenceLevel: level,393      totalFloorArea: Math.round(items.reduce((s, i) => s + val(i.unit!.aireEtagesM2), 0)),394      totalLandArea: Math.round(items.reduce((s, i) => s + val(i.unit!.superficieTerrainM2), 0)),395      totalDwellings: items.reduce((s, i) => s + val(i.unit!.nbLogements), 0),396      avgYearBuilt: yb.length ? Math.round(yb.reduce((s, v) => s + v, 0) / yb.length) : null,397      municipalities: byKey((i) => i.unit!.municipalite ?? "—"),398      types: byKey((i) => i.unit!.typeProp).map(({ name, ...v }) => ({ type: name, ...v })),399      history,400      growthPct: g21 > 0 ? (g26 / g21 - 1) * 100 : null,401    },402  };403}404405export interface ManualParams {406  municipality: string;407  typeProp: string;408  floorArea?: number;409  yearBuilt?: number;410  landArea?: number;411}412413export function estimateManual(p: ManualParams): UnitEstimate | null {414  const center = municipalityCenter(p.municipality);415  if (!center || !center.n) return null;416  const subject: Subject = {417    lat: center.lat,418    lng: center.lng,419    typeProp: p.typeProp,420    floorArea: p.floorArea ?? null,421    yearBuilt: p.yearBuilt ?? null,422    landArea: p.landArea ?? null,423    modelEstimate: null,424    modelP10: null,425    modelP90: null,426  };427  const candidates = candidatesAround(center.lat, center.lng);428  const index = getMarketIndex(indexType(p.typeProp));429  const result = estimate(subject, toComps(candidates), index, nowISO());430  if (!Number.isFinite(result.estimate)) return null;431  const context = buildContext(432    p.typeProp,433    center.lat,434    center.lng,435    candidates,436    index,437    p.municipality,438    result.estimate439  );440  return { unit: null, result, context };441}442
Files main
Menu

Theme