Repository Public
1# =============================================================================2# SP BOUCHER | SOFTWARE & RESEARCH3# ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project : Immo·Ka9# File : immoka/mortgage/validate.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/validate.py : couche de validation des observations de taux.91# Règle absolue : ne jamais inventer ni laisser passer un taux impossible.92# 4.19 % -> 419 % doit être rejeté ; une bonne donnée n'est jamais écrasée93# par une donnée manifestement erronée (garde-fou complémentaire dans94# store.record_observations).95# -----------------------------------------------------------------------------96from __future__ import annotations9798RATE_MIN = 0.25 # sous 0,25 % : impossible pour une hypothèque canadienne99RATE_MAX = 20.0 # au-delà de 20 % : aberrant (même les prêts privés)100TERM_MIN_MONTHS = 3101TERM_MAX_MONTHS = 120102103VALID_RATE_TYPES = {"fixed", "variable", "adjustable", "other"}104VALID_KINDS = {"posted", "special"}105VALID_INSURED = {"insured", "insurable", "uninsured", "unknown"}106VALID_PURPOSES = {"purchase", "renewal", "refinance", "unknown"}107108REQUIRED_FIELDS = ("provider", "institution", "rate_type", "term_months",109 "kind", "rate", "source_url")110111112def validate_product(p: dict) -> tuple[bool, list[str]]:113 """Valide UNE observation normalisée. Retourne (ok, problèmes)."""114 issues: list[str] = []115 for f in REQUIRED_FIELDS:116 if p.get(f) in (None, ""):117 issues.append(f"champ manquant: {f}")118 if issues:119 return False, issues120 rate = p["rate"]121 if not isinstance(rate, (int, float)):122 issues.append(f"taux non numérique: {rate!r}")123 elif rate <= 0:124 issues.append(f"taux nul ou négatif: {rate}")125 elif rate < RATE_MIN or rate > RATE_MAX:126 issues.append(f"taux impossible: {rate}")127 term = p["term_months"]128 if not isinstance(term, int) or not (TERM_MIN_MONTHS <= term <= TERM_MAX_MONTHS):129 issues.append(f"terme invalide: {term!r}")130 if p["rate_type"] not in VALID_RATE_TYPES:131 issues.append(f"rate_type invalide: {p['rate_type']}")132 if p["kind"] not in VALID_KINDS:133 issues.append(f"kind invalide: {p['kind']}")134 if p.get("insured_status", "unknown") not in VALID_INSURED:135 issues.append(f"insured_status invalide: {p.get('insured_status')}")136 if p.get("purpose", "purchase") not in VALID_PURPOSES:137 issues.append(f"purpose invalide: {p.get('purpose')}")138 apr = p.get("apr")139 if apr is not None:140 if not isinstance(apr, (int, float)) or apr < RATE_MIN or apr > RATE_MAX:141 issues.append(f"APR impossible: {apr!r}")142 elif isinstance(rate, (int, float)) and apr < rate - 0.02:143 issues.append(f"APR ({apr}) inférieur au taux contractuel ({rate})")144 return not issues, issues145146147def validate_batch(products: list[dict]) -> tuple[list[dict], list[str]]:148 """Valide une passe complète : élimine invalides et duplicatas exacts.149 Retourne (produits valides, problèmes)."""150 from .store import product_key151 ok_products: list[dict] = []152 problems: list[str] = []153 seen: set[tuple[str, float]] = set()154 for p in products:155 valid, issues = validate_product(p)156 if not valid:157 name = p.get("product_name") or "?"158 problems.extend(f"{name}: {i}" for i in issues)159 continue160 key = (product_key(p), round(float(p["rate"]), 4))161 if key in seen:162 continue # duplicata exact silencieusement ignoré163 seen.add(key)164 ok_products.append(p)165 return ok_products, problems166