Repository Public
1# =============================================================================2# SP BOUCHER | SOFTWARE & RESEARCH3# ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project : Immo·Ka9# File : immoka/mortgage/providers/td.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/td.py : TD Canada Trust — API JSON publique getRates91# (POST ratesType=resl, celle que consomme leur page de taux). Chaque code92# MTG{F|V}{mois}{C|O} porte deux tableaux highRatio / nonHighRatio de la93# forme [affiché, escompte, spécial, APR, drapeau]. Le « affiché » des94# produits variables est le TD Mortgage Prime. ⚠️ Pour les termes sans offre95# spéciale réelle, TD publie un « spécial » reconstruit (escompte négatif)96# dont l'APR correspond en fait au taux AFFICHÉ : ces lignes incohérentes97# (APR < spécial) sont écartées — jamais interprétées.98# -----------------------------------------------------------------------------99from __future__ import annotations100101import json102import re103104from .base import RateProvider105106API_URL = "https://psservice.td.com/ca/en/carate/getRates"107PAGE_URL = ("https://www.td.com/ca/en/personal-banking/products/mortgages/"108 "mortgage-rates")109110CODE_RX = re.compile(r"^MTG([FV])(\d{3})([CO])$")111112IDX_POSTED, IDX_SPECIAL, IDX_APR = 0, 2, 3113114115def _num(v) -> float | None:116 try:117 return float(str(v).strip())118 except (TypeError, ValueError):119 return None120121122def _label(months: int) -> str:123 if months < 12:124 return f"{months} mois"125 years = months // 12126 return f"{years} an" if years == 1 else f"{years} ans"127128129class TdProvider(RateProvider):130 provider_id = "td"131 institution = "TD Canada Trust"132 source_url = PAGE_URL133 request_delay = 1.0134135 def fetch(self) -> list[dict]:136 wait_kw = {"timeout": self.timeout,137 "headers": {"Content-Type": "application/json"}}138 resp = self.session.post(API_URL, json={"ratesType": "resl"}, **wait_kw)139 resp.raise_for_status()140 return self.parse(resp.text)141142 def parse(self, payload: str) -> list[dict]:143 data = json.loads(payload)144 if not isinstance(data, dict):145 raise ValueError("réponse TD inattendue (structure changée)")146 for wrapper in ("rates", "data", "result"):147 if wrapper in data and isinstance(data[wrapper], dict):148 data = data[wrapper]149 break150 out: list[dict] = []151 prime: float | None = None152 for code, tables in data.items():153 m = CODE_RX.match(str(code))154 if not m or not isinstance(tables, dict):155 continue # FLT* (FlexLine/HELOC) et codes inconnus : ignorés156 rtype = "fixed" if m.group(1) == "F" else "variable"157 term = int(m.group(2))158 openness = "fermé" if m.group(3) == "C" else "ouvert"159 base = ("Fixe" if rtype == "fixed" else "Variable")160 non_hr = tables.get("nonHighRatio") or []161 high_r = tables.get("highRatio") or []162 posted = _num(non_hr[IDX_POSTED]) if len(non_hr) > IDX_POSTED else None163 if posted and posted > 0:164 if rtype == "variable":165 # l'« affiché » des codes MTGV est le TD Mortgage Prime,166 # pas le taux du produit : jamais émis comme taux variable167 prime = posted168 else:169 out.append(self.make_product(170 rate=posted, rate_type=rtype, term_months=term,171 kind="posted",172 product_name=f"{base} {openness} {_label(term)}",173 raw={"code": code, "row": non_hr}))174 for arr, insured, suffix in ((non_hr, "uninsured", ""),175 (high_r, "insured", ", ratio élevé")):176 if len(arr) <= IDX_APR:177 continue178 special = _num(arr[IDX_SPECIAL])179 if special is None or special <= 0:180 continue181 if posted is not None and special == posted and rtype == "fixed" \182 and _num(arr[1]) in (0, None):183 continue # pas de spécial publié pour ce produit184 apr = _num(arr[IDX_APR])185 if apr is not None and apr < special - 0.02:186 continue # « spécial » reconstruit : APR = celui du taux affiché187 out.append(self.make_product(188 rate=special, rate_type=rtype, term_months=term,189 kind="special", apr=apr,190 product_name=f"{base} {openness} {_label(term)} "191 f"(offre spéciale{suffix})",192 insured_status=insured,193 conditions="Base = TD Mortgage Prime"194 if rtype == "variable" else None,195 raw={"code": code, "row": arr}))196 if prime and prime > 0:197 out.append(self.make_product(198 rate=prime, rate_type="other", term_months=12, kind="posted",199 product_name="TD Mortgage Prime", purpose="unknown",200 raw={"field": "MTGV*[0]", "value": prime}))201 return out202