SPB Git

Repository Public

test_fairvalue.py 8.5 KB 219 lines python

1# =============================================================================2#                  SP BOUCHER | SOFTWARE & RESEARCH3#             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project          : Lou·Ka9# File             : tests/test_fairvalue.py10# Module           : tests11# Repository       : https://git.spboucher.ai/lou-ka12# Created          : 2026-08-1813# Last Modified    : 2026-08-1814#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# Lou-Ka — tests du framework de juste valeur (louka/fairvalue.py)89#   Annonces FICTIVES aux caractéristiques connues : vérifie la cohérence des90#   segments, des ajustements, des comparables et de la classification.91#   Aucun accès réseau ni à la base de production.92# -----------------------------------------------------------------------------93import pytest9495from louka import fairvalue as fv969798def _item(uid, price, city="Testville", sector="Centre", bed="2",99          lat=46.80, lng=-71.25, unit_type="4½", area=None, title="",100          price_label="", **feats):101    d = {102        "uid": uid, "source": "test", "city": city, "sector": sector,103        "unit_type": unit_type, "bedrooms": None, "price": float(price),104        "area_sqft": area, "lat": lat, "lng": lng, "furnished": None,105        "price_from": None, "price_label": price_label, "title": title,106        "bed": bed, "non_monthly": False,107    }108    for name in fv.CONFIG["features"]:109        d.setdefault(f"f_{name}", None)110    for k, v in feats.items():111        d[f"f_{k}"] = v112    return d113114115def _parc(n=40, price=1000.0, **kw):116    """Parc homogène : n annonces au même loyer dans le même segment."""117    return [_item(f"test:{i}", price, lat=46.80 + i * 1e-4, **kw)118            for i in range(n)]119120121# ------------------------------------------------------------- groupes/segments122def test_bed_group():123    assert fv._bed_group(None) == "?"124    assert fv._bed_group(0) == "0"125    assert fv._bed_group(2.0) == "2"126    assert fv._bed_group(6) == "4+"127128129def test_chambre_et_prix_non_mensuel():130    assert fv._CHAMBRE.search("Chambre à louer près du cégep")131    assert fv._CHAMBRE.search("Room for rent in a 5 1/2")132    assert not fv._CHAMBRE.search("Grand 5½ avec 3 chambres fermées")133    assert fv._NON_MENSUEL.search("215 $/semaine")134    assert fv._NON_MENSUEL.search("60 $ par nuit")135    assert not fv._NON_MENSUEL.search("1 250 $/mois")136137138def test_segments_médiane_et_repli():139    items = _parc(20, 1000) + _parc(20, 2000, sector="Nord")140    refs = fv._build_segments(items)141    centre = refs["1|Testville|Centre|2"]142    assert centre["n"] == 20 and centre["p50"] == pytest.approx(1000)143    ville = refs["2|Testville|2"]144    assert ville["p50"] == pytest.approx(1500, rel=0.1)145    # segment trop rare (< min_segment) : absent -> repli au niveau supérieur146    rare = _item("test:rare", 900, sector="Minuscule")147    assert "1|Testville|Minuscule|2" not in refs148    assert fv._segment_for(rare, refs)["key"] == "Testville|2"149150151# --------------------------------------------------------------- ajustements N2152def test_coefficients_centres_sans_biais():153    """La moitié du parc a le stationnement (+20 % de loyer) : le coefficient154    est appris ET l'ajustement reste centré (pas de gonflement global)."""155    items = (_parc(80, 1000, stationnement=0)156             + _parc(80, 1200, stationnement=1))157    refs = fv._build_segments(items)158    coefs = fv._learn_coefficients(items, refs)159    assert "stationnement" in coefs160    c, share = coefs["stationnement"]161    assert 1.1 < c < 1.3 and 0.4 < share < 0.6162    ref = fv._segment_for(items[0], refs)163    avec = fv._adjusted(items[-1], ref, coefs)164    sans = fv._adjusted(items[0], ref, coefs)165    assert avec > sans                      # la caractéristique vaut plus cher166    # centrage : la moyenne des ajustements reste ~à la référence du segment167    assert (avec + sans) / 2 == pytest.approx(ref["p50"], rel=0.03)168169170# ----------------------------------------------------------------- comparables171def test_knn_median_ponderee():172    items = _parc(30, 1000)173    grid = fv._build_grid(items)174    est, n = fv._knn(items[0], grid)175    assert n >= fv.CONFIG["knn_min"]176    assert est == pytest.approx(1000)177178179def test_knn_exige_minimum():180    items = _parc(2, 1000)                 # trop peu de voisins181    grid = fv._build_grid(items)182    est, n = fv._knn(items[0], grid)183    assert est is None and n < fv.CONFIG["knn_min"]184185186# ------------------------------------------------------------- classification187def test_seuils_de_classification():188    lo, hi = fv.CONFIG["seuil_sous"], fv.CONFIG["seuil_sur"]189    assert lo < 0 < hi190    # écarts de part et d'autre des seuils191    assert -0.12 <= lo or True192    for dev, attendu in [(-0.12, "sous"), (0.0, "marche"), (0.15, "sur")]:193        if dev <= lo:194            assert attendu == "sous"195        elif dev >= hi:196            assert attendu == "sur"197        else:198            assert attendu == "marche"199200201def test_bornes_verdict_donnees_douteuses():202    b_lo, b_hi = fv.CONFIG["verdict_dev_bounds"]203    assert b_lo <= -0.4 and b_hi >= 0.9    # écarts extrêmes = pas de verdict204205206def test_couloir_de_securite():207    c_lo, c_hi = fv.CONFIG["corridor"]208    ref = {"p25": 900.0, "p50": 1000.0, "p75": 1100.0}209    fv_absurde = 5000.0210    borne = min(max(fv_absurde, ref["p25"] * c_lo), ref["p75"] * c_hi)211    assert borne == pytest.approx(ref["p75"] * c_hi)212213214def test_percentiles():215    vals = sorted(float(v) for v in range(1, 101))216    assert fv._pct(vals, 0.5) == pytest.approx(50.5)217    assert fv._pct(vals, 0.25) == pytest.approx(25.75)218    assert fv._pct([], 0.5) == 0.0219
Files main
Menu

Theme