SPB Git

Repository Public

revenu.py 16.8 KB 342 lines python

1# =============================================================================2#                  SP BOUCHER | SOFTWARE & RESEARCH3#             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project          : Valo-Plex9# File             : moteur/plexmoteur/revenu.py10# Description      : Approche par le revenu, appliquée en masse.11# Module           : moteur12# Repository       : https://git.spboucher.ai/valo-plex13# Project Website  : https://www.valo-plex.com14# Created          : 2026-12-0115# 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"""Approche par le revenu, appliquée en masse.90911. Revenu brut potentiel au marché : logements × loyer de marché estimé × 12.922. Revenu en place : le précédent, ramené par le rapport mesuré entre les93   revenus PUBLIÉS par les inscriptions de plex et leur revenu au marché94   (locataires en place sous le marché). C'est le « revenu paritaire » du MEFQ95   lu à l'envers.963. Dépenses normalisées : barème SCHL (entretien, gestion, conciergerie,97   autres), taxes au taux effectif mesuré dans la municipalité, inoccupation.984. Revenu net ÷ taux de capitalisation EXTRAIT des ventes réelles de la région99   et de la taille (IAAO : le taux vient du marché, pas d'un barème).100101La valeur par le revenu est l'une des trois approches réconciliées dans la102valeur affichée (``reconcilier.py``) ; son poids est appris sur les ventes, hors103échantillon.104105Commercial : aucun loyer commercial n'est observé. Le revenu net normalisé106d'un immeuble commercial est son aire louable multipliée par un loyer net de107marché PUBLIÉ (par genre d'actif et par marché, ``params.COMMERCIAL``), moins108l'inoccupation publiée et les frais non récupérables. Le taux de109capitalisation, lui, reste EXTRAIT des ventes réelles de la catégorie : c'est110lui qui cale le niveau. Une catégorie sans loyer publié utilisable (hôtels,111résidences, loisirs, automobile) n'a pas d'approche par le revenu en masse.112"""113from __future__ import annotations114115import numpy as np116import pandas as pd117118from . import config, socle, typologie119from . import variables as V120from .params import PARAMS121122K_LISSAGE = 20.0123FENETRE_TGA = 548            # jours de ventes pour extraire taux et multiplicateurs124FENETRE_TGA_COMMERCIAL = 1460125TGA_BORNES = {typologie.RESIDENTIEL: (0.005, 0.15), typologie.COMMERCIAL: (0.01, 0.30)}126MIN_TGA = 8                  # ventes en deçà desquelles aucun taux n'est extrait pour le marché entier127D = PARAMS["depenses"]128PI2_PAR_M2 = 10.7639129MONTREAL, QUEBEC = (6, 13, 14, 15, 16), (3, 12)130131132def _lisse(df: pd.DataFrame, valeur: str, niveaux: list[list[str]]) -> pd.Series:133    """Médiane par le niveau le plus fin, lissée vers les niveaux plus larges."""134    est = pd.Series(float(df[valeur].median()), index=df.index)135    for cles in niveaux:          # du plus large au plus fin136        g = df.groupby(cles)[valeur].agg(["median", "size"])137        j = df[cles].join(g, on=cles)138        est = (j["size"] * j["median"] + K_LISSAGE * est) / (j["size"] + K_LISSAGE)139    return est140141142def tables_inscriptions(con) -> dict:143    """Taux de taxe effectif par municipalité et rapport revenu en place /144    revenu au marché par région et taille, mesurés sur les inscriptions."""145    A = pd.read_sql_query("""146      SELECT a.uid, i.id, i.code_mun, t.region_code, i.logements, i.role, i.loyer_porte, a.revenu, a.prix,147             COALESCE(a.taxe_mun, 0) + COALESCE(a.taxe_scol, 0) taxes, a.taxe_mun, a.logements a_log, a.eval_ratio148      FROM annonce a JOIN immeuble i ON i.id = a.id LEFT JOIN territoire t ON t.code_mun = i.code_mun149      WHERE a.lien_niveau = 'unite' AND i.marche = 'residentiel'""", con)150    A["groupe"] = V.groupe(A["logements"])151    A["region"] = pd.to_numeric(A["region_code"], errors="coerce").fillna(0).astype(int)152    T = A[(A["taxe_mun"] > 0)].copy()153    T["taux"] = T["taxes"] / T["role"]154    T = T[T["taux"].between(0.003, 0.04)].drop_duplicates("id")155    prov_taux = float(T["taux"].median())156    reg = T.groupby("region")["taux"].agg(["median", "size"])157    mun = T.groupby("code_mun")["taux"].agg(["median", "size"])158    R = A[(A["revenu"] > 0) & (A["a_log"] == A["logements"]) & A["loyer_porte"].notna()].copy()159    R["k"] = R["revenu"] / (R["logements"] * R["loyer_porte"] * 12)160    R = R[R["k"].between(0.3, 1.6)].drop_duplicates("id")161    R["macro"] = np.where(R["region"].isin([6, 13]), 1, np.where(R["region"].isin([14, 15, 16]), 2, 3))162    k_prov = float(R["k"].median())163    k_macro = R.groupby("macro")["k"].agg(["median", "size"])164    return {"taux_prov": prov_taux, "taux_reg": reg, "taux_mun": mun, "n_taxes": int(len(T)),165            "k_prov": k_prov, "k_macro": k_macro, "n_revenus": int(len(R))}166167168def calculer(B: pd.DataFrame, T: dict) -> pd.DataFrame:169    """Revenu, dépenses normalisées et revenu net de chaque immeuble de ``B``170    (colonnes : logements, loyer_porte, role, code_mun, region)."""171    n = B["logements"].to_numpy(float)172    out = pd.DataFrame(index=B.index)173    rbp = n * B["loyer_porte"].to_numpy(float) * 12174    macro = np.where(B["region"].isin([6, 13]), 1, np.where(B["region"].isin([14, 15, 16]), 2, 3))175    km = pd.DataFrame({"macro": macro}, index=B.index).join(T["k_macro"], on="macro")176    kn = km["size"].fillna(0).to_numpy(float)177    k = (kn * np.nan_to_num(km["median"].to_numpy(float)) + K_LISSAGE * T["k_prov"]) / (kn + K_LISSAGE)178    place = rbp * np.minimum(k, 1.0)179    reg = B[["region"]].join(T["taux_reg"], on="region")180    rn = reg["size"].fillna(0).to_numpy(float)181    taux_reg = (rn * np.nan_to_num(reg["median"].to_numpy(float)) + K_LISSAGE * T["taux_prov"]) / (rn + K_LISSAGE)182    mun = B[["code_mun"]].join(T["taux_mun"], on="code_mun")183    mn = mun["size"].fillna(0).to_numpy(float)184    taux = (mn * np.nan_to_num(mun["median"].to_numpy(float)) + 5.0 * taux_reg) / (mn + 5.0)185    inocc = np.full(len(B), D["inoccupation_pct"]["valeur"])186    for code, v in D["inoccupation_pct"]["par_region"].items():187        inocc[B["region"].to_numpy() == int(code)] = v188    grand = n >= 12189    rbe = place * (1 - inocc / 100)190    taxes = B["role"].to_numpy(float) * taux191    gestion = rbe * np.where(grand, D["gestion_pct"]["valeur_12_plus"], D["gestion_pct"]["valeur"]) / 100192    fixes = n * (D["entretien_par_logement"]["valeur"] + D["assurances_par_logement"]["valeur"]193                 + np.where(grand, D["conciergerie_par_logement"]["valeur_12_plus"],194                            D["conciergerie_par_logement"]["valeur"]))195    autres = rbe * D["autres_pct"]["valeur"] / 100196    dep = taxes + gestion + fixes + autres197    out["rbp_marche"] = rbp198    out["rapport_place"] = np.minimum(k, 1.0)199    out["revenu_place"] = place200    out["inoccupation_pct"] = inocc201    out["taux_taxe"] = taux202    out["taxes"] = taxes203    out["depenses"] = dep204    out["rne"] = rbe - dep205    return out206207208def zone(region) -> np.ndarray:209    """Marché des loyers publiés : « montreal » (régions 06, 13 à 16), « quebec »210    (03, 12), « ailleurs »."""211    r = np.asarray(region)212    return np.where(np.isin(r, MONTREAL), "montreal", np.where(np.isin(r, QUEBEC), "quebec", "ailleurs"))213214215def calculer_commercial(B: pd.DataFrame) -> pd.DataFrame:216    """Revenu net normalisé des immeubles commerciaux de ``B`` (colonnes :217    categorie, aire_m2, region) d'après les loyers nets publiés. Rien n'est218    rendu pour une catégorie ou un marché sans loyer publié, ni sans aire."""219    C = PARAMS["commercial"]220    n = len(B)221    out = pd.DataFrame({c: np.full(n, np.nan) for c in222                        ("rbp_marche", "revenu_place", "inoccupation_pct", "depenses", "rne", "loyer_net_pi2")},223                       index=B.index)224    aire = pd.to_numeric(B["aire_m2"], errors="coerce").to_numpy(float)225    z = zone(B["region"].to_numpy())226    cat = B["categorie"].to_numpy()227    for c, regles in C["categories"].items():228        loyers = regles.get("loyer_net_pi2") or {}229        for zn in ("montreal", "quebec", "ailleurs"):230            loyer = loyers.get(zn)231            if not loyer:232                continue233            m = (cat == c) & (z == zn) & (aire > 0)234            if not m.any():235                continue236            vac = (regles.get("inoccupation_pct") or {}).get(zn, C["inoccupation_defaut_pct"])237            louable = aire[m] * PI2_PAR_M2 * regles.get("part_louable", C["part_louable_defaut"])238            rbp = louable * loyer239            rbe = rbp * (1 - vac / 100)240            dep = rbe * C["frais_non_recuperables_pct"] / 100241            out.loc[m, "loyer_net_pi2"] = loyer242            out.loc[m, "rbp_marche"] = rbp243            out.loc[m, "revenu_place"] = rbe244            out.loc[m, "inoccupation_pct"] = vac245            out.loc[m, "depenses"] = dep246            out.loc[m, "rne"] = rbe - dep247    return out248249250def taux_marche(W: pd.DataFrame, marche: str) -> pd.DataFrame:251    """Taux de capitalisation (et multiplicateur de revenu brut) extraits des252    ventes ``W`` (colonnes : prix, rne, revenu_place, taille, region, groupe),253    par région et groupe, lissés vers le groupe à l'échelle de la province. La254    région 0 porte la province."""255    cols = ["region", "groupe", "n", "tga", "mrb", "tga_brut", "mrb_brut", "prix_unite"]256    bas, haut = TGA_BORNES[marche]257    S = W[(W["rne"] > 0) & (W["prix"] > 0)].copy()258    S["tga"] = S["rne"] / S["prix"]259    S["mrb"] = S["prix"] / S["revenu_place"]260    S = S[S["tga"].between(bas, haut) & S["mrb"].between(2, 60)]261    if len(S) < MIN_TGA:262        return pd.DataFrame(columns=cols)263    S["tga_l"] = _lisse(S, "tga", [["groupe"], ["region", "groupe"]])264    S["mrb_l"] = _lisse(S, "mrb", [["groupe"], ["region", "groupe"]])265    S["pu"] = S["prix"] / S["taille"]266    M = S.groupby(["region", "groupe"]).agg(n=("prix", "size"), tga=("tga_l", "first"), mrb=("mrb_l", "first"),267                                            tga_brut=("tga", "median"), mrb_brut=("mrb", "median"),268                                            prix_unite=("pu", "median")).reset_index()269    # province : la médiane du groupe, lissée vers le marché entier quand le groupe est mince270    tous_tga, tous_mrb = float(S["tga"].median()), float(S["mrb"].median())271    P = S.groupby("groupe").agg(n=("prix", "size"), tga_brut=("tga", "median"), mrb_brut=("mrb", "median"),272                                prix_unite=("pu", "median")).reset_index()273    P["tga"] = (P["n"] * P["tga_brut"] + K_LISSAGE * tous_tga) / (P["n"] + K_LISSAGE)274    P["mrb"] = (P["n"] * P["mrb_brut"] + K_LISSAGE * tous_mrb) / (P["n"] + K_LISSAGE)275    P["region"] = 0276    return pd.concat([M[cols], P[cols]], ignore_index=True)277278279def appliquer_taux(B: pd.DataFrame, rne, revenu_place, M: pd.DataFrame) -> pd.DataFrame:280    """Valeur par le revenu (revenu net ÷ taux) et par le multiplicateur, pour281    les immeubles ``B`` (colonnes region, groupe)."""282    out = pd.DataFrame(index=B.index)283    if not len(M):284        for c in ("tga", "mrb", "valeur_revenu", "valeur_mrb"):285            out[c] = np.nan286        return out287    cle = M[M["region"] != 0].set_index(["region", "groupe"])288    prov = M[M["region"] == 0].set_index("groupe")289    j = B[["region", "groupe"]].join(cle[["tga", "mrb"]], on=["region", "groupe"])290    p = B[["groupe"]].join(prov[["tga", "mrb"]], on="groupe")291    out["tga"] = j["tga"].fillna(p["tga"]).to_numpy(float)292    out["mrb"] = j["mrb"].fillna(p["mrb"]).to_numpy(float)293    rne = np.asarray(rne, float)294    with np.errstate(all="ignore"):295        out["valeur_revenu"] = np.where(rne > 0, rne / out["tga"], np.nan)296        out["valeur_mrb"] = np.asarray(revenu_place, float) * out["mrb"]297    return out298299300def fenetre(marche: str) -> int:301    return FENETRE_TGA_COMMERCIAL if marche == typologie.COMMERCIAL else FENETRE_TGA302303304def approche(C: pd.DataFrame, H: pd.DataFrame, know: int, marche: str) -> tuple[pd.DataFrame, pd.DataFrame]:305    """Approche par le revenu des cibles ``C`` d'après les ventes de marché ``H``306    connues à ``know`` (les deux portent ``rne``, ``revenu_place``, ``taille``,307    ``region``, ``groupe`` ; ``H`` porte ``prix`` et ``jour``). Rend la table308    de ``appliquer_taux`` et la table des taux extraits."""309    W = H[(H["jour"] > know - fenetre(marche)) & (H["jour"] <= know)]310    M = taux_marche(W, marche)311    return appliquer_taux(C, C["rne"].to_numpy(float), C["revenu_place"].to_numpy(float), M), M312313314def revenus(B: pd.DataFrame, T: dict, marche: str) -> pd.DataFrame:315    """Revenu net normalisé de ``B`` selon son marché."""316    if marche == typologie.COMMERCIAL:317        return calculer_commercial(B)318    return calculer(B, T)319320321def ecrire_marche(con, tables: dict, T: dict) -> None:322    """``tables`` : marché → table des taux extraits à la date de valeur."""323    config.script(con, """324    DROP TABLE IF EXISTS marche_revenu;325    CREATE TABLE marche_revenu (region INTEGER NOT NULL, groupe INTEGER NOT NULL, n INTEGER NOT NULL,326      tga REAL, mrb REAL, tga_brut REAL, mrb_brut REAL, prix_porte REAL, marche TEXT NOT NULL DEFAULT 'residentiel',327      nom TEXT, PRIMARY KEY (region, groupe)) WITHOUT ROWID;328    DROP TABLE IF EXISTS taux_taxe;329    CREATE TABLE taux_taxe (code_mun TEXT PRIMARY KEY, taux REAL NOT NULL, n INTEGER NOT NULL) WITHOUT ROWID;330    """)331    f = lambda v: None if v is None or not np.isfinite(v) else float(v)332    for marche, M in tables.items():333        con.executemany("INSERT INTO marche_revenu VALUES (?,?,?,?,?,?,?,?,?,?)",334                        [(int(r.region), int(r.groupe), int(r.n), f(r.tga), f(r.mrb), f(r.tga_brut), f(r.mrb_brut),335                          f(r.prix_unite), marche, typologie.GROUPES[int(r.groupe)]) for r in M.itertuples()])336    con.executemany("INSERT INTO taux_taxe VALUES (?,?,?)",337                    [(c, float(r["median"]), int(r["size"])) for c, r in T["taux_mun"].iterrows()])338    socle.noter(con, "revenu", {"taux_taxe_province": round(T["taux_prov"], 5), "n_taxes": T["n_taxes"],339                                "rapport_place_province": round(T["k_prov"], 3), "n_revenus": T["n_revenus"],340                                "rapport_place_macro": {str(k): [round(float(v["median"]), 3), int(v["size"])]341                                                        for k, v in T["k_macro"].iterrows()}})342
Files main
Menu

Theme