SPB Git

Repository Public

calc.py 14.5 KB 344 lines python

1# =============================================================================2#                  SP BOUCHER | SOFTWARE & RESEARCH3#             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project          : Immo·Ka9# File             : immoka/mortgage/calc.py10# Module           : immoka11# Repository       : https://git.spboucher.ai/immo-ka12# Created          : 2026-08-2413# Last Modified    : 2026-08-2414#15# =============================================================================16# AUTHOR & PROFESSIONAL AFFILIATION17# =============================================================================18#19# Author           : Simon-Pierre Boucher20# Position         : Professor of Finance21# Institution      : Université du Québec en Outaouais (UQO)22# Department       : Département des sciences administratives23# Organization     : SP Boucher24#25# Website          : https://spboucher.ai26# Git              : https://git.spboucher.ai27#28# =============================================================================29# OFFICIAL CONTACT DIRECTORY30# =============================================================================31#32# General          : info@spboucher.ai33# Professional     : contact@spboucher.ai34# Direct           : simon@spboucher.ai35# Research         : research@spboucher.ai36# Development      : dev@spboucher.ai37# Support          : support@spboucher.ai38# Security/Admin   : admin@spboucher.ai39# Notifications    : notifications@spboucher.ai40#41# Preferred Contact: contact@spboucher.ai42#43# =============================================================================44# COPYRIGHT & INTELLECTUAL PROPERTY45# =============================================================================46#47# Copyright (c) 202648# Simon-Pierre Boucher49#50# All rights reserved where applicable.51#52# This file is governed by the applicable project license,53# copyright notices, institutional agreements and relevant law.54#55# Unless expressly authorized by the applicable license or56# rights holder, copying, redistribution, sublicensing,57# publication and commercial exploitation are not permitted.58#59# Existing third-party rights and notices remain unaffected.60#61# =============================================================================62# CONFIDENTIALITY & SECURITY63# =============================================================================64#65# Classification   : Public66# Distribution     : Public repository; use is governed by the project license67# Security Contact : admin@spboucher.ai68#69# Access to this source does not independently grant permission70# to redistribute or disclose confidential materials.71#72# Do not embed credentials, private keys, access tokens,73# certificates or confidential personal information.74#75# =============================================================================76# LICENSE & MAINTENANCE77# =============================================================================78#79# License          : None specified (no license file in this repository)80# Maintainer       : Simon-Pierre Boucher81# Technical Contact: dev@spboucher.ai82#83# =============================================================================84# END OF SP BOUCHER SOURCE HEADER85# =============================================================================8687# -----------------------------------------------------------------------------88# Immo-Ka — Agrégateur de maisons à vendre (province de Québec)89# Auteur : Simon-Pierre Boucher — contact@spboucher.ai90# mortgage/calc.py : mathématiques hypothécaires canadiennes.91#   Taux fixes : intérêt composé SEMESTRIELLEMENT, non à l'avance (Loi sur92#   l'intérêt, art. 6) — jamais la formule américaine (composition mensuelle).93#   Taux variables : composition mensuelle (convention majoritaire des94#   prêteurs canadiens).95# -----------------------------------------------------------------------------96from __future__ import annotations9798import math99100# Fréquences de paiement : nombre de versements par année.101FREQUENCIES: dict[str, int] = {102    "monthly": 12,103    "semimonthly": 24,104    "biweekly": 26,105    "accelerated-biweekly": 26,106    "weekly": 52,107    "accelerated-weekly": 52,108}109110# Taux de qualification minimal (test de résistance B-20 / ligne directrice111# du BSIF) : max(taux contractuel + 2 points, plancher).112STRESS_TEST_FLOOR = 5.25113STRESS_TEST_BUFFER = 2.0114115AMORTIZATIONS_YEARS = [10, 15, 20, 25, 30]116TERMS_MONTHS = [12, 24, 36, 48, 60, 84, 120]117118119def periodic_rate(annual_pct: float, frequency: str = "monthly",120                  compounding: str = "semi-annual") -> float:121    """Taux périodique équivalent au taux nominal annuel `annual_pct` (%).122123    compounding="semi-annual" : convention canadienne des prêts fixes —124    i = (1 + r/2)^(2/f) − 1.  "monthly" : prêts variables — i = (1+r/12)^(12/f) − 1.125    """126    if annual_pct < 0:127        raise ValueError("taux négatif")128    f = FREQUENCIES[frequency]129    r = annual_pct / 100.0130    if compounding == "monthly":131        return (1.0 + r / 12.0) ** (12.0 / f) - 1.0132    return (1.0 + r / 2.0) ** (2.0 / f) - 1.0133134135def payment(principal: float, annual_pct: float, amort_years: float,136            frequency: str = "monthly",137            compounding: str = "semi-annual") -> float:138    """Versement périodique (arrondi au cent).139140    Fréquences accélérées : convention canadienne — le versement mensuel141    divisé par 2 (aux deux semaines) ou par 4 (hebdomadaire), ce qui raccourcit142    l'amortissement réel.143    """144    if principal <= 0:145        return 0.0146    if frequency in ("accelerated-biweekly", "accelerated-weekly"):147        m = payment(principal, annual_pct, amort_years, "monthly", compounding)148        return round(m / (2 if frequency == "accelerated-biweekly" else 4), 2)149    i = periodic_rate(annual_pct, frequency, compounding)150    n = round(amort_years * FREQUENCIES[frequency])151    if i == 0:152        return round(principal / n, 2)153    return round(principal * i / (1.0 - (1.0 + i) ** -n), 2)154155156def schedule(principal: float, annual_pct: float, amort_years: float,157             frequency: str = "monthly", compounding: str = "semi-annual",158             pay_amount: float | None = None,159             max_periods: int | None = None) -> list[dict]:160    """Tableau d'amortissement complet : [{n, payment, interest, principal,161    balance}]. Le dernier versement est ajusté au solde exact. Les fréquences162    accélérées s'éteignent avant l'amortissement contractuel (comportement163    attendu). `max_periods` borne la simulation (ex. durée du terme)."""164    if principal <= 0:165        return []166    i = periodic_rate(annual_pct, frequency, compounding)167    pmt = pay_amount if pay_amount is not None else payment(168        principal, annual_pct, amort_years, frequency, compounding)169    if pmt <= 0:170        return []171    hard_cap = round(amort_years * FREQUENCIES[frequency]) + FREQUENCIES[frequency]172    if frequency.startswith("accelerated"):173        hard_cap = round(40 * FREQUENCIES[frequency])  # s'éteint plus tôt174    limit = min(max_periods, hard_cap) if max_periods else hard_cap175    rows: list[dict] = []176    bal = round(principal, 2)177    n = 0178    while bal > 0.005 and n < limit:179        n += 1180        interest = round(bal * i, 2)181        cap = round(pmt - interest, 2)182        if cap <= 0 and n > 1:183            break  # paiement insuffisant : ne jamais boucler à l'infini184        if cap >= bal:  # dernier versement ajusté185            cap = bal186            row_pay = round(cap + interest, 2)187        else:188            row_pay = pmt189        bal = round(bal - cap, 2)190        rows.append({"n": n, "payment": row_pay, "interest": interest,191                     "principal": cap, "balance": bal})192    return rows193194195def annual_rollup(rows: list[dict], frequency: str = "monthly") -> list[dict]:196    """Agrège un tableau d'amortissement par année de prêt."""197    f = FREQUENCIES[frequency]198    out: list[dict] = []199    for r in rows:200        year = (r["n"] - 1) // f + 1201        if not out or out[-1]["year"] != year:202            out.append({"year": year, "payment": 0.0, "interest": 0.0,203                        "principal": 0.0, "balance": r["balance"]})204        acc = out[-1]205        acc["payment"] = round(acc["payment"] + r["payment"], 2)206        acc["interest"] = round(acc["interest"] + r["interest"], 2)207        acc["principal"] = round(acc["principal"] + r["principal"], 2)208        acc["balance"] = r["balance"]209    return out210211212def term_summary(principal: float, annual_pct: float, amort_years: float,213                 term_months: int, frequency: str = "monthly",214                 compounding: str = "semi-annual") -> dict:215    """Bilan du terme : versement, nombre de versements, capital payé,216    intérêts payés, solde à l'échéance du terme."""217    f = FREQUENCIES[frequency]218    n_term = round(f * term_months / 12)219    rows = schedule(principal, annual_pct, amort_years, frequency,220                    compounding, max_periods=n_term)221    pmt = payment(principal, annual_pct, amort_years, frequency, compounding)222    interest = round(sum(r["interest"] for r in rows), 2)223    cap = round(sum(r["principal"] for r in rows), 2)224    balance = rows[-1]["balance"] if rows else round(principal, 2)225    payments_per_year = f226    return {227        "payment": pmt,228        "frequency": frequency,229        "payments_per_year": payments_per_year,230        "payments_in_term": len(rows),231        "annual_cost": round(pmt * payments_per_year, 2),232        "principal_paid": cap,233        "interest_paid": interest,234        "balance_end_of_term": balance,235        "paid_off": balance <= 0.005,236    }237238239def payoff_years(principal: float, annual_pct: float, amort_years: float,240                 frequency: str, compounding: str = "semi-annual") -> float:241    """Durée réelle d'extinction (années) — utile pour les fréquences242    accélérées qui raccourcissent l'amortissement."""243    rows = schedule(principal, annual_pct, amort_years, frequency, compounding)244    if not rows or rows[-1]["balance"] > 0.005:245        return float(amort_years)246    return round(len(rows) / FREQUENCIES[frequency], 2)247248249def max_loan(target_payment: float, annual_pct: float, amort_years: float,250             frequency: str = "monthly",251             compounding: str = "semi-annual") -> float:252    """Prêt maximal finançable avec un versement donné (calcul inverse)."""253    if target_payment <= 0:254        return 0.0255    if frequency in ("accelerated-biweekly", "accelerated-weekly"):256        # équivalent : versement mensuel = paiement × 2 ou × 4257        mult = 2 if frequency == "accelerated-biweekly" else 4258        return max_loan(target_payment * mult, annual_pct, amort_years,259                        "monthly", compounding)260    i = periodic_rate(annual_pct, frequency, compounding)261    n = round(amort_years * FREQUENCIES[frequency])262    if i == 0:263        return round(target_payment * n, 2)264    return round(target_payment * (1.0 - (1.0 + i) ** -n) / i, 2)265266267def required_rate(principal: float, target_payment: float, amort_years: float,268                  frequency: str = "monthly",269                  compounding: str = "semi-annual") -> float | None:270    """Taux annuel (%) tel que le versement du prêt = `target_payment`.271    Bisection sur [0, 25]. None si même 0 % ne suffit pas."""272    if principal <= 0 or target_payment <= 0:273        return None274    if payment(principal, 0.0, amort_years, frequency, compounding) > target_payment:275        return None276    lo, hi = 0.0, 25.0277    if payment(principal, hi, amort_years, frequency, compounding) < target_payment:278        return hi279    for _ in range(60):280        mid = (lo + hi) / 2281        if payment(principal, mid, amort_years, frequency, compounding) > target_payment:282            hi = mid283        else:284            lo = mid285    return round(lo, 2)286287288def qualifying_rate(contract_pct: float) -> float:289    """Taux de qualification du test de résistance canadien."""290    return round(max(contract_pct + STRESS_TEST_BUFFER, STRESS_TEST_FLOOR), 2)291292293def stress_scenarios(principal: float, annual_pct: float, amort_years: float,294                     frequency: str = "monthly",295                     compounding: str = "semi-annual",296                     bumps: tuple = (0.0, 1.0, 2.0, 3.0)) -> list[dict]:297    """« Et si les taux montent ? » — versement à +0/+1/+2/+3 points."""298    return [{299        "bump": b,300        "rate": round(annual_pct + b, 2),301        "payment": payment(principal, annual_pct + b, amort_years,302                           frequency, compounding),303    } for b in bumps]304305306def renewal_scenarios(principal: float, annual_pct: float, amort_years: float,307                      term_months: int, frequency: str = "monthly",308                      compounding: str = "semi-annual",309                      bumps: tuple = (-1.0, 0.0, 1.0, 2.0)) -> dict:310    """Scénario de renouvellement : solde restant à la fin du terme, puis311    versement recalculé sur l'amortissement résiduel à divers taux."""312    summary = term_summary(principal, annual_pct, amort_years, term_months,313                           frequency, compounding)314    balance = summary["balance_end_of_term"]315    remaining_years = max(amort_years - term_months / 12.0, 1.0)316    rows = []317    for b in bumps:318        r = round(annual_pct + b, 2)319        if r <= 0 or balance <= 0:320            continue321        rows.append({"bump": b, "rate": r,322                     "payment": payment(balance, r, remaining_years,323                                        frequency, compounding)})324    return {"balance_at_renewal": balance,325            "remaining_amortization_years": round(remaining_years, 1),326            "scenarios": rows}327328329def gds_tds(gross_annual_income: float, mortgage_payment_monthly: float,330            property_tax_monthly: float = 0.0, heating_monthly: float = 0.0,331            condo_fees_monthly: float = 0.0,332            other_debts_monthly: float = 0.0) -> dict:333    """Ratios ABD/ATD (GDS/TDS). Convention : 50 % des frais de copropriété.334    Seuils usuels assurés SCHL : ABD ≤ 39 %, ATD ≤ 44 %. Informatif seulement."""335    if gross_annual_income <= 0:336        return {"gds": None, "tds": None, "gds_ok": None, "tds_ok": None}337    monthly_income = gross_annual_income / 12.0338    housing = (mortgage_payment_monthly + property_tax_monthly +339               heating_monthly + 0.5 * condo_fees_monthly)340    gds = round(100.0 * housing / monthly_income, 1)341    tds = round(100.0 * (housing + other_debts_monthly) / monthly_income, 1)342    return {"gds": gds, "tds": tds, "gds_ok": gds <= 39.0, "tds_ok": tds <= 44.0,343            "gds_limit": 39.0, "tds_limit": 44.0}344
Files main
Menu

Theme