SPB Git

Repository Public

cibc.py 9.2 KB 231 lines python

1# =============================================================================2#                  SP BOUCHER | SOFTWARE & RESEARCH3#             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project          : Immo·Ka9# File             : immoka/mortgage/providers/cibc.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/cibc.py : CIBC — pseudo-JSON JS productRatesLegacy91#   (blocs `var CODE = {...}` avec lignes [terme, ?, colId, valeur, …]).92#   colId 1 = affiché, 18 = spécial, 2 = APR du spécial ; sentinelle93#   -99.999999991 et spécial 0.00 = non publié ; colId 34 = colonne94#   d'identité inconnue, jamais devinée. MICRO/MICROVAR ne portent que95#   l'offre spéciale (leur « affiché » duplique FRCM).96# -----------------------------------------------------------------------------97from __future__ import annotations9899import re100101from .base import RateProvider102103BASE_URL = ("https://www.cibconline.cibc.com/ebm-pno/api/v1/json/"104            "productRatesLegacy?lobId={lob}&sourceProductCode={codes}")105LOB5_CODES = "FRCM,FOM,CCM,5YRVARCLO,MICRO,MICROVAR,VROM"106PAGE_URL = "https://www.cibc.com/en/interest-rates/mortgage-rates.html"107108COL_POSTED, COL_APR, COL_SPECIAL = 1, 2, 18109SENTINEL = -99.0110111# code -> (rate_type, libellé de base, spécial seulement, libellé du spécial)112PRODUCTS: dict[str, tuple] = {113    "FRCM": ("fixed", "Fixe fermé", False, "offre spéciale"),114    "FOM": ("fixed", "Fixe ouvert", False, "offre spéciale"),115    "CCM": ("fixed", "Fermé convertible", False, "offre spéciale"),116    "5YRVARCLO": ("variable", "Variable Flex fermé", False, "offre spéciale"),117    "VROM": ("variable", "Variable ouvert", False, "offre spéciale"),118    # MICRO/MICROVAR : l'offre mise en avant sur la page des taux — libellé119    # distinct pour ne pas entrer en collision avec le spécial FRCM/5YRVARCLO.120    "MICRO": ("fixed", "Fixe fermé", True, "offre annoncée"),121    "MICROVAR": ("variable", "Variable Flex fermé", True, "offre annoncée"),122}123124BLOCK_RX = re.compile(r"var\s+(\w+)\s*=\s*\{(.*?)\]\s*\}", re.S)125ROW_RX = re.compile(r"\[([^\[\]]*)\]")126TERM_RX = re.compile(r"^(\d{1,3})_.*_(Year|Years|Month|Months)_T$")127128129def _cells(row: str) -> list:130    out = []131    for cell in row.split(","):132        c = cell.strip().strip("'\"")133        out.append(None if c == "null" else c)134    return out135136137def _term_months(token) -> int | None:138    m = TERM_RX.match(str(token or ""))139    if not m:140        return None141    n = int(m.group(1))142    return n * 12 if m.group(2).startswith("Year") else n143144145def _num(v) -> float | None:146    try:147        return float(str(v).strip())148    except (TypeError, ValueError):149        return None150151152def _label(months: int) -> str:153    if months < 12:154        return f"{months} mois"155    years = months // 12156    return f"{years} an" if years == 1 else f"{years} ans"157158159class CibcProvider(RateProvider):160    provider_id = "cibc"161    institution = "CIBC"162    source_url = PAGE_URL163    request_delay = 1.2164165    def fetch(self) -> list[dict]:166        text = self.get(BASE_URL.format(lob=5, codes=LOB5_CODES)).text167        try:168            text += "\n" + self.get(BASE_URL.format(lob=1, codes="PRIME")).text169        except Exception:  # noqa: BLE001 — prime facultatif170            pass171        return self.parse(text)172173    def parse(self, payload: str) -> list[dict]:174        out: list[dict] = []175        for var_name, body in BLOCK_RX.findall(payload):176            name = var_name[1:] if var_name[:1] == "p" and \177                var_name[1:2].isdigit() else var_name178            if name == "PRIME":179                out.extend(self._parse_prime(body))180                continue181            if name not in PRODUCTS:182                continue183            rtype, base_label, special_only, special_label = PRODUCTS[name]184            # (terme -> {colId: valeur})185            grid: dict[int, dict[int, float]] = {}186            for row in ROW_RX.findall(body):187                cells = _cells(row)188                if len(cells) < 4:189                    continue190                term = _term_months(cells[0])191                col = _num(cells[2])192                val = _num(cells[3])193                if term is None or col is None or val is None:194                    continue195                if val < SENTINEL + 1 or val <= 0:196                    continue  # sentinelle -99.999999991 ou 0.00 : non publié197                grid.setdefault(term, {})[int(col)] = val198            for term, cols in sorted(grid.items()):199                posted = cols.get(COL_POSTED)200                special = cols.get(COL_SPECIAL)201                if posted and not special_only:202                    out.append(self.make_product(203                        rate=posted, rate_type=rtype, term_months=term,204                        kind="posted",205                        product_name=f"{base_label} {_label(term)}",206                        conditions="Base = taux préférentiel CIBC"207                                   if rtype == "variable" and name == "5YRVARCLO"208                                   else None,209                        raw={"code": name, "cols": cols}))210                if special:211                    out.append(self.make_product(212                        rate=special, rate_type=rtype, term_months=term,213                        kind="special", apr=cols.get(COL_APR),214                        product_name=f"{base_label} {_label(term)} "215                                     f"({special_label})",216                        raw={"code": name, "cols": cols}))217        return out218219    def _parse_prime(self, body: str) -> list[dict]:220        for row in ROW_RX.findall(body):221            cells = _cells(row)222            if len(cells) < 4:223                continue224            rate = _num(cells[3])225            if rate and rate > 0:226                return [self.make_product(227                    rate=rate, rate_type="other", term_months=12,228                    kind="posted", product_name="Taux préférentiel CIBC",229                    purpose="unknown", raw={"code": "PRIME", "value": rate})]230        return []231
Files main
Menu

Theme