Repository Public
1# =============================================================================2# SP BOUCHER | SOFTWARE & RESEARCH3# ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project : Valo-Plex9# File : moteur/plexmoteur/reconcilier.py10# Description : Réconciliation des trois approches de la valeur.11# Module : moteur12# Repository : https://git.spboucher.ai/valo-plex13# Project Website : https://www.valo-plex.com14# Created : 2026-12-0315# Last Modified : 2026-12-0316#17# =============================================================================18# AUTHOR & PROFESSIONAL AFFILIATION19# =============================================================================20#21# Author : Simon-Pierre Boucher22# Position : Professor of Finance23# Institution : Université du Québec en Outaouais (UQO)24# Department : Département des sciences administratives25# Organization : SP Boucher26#27# Website : https://spboucher.ai28# Git : https://git.spboucher.ai29#30# =============================================================================31# OFFICIAL CONTACT DIRECTORY32# =============================================================================33#34# General : info@spboucher.ai35# Professional : contact@spboucher.ai36# Direct : simon@spboucher.ai37# Research : research@spboucher.ai38# Development : dev@spboucher.ai39# Support : support@spboucher.ai40# Security/Admin : admin@spboucher.ai41# Notifications : notifications@spboucher.ai42#43# Preferred Contact: contact@spboucher.ai44#45# =============================================================================46# COPYRIGHT & INTELLECTUAL PROPERTY47# =============================================================================48#49# Copyright (c) 202650# Simon-Pierre Boucher51#52# All rights reserved where applicable.53#54# This file is governed by the applicable project license,55# copyright notices, institutional agreements and relevant law.56#57# Unless expressly authorized by the applicable license or58# rights holder, copying, redistribution, sublicensing,59# publication and commercial exploitation are not permitted.60#61# Existing third-party rights and notices remain unaffected.62#63# =============================================================================64# CONFIDENTIALITY & SECURITY65# =============================================================================66#67# Classification : Public68# Distribution : Public repository; use is governed by the project license69# Security Contact : admin@spboucher.ai70#71# Access to this source does not independently grant permission72# to redistribute or disclose confidential materials.73#74# Do not embed credentials, private keys, access tokens,75# certificates or confidential personal information.76#77# =============================================================================78# LICENSE & MAINTENANCE79# =============================================================================80#81# License : None specified (no license file in this repository)82# Maintainer : Simon-Pierre Boucher83# Technical Contact: dev@spboucher.ai84#85# =============================================================================86# END OF SP BOUCHER SOURCE HEADER87# =============================================================================8889"""Réconciliation des trois approches de la valeur : hédonique (modèle appris90sur les caractéristiques et les ventes), par comparaison (ventes comparables91ajustées) et par le revenu (revenu net ÷ taux de capitalisation du marché).9293Un évaluateur pondère ses approches selon la confiance qu'il leur prête. Ici94les poids ne sont pas choisis : ils sont appris, groupe par groupe, sur des95ventes que chaque approche a estimées SANS les avoir vues. Pour chaque groupe96on retire d'abord à chaque approche son biais médian, puis on cherche sur une97grille les poids (positifs, de somme 1) qui minimisent l'erreur absolue98moyenne en logarithme. Une approche qui n'apporte rien reçoit un poids nul ;99une approche absente pour un immeuble (pas assez de comparables, pas de100revenu) cède son poids aux autres.101"""102from __future__ import annotations103104import itertools105106import numpy as np107108METHODES = ("hedonique", "comparables", "revenu")109PAS = 0.05110PRESENCE_MIN = 0.5 # part des ventes du groupe où une approche doit exister pour être pesée111MIN_COMPLETES = 60 # ventes estimées par toutes les approches pesées, en deçà : poids du marché entier112113114def _grille(k: int) -> np.ndarray:115 """Tous les vecteurs de ``k`` poids multiples de ``PAS`` et de somme 1."""116 n = int(round(1 / PAS))117 lignes = [c for c in itertools.product(range(n + 1), repeat=k) if sum(c) == n]118 return np.array(lignes, float) / n119120121def _ajuster(y: np.ndarray, L: np.ndarray) -> dict | None:122 """Biais et poids d'un ensemble de ventes ; ``None`` s'il est trop mince."""123 fini = np.isfinite(L) & np.isfinite(y)[:, None]124 if fini[:, 0].sum() < MIN_COMPLETES:125 return None126 presentes = [m for m in range(L.shape[1]) if fini[:, m].mean() >= PRESENCE_MIN or m == 0]127 biais = np.zeros(L.shape[1])128 for m in range(L.shape[1]):129 if fini[:, m].sum() >= 20:130 biais[m] = float(np.median(L[fini[:, m], m] - y[fini[:, m]]))131 while True:132 lignes = fini[:, presentes].all(axis=1)133 if lignes.sum() >= MIN_COMPLETES or len(presentes) == 1:134 break135 # trop peu de ventes vues par toutes : on retire l'approche la moins présente136 presentes.remove(min(presentes[1:], key=lambda m: fini[:, m].sum()))137 if lignes.sum() < MIN_COMPLETES:138 return None139 G = _grille(len(presentes))140 Lc = L[lignes][:, presentes] - biais[presentes]141 err = np.abs(Lc @ G.T - y[lignes][:, None]).mean(axis=0)142 # à erreur égale (au dix-millième), le plus de poids à la première approche : choix stable143 meilleur = min(range(len(G)), key=lambda i: (round(float(err[i]), 4), -G[i][0]))144 poids = np.zeros(L.shape[1])145 poids[presentes] = G[meilleur]146 return {"poids": [float(p) for p in poids], "biais": [float(b) for b in biais], "n": int(lignes.sum()),147 "erreur": float(err[meilleur]), "erreur_hedonique": float(np.abs(Lc[:, 0] - y[lignes]).mean())}148149150def apprendre(y, L, g, groupes) -> dict:151 """Règles de réconciliation par groupe. ``y`` : log du prix ; ``L`` : log152 des valeurs par approche (colonnes de ``METHODES``, NaN si absente) ;153 ``g`` : groupe de chaque vente ; ``groupes`` : les groupes du marché."""154 y, L, g = np.asarray(y, float), np.asarray(L, float), np.asarray(g)155 tous = _ajuster(y, L) or {"poids": [1.0, 0.0, 0.0], "biais": [0.0, 0.0, 0.0], "n": 0}156 regles = {}157 for k in groupes:158 r = _ajuster(y[g == k], L[g == k]) if (g == k).any() else None159 regles[int(k)] = dict(r, propre=True) if r else dict(tous, propre=False)160 return {"methodes": list(METHODES), "groupes": regles, "ensemble": tous}161162163def appliquer(L, g, R: dict) -> tuple[np.ndarray, np.ndarray, np.ndarray]:164 """Valeur réconciliée (log), poids effectifs par approche et désaccord165 (écart-type des approches retenues, en log). Sans approche hédonique, rien166 n'est rendu."""167 L, g = np.asarray(L, float), np.asarray(g)168 n, k = L.shape169 P = np.zeros((n, k))170 B = np.zeros((n, k))171 for cle, r in R["groupes"].items():172 m = g == int(cle)173 P[m], B[m] = r["poids"], r["biais"]174 autres = ~np.isin(g, [int(c) for c in R["groupes"]])175 P[autres], B[autres] = R["ensemble"]["poids"], R["ensemble"]["biais"]176 Lc = L - B177 P = np.where(np.isfinite(Lc), P, 0.0)178 s = P.sum(axis=1)179 # toutes les approches pesées manquent (ou l'hédonique seule, de poids nul, existe) : l'hédonique fait foi180 seul = (s <= 0) & np.isfinite(Lc[:, 0])181 P[seul, 0] = 1.0182 s = P.sum(axis=1)183 with np.errstate(all="ignore"):184 P = P / s[:, None]185 rec = np.nansum(np.where(P > 0, P * Lc, 0.0), axis=1)186 moy = rec[:, None]187 disp = np.sqrt(np.nansum(np.where(P > 0, P * (Lc - moy) ** 2, 0.0), axis=1))188 vide = ~np.isfinite(L[:, 0]) | (s <= 0)189 rec[vide], disp[vide] = np.nan, np.nan190 P[vide] = np.nan191 return rec, P, disp192193194def corriger(L, g, R: dict) -> np.ndarray:195 """Log des valeurs par approche, biais médian du groupe retiré."""196 L, g = np.asarray(L, float), np.asarray(g)197 B = np.tile(np.asarray(R["ensemble"]["biais"], float), (len(L), 1))198 for cle, r in R["groupes"].items():199 B[g == int(cle)] = r["biais"]200 return L - B201