auto: sync 2026-06-02 00:53

This commit is contained in:
Capucine Gest
2026-06-02 00:53:39 +02:00
parent 52d531182d
commit 7db6ee531e
3 changed files with 250 additions and 6 deletions
+57 -5
View File
@@ -5,7 +5,7 @@ import cpiOverridesRaw from "@/data/cpi_overrides.json";
import rateDecisionsRaw from "@/data/rate_decisions.json";
import { fetchFFThisWeek, fetchFFEvents } from "@/lib/forexfactory";
import type { FFEvent } from "@/lib/forexfactory";
import { fetchTECoreInflation, fetchTEMoMInflation } from "@/lib/tecpi";
import { fetchTECoreInflation, fetchTEMoMInflation, fetchTEInflationYoY, fetchTECoreCPIMoM, fetchTECPIIndex, fetchTECoreConsumerPricesIndex } from "@/lib/tecpi";
import { fetchTEInflationForecasts } from "@/lib/tradingeconomics";
const FRED_BASE = "https://api.stlouisfed.org/fred/series/observations";
@@ -1019,13 +1019,16 @@ export async function GET(req: NextRequest) {
}
// ── TE CPI override (priorité maximale — données du jour, toutes devises) ───
// Deux pages TE en parallèle : core YoY + MoM
// Remplace séries FRED stale/erronées (GBP headline au lieu de core,
// JPY PCPI total ≠ core, CHF/CAD/AUD/NZD retard 118 mois)
// Remplace séries FRED stale/erronées.
// Nouvelles données : cpiYoY headline, cpiCoreMoM (pages individuelles), cpiIndex MoM%
{
const [teCoreMap, teMoMMap] = await Promise.all([
const [teCoreMap, teMoMMap, teYoYMap, teCoreMoMMap, teIdxMap, teCoreIdxMap] = await Promise.all([
fetchTECoreInflation(),
fetchTEMoMInflation(),
fetchTEInflationYoY(),
fetchTECoreCPIMoM(),
fetchTECPIIndex(),
fetchTECoreConsumerPricesIndex(),
]);
const teCore = teCoreMap[currency];
@@ -1051,6 +1054,55 @@ export async function GET(req: NextRequest) {
lastUpdated: teMoM.refMonth,
};
}
// Inflation Rate YoY (headline)
const teYoY = teYoYMap[currency];
if (teYoY) {
const surprise = parseFloat((teYoY.value - teYoY.prev).toFixed(3));
indicators.cpiYoY = {
value: teYoY.value,
prev: teYoY.prev,
surprise,
trend: surprise > 0 ? "up" : surprise < 0 ? "down" : "flat",
lastUpdated: teYoY.refMonth,
};
}
// Core CPI MoM (pages individuelles, décimales précises)
const teCoreMoM = teCoreMoMMap[currency];
if (teCoreMoM) {
const surprise = parseFloat((teCoreMoM.value - teCoreMoM.prev).toFixed(3));
indicators.cpiCoreMoM = {
value: teCoreMoM.value,
prev: teCoreMoM.prev,
surprise,
trend: surprise > 0 ? "up" : surprise < 0 ? "down" : "flat",
lastUpdated: teCoreMoM.refMonth,
};
}
// CPI Index → MoM% (avec rawValues pour tooltip)
const teIdx = teIdxMap[currency];
if (teIdx) {
const surprise = parseFloat((teIdx.momPct - (teIdxMap[currency]?.rawPrev ?? 0)).toFixed(3));
indicators.cpiIndex = {
value: teIdx.momPct,
prev: null,
surprise: null,
trend: teIdx.momPct > 0 ? "up" : teIdx.momPct < 0 ? "down" : "flat",
lastUpdated: teIdx.refMonth,
};
}
// Raw index values for tooltips (CPI + Core CPI)
const teRawCore = teCoreIdxMap[currency];
// Stored in the response as rawCpiIndex and rawCoreIndex
const rawCpiIndex = teIdx ? { last: teIdx.rawLast, prev: teIdx.rawPrev, refMonth: teIdx.refMonth } : null;
const rawCoreIndex = teRawCore ? { last: teRawCore.rawLast, prev: teRawCore.rawPrev, refMonth: teRawCore.refMonth } : null;
// Attach raw values to indicators for tooltip access
if (indicators.cpiIndex && rawCpiIndex) (indicators.cpiIndex as Record<string,unknown>)["_raw"] = rawCpiIndex;
if (indicators.cpiCoreMoM && rawCoreIndex) (indicators.cpiCoreMoM as Record<string,unknown>)["_raw"] = rawCoreIndex;
}
// Stale-if-error
+192
View File
@@ -72,6 +72,198 @@ export async function fetchTECoreInflation(): Promise<CoreCPIMap> {
}
}
// ── Inflation Rate YoY (headline) ────────────────────────────────────────────
export async function fetchTEInflationYoY(): Promise<CoreCPIMap> {
try {
const res = await fetch(
"https://tradingeconomics.com/country-list/inflation-rate?continent=world",
{
next: { revalidate: 21600 },
headers: {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 Chrome/124.0.0.0 Safari/537.36",
"Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",
"Accept-Language": "en-US,en;q=0.9",
},
}
);
if (!res.ok) { console.warn("[tecpi-yoy] HTTP", res.status); return {}; }
const html = await res.text();
return parseCoreInflationHTML(html); // même structure de parsing
} catch (err) {
console.error("[tecpi-yoy] error:", err);
return {};
}
}
// ── CPI Index → MoM% ─────────────────────────────────────────────────────────
// Scrape country-list/consumer-price-index-cpi
// Calcule MoM% = (Last - Previous) / Previous × 100
// Retourne aussi les valeurs brutes pour le tooltip
export interface CPIIndexEntry {
momPct: number; // MoM% calculé
rawLast: number; // valeur brute (index points)
rawPrev: number;
refMonth: string;
}
export type CPIIndexMap = Partial<Record<Currency, CPIIndexEntry>>;
export async function fetchTECPIIndex(): Promise<CPIIndexMap> {
try {
const res = await fetch(
"https://tradingeconomics.com/country-list/consumer-price-index-cpi?continent=world",
{
next: { revalidate: 21600 },
headers: {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 Chrome/124.0.0.0 Safari/537.36",
"Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",
"Accept-Language": "en-US,en;q=0.9",
},
}
);
if (!res.ok) { console.warn("[tecpi-idx] HTTP", res.status); return {}; }
const html = await res.text();
return parseCPIIndexHTML(html, TE_COUNTRY_CPI);
} catch (err) {
console.error("[tecpi-idx] error:", err);
return {};
}
}
function parseCPIIndexHTML(html: string, countryMap: Record<Currency, string>): CPIIndexMap {
const result: CPIIndexMap = {};
const seen = new Set<Currency>();
const rowPattern = /<tr[^>]*>([\s\S]*?)<\/tr>/g;
let m: RegExpExecArray | null;
while ((m = rowPattern.exec(html)) !== null) {
const text = m[1].replace(/<[^>]+>/g, " ").replace(/\s+/g, " ").trim();
for (const [ccy, country] of Object.entries(countryMap) as [Currency, string][]) {
if (seen.has(ccy)) continue;
if (!text.startsWith(country)) continue;
const nums = text.match(/-?\d+(?:\.\d+)?/g);
const dateMatch = text.match(/([A-Za-z]{3}\/\d{2})/);
if (nums && nums.length >= 2) {
const rawLast = parseFloat(nums[0]);
const rawPrev = parseFloat(nums[1]);
if (rawPrev !== 0) {
result[ccy] = {
momPct: parseFloat(((rawLast - rawPrev) / rawPrev * 100).toFixed(3)),
rawLast,
rawPrev,
refMonth: dateMatch ? parseRefDate(dateMatch[1]) : "",
};
seen.add(ccy);
}
}
break;
}
if (seen.size === 8) break;
}
return result;
}
// ── Core Consumer Prices index → MoM% (depuis pages individuelles) ───────────
// La country-list arrondit à l'entier → 0% faux pour CAD/JPY/CHF.
// On scrape la meta description de chaque page individuelle (décimales disponibles).
// Format meta : "...increased to 0.40 percent in April from 0.20 percent..."
// Pour CHF on utilise /switzerland/core-consumer-prices (pas de page -mom)
const TE_CORE_MOM_SLUG: Record<Currency, string> = {
USD: "united-states/core-inflation-rate-mom",
EUR: "euro-area/core-inflation-rate-mom",
GBP: "united-kingdom/core-inflation-rate-mom",
JPY: "japan/core-inflation-rate-mom",
CAD: "canada/core-inflation-rate-mom",
AUD: "australia/core-inflation-rate-mom",
NZD: "new-zealand/core-inflation-rate-mom",
CHF: "switzerland/core-consumer-prices", // index → MoM calculé
};
async function fetchOneTEMeta(url: string): Promise<string> {
try {
const res = await fetch(url, {
next: { revalidate: 21600 },
headers: {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 Chrome/124.0.0.0 Safari/537.36",
"Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",
"Accept-Language": "en-US,en;q=0.9",
},
});
if (!res.ok) return "";
const html = await res.text();
const m = html.match(/name=["']description["'][^>]*content=["']([^"']+)["']/i)
?? html.match(/content=["']([^"']+)["'][^>]*name=["']description["']/i);
return m?.[1] ?? "";
} catch { return ""; }
}
function parseMetaForMoM(desc: string): { value: number; prev: number } | null {
// Pattern : "increased to X percent ... from Y percent"
const m = desc.match(
/(?:increased|decreased|declined|rose|fell|remained|eased|changed)\s+to\s*([\d.]+)\s+percent[^.]*from\s+([\d.]+)\s+percent/i
);
if (m) return { value: parseFloat(m[1]), prev: parseFloat(m[2]) };
// Pattern alternatif pour les index : "increased to X from Y points"
const m2 = desc.match(
/(?:increased|decreased|declined|rose|fell|remained|eased|changed)\s+to\s*([\d.]+)\s+(?:points?|index)[^.]*from\s+([\d.]+)/i
);
if (m2) {
const last = parseFloat(m2[1]);
const prev = parseFloat(m2[2]);
if (prev !== 0) return { value: parseFloat(((last - prev) / prev * 100).toFixed(3)), prev: prev };
}
return null;
}
export async function fetchTECoreCPIMoM(): Promise<MoMCPIMap> {
const entries = await Promise.all(
(Object.entries(TE_CORE_MOM_SLUG) as [Currency, string][]).map(async ([ccy, slug]) => {
const desc = await fetchOneTEMeta(`https://tradingeconomics.com/${slug}`);
const parsed = parseMetaForMoM(desc);
if (!parsed) return null;
// Extraire la date de référence depuis la meta (ex: "in April from ... in March of 2026")
const dateM = desc.match(/in\s+([A-Za-z]+)\s+(?:of\s+)?(\d{4})/i);
const MONTHS: Record<string, string> = { January:"01",February:"02",March:"03",April:"04",May:"05",June:"06",July:"07",August:"08",September:"09",October:"10",November:"11",December:"12" };
const refMonth = dateM ? `${dateM[2]}-${MONTHS[dateM[1]] ?? "01"}-01` : "";
return [ccy, { value: parsed.value, prev: parsed.prev, refMonth }] as [Currency, MoMCPIEntry];
})
);
const result: MoMCPIMap = {};
for (const entry of entries) {
if (entry) result[entry[0]] = entry[1];
}
return result;
}
// ── Core Consumer Prices index (for tooltip raw values alongside CoreMoM) ────
export async function fetchTECoreConsumerPricesIndex(): Promise<CPIIndexMap> {
try {
const res = await fetch(
"https://tradingeconomics.com/country-list/core-consumer-prices?continent=world",
{
next: { revalidate: 21600 },
headers: {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 Chrome/124.0.0.0 Safari/537.36",
"Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",
"Accept-Language": "en-US,en;q=0.9",
},
}
);
if (!res.ok) return {};
const html = await res.text();
return parseCPIIndexHTML(html, TE_COUNTRY_CPI);
} catch { return {}; }
}
// ── MoM inflation rate ────────────────────────────────────────────────────────
export async function fetchTEMoMInflation(): Promise<MoMCPIMap> {
+1 -1
View File
File diff suppressed because one or more lines are too long