Repository Public
1# =============================================================================2# SP BOUCHER | SOFTWARE & RESEARCH3# ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project : Immo·Ka9# File : immoka/mortgage/api.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/api.py : routes /api/mortgage/* — taux courants, meilleur taux,91# historique, santé des providers, calculateur canadien, abordabilité.92# Lecture seule sur mortgage.db (le scheduler écrit) ; cache applicatif93# 5 min sur les lectures ; jamais d'internals de scraping exposés (le champ94# raw est retiré au niveau du store).95# -----------------------------------------------------------------------------96from __future__ import annotations9798import time99100from fastapi import APIRouter, Body, HTTPException, Query101102from . import calc, cmhc, store103104router = APIRouter(prefix="/api/mortgage", tags=["mortgage"])105106CACHE_TTL_S = 300107_cache: dict[str, tuple[float, object]] = {}108109RATE_TYPES = {"fixed", "variable", "adjustable", "other"}110KINDS = {"posted", "special"}111INSURED = {"insured", "insurable", "uninsured", "unknown"}112113114def _cached(key: str, builder):115 hit = _cache.get(key)116 now = time.time()117 if hit and now - hit[0] < CACHE_TTL_S:118 return hit[1]119 value = builder()120 _cache[key] = (now, value)121 if len(_cache) > 512: # borne mémoire : purge des entrées expirées122 for k in [k for k, (t, _) in _cache.items() if now - t >= CACHE_TTL_S]:123 _cache.pop(k, None)124 return value125126127def _check(value, allowed: set, label: str):128 if value is not None and value not in allowed:129 raise HTTPException(422, f"{label} invalide : {value}")130 return value131132133@router.get("/rates")134def rates(rate_type: str | None = None, term_months: int | None = None,135 kind: str | None = None, insured_status: str | None = None,136 purpose: str | None = Query("purchase"),137 provider: str | None = None):138 """Taux courants (dernière donnée valide par produit), filtrables."""139 _check(rate_type, RATE_TYPES, "rate_type")140 _check(kind, KINDS, "kind")141 _check(insured_status, INSURED, "insured_status")142 if purpose in ("", "all"):143 purpose = None144 key = f"rates|{rate_type}|{term_months}|{kind}|{insured_status}|{purpose}|{provider}"145146 def build():147 con = store.connect()148 rows = store.current_rates(149 con, rate_type=rate_type, term_months=term_months, kind=kind,150 insured_status=insured_status, purpose=purpose, provider=provider)151 con.close()152 return {"count": len(rows), "rates": rows,153 "stale_hours_threshold": store.STALE_H}154 return _cached(key, build)155156157@router.get("/rates/best")158def rates_best(rate_type: str = "fixed", term_months: int = 60,159 insured_status: str | None = None, purpose: str = "purchase"):160 """Meilleur taux courant par produit comparable + comparateur par banque."""161 _check(rate_type, RATE_TYPES, "rate_type")162 _check(insured_status, INSURED, "insured_status")163 key = f"best|{rate_type}|{term_months}|{insured_status}|{purpose}"164165 def build():166 con = store.connect()167 best = store.best_rate(con, rate_type=rate_type,168 term_months=term_months,169 insured_status=insured_status, purpose=purpose)170 con.close()171 if best is None:172 raise HTTPException(404, "Aucun taux courant pour ces critères")173 return best174 return _cached(key, build)175176177@router.get("/rates/history")178def rates_history(rate_type: str = "fixed", term_months: int = 60,179 provider: str | None = None, kind: str | None = None,180 days: int = 365):181 """Périodes de validité par produit — reconstruit « le taux X à date ». """182 _check(rate_type, RATE_TYPES, "rate_type")183 _check(kind, KINDS, "kind")184 days = max(1, min(days, 730))185 key = f"hist|{rate_type}|{term_months}|{provider}|{kind}|{days}"186187 def build():188 con = store.connect()189 rows = store.history(con, rate_type, term_months,190 provider=provider, kind=kind, days=days)191 con.close()192 return {"count": len(rows), "days": days, "history": rows}193 return _cached(key, build)194195196@router.get("/providers")197def providers():198 """Santé des connecteurs de taux (OK / WARNING / ERROR + fraîcheur)."""199 def build():200 from .providers import PROVIDERS201 con = store.connect()202 health = store.provider_health(con)203 con.close()204 names = {slug: cls.institution for slug, cls in PROVIDERS.items()}205 urls = {slug: cls.source_url for slug, cls in PROVIDERS.items()}206 out = []207 for h in health:208 out.append({209 "provider": h["provider"],210 "institution": names.get(h["provider"], h["provider"]),211 "source_url": urls.get(h["provider"]),212 "level": h["level"],213 "status": h["status"],214 "age_minutes": h["age_minutes"],215 "current_products": h["current_products"],216 "last_data_at": h["last_data_at"],217 })218 return {"providers": out,219 "registered": sorted(names),220 "stale_hours_threshold": store.STALE_H}221 return _cached("providers", build)222223224@router.get("/market")225def market(rate_type: str = "fixed", term_months: int = 60):226 """Métriques Mortgage Intelligence pour un produit donné."""227 _check(rate_type, RATE_TYPES, "rate_type")228229 def build():230 con = store.connect()231 stats = store.market_stats(con, rate_type=rate_type,232 term_months=term_months)233 con.close()234 if stats is None:235 raise HTTPException(404, "Aucun taux courant pour ces critères")236 return stats237 return _cached(f"market|{rate_type}|{term_months}", build)238239240@router.get("/intelligence")241def intelligence():242 """Vue d'ensemble du marché : les produits phares en un appel."""243 def build():244 con = store.connect()245 combos = [("fixed", 12), ("fixed", 36), ("fixed", 48),246 ("fixed", 60), ("fixed", 120), ("variable", 60)]247 grid = []248 for rtype, term in combos:249 s = store.market_stats(con, rate_type=rtype, term_months=term)250 if s:251 grid.append(s)252 prime_rows = store.current_rates(con, rate_type="other")253 con.close()254 prime = [{"institution": r["institution"], "rate": r["rate"],255 "product_name": r["product_name"],256 "age_minutes": r["age_minutes"]}257 for r in prime_rows if "préférentiel" in258 (r["product_name"] or "").lower() or "prime" in259 (r["product_name"] or "").lower()]260 return {"products": grid, "prime_rates": prime}261 return _cached("intelligence", build)262263264# ---------------------------------------------------------------------------265# Calculateur266# ---------------------------------------------------------------------------267268def _pick_rate(rate_type: str, term_months: int,269 insured_status: str | None) -> dict | None:270 con = store.connect()271 best = store.best_rate(con, rate_type=rate_type, term_months=term_months,272 insured_status=insured_status)273 con.close()274 return best275276277def _validate_scenario(price: float, down: float, amort: int, term: int,278 frequency: str) -> None:279 if price <= 0 or price > 100_000_000:280 raise HTTPException(422, "Prix invalide")281 if down < 0 or down >= price:282 raise HTTPException(422, "Mise de fonds invalide")283 if amort not in calc.AMORTIZATIONS_YEARS and not (5 <= amort <= 30):284 raise HTTPException(422, "Amortissement invalide (5–30 ans)")285 if not 3 <= term <= 120:286 raise HTTPException(422, "Terme invalide (3–120 mois)")287 if frequency not in calc.FREQUENCIES:288 raise HTTPException(422, f"Fréquence invalide : {frequency}")289290291@router.post("/calculate")292def calculate(body: dict = Body(...)):293 """Calcul hypothécaire canadien complet pour un scénario.294295 Entrées : price, down_payment (ou down_payment_pct), amortization_years,296 term_months, frequency, rate_type, rate (sinon meilleur taux observé),297 insured_status?, include_schedule?, income?, other_debts_monthly?,298 property_tax_monthly?, heating_monthly?, condo_fees_monthly?.299 """300 try:301 price = float(body.get("price") or 0)302 if body.get("down_payment") is not None:303 down = float(body["down_payment"])304 else:305 down = price * float(body.get("down_payment_pct") or 20) / 100306 amort = int(body.get("amortization_years") or 25)307 term = int(body.get("term_months") or 60)308 frequency = str(body.get("frequency") or "monthly")309 rate_type = str(body.get("rate_type") or "fixed")310 except (TypeError, ValueError):311 raise HTTPException(422, "Paramètres numériques invalides")312 _check(rate_type, {"fixed", "variable"}, "rate_type")313 _validate_scenario(price, down, amort, term, frequency)314315 quote = cmhc.insurance_quote(price, down, amort)316 rate_source = None317 rate = body.get("rate")318 if rate is None:319 insured = "insured" if quote["required"] and quote["eligible"] else None320 best = _pick_rate(rate_type, term, insured)321 if best is None:322 raise HTTPException(323 503, "Aucun taux courant disponible — réessayez plus tard")324 rate = best["rate"]325 rate_source = {k: best[k] for k in326 ("provider", "institution", "product_name", "kind",327 "rate", "apr", "insured_status", "source_url",328 "last_checked", "age_minutes", "stale")}329 rate = float(rate)330 if not 0 < rate <= 25:331 raise HTTPException(422, "Taux invalide")332 if quote["required"] and not quote["eligible"]:333 principal = price - down # non assurable : calcul quand même, signalé334 else:335 principal = quote["total_mortgage"] if quote["required"] else price - down336337 compounding = "semi-annual" if rate_type == "fixed" else "monthly"338 pay = calc.payment(principal, rate, amort, frequency, compounding)339 monthly_eq = calc.payment(principal, rate, amort, "monthly", compounding)340 q_rate = calc.qualifying_rate(rate)341 q_pay = calc.payment(principal, q_rate, amort, frequency, compounding)342 out = {343 "inputs": {"price": price, "down_payment": round(down, 2),344 "down_payment_pct": round(down / price * 100, 2),345 "rate": rate, "rate_type": rate_type,346 "term_months": term, "amortization_years": amort,347 "frequency": frequency, "compounding": compounding},348 "insurance": quote,349 "principal": round(principal, 2),350 "payment": pay,351 "payment_monthly_equivalent": monthly_eq,352 "qualifying": {"rate": q_rate, "payment": q_pay,353 "note": "Test de résistance : max(taux + 2, 5,25 %)"},354 "term": calc.term_summary(principal, rate, amort, term,355 frequency, compounding),356 "stress": calc.stress_scenarios(principal, rate, amort,357 frequency, compounding),358 "renewal": calc.renewal_scenarios(principal, rate, amort, term,359 frequency, compounding),360 "payoff_years": calc.payoff_years(principal, rate, amort,361 frequency, compounding),362 "rate_source": rate_source,363 }364 rows = calc.schedule(principal, rate, amort, frequency, compounding)365 out["annual"] = calc.annual_rollup(rows, frequency)366 if body.get("include_schedule"):367 out["schedule"] = rows368 income = body.get("income")369 if income:370 out["ratios"] = calc.gds_tds(371 float(income), monthly_eq,372 float(body.get("property_tax_monthly") or 0),373 float(body.get("heating_monthly") or 0),374 float(body.get("condo_fees_monthly") or 0),375 float(body.get("other_debts_monthly") or 0))376 return out377378379@router.post("/affordability")380def affordability(body: dict = Body(...)):381 """Capacité d'achat : prix max selon un versement cible OU selon les382 revenus (ABD/ATD au taux de qualification) ; taux requis pour un383 versement cible vs meilleur taux observé."""384 try:385 amort = int(body.get("amortization_years") or 25)386 term = int(body.get("term_months") or 60)387 frequency = str(body.get("frequency") or "monthly")388 rate_type = str(body.get("rate_type") or "fixed")389 down = float(body.get("down_payment") or 0)390 except (TypeError, ValueError):391 raise HTTPException(422, "Paramètres numériques invalides")392 _check(rate_type, {"fixed", "variable"}, "rate_type")393 if frequency not in calc.FREQUENCIES:394 raise HTTPException(422, f"Fréquence invalide : {frequency}")395396 rate = body.get("rate")397 rate_source = None398 if rate is None:399 best = _pick_rate(rate_type, term, None)400 if best is None:401 raise HTTPException(402 503, "Aucun taux courant disponible — réessayez plus tard")403 rate = best["rate"]404 rate_source = {k: best[k] for k in405 ("provider", "institution", "product_name", "kind",406 "rate", "source_url", "age_minutes", "stale")}407 rate = float(rate)408 if not 0 < rate <= 25:409 raise HTTPException(422, "Taux invalide")410 compounding = "semi-annual" if rate_type == "fixed" else "monthly"411 q_rate = calc.qualifying_rate(rate)412 out: dict = {"rate": rate, "qualifying_rate": q_rate,413 "rate_source": rate_source}414415 target = body.get("target_payment_monthly")416 if target:417 target = float(target)418 loan = calc.max_loan(target, rate, amort, "monthly", compounding)419 loan_q = calc.max_loan(target, q_rate, amort, "monthly", compounding)420 out["from_payment"] = {421 "target_payment_monthly": target,422 "max_loan": loan, "max_price": round(loan + down, 2),423 "max_loan_stress_tested": loan_q,424 "max_price_stress_tested": round(loan_q + down, 2),425 }426 income = body.get("income")427 if income:428 income = float(income)429 gds_room = income / 12 * 0.39 \430 - float(body.get("property_tax_monthly") or 0) \431 - float(body.get("heating_monthly") or 0) \432 - float(body.get("condo_fees_monthly") or 0) * 0.5433 tds_room = income / 12 * 0.44 \434 - float(body.get("property_tax_monthly") or 0) \435 - float(body.get("heating_monthly") or 0) \436 - float(body.get("condo_fees_monthly") or 0) * 0.5 \437 - float(body.get("other_debts_monthly") or 0)438 room = max(0.0, min(gds_room, tds_room))439 loan_q = calc.max_loan(room, q_rate, amort, "monthly", compounding)440 out["from_income"] = {441 "income": income, "max_payment_monthly": round(room, 2),442 "max_loan_stress_tested": loan_q,443 "max_price_estimate": round(loan_q + down, 2),444 "note": ("Indicatif seulement (ABD 39 % / ATD 44 % au taux de "445 "qualification) — ne constitue pas une préapprobation."),446 }447 principal = body.get("principal")448 target_rate_payment = body.get("required_rate_for_payment")449 if principal and target_rate_payment:450 req = calc.required_rate(float(principal), float(target_rate_payment),451 amort, "monthly", compounding)452 out["required_rate"] = {453 "principal": float(principal),454 "target_payment_monthly": float(target_rate_payment),455 "rate": req,456 "achievable_now": req is not None and req >= rate,457 "best_observed": rate,458 }459 return out460