Repository Public
1/**2 * =============================================================================3 * SP BOUCHER | SOFTWARE & RESEARCH4 * ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5 * =============================================================================6 *7 * Project : Vrai-Prix8 * File : src/lib/engine.ts9 * Module : lib10 * Repository : https://git.spboucher.ai/vrai-prix11 * Created : 2026-08-0912 * Last Modified : 2026-08-0913 *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 * Moteur d'estimation Vrai-Prix — transparent par conception.44 *45 * Deux sources combinées :46 * 1. Modèle hédonique (LightGBM, entraîné sur ~690 k ventes QC 2021-2026,47 * pré-calculé pour chaque unité d'évaluation) — colonne est_2026 + P10/P90.48 * 2. Comparables : ventes réelles proches, ajustées (marché, superficie, âge),49 * médiane pondérée (distance, récence, similarité).50 *51 * Chaque ajustement est retourné en dollars pour affichage — aucune boîte noire.52 */5354export interface Subject {55 lat: number;56 lng: number;57 typeProp: string; // unifamilial | plex | condo_ou_multi | chalet | maison_mobile | terrain | autre58 floorArea?: number | null;59 yearBuilt?: number | null;60 landArea?: number | null;61 modelEstimate?: number | null;62 modelP10?: number | null;63 modelP90?: number | null;64}6566export interface CompInput {67 id: string;68 date: string; // YYYY-MM-DD69 amount: number;70 lat: number;71 lng: number;72 propertyType: string | null;73 yearBuilt: number | null;74 floorArea: number | null;75 street: string | null;76 city: string | null;77}7879export interface AdjustedComp extends CompInput {80 distanceM: number;81 monthsAgo: number;82 adjTime: number;83 adjArea: number;84 adjAge: number;85 adjustedPrice: number;86 weight: number;87}8889export interface MarketIndexPoint {90 month: string; // YYYY-MM91 idx: number; // 1.0 = niveau actuel92}9394export interface EstimateResult {95 estimate: number;96 low: number;97 high: number;98 confidencePct: number;99 confidenceLevel: "A" | "B" | "C" | "D";100 modelEstimate: number | null;101 compsEstimate: number | null;102 modelWeight: number;103 comps: AdjustedComp[];104 nCompsUsed: number;105 compsDispersionPct: number | null;106}107108/** Correspondance type d'unité (rôle) -> types de transactions comparables. */109export const TYPE_MATCH: Record<string, string[]> = {110 unifamilial: ["unifamilial"],111 plex: ["plex"],112 condo_ou_multi: ["condo", "plex"],113 chalet: ["unifamilial", "indéterminé"],114 maison_mobile: ["unifamilial", "indéterminé"],115 terrain: ["indéterminé"],116 autre: ["unifamilial", "condo", "plex", "indéterminé"],117};118119export function haversineM(120 lat1: number,121 lng1: number,122 lat2: number,123 lng2: number124): number {125 const R = 6371000;126 const toRad = (d: number) => (d * Math.PI) / 180;127 const dLat = toRad(lat2 - lat1);128 const dLng = toRad(lng2 - lng1);129 const a =130 Math.sin(dLat / 2) ** 2 +131 Math.cos(toRad(lat1)) * Math.cos(toRad(lat2)) * Math.sin(dLng / 2) ** 2;132 return 2 * R * Math.asin(Math.sqrt(a));133}134135export function monthsBetween(fromISO: string, toISO: string): number {136 const a = new Date(fromISO);137 const b = new Date(toISO);138 return (b.getTime() - a.getTime()) / (1000 * 3600 * 24 * 30.44);139}140141/** Facteur marché entre le mois de vente et aujourd'hui (idx courant = dernier). */142export function timeFactor(143 saleMonth: string,144 index: MarketIndexPoint[]145): number {146 if (index.length === 0) return 1;147 const last = index[index.length - 1].idx;148 let saleIdx: number | null = null;149 for (const p of index) {150 if (p.month <= saleMonth) saleIdx = p.idx;151 }152 if (saleIdx === null) saleIdx = index[0].idx;153 if (saleIdx <= 0) return 1;154 return last / saleIdx;155}156157/** Ajustement superficie : 50 % du $/m² marginal du comparable. */158export function areaAdjustment(159 subjectArea: number | null | undefined,160 comp: { floorArea: number | null; amount: number }161): number {162 if (!subjectArea || !comp.floorArea || comp.floorArea <= 0) return 0;163 const ppm2 = comp.amount / comp.floorArea;164 const adj = (subjectArea - comp.floorArea) * 0.5 * ppm2;165 // borné à ±25 % du prix du comparable166 const cap = 0.25 * comp.amount;167 return Math.max(-cap, Math.min(cap, adj));168}169170/** Ajustement âge : 0,5 %/an d'écart, borné à ±10 %. */171export function ageAdjustment(172 subjectYear: number | null | undefined,173 comp: { yearBuilt: number | null; amount: number }174): number {175 if (!subjectYear || !comp.yearBuilt) return 0;176 const pct = Math.max(-0.1, Math.min(0.1, (subjectYear - comp.yearBuilt) * 0.005));177 return pct * comp.amount;178}179180export function weightedMedian(values: number[], weights: number[]): number {181 const order = values182 .map((v, i) => ({ v, w: weights[i] }))183 .sort((a, b) => a.v - b.v);184 const total = order.reduce((s, o) => s + o.w, 0);185 if (total <= 0) return NaN;186 let acc = 0;187 for (const o of order) {188 acc += o.w;189 if (acc >= total / 2) return o.v;190 }191 return order[order.length - 1].v;192}193194export function adjustComps(195 subject: Subject,196 candidates: CompInput[],197 index: MarketIndexPoint[],198 nowISO: string199): AdjustedComp[] {200 const types = TYPE_MATCH[subject.typeProp] ?? TYPE_MATCH.autre;201 let pool = candidates.filter(202 (c) => c.propertyType !== null && types.includes(c.propertyType)203 );204 if (pool.length < 6) pool = candidates; // relâche le filtre de type si marché mince205206 // filtre superficie ±20 %, relâché à ±40 % puis abandonné si trop peu207 if (subject.floorArea) {208 for (const tol of [0.2, 0.4]) {209 const filtered = pool.filter(210 (c) =>211 c.floorArea != null &&212 Math.abs(c.floorArea - subject.floorArea!) <=213 tol * subject.floorArea!214 );215 if (filtered.length >= 6) {216 pool = filtered;217 break;218 }219 }220 }221222 const comps = pool.map((c) => {223 const distanceM = haversineM(subject.lat, subject.lng, c.lat, c.lng);224 const monthsAgo = monthsBetween(c.date, nowISO);225 const tf = timeFactor(c.date.slice(0, 7), index);226 const adjTime = c.amount * (tf - 1);227 const adjArea = areaAdjustment(subject.floorArea, c);228 const adjAge = ageAdjustment(subject.yearBuilt, c);229 const adjustedPrice = c.amount + adjTime + adjArea + adjAge;230 const areaDiffPct =231 subject.floorArea && c.floorArea232 ? Math.abs(c.floorArea - subject.floorArea) / subject.floorArea233 : 0.15;234 const weight =235 Math.exp(-((distanceM / 1500) ** 2)) *236 Math.exp(-((monthsAgo / 24) ** 2)) *237 Math.exp(-((areaDiffPct / 0.25) ** 2));238 return { ...c, distanceM, monthsAgo, adjTime, adjArea, adjAge, adjustedPrice, weight };239 });240241 return comps242 .filter((c) => c.adjustedPrice > 0 && c.weight > 1e-4)243 .sort((a, b) => b.weight - a.weight)244 .slice(0, 12);245}246247function pctDispersion(comps: AdjustedComp[], center: number): number | null {248 if (comps.length < 3 || center <= 0) return null;249 const dev = comps.map((c) => Math.abs(c.adjustedPrice - center) / center);250 dev.sort((a, b) => a - b);251 return dev[Math.floor(dev.length / 2)] * 100;252}253254export function estimate(255 subject: Subject,256 candidates: CompInput[],257 index: MarketIndexPoint[],258 nowISO: string259): EstimateResult {260 const comps = adjustComps(subject, candidates, index, nowISO);261 const compsEstimate =262 comps.length >= 3263 ? weightedMedian(264 comps.map((c) => c.adjustedPrice),265 comps.map((c) => c.weight)266 )267 : null;268269 const model = subject.modelEstimate ?? null;270 let modelWeight = 0;271 let estimateValue: number;272 if (model !== null && compsEstimate !== null) {273 modelWeight = 0.65;274 estimateValue = modelWeight * model + (1 - modelWeight) * compsEstimate;275 } else if (model !== null) {276 modelWeight = 1;277 estimateValue = model;278 } else if (compsEstimate !== null) {279 estimateValue = compsEstimate;280 } else {281 estimateValue = NaN;282 }283284 // fourchette : intervalle du modèle recentré, sinon dispersion des comparables285 let low: number, high: number;286 if (model !== null && subject.modelP10 != null && subject.modelP90 != null && model > 0) {287 low = estimateValue * (subject.modelP10 / model);288 high = estimateValue * (subject.modelP90 / model);289 } else {290 const disp = pctDispersion(comps, compsEstimate ?? estimateValue) ?? 25;291 low = estimateValue * (1 - disp / 100);292 high = estimateValue * (1 + disp / 100);293 }294295 const dispersion = pctDispersion(comps, compsEstimate ?? estimateValue);296 // confiance : nb de comparables, dispersion, largeur de fourchette, présence du modèle297 let score = 35;298 score += Math.min(25, comps.length * 2.5);299 if (dispersion !== null) score += Math.max(0, 20 - dispersion);300 if (model !== null) score += 15;301 const widthPct = estimateValue > 0 ? ((high - low) / estimateValue) * 100 : 100;302 score -= Math.max(0, (widthPct - 30) / 3);303 score = Math.max(5, Math.min(97, score));304 const level = score >= 75 ? "A" : score >= 60 ? "B" : score >= 45 ? "C" : "D";305306 return {307 estimate: Math.round(estimateValue / 100) * 100,308 low: Math.round(low / 100) * 100,309 high: Math.round(high / 100) * 100,310 confidencePct: Math.round(score),311 confidenceLevel: level,312 modelEstimate: model,313 compsEstimate: compsEstimate !== null ? Math.round(compsEstimate / 100) * 100 : null,314 modelWeight,315 comps,316 nCompsUsed: comps.length,317 compsDispersionPct: dispersion !== null ? Math.round(dispersion * 10) / 10 : null,318 };319}320