SPB Git

Repository Public

bmo.py 9.2 KB 222 lines python

1# =============================================================================2#                  SP BOUCHER | SOFTWARE & RESEARCH3#             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project          : Immo·Ka9# File             : immoka/mortgage/providers/bmo.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/providers/bmo.py : BMO — 3 JSON publics public-data (spéciaux,91#   grille affichée EPM, prime). ⚠️ bmo.com filtre l'empreinte TLS (Akamai) :92#   cascade requests → curl_cffi (si dispo) → Scrapfly asp. Les clés Over2593#   sont les variantes amortissement > 25 ans ; 18YearOpen et 12Variable*94#   sont des reliquats hérités (valeurs figées) et sont ignorés.95# -----------------------------------------------------------------------------96from __future__ import annotations9798import json99100from .base import RateProvider101102URLS = {103    "ca-mortgages-special-rates":104        "https://www.bmo.com/public-data/api/v2.0/bmo-ca-mortgages-rates.json",105    "epm-mortgage":106        "https://www.bmo.com/public-data/api/epm/v1.0/bmo-epm-mortgage.json",107    "epm-prime":108        "https://www.bmo.com/public-data/api/epm/v1.0/bmo-epm-prime.json",109}110PAGE_URL = "https://www.bmo.com/en-ca/main/personal/mortgages/mortgage-rates/"111112# clé spéciale -> (rate_type, terme mois, nom, clé APR, amort max, insured)113SPECIAL_MAP: dict[str, tuple] = {114    "fixed3YearClosedSpecial":115        ("fixed", 36, "Fixe fermé 3 ans (offre spéciale)",116         "fixed3YearClosedSpecialApr", 25, "unknown"),117    "fixed3YearClosedSpecialOver25":118        ("fixed", 36, "Fixe fermé 3 ans (offre spéciale, amort. >25 ans)",119         "fixed3YearClosedSpecialOver25Apr", 30, "uninsured"),120    "smartFixed5YearClosedSpecial":121        ("fixed", 60, "Smart Fixed fermé 5 ans (offre spéciale)",122         "smartFixed5YearClosedSpecialApr", 25, "uninsured"),123    "smartFixed5YearClosedHighRatioSpecial":124        ("fixed", 60, "Smart Fixed fermé 5 ans (offre spéciale, ratio élevé)",125         "smartFixed5YearClosedHighRatioSpecialApr", 25, "insured"),126    "variable5YearClosedSpecial":127        ("variable", 60, "Variable fermé 5 ans (offre spéciale)",128         "variable5YearClosedSpecialApr", 25, "unknown"),129    "variable5YearClosedSpecialOver25":130        ("variable", 60, "Variable fermé 5 ans (offre spéciale, amort. >25 ans)",131         "variable5YearClosedSpecialOver25Apr", 30, "uninsured"),132}133134EPM_SKIP = {"18YearOpen", "12VariableLimited", "12VariableOpen"}135136137def _num(v) -> float | None:138    try:139        return float(str(v).strip())140    except (TypeError, ValueError):141        return None142143144class BmoProvider(RateProvider):145    provider_id = "bmo"146    institution = "BMO Banque de Montréal"147    source_url = PAGE_URL148    request_delay = 1.2149150    def _get_json_text(self, url: str) -> str:151        try:152            return self.get(url).text153        except Exception:  # noqa: BLE001 — TLS Akamai : on escalade154            pass155        try:156            from curl_cffi import requests as curl_requests157            resp = curl_requests.get(url, impersonate="chrome",158                                     timeout=self.timeout)159            resp.raise_for_status()160            return resp.text161        except ImportError:162            pass163        return self.get_scrapfly(url, render_js=False, asp=True)164165    def fetch(self) -> list[dict]:166        docs: dict[str, dict] = {}167        for key, url in URLS.items():168            text = self._get_json_text(url)169            docs[key] = json.loads(text)170        return self.parse_docs(docs)171172    def parse(self, payload: str) -> list[dict]:173        """Pour les tests fixtures : payload = JSON {clé: {url, payload}}."""174        data = json.loads(payload)175        docs: dict[str, dict] = {}176        for key, entry in data.items():177            doc = entry.get("payload") if isinstance(entry, dict) and \178                "payload" in entry else entry179            if isinstance(doc, str):180                doc = json.loads(doc)181            docs[key] = doc182        return self.parse_docs(docs)183184    def parse_docs(self, docs: dict[str, dict]) -> list[dict]:185        out: list[dict] = []186        specials = docs.get("ca-mortgages-special-rates") or {}187        for key, (rtype, term, name, apr_key, amort, insured) in \188                SPECIAL_MAP.items():189            rate = _num(specials.get(key))190            if rate is None or rate <= 0:191                continue192            out.append(self.make_product(193                rate=rate, rate_type=rtype, term_months=term, kind="special",194                product_name=name, apr=_num(specials.get(apr_key)),195                insured_status=insured, amortization_max_years=amort,196                raw={"key": key, "value": specials.get(key)}))197        epm = docs.get("epm-mortgage") or {}198        grid = epm.get("mortgageRates") or epm199        for rtype_key, rtype, prefix in (("fixed", "fixed", "Fixe"),200                                         ("variable", "variable", "Variable")):201            for key, cell in (grid.get(rtype_key) or {}).items():202                if key in EPM_SKIP or not isinstance(cell, dict):203                    continue204                rate = _num(cell.get("value"))205                term = _num(cell.get("term_months"))206                if rate is None or rate <= 0 or not term:207                    continue208                label = cell.get("fr") or cell.get("en") or key209                out.append(self.make_product(210                    rate=rate, rate_type=rtype, term_months=int(term),211                    kind="posted", product_name=f"{prefix} {label}",212                    raw={"key": key, "cell": cell}))213        prime = docs.get("epm-prime") or {}214        prime_rate = _num((prime.get("caPrimeRate") or {}).get("value"))215        if prime_rate and prime_rate > 0:216            out.append(self.make_product(217                rate=prime_rate, rate_type="other", term_months=12,218                kind="posted", product_name="Taux préférentiel BMO",219                purpose="unknown",220                raw={"caPrimeRate": prime.get("caPrimeRate")}))221        return out222
Files main
Menu

Theme