Repository Public
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project : Vrai-Prix iOS9// File : VraiPrix/Features/Market/MarketTestView.swift10// Description : « l'estimation à l'épreuve du marché » — le moteur11// confronté aux propriétés réellement à vendre : rapport12// estimation / prix demandé, écart médian, tenue de l'indice13// de fiabilité, par type et par prix.14// Module : VraiPrix15// Repository : https://git.spboucher.ai/vrai-prix-ios-v316// Project Website : https://www.vrai-prix.com17// Created : 2026-11-2618// Last Modified : 2026-11-2619//20// =============================================================================21// AUTHOR & PROFESSIONAL AFFILIATION22// =============================================================================23//24// Author : Simon-Pierre Boucher25// Position : Professor of Finance26// Institution : Université du Québec en Outaouais (UQO)27// Department : Département des sciences administratives28// Organization : SP Boucher29//30// Website : https://spboucher.ai31// Git : https://git.spboucher.ai32//33// =============================================================================34// OFFICIAL CONTACT DIRECTORY35// =============================================================================36//37// General : info@spboucher.ai38// Professional : contact@spboucher.ai39// Direct : simon@spboucher.ai40// Research : research@spboucher.ai41// Development : dev@spboucher.ai42// Support : support@spboucher.ai43// Security/Admin : admin@spboucher.ai44// Notifications : notifications@spboucher.ai45//46// Preferred Contact: support@spboucher.ai47//48// =============================================================================49// COPYRIGHT & INTELLECTUAL PROPERTY50// =============================================================================51//52// Copyright (c) 202653// Simon-Pierre Boucher54//55// All rights reserved where applicable.56//57// This file is governed by the applicable project license,58// copyright notices, institutional agreements and relevant law.59//60// Unless expressly authorized by the applicable license or61// rights holder, copying, redistribution, sublicensing,62// publication and commercial exploitation are not permitted.63//64// Existing third-party rights and notices remain unaffected.65//66// =============================================================================67// CONFIDENTIALITY & SECURITY68// =============================================================================69//70// Classification : Public71// Distribution : Public repository; use is governed by the project license72// Security Contact : admin@spboucher.ai73//74// Access to this source does not independently grant permission75// to redistribute or disclose confidential materials.76//77// Do not embed credentials, private keys, access tokens,78// certificates or confidential personal information.79//80// =============================================================================81// LICENSE & MAINTENANCE82// =============================================================================83//84// License : None specified (no license file in this repository)85// Maintainer : Simon-Pierre Boucher86// Technical Contact: dev@spboucher.ai87//88// =============================================================================89// END OF SP BOUCHER SOURCE HEADER90// =============================================================================9192import Charts93import SwiftUI9495struct MarketTestView: View {96 @State private var state: Loadable<MarketTest> = .loading97 @State private var drawn = 0.09899 var body: some View {100 ScrollView {101 Group {102 switch state {103 case .loading: LoadingState(label: "Chargement des mesures")104 case .failed(let e): ErrorState(error: e, subject: "Cette page") { Task { await load() } }105 case .loaded(let m, let stale): content(m, stale: stale)106 }107 }108 .pageColumn()109 .padding(.top, 10).padding(.bottom, 36)110 }111 .background(Theme.bg)112 .navigationTitle("À l'épreuve du marché")113 .navigationBarTitleDisplayMode(.inline)114 .task { await load() }115 }116117 private func load() async {118 if state.value != nil { return }119 do {120 let f = try await APIClient.shared.fetch("api/stats/marche", as: MarketTest.self)121 state = .loaded(f.value, stale: f.stale)122 } catch is CancellationError {123 } catch { state = .failed(apiError(error)) }124 }125126 @ViewBuilder127 private func content(_ m: MarketTest, stale: Bool) -> some View {128 VStack(alignment: .leading, spacing: 0) {129 if stale { StaleNotice().padding(.bottom, 12) }130 Text("Une estimation se vérifie. Chaque nuit, les estimations sont comparées aux prix demandés des propriétés réellement à vendre. Un prix demandé n'est pas un prix vendu : l'écart mesure à la fois le moteur et les attentes des vendeurs.")131 .font(.body).foregroundStyle(Theme.ink2).fixedSize(horizontal: false, vertical: true)132133 if let g = m.global {134 FigureGrid {135 Figure(label: "Propriétés comparées", value: Fmt.int(g.n), note: m.source?.copiedAt.map { "au " + Fmt.day($0) })136 Figure(label: "Écart médian absolu", value: Fmt.share(g.mdape), note: "entre estimation et prix demandé")137 Figure(label: "À moins de 10 %", value: Fmt.share(g.within10), note: "des propriétés")138 Figure(label: "À moins de 20 %", value: Fmt.share(g.within20), note: "des propriétés")139 Figure(label: "Prix demandé dans la fourchette", value: Fmt.share(g.inP10P90))140 Figure(label: "Prix demandé au-dessus de l'estimation", value: Fmt.share(g.askAbove))141 }142 .padding(.top, 22)143 }144145 if let h = m.histogram, !h.bins.isEmpty {146 SectionHeader("Répartition", note: "Rapport entre l'estimation et le prix demandé. À 1,00, l'estimation égale le prix demandé.").padding(.top, 36)147 Chart {148 ForEach(h.bins) { b in149 RectangleMark(xStart: .value("De", b.lo + 0.003), xEnd: .value("À", b.hi - 0.003), yStart: .value("Base", 0.0), yEnd: .value("Propriétés", Double(b.n) * drawn))150 .foregroundStyle(abs((b.lo + b.hi) / 2 - 1) <= 0.1 ? Theme.ink : Theme.ink3.opacity(0.55))151 }152 RuleMark(x: .value("Égalité", 1.0)).foregroundStyle(Theme.brand).lineStyle(StrokeStyle(lineWidth: 2))153 }154 .chartYScale(domain: 0...Double(h.bins.map(\.n).max() ?? 1) * 1.08)155 .chartXScale(domain: 0.45...1.55)156 .chartXAxis {157 AxisMarks(values: [0.5, 0.75, 1.0, 1.25, 1.5]) { v in158 AxisValueLabel { if let d = v.as(Double.self) { Text(Fmt.decimal(d, digits: 2)).font(.chartAxis).monospacedDigit().foregroundStyle(Theme.ink3) } }159 }160 }161 .chartYAxis {162 AxisMarks(position: .leading, values: .automatic(desiredCount: 3)) { v in163 AxisGridLine().foregroundStyle(Theme.line)164 AxisValueLabel { if let d = v.as(Double.self) { Text(Fmt.int(Int(d))).font(.chartAxis).monospacedDigit().foregroundStyle(Theme.ink3) } }165 }166 }167 .frame(height: 190)168 .padding(.top, 14)169 .drawOnAppear($drawn)170 .accessibilityElement(children: .ignore)171 .accessibilityLabel("Histogramme du rapport entre l'estimation et le prix demandé. \(Fmt.int(h.below)) propriétés sous 0,5 et \(Fmt.int(h.above)) au-dessus de 1,5 ne sont pas montrées.")172 Text("En charbon : les propriétés dont l'estimation est à moins de 10 % du prix demandé. \(Fmt.int(h.below)) propriétés sous 0,50 et \(Fmt.int(h.above)) au-dessus de 1,50 sont hors du graphique.")173 .font(.footnote).num().foregroundStyle(Theme.ink3).fixedSize(horizontal: false, vertical: true).padding(.top, 10)174 }175176 if !m.byConfidence.isEmpty {177 SectionHeader("L'indice de fiabilité tient-il parole ?", note: "Si l'indice est honnête, l'écart doit grandir de A à D.").padding(.top, 36)178 table(m.byConfidence.map { ("Fiabilité " + ($0.key ?? ""), $0) }).padding(.top, 10)179 }180 if !m.methods.isEmpty {181 SectionHeader("Par méthode", note: "La même épreuve pour chaque lecture de la valeur.").padding(.top, 36)182 VStack(spacing: 0) {183 Hairline().padding(.top, 10)184 ForEach(m.methods) { x in185 FactRow(label: x.label + (x.main == true ? " (retenue)" : "")) {186 VStack(alignment: .trailing, spacing: 2) {187 Text("écart médian " + Fmt.share(x.mdape)).font(.subheadline.weight(.semibold)).num().foregroundStyle(Theme.ink)188 Text("couvre " + Fmt.share(x.coverage, digits: 0) + " · " + Fmt.share(x.within10, digits: 0) + " à moins de 10 %").font(.caption).num().foregroundStyle(Theme.ink3)189 }190 }191 }192 }193 }194 if !m.byType.isEmpty {195 SectionHeader("Par type de propriété").padding(.top, 36)196 table(m.byType.prefix(8).map { ($0.key ?? "", $0) }).padding(.top, 10)197 }198 if !m.byBracket.isEmpty {199 SectionHeader("Par tranche de prix demandé", note: "L'écart est le plus grand sous 300 000 $ : terrains, chalets et propriétés atypiques y sont nombreux.").padding(.top, 36)200 table(m.byBracket.map { (bracket($0.key ?? ""), $0) }).padding(.top, 10)201 }202 if let s = m.source {203 Text("Annonces : \(Fmt.int(s.totalListings)) relevées, \(Fmt.int(s.evaluated)) rattachées à une unité du rôle, \(Fmt.int(s.valid)) retenues. Distance médiane du rattachement : \(Fmt.decimal(s.matchMedianM, digits: 0)) m.")204 .font(.footnote).num().foregroundStyle(Theme.ink3).fixedSize(horizontal: false, vertical: true).padding(.top, 26)205 Text("Cette épreuve rattache chaque inscription à l'unité du rôle la plus proche. Les fiches et les listes de l'app sont plus strictes : elles ne donnent une valeur qu'aux inscriptions jumelées sûrement à leur unité.")206 .font(.footnote).foregroundStyle(Theme.ink3).fixedSize(horizontal: false, vertical: true).padding(.top, 8)207 }208 }209 }210211 private func bracket(_ k: String) -> String {212 k.replacingOccurrences(of: "<", with: "Moins de ").replacingOccurrences(of: ">", with: "Plus de ").replacingOccurrences(of: "k", with: " k$")213 .replacingOccurrences(of: "M", with: " M$").replacingOccurrences(of: "-", with: " à ")214 }215216 private func table(_ rows: [(String, MarketTest.Row)]) -> some View {217 VStack(spacing: 0) {218 Hairline()219 ForEach(rows, id: \.0) { label, r in220 FactRow(label: label) {221 VStack(alignment: .trailing, spacing: 2) {222 Text("écart médian " + Fmt.share(r.mdape)).font(.subheadline.weight(.semibold)).num().foregroundStyle(Theme.ink)223 Text("\(Fmt.int(r.n)) propriétés · " + Fmt.share(r.within10, digits: 0) + " à moins de 10 %").font(.caption).num().foregroundStyle(Theme.ink3)224 }225 }226 }227 }228 }229}230