SPB Git

Repository Public

pricing.ts 6.9 KB 168 lines typescript

1/**2 * =============================================================================3 *                  SP BOUCHER | SOFTWARE & RESEARCH4 *             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5 * =============================================================================6 *7 * Project          : Vrai-Prix8 * File             : src/lib/cost/pricing.ts9 * Module           : lib10 * Repository       : https://git.spboucher.ai/vrai-prix11 * Created          : 2026-09-0812 * Last Modified    : 2026-09-0813 *14 * Author           : Simon-Pierre Boucher15 * Position         : Professor of Finance16 * Institution      : Université du Québec en Outaouais (UQO)17 * Organization     : SP Boucher18 * Website          : https://spboucher.ai19 * Git              : https://git.spboucher.ai20 *21 * Preferred Contact: contact@spboucher.ai22 * Development      : dev@spboucher.ai23 * Support          : support@spboucher.ai24 * Security/Admin   : admin@spboucher.ai25 *26 * Copyright (c) 202627 * Simon-Pierre Boucher28 * All rights reserved where applicable. This file is governed by the29 * applicable project license, copyright notices and relevant law.30 * Existing third-party rights and notices remain unaffected.31 *32 * License          : None specified (no license file in this repository)33 *34 * Do not embed credentials, private keys, access tokens,35 * certificates or confidential personal information.36 *37 * =============================================================================38 * END OF SP BOUCHER SOURCE HEADER39 * =============================================================================40 */4142/**43 * Agrégation des prix : observations multi-sources → prix canonique robuste.44 * Module PUR (les fonctions reçoivent des listes d'observations déjà lues).45 *46 * Règles (§52-55) : préférer le prix régulier au prix promotionnel ; médiane47 * robuste ; détection d'aberrations (MAD / IQR / règles métier) — jamais de48 * suppression silencieuse (outlier = true) ; score de confiance par article.49 */50import type { PriceKind } from "./types";5152export interface PriceObservation {53  source: string;54  sourceQuality: number; // 0-155  price: number; // dans l'unité canonique56  observedAt: string; // YYYY-MM-DD57  url: string | null;58  sourceUnit: string;59  conversionFactor: number;60  regular: boolean;61  kind: PriceKind;62  locationMatch: boolean; // observation dans la région d'analyse63}6465export interface CanonicalPrice {66  price: number;67  low: number;68  high: number;69  kind: PriceKind;70  sourceCount: number;71  observedAt: string | null;72  confidence: number;73  used: PriceObservation[];74  outliers: { obs: PriceObservation; reason: string }[];75  dispersionPct: number; // (high-low)/price76}7778export function median(xs: number[]): number {79  if (!xs.length) return NaN;80  const s = [...xs].sort((a, b) => a - b);81  const m = Math.floor(s.length / 2);82  return s.length % 2 ? s[m] : (s[m - 1] + s[m]) / 2;83}8485/** Déviation absolue médiane (échelle robuste). */86export function mad(xs: number[]): number {87  const m = median(xs);88  return median(xs.map((x) => Math.abs(x - m)));89}9091export function daysBetween(a: string, b: string): number {92  return Math.round((new Date(b).getTime() - new Date(a).getTime()) / 86400000);93}9495/**96 * Détecte les aberrations : écart > 3,5 MAD (si ≥ 4 obs) ou ratio > 2,5× / < 0,4×97 * la médiane (règle métier, si ≥ 2 obs). Retourne les indices aberrants.98 */99export function detectOutliers(prices: number[]): { idx: number; reason: string }[] {100  const out: { idx: number; reason: string }[] = [];101  if (prices.length < 2) return out;102  const m = median(prices);103  const s = mad(prices) * 1.4826; // ≈ σ robuste104  prices.forEach((p, i) => {105    if (m > 0 && (p > m * 2.5 || p < m * 0.4)) out.push({ idx: i, reason: `ratio ${(p / m).toFixed(2)}× la médiane` });106    else if (prices.length >= 4 && s > 0 && Math.abs(p - m) / s > 3.5) out.push({ idx: i, reason: `> 3,5 MAD (${((p - m) / s).toFixed(1)} σ)` });107  });108  return out;109}110111/**112 * Prix canonique d'un article à une date donnée.113 * - garde la plus récente observation par source (fenêtre `windowDays`) ;114 * - préfère le prix régulier ; les promos ne comptent que s'il n'y a rien d'autre ;115 * - médiane robuste ; low/high = min/max des observations conservées ;116 * - confiance : fraîcheur 25 · nb de sources 25 · qualité 25 · dispersion 15 · localisation 10.117 */118export function canonicalPrice(obs: PriceObservation[], asOf: string, windowDays = 120): CanonicalPrice | null {119  const inWindow = obs.filter((o) => o.observedAt <= asOf && daysBetween(o.observedAt, asOf) <= windowDays && o.price > 0);120  if (!inWindow.length) return null;121  // plus récente par source (et préférence régulier)122  const bySource = new Map<string, PriceObservation>();123  for (const o of inWindow.sort((a, b) => (a.observedAt < b.observedAt ? 1 : -1))) {124    const cur = bySource.get(o.source);125    if (!cur || (!cur.regular && o.regular)) bySource.set(o.source, o);126  }127  let used = [...bySource.values()];128  const regulars = used.filter((o) => o.regular);129  if (regulars.length) used = regulars;130  const prices = used.map((o) => o.price);131  const outIdx = detectOutliers(prices);132  const outliers = outIdx.map((o) => ({ obs: used[o.idx], reason: o.reason }));133  const kept = used.filter((_, i) => !outIdx.some((o) => o.idx === i));134  const final = kept.length ? kept : used;135  const fp = final.map((o) => o.price);136  const price = median(fp);137  const low = Math.min(...fp);138  const high = Math.max(...fp);139  const observedAt = final.map((o) => o.observedAt).sort().at(-1) ?? null;140  const ageDays = observedAt ? daysBetween(observedAt, asOf) : 999;141  const freshness = 25 * Math.max(0, 1 - ageDays / windowDays);142  const nSources = 25 * Math.min(1, final.length / 3);143  const quality = 25 * (final.reduce((s, o) => s + o.sourceQuality, 0) / final.length);144  const dispersionPct = price > 0 ? (high - low) / price : 1;145  const dispersion = 15 * Math.max(0, 1 - dispersionPct / 0.5);146  const loc = 10 * (final.some((o) => o.locationMatch) ? 1 : 0.5);147  const kinds = new Set(final.map((o) => o.kind));148  const kind: PriceKind = kinds.size === 1 ? final[0].kind : kinds.has("observed") ? "observed" : "derived";149  return {150    price, low, high, kind, sourceCount: final.length, observedAt,151    confidence: Math.round(freshness + nSources + quality + dispersion + loc),152    used: final, outliers, dispersionPct,153  };154}155156/**157 * Actualisation par indice : Cost_t1 = Cost_t0 × Index_t1 / Index_t0.158 * `series` triée par période croissante ; on prend la dernière valeur ≤ date.159 */160export function indexFactor(series: { period: string; value: number }[], fromDate: string, toDate: string): { factor: number; from: { period: string; value: number }; to: { period: string; value: number } } | null {161  const at = (d: string) => [...series].filter((p) => p.period <= d).at(-1) ?? series[0];162  if (!series.length) return null;163  const a = at(fromDate);164  const b = at(toDate);165  if (!a || !b || a.value <= 0) return null;166  return { factor: b.value / a.value, from: a, to: b };167}168
Files main
Menu

Theme