Repository Public
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project : Immo-Ka iOS9// File : ImmoKa/Core/Finance/Mortgage.swift10// Module : ImmoKa11// Repository : https://git.spboucher.ai/immo-ka-ios-v312// Project Website : https://www.immo-ka.com13// Created : 2026-11-2514// Last Modified : 2026-11-2515//16// =============================================================================17// AUTHOR & PROFESSIONAL AFFILIATION18// =============================================================================19//20// Author : Simon-Pierre Boucher21// Position : Professor of Finance22// Institution : Université du Québec en Outaouais (UQO)23// Department : Département des sciences administratives24// Organization : SP Boucher25//26// Website : https://spboucher.ai27// Git : https://git.spboucher.ai28//29// =============================================================================30// OFFICIAL CONTACT DIRECTORY31// =============================================================================32//33// General : info@spboucher.ai34// Professional : contact@spboucher.ai35// Direct : simon@spboucher.ai36// Research : research@spboucher.ai37// Development : dev@spboucher.ai38// Support : support@spboucher.ai39// Security/Admin : admin@spboucher.ai40// Notifications : notifications@spboucher.ai41//42// Preferred Contact: support@spboucher.ai43//44// =============================================================================45// COPYRIGHT & INTELLECTUAL PROPERTY46// =============================================================================47//48// Copyright (c) 202649// Simon-Pierre Boucher50//51// All rights reserved where applicable.52//53// This file is governed by the applicable project license,54// copyright notices, institutional agreements and relevant law.55//56// Unless expressly authorized by the applicable license or57// rights holder, copying, redistribution, sublicensing,58// publication and commercial exploitation are not permitted.59//60// Existing third-party rights and notices remain unaffected.61//62// =============================================================================63// CONFIDENTIALITY & SECURITY64// =============================================================================65//66// Classification : Public67// Distribution : Public repository; use is governed by the project license68// Security Contact : admin@spboucher.ai69//70// Access to this source does not independently grant permission71// to redistribute or disclose confidential materials.72//73// Do not embed credentials, private keys, access tokens,74// certificates or confidential personal information.75//76// =============================================================================77// LICENSE & MAINTENANCE78// =============================================================================79//80// License : None specified (no license file in this repository)81// Maintainer : Simon-Pierre Boucher82// Technical Contact: dev@spboucher.ai83//84// =============================================================================85// END OF SP BOUCHER SOURCE HEADER86// =============================================================================8788//89// Immo-Ka iOS v290// File: ImmoKa/Core/Finance/Mortgage.swift91// Description: calculs de financement d'un achat au Québec — versement hypothécaire, mise de fonds minimale,92// assurance prêt, droits de mutation, test de résistance. Logique pure, testée. Tous les93// résultats sont des ESTIMATIONS à présenter comme telles (elles ne remplacent ni un prêteur94// ni un notaire).95//96// Règles vérifiées le 2026-11-25, sources :97// · Droits de mutation, barème de base 2026 (0,5 % jusqu'à 62 900 $, 1 % jusqu'à 315 000 $, 1,5 % au-delà ;98// indexation de 2,3438 %, Gazette officielle du Québec, Partie 1, 7 juin 2025) :99// https://www.quebec.ca/gouvernement/gestion-municipale/finances-fiscalite-municipales/fiscalite/droits-mutations-immobilieres100// Loi concernant les droits sur les mutations immobilières : https://legisquebec.gouv.qc.ca/fr/showdoc/cs/d-15.1101// · Tranches municipales 2026 (pages officielles des villes) : Montréal102// https://montreal.ca/articles/comment-sont-calcules-les-droits-sur-les-mutations-immobilieres-9279 ;103// Québec https://www.ville.quebec.qc.ca/citoyens/taxes_evaluation/droits_mutation_immobiliere.aspx ;104// Laval https://www.laval.ca/taxes-evaluation-fonciere/droits-mutation-immobiliere ;105// Gatineau https://www.gatineau.ca/portail/default.aspx?p=guichet_municipal%2Ftaxes_municipales%2Fbase_imposition_droits_mutation_immobiliere_taxe_bienvenue ;106// Longueuil https://droitsmutation.longueuil.quebec ; Sherbrooke, Lévis, Trois-Rivières, Saguenay, Terrebonne,107// Brossard, Repentigny, Saint-Jean-sur-Richelieu, Drummondville, Granby, Mirabel, Blainville, Saint-Jérôme108// (pages « taxes » de chaque ville). Autres villes à 3 % dès 500 000 $ : tableau de109// https://www.calculconversion.com/calcul-taxe-de-bienvenue-mutation.html (source secondaire, 21 janv. 2026).110// · Assurance prêt (SCHL, Sagen, Canada Guaranty — même barème) :111// https://www.cmhc-schl.gc.ca/professionals/project-funding-and-mortgage-financing/mortgage-loan-insurance/mortgage-loan-insurance-homeownership-programs/premium-information-for-homeowner-and-small-rental-loans112// https://www.sagen.ca/products-and-services/homebuyer-95 ; réformes du 15 déc. 2024 (plafond de 1,5 M$,113// amortissement de 30 ans pour premiers acheteurs et constructions neuves) :114// https://www.canada.ca/fr/ministere-finances/nouvelles/2024/09/mise-en-uvre-des-reformes-hypothecaires-les-plus-audacieuses-des-dernieres-decennies.html115// · Mise de fonds minimale (ACFC) :116// https://www.canada.ca/fr/agence-consommation-matiere-financiere/services/hypotheques/combien-mise-de-fonds.html117// · Taxe sur la prime d'assurance au Québec : 9 % pour les primes payées jusqu'au 31 déc. 2026, 9,975 % ensuite ;118// payable comptant, jamais ajoutée au prêt :119// https://www.revenuquebec.ca/fr/salle-de-presse/nouvelles-fiscales/details/2026-04-09/uniformisation-du-taux-de-la-taxe-sur-les-primes-dassurance-avec-celui-de-la-tvq120// · Test de résistance, max(taux + 2 points, 5,25 %) (BSIF) :121// https://www.osfi-bsif.gc.ca/en/supervision/financial-institutions/banks/minimum-qualifying-rate-uninsured-mortgages122// · Capitalisation semestrielle des prêts à taux fixe (Loi sur l'intérêt, art. 6) :123// https://laws-lois.justice.gc.ca/fra/lois/i-15/page-1.html124//125// Author: Simon-Pierre Boucher126// Contact: contact@spboucher.ai127//128129import Foundation130131enum Mortgage {132 // MARK: Versement133134 /// Taux périodique mensuel. Taux fixe : capitalisation semestrielle, i = (1 + r/2)^(1/6) − 1 ;135 /// taux variable : capitalisation mensuelle, i = r/12. `annualPct` en pourcentage (4,74).136 static func monthlyRate(annualPct: Double, fixed: Bool = true) -> Double {137 let r = annualPct / 100138 return fixed ? pow(1 + r / 2, 1.0 / 6.0) - 1 : r / 12139 }140141 /// Versement mensuel : P × i / (1 − (1 + i)^−N).142 static func monthlyPayment(principal: Double, annualPct: Double, years: Int, fixed: Bool = true) -> Double {143 guard principal > 0, years > 0 else { return 0 }144 let n = Double(years * 12)145 let i = monthlyRate(annualPct: annualPct, fixed: fixed)146 if i <= 0 { return principal / n }147 return principal * i / (1 - pow(1 + i, -n))148 }149150 /// Solde du prêt après `months` versements.151 static func balance(principal: Double, annualPct: Double, years: Int, afterMonths months: Int, fixed: Bool = true) -> Double {152 let i = monthlyRate(annualPct: annualPct, fixed: fixed)153 let pay = monthlyPayment(principal: principal, annualPct: annualPct, years: years, fixed: fixed)154 if i <= 0 { return max(0, principal - pay * Double(months)) }155 let g = pow(1 + i, Double(months))156 return max(0, principal * g - pay * (g - 1) / i)157 }158159 /// Solde restant à la fin de chaque année (courbe d'amortissement), année 0 comprise.160 static func yearlyBalances(principal: Double, annualPct: Double, years: Int, fixed: Bool = true) -> [Double] {161 (0...max(0, years)).map { balance(principal: principal, annualPct: annualPct, years: years, afterMonths: $0 * 12, fixed: fixed) }162 }163164 /// Taux de qualification du test de résistance : max(taux contractuel + 2 points, 5,25 %).165 static func qualifyingRate(_ annualPct: Double) -> Double { max(annualPct + 2, 5.25) }166167 // MARK: Mise de fonds et assurance prêt168169 /// Prix à partir duquel un prêt n'est plus assurable (mise de fonds de 20 % exigée).170 static let maxInsurablePrice = 1_500_000.0171172 /// Mise de fonds minimale : 5 % des premiers 500 000 $, 10 % de l'excédent ; 20 % à 1,5 M$ et plus.173 static func minDownPayment(price: Double) -> Double {174 guard price > 0 else { return 0 }175 if price >= maxInsurablePrice { return 0.20 * price }176 return 0.05 * min(price, 500_000) + 0.10 * max(0, price - 500_000)177 }178179 /// Barème des primes (rapport prêt-valeur maximal, prime en fraction du prêt).180 static let premiumTable: [(ltv: Double, rate: Double)] = [181 (0.65, 0.0060), (0.75, 0.0170), (0.80, 0.0240), (0.85, 0.0280), (0.90, 0.0310), (0.95, 0.0400),182 ]183 /// Surprime pour un amortissement assuré de plus de 25 ans (premier acheteur ou construction neuve).184 static let surcharge30Years = 0.0020185186 /// Taux de la taxe québécoise sur la prime, selon la date de paiement de la prime.187 static func premiumTaxRate(on date: Date = Date()) -> Double {188 var c = DateComponents(); c.year = 2027; c.month = 1; c.day = 1189 let pivot = Calendar(identifier: .gregorian).date(from: c) ?? .distantFuture190 return date < pivot ? 0.09 : 0.09975191 }192193 struct Insurance: Equatable, Sendable {194 /// la mise de fonds est sous 20 % : l'assurance est exigée195 var required: Bool196 /// le prêt peut être assuré (prix sous 1,5 M$, mise de fonds minimale respectée, amortissement admis)197 var eligible: Bool198 var ltv: Double199 var premiumRate: Double200 /// prime, ajoutée au prêt201 var premium: Double202 /// taxe sur la prime, payable comptant chez le notaire203 var tax: Double204 var issue: String?205 }206207 static func insurance(price: Double, downPayment: Double, years: Int, date: Date = Date()) -> Insurance {208 guard price > 0 else { return Insurance(required: false, eligible: true, ltv: 0, premiumRate: 0, premium: 0, tax: 0) }209 let loan = max(0, price - downPayment)210 let ltv = loan / price211 if ltv <= 0.80 + 1e-9 { return Insurance(required: false, eligible: true, ltv: ltv, premiumRate: 0, premium: 0, tax: 0) }212 var issue: String?213 if price >= maxInsurablePrice { issue = "À 1,5 M$ et plus, une mise de fonds d'au moins 20 % est exigée." }214 else if downPayment + 0.5 < minDownPayment(price: price) { issue = "Mise de fonds sous le minimum légal de \(Fmt.money(minDownPayment(price: price)))." }215 else if years > 30 { issue = "Un prêt assuré s'amortit sur 30 ans au plus." }216 guard issue == nil, let row = premiumTable.first(where: { ltv <= $0.ltv + 1e-9 }) else {217 return Insurance(required: true, eligible: false, ltv: ltv, premiumRate: 0, premium: 0, tax: 0,218 issue: issue ?? "Mise de fonds sous le minimum légal.")219 }220 let rate = row.rate + (years > 25 ? surcharge30Years : 0)221 let premium = (loan * rate * 100).rounded() / 100222 return Insurance(required: true, eligible: true, ltv: ltv, premiumRate: rate, premium: premium,223 tax: (premium * premiumTaxRate(on: date) * 100).rounded() / 100,224 issue: years > 25 ? "Amortissement de 30 ans : réservé aux premiers acheteurs et aux constructions neuves." : nil)225 }226227 // MARK: Droits de mutation (« taxe de bienvenue »)228229 /// Tranches de base 2026, communes à tout le Québec : (plafond de la tranche, taux).230 static let transferBase: [(cap: Double, rate: Double)] = [(62_900, 0.005), (315_000, 0.010)]231232 /// Suite du barème après les deux tranches de base, par municipalité (2026).233 private static let std3: [(cap: Double, rate: Double)] = [(500_000, 0.015), (.infinity, 0.03)]234 private static let municipal: [String: [(cap: Double, rate: Double)]] = {235 var m: [String: [(cap: Double, rate: Double)]] = [236 "montreal": [(552_300, 0.015), (1_104_700, 0.02), (2_136_500, 0.025), (3_113_000, 0.035), (.infinity, 0.04)],237 "quebec": [(500_000, 0.015), (750_000, 0.025), (.infinity, 0.03)],238 "saguenay": [(500_000, 0.015), (1_000_000, 0.025), (.infinity, 0.03)],239 "longueuil": [(630_100, 0.015), (.infinity, 0.03)],240 "blainville": [(750_000, 0.015), (.infinity, 0.03)],241 "chateauguay": [(615_620, 0.015), (.infinity, 0.03)],242 "vaudreuil-dorion": [(619_300, 0.015), (.infinity, 0.03)],243 "boisbriand": [(500_000, 0.015), (800_000, 0.025), (.infinity, 0.03)],244 "dollard-des-ormeaux": [(500_000, 0.015), (750_000, 0.025), (.infinity, 0.03)],245 "farnham": [(500_000, 0.015), (750_000, 0.025), (.infinity, 0.03)],246 "cote-saint-luc": [(800_000, 0.015), (3_000_000, 0.025), (.infinity, 0.03)],247 "kirkland": [(500_000, 0.015), (1_000_000, 0.02), (.infinity, 0.025)],248 "magog": [(500_000, 0.015), (750_000, 0.02), (1_000_000, 0.025), (.infinity, 0.03)],249 "otterburn-park": [(500_000, 0.015), (750_000, 0.02), (1_000_000, 0.025), (.infinity, 0.03)],250 "montreal-est": [(500_000, 0.015), (750_000, 0.02), (1_000_000, 0.025), (.infinity, 0.03)],251 "mont-tremblant": [(500_000, 0.015), (750_000, 0.02), (.infinity, 0.03)],252 "saint-sauveur": [(500_000, 0.015), (750_000, 0.02), (.infinity, 0.03)],253 "morin-heights": [(500_000, 0.015), (1_000_000, 0.025), (.infinity, 0.03)],254 "sainte-julie": [(500_000, 0.015), (1_000_000, 0.025), (.infinity, 0.03)],255 "val-d-or": [(500_000, 0.015), (.infinity, 0.02)],256 ]257 // 3 % au-delà de 500 000 $ : confirmées sur leur site officiel, puis la liste secondaire258 for city in ["laval", "gatineau", "sherbrooke", "levis", "trois-rivieres", "terrebonne", "brossard", "repentigny",259 "saint-jean-sur-richelieu", "drummondville", "granby", "mirabel", "saint-jerome",260 "alma", "boucherville", "candiac", "chambly", "lorraine", "mascouche", "mcmasterville",261 "mont-saint-hilaire", "rimouski", "rosemere", "rouyn-noranda", "sainte-agathe-des-monts",262 "saint-bruno-de-montarville", "saint-bruno", "saint-colomban", "saint-eustache", "saint-hyacinthe",263 "saint-lambert", "sainte-therese", "salaberry-de-valleyfield", "shawinigan", "sorel-tracy",264 "val-david", "victoriaville"] {265 m[city] = std3266 }267 return m268 }()269270 /// Gatineau avant le 25 février 2026 (barème modifié en cours d'année).271 private static let gatineauBefore: [(cap: Double, rate: Double)] = [(750_000, 0.015), (1_000_000, 0.025), (.infinity, 0.03)]272273 struct TransferTax: Equatable, Sendable {274 struct Slice: Equatable, Sendable, Identifiable {275 var from: Double276 var to: Double277 var rate: Double278 var amount: Double279 var id: Double { from }280 }281 var total: Double282 var slices: [Slice]283 /// vrai : la ville a son propre barème au-delà de la base ; faux : barème de base du Québec284 var municipalScale: Bool285 }286287 /// Clé de municipalité : sans accents, minuscules, arrondissements de Montréal ramenés à la ville.288 static func municipalityKey(_ city: String) -> String {289 var s = Fmt.slug(city)290 if s.hasPrefix("ville-de-") { s.removeFirst(9) }291 if s.hasPrefix("montreal-") && s != "montreal-est" && s != "montreal-ouest" { return "montreal" }292 if s.hasPrefix("quebec-") { return "quebec" }293 if s.hasPrefix("gatineau-") { return "gatineau" }294 if s.hasPrefix("laval-") { return "laval" }295 if s.hasPrefix("longueuil-") { return "longueuil" }296 return s297 }298299 /// Droits de mutation sur une base d'imposition (en pratique : le prix payé, ou la valeur au rôle300 /// multipliée par le facteur comparatif si elle est plus élevée). Exonération sous 5 000 $.301 static func transferTax(base: Double, city: String, date: Date = Date()) -> TransferTax {302 guard base >= 5_000 else { return TransferTax(total: 0, slices: [], municipalScale: false) }303 let key = municipalityKey(city)304 var upper = municipal[key]305 if key == "gatineau" {306 var c = DateComponents(); c.year = 2026; c.month = 2; c.day = 25307 if let pivot = Calendar(identifier: .gregorian).date(from: c), date < pivot { upper = gatineauBefore }308 }309 let scale = transferBase + (upper ?? [(.infinity, 0.015)])310 var slices: [TransferTax.Slice] = []311 var floor = 0.0312 for (cap, rate) in scale {313 guard base > floor else { break }314 let top = min(base, cap)315 slices.append(.init(from: floor, to: top, rate: rate, amount: (top - floor) * rate))316 floor = cap317 }318 let total = (slices.reduce(0) { $0 + $1.amount } * 100).rounded() / 100319 return TransferTax(total: total, slices: slices, municipalScale: upper != nil)320 }321322 // MARK: Scénario complet323324 struct Scenario: Equatable, Sendable {325 var price: Double326 var downPayment: Double327 var annualPct: Double328 var years: Int329 var fixed: Bool = true330 var city: String = ""331 }332333 struct Result: Equatable, Sendable {334 var loan: Double // prêt avant prime335 var insurance: Insurance336 var principal: Double // prêt, prime comprise337 var monthly: Double338 var totalInterest: Double // sur tout l'amortissement, à taux constant339 var transferTax: TransferTax340 /// à prévoir à la clôture : mise de fonds, droits de mutation, taxe sur la prime341 var cashAtClosing: Double342 var qualifyingRate: Double343 var qualifyingMonthly: Double344 var minDown: Double345 }346347 static func compute(_ s: Scenario, date: Date = Date()) -> Result {348 let down = min(max(0, s.downPayment), s.price)349 let loan = max(0, s.price - down)350 let ins = insurance(price: s.price, downPayment: down, years: s.years, date: date)351 let principal = loan + (ins.eligible ? ins.premium : 0)352 let monthly = monthlyPayment(principal: principal, annualPct: s.annualPct, years: s.years, fixed: s.fixed)353 let tax = transferTax(base: s.price, city: s.city, date: date)354 let q = qualifyingRate(s.annualPct)355 return Result(loan: loan, insurance: ins, principal: principal, monthly: monthly,356 totalInterest: max(0, monthly * Double(s.years * 12) - principal),357 transferTax: tax, cashAtClosing: down + tax.total + ins.tax,358 qualifyingRate: q,359 qualifyingMonthly: monthlyPayment(principal: principal, annualPct: q, years: s.years, fixed: s.fixed),360 minDown: minDownPayment(price: s.price))361 }362}363