SPB Git

Repository Public

statcan.ts 8.3 KB 155 lines typescript

1/**2 * =============================================================================3 *                  SP BOUCHER | SOFTWARE & RESEARCH4 *             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5 * =============================================================================6 *7 * Project          : Vrai-Prix8 * File             : src/lib/cost/connectors/statcan.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 * Connecteur Statistique Canada — Indices des prix de la construction de44 * bâtiments (tableau 18-10-0289-01, trimestriel, licence ouverte) via l'API45 * WDS. Séries : Québec (province), RMR de Québec, Montréal, Ottawa–Gatineau ;46 * bâtiments résidentiels, appartements, maison individuelle, maison en rangée ;47 * agrégat + divisions (Montréal et Québec résidentiel).48 * Code d'indice : statcan:18100289:<geo>:<type>:<division>.49 */50import type { CanonicalIndexObservation, CanonicalObservation, ConnectorConfig, CostConnector, RawDocument, RawObservation, SourceDocument, ValidationResult } from "./types";51import { contentHash } from "./firecrawl";52import { validateObservations } from "./validate";53import { recentPricesFor, referencePriceFor } from "./store";5455export const STATCAN_PARSER_VERSION = "statcan-1.0";56const PID = 18100289;57export const WDS = "https://www150.statcan.gc.ca/t1/wds/rest/getDataFromCubePidCoordAndLatestNPeriods";5859export const STATCAN_CONFIG: ConnectorConfig = {60  key: "statcan", name: "Statistique Canada — IPCB 18-10-0289-01", domain: "www150.statcan.gc.ca", maxPages: 5,61  allowedPaths: [/^https:\/\/www150\.statcan\.gc\.ca\/t1\/wds\/rest\//], excludedPaths: [], refreshDays: 30, timeoutMs: 60_000, retries: 2, rateLimitMs: 1000, concurrency: 1,62};6364export const GEOS: Record<number, string> = { 8: "Québec (province)", 9: "Québec (RMR)", 10: "Montréal", 12: "Ottawa–Gatineau (partie ontarienne)" };65export const TYPES: Record<number, string> = { 1: "Bâtiments résidentiels", 2: "Immeubles d'appartements", 5: "Maison individuelle", 6: "Maison en rangée" };66export const DIVISIONS: Record<number, string> = {67  1: "Agrégat des divisions", 4: "Béton", 5: "Maçonnerie", 8: "Bois, plastiques et composites", 9: "Isolation thermique et étanchéité", 10: "Ouvertures et fermetures", 11: "Revêtements de finition",68  16: "Plomberie", 17: "Chauffage, ventilation et conditionnement d'air", 19: "Électricité", 22: "Terrassements", 23: "Aménagements extérieurs",69};7071export interface SeriesSpec { geo: number; type: number; division: number }7273export function seriesList(): SeriesSpec[] {74  const out: SeriesSpec[] = [];75  for (const geo of [8, 9, 10, 12]) for (const type of [1, 2, 5, 6]) out.push({ geo, type, division: 1 });76  for (const geo of [9, 10]) for (const division of Object.keys(DIVISIONS).map(Number)) if (division !== 1) out.push({ geo, type: 1, division });77  return out;78}7980export const coordinate = (s: SeriesSpec) => `${s.geo}.${s.type}.${s.division}.0.0.0.0.0.0.0`;81export const indexCode = (s: SeriesSpec) => `statcan:${PID}:${s.geo}:${s.type}:${s.division}`;8283interface WdsPoint { refPer: string; value: number | null; statusCode?: number }84interface WdsItem { status: string; object: { coordinate: string; vectorId?: number; vectorDataPoint: WdsPoint[] } }8586export async function fetchWds(specs: SeriesSpec[], latestN = 40, timeoutMs = 60_000): Promise<WdsItem[]> {87  const out: WdsItem[] = [];88  for (let i = 0; i < specs.length; i += 20) {89    const batch = specs.slice(i, i + 20).map((s) => ({ productId: PID, coordinate: coordinate(s), latestN }));90    const ctrl = new AbortController();91    const t = setTimeout(() => ctrl.abort(), timeoutMs);92    try {93      const res = await fetch(WDS, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(batch), signal: ctrl.signal });94      if (!res.ok) throw new Error(`StatCan WDS HTTP ${res.status}`);95      out.push(...((await res.json()) as WdsItem[]));96    } finally {97      clearTimeout(t);98    }99    if (i + 20 < specs.length) await new Promise((r) => setTimeout(r, 1000));100  }101  return out;102}103104/** Points → observations d'indice avec variations trimestrielle et annuelle. */105export function pointsToObservations(spec: SeriesSpec, points: WdsPoint[], retrievedAt: string): CanonicalIndexObservation[] {106  const pts = points.filter((p) => p.value != null && Number.isFinite(p.value)).sort((a, b) => a.refPer.localeCompare(b.refPer));107  return pts.map((p, i) => {108    const prev = i > 0 ? pts[i - 1] : null;109    const yearAgo = pts.find((q) => q.refPer === shiftYear(p.refPer, -1)) ?? null;110    return {111      kind: "index", indexCode: indexCode(spec), geography: GEOS[spec.geo] ?? String(spec.geo), buildingType: TYPES[spec.type] ?? String(spec.type), division: DIVISIONS[spec.division] ?? String(spec.division),112      period: p.refPer, value: p.value as number, pctQoq: prev?.value ? r1(((p.value as number) / prev.value - 1) * 100) : null, pctYoy: yearAgo?.value ? r1(((p.value as number) / yearAgo.value - 1) * 100) : null, retrievedAt,113    };114  });115}116117const r1 = (x: number) => Math.round(x * 10) / 10;118function shiftYear(iso: string, dy: number): string {119  return `${Number(iso.slice(0, 4)) + dy}${iso.slice(4)}`;120}121122export const statcanConnector: CostConnector = {123  config: STATCAN_CONFIG,124  async discover() {125    return [{ url: WDS, title: "StatCan 18-10-0289-01 (WDS)", meta: { series: seriesList().length } }];126  },127  async fetch(doc) {128    const items = await fetchWds(seriesList(), 40, STATCAN_CONFIG.timeoutMs);129    const md = JSON.stringify(items.map((it) => ({ c: it.object?.coordinate, s: it.status, p: it.object?.vectorDataPoint?.map((p) => [p.refPer, p.value]) })));130    // les indices changent à chaque diffusion : le hash porte sur les données, pas sur la date de récupération131    return { url: doc.url, fetchedAt: new Date().toISOString(), markdown: md, metadata: { items: items.length }, statusCode: 200, contentHash: contentHash(md), unchanged: false, meta: doc.meta };132  },133  async extract(raw) {134    const items = JSON.parse(raw.markdown) as { c: string; s: string; p: [string, number | null][] }[];135    return items.filter((it) => it.s === "SUCCESS" && it.c).map((it) => ({136      externalId: it.c, sourceUrl: `https://www150.statcan.gc.ca/t1/tbl1/fr/tv.action?pid=${PID}01`, retrievedAt: raw.fetchedAt, effectiveDate: it.p.at(-1)?.[0] ?? null, title: `IPCB ${it.c}`, description: null, unit: "index", price: it.p.at(-1)?.[1] ?? null,137      regularPrice: null, salePrice: null, currency: "CAD", location: it.c.split(".")[0], category: "index", payload: { points: it.p },138    } satisfies RawObservation));139  },140  async normalize(obs, raw) {141    const out: CanonicalObservation[] = [];142    for (const o of obs) {143      const [geo, type, division] = (o.externalId ?? "").split(".").map(Number);144      const pts = (o.payload.points as [string, number | null][]).map(([refPer, value]) => ({ refPer, value }));145      out.push(...pointsToObservations({ geo, type, division }, pts, raw.fetchedAt));146    }147    return out;148  },149  validate(obs, opts): ValidationResult {150    return validateObservations(obs, { recentPrices: (c) => recentPricesFor(c, 120, opts.db), referencePrice: (c) => referencePriceFor(c, opts.db) });151  },152};153154export type { RawDocument, SourceDocument };155
Files main
Menu

Theme