Repository Public MIT
1/**2 * =============================================================================3 * SP BOUCHER | SOFTWARE & RESEARCH4 * ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5 * =============================================================================6 *7 * Project : VQuant8 * File : server/next/market.ts9 * Module : server10 * Repository : https://git.spboucher.ai/vquant11 * Project Website : https://vquant.spboucher.ai12 * Created : 2026-11-2013 * Last Modified : 2026-11-2014 *15 * Author : Simon-Pierre Boucher16 * Position : Professor of Finance17 * Institution : Université du Québec en Outaouais (UQO)18 * Organization : SP Boucher19 * Website : https://spboucher.ai20 * Git : https://git.spboucher.ai21 *22 * Preferred Contact: contact@spboucher.ai23 * Development : dev@spboucher.ai24 * Support : support@spboucher.ai25 * Security/Admin : admin@spboucher.ai26 *27 * Copyright (c) 202628 * Simon-Pierre Boucher29 * All rights reserved where applicable. This file is governed by the30 * applicable project license, copyright notices and relevant law.31 * Existing third-party rights and notices remain unaffected.32 *33 * SPDX Identifier : MIT34 * License : MIT License35 * License File : LICENSE36 *37 * Do not embed credentials, private keys, access tokens,38 * certificates or confidential personal information.39 *40 * =============================================================================41 * END OF SP BOUCHER SOURCE HEADER42 * =============================================================================43 */4445/**46 * Market overview (contract: docs/next/CONTRACT.md §3).47 *48 * GET /api/v2/market/overview49 *50 * One page of context: indices, sectors, Treasury yields and curve, currencies, commodities, crypto, volatility,51 * movers and the economic calendar of the coming days. Every section is fetched on its own and carries its own52 * freshness; when the provider refuses or fails one, that section comes back empty with the reason in53 * `freshness.note` and the rest of the page is unaffected. The whole document is cached 45 s and built once for54 * all the clients that ask during a refresh (single flight).55 *56 * Units: `changePct` is in percentage points (−1.24 = −1.24 %), as quotes are everywhere in this API; Treasury57 * yields are in percent (5.04 = 5.04 %) and their `change` is in percentage points against the previous day.58 */59import type { Express, Request, Response } from "express";60import { ProviderError, SingleFlight, TtlCache, cachedFlight, classifyQuoteFreshness, clockInZone, dataErrorResponse, dateInZone, fmpBatchQuotes, isoDay, providerJson, sanitizeProviderMessage, type Freshness } from "./dataLayer";61import { logger } from "../utils/logger";6263export interface OverviewItem {64 symbol: string | null;65 name: string;66 price: number | null;67 change: number | null;68 changePct: number | null;69 unit: "points" | "rate" | "currency" | "yield_pct" | "pct_change";70 extra?: Record<string, unknown>;71}72export type SectionId = "indices" | "sectors" | "rates" | "fx" | "commodities" | "crypto" | "volatility" | "movers";73export interface OverviewSection {74 id: SectionId;75 title: string;76 /** false when the provider refused or failed this section (items is then empty and freshness.note says why). */77 available: boolean;78 freshness: Freshness;79 items: OverviewItem[];80}81export interface CurvePoint {82 tenor: string;83 months: number;84 yield: number;85}86export interface YieldCurve {87 date: string | null;88 points: CurvePoint[];89 previous: { date: string; points: CurvePoint[] } | null;90 freshness: Freshness;91}92export interface CalendarEvent {93 /** ISO datetime, UTC. */94 date: string;95 event: string;96 country: string | null;97 currency: string | null;98 actual: number | null;99 estimate: number | null;100 previous: number | null;101 impact: string | null;102 unit: string | null;103}104export interface MarketStatus {105 isOpen: boolean;106 session: "pre" | "regular" | "post" | "closed";107 note: string;108}109export interface MarketOverview {110 asOf: number;111 status: MarketStatus;112 sections: OverviewSection[];113 yieldCurve: YieldCurve;114 calendar: CalendarEvent[];115 calendarFreshness: Freshness;116}117118const NY = "America/New_York";119const finite = (v: unknown): number | null => (typeof v === "number" && Number.isFinite(v) ? v : null);120const reason = (e: unknown): string => (e instanceof ProviderError ? e.message : sanitizeProviderMessage((e as Error)?.message ?? "error"));121122// ─── Market status ───────────────────────────────────────────────────────────123124/**125 * US equity session from the New York clock, corrected by what the provider says about the exchange: the clock126 * knows nothing of holidays, the provider does. `exchangeOpen` null = the provider did not answer.127 */128export function marketStatus(nowMs: number, exchangeOpen: boolean | null): MarketStatus {129 const { minutes, weekday } = clockInZone(nowMs, NY);130 const weekdayOpen = weekday >= 1 && weekday <= 5;131 let session: MarketStatus["session"] = "closed";132 if (weekdayOpen) {133 if (minutes >= 4 * 60 && minutes < 9 * 60 + 30) session = "pre";134 else if (minutes >= 9 * 60 + 30 && minutes < 16 * 60) session = "regular";135 else if (minutes >= 16 * 60 && minutes < 20 * 60) session = "post";136 }137 if (exchangeOpen === null) return { isOpen: session === "regular", session, note: "US equity session from the New York clock only: market holidays and early closes are not checked (market hours unavailable)." };138 if (exchangeOpen) return { isOpen: true, session: "regular", note: "NYSE regular session, as reported by FMP market hours." };139 if (session === "regular") return { isOpen: false, session: "closed", note: "NYSE is closed (holiday or early close), as reported by FMP market hours." };140 const label = session === "pre" ? "Pre-market hours" : session === "post" ? "After-hours" : "NYSE is closed";141 return { isOpen: false, session, note: `${label} (New York time); regular session 09:30–16:00.` };142}143144// ─── Sections ────────────────────────────────────────────────────────────────145146const QUOTE_SECTIONS: { id: SectionId; title: string; unit: OverviewItem["unit"]; symbols: string[] }[] = [147 { id: "indices", title: "Indices", unit: "points", symbols: ["^GSPC", "^DJI", "^IXIC", "^RUT", "^GSPTSE", "^FTSE", "^GDAXI", "^FCHI", "^STOXX50E", "^N225", "^HSI"] },148 { id: "fx", title: "Currencies", unit: "rate", symbols: ["EURUSD", "USDJPY", "GBPUSD", "USDCAD", "USDCHF", "AUDUSD", "NZDUSD", "EURCAD"] },149 { id: "commodities", title: "Commodities", unit: "currency", symbols: ["GCUSD", "SIUSD", "CLUSD", "BZUSD", "NGUSD", "HGUSD"] },150 { id: "crypto", title: "Crypto", unit: "currency", symbols: ["BTCUSD", "ETHUSD", "SOLUSD", "XRPUSD"] },151 { id: "volatility", title: "Volatility", unit: "points", symbols: ["^VIX", "^VVIX", "^VXN"] },152];153154const unavailable = (id: SectionId, title: string, e: unknown, retrievedAt: number): OverviewSection => ({155 id,156 title,157 available: false,158 freshness: { kind: "polled", asOf: null, provider: "fmp", retrievedAt, note: `Unavailable: ${reason(e)}` },159 items: [],160});161162async function quoteSection(def: (typeof QUOTE_SECTIONS)[number]): Promise<OverviewSection> {163 const retrievedAt = Date.now();164 try {165 const rows = await fmpBatchQuotes(def.symbols);166 const by = new Map(rows.map((r) => [r.symbol.toUpperCase(), r]));167 const items: OverviewItem[] = [];168 const absent: string[] = [];169 let newest: number | null = null;170 for (const s of def.symbols) {171 const q = by.get(s);172 if (!q || finite(q.price) === null) {173 absent.push(s);174 continue;175 }176 const ts = finite(q.timestamp);177 if (ts !== null && ts > 0) newest = Math.max(newest ?? 0, ts * 1000);178 items.push({179 symbol: s,180 name: q.name ?? s,181 price: finite(q.price),182 change: finite(q.change),183 changePct: finite(q.changePercentage),184 unit: def.unit,185 extra: { dayLow: finite(q.dayLow), dayHigh: finite(q.dayHigh), previousClose: finite(q.previousClose), providerTimestamp: ts !== null && ts > 0 ? ts * 1000 : null, ...(def.unit === "currency" ? { currency: "USD" } : {}) },186 });187 }188 if (items.length === 0) return unavailable(def.id, def.title, new ProviderError("fmp", "not_found", `FMP returned no quote for ${def.symbols.join(", ")}.`), retrievedAt);189 const freshness = classifyQuoteFreshness("fmp", newest, retrievedAt);190 if (absent.length > 0) freshness.note = [freshness.note, `No quote from FMP for ${absent.join(", ")}.`].filter(Boolean).join(" ");191 return { id: def.id, title: def.title, available: true, freshness, items };192 } catch (e) {193 return unavailable(def.id, def.title, e, retrievedAt);194 }195}196197/** Average change of listed stocks per sector (FMP snapshot). The most recent day that has data, looking back a week. */198async function sectorSection(nowMs: number, exchangeOpen: boolean | null): Promise<OverviewSection> {199 const retrievedAt = Date.now();200 const exchange = "NYSE";201 try {202 const today = dateInZone(nowMs, NY);203 for (let back = 0; back < 7; back++) {204 const date = isoDay(Date.parse(`${today}T00:00:00Z`) - back * 86_400_000);205 const dow = new Date(`${date}T00:00:00Z`).getUTCDay();206 if (dow === 0 || dow === 6) continue;207 const rows = await providerJson<{ sector?: string; averageChange?: number; date?: string }[]>("fmp", "/sector-performance-snapshot", { params: { date, exchange } });208 const items: OverviewItem[] = (Array.isArray(rows) ? rows : [])209 .filter((r) => typeof r.sector === "string" && finite(r.averageChange) !== null)210 .map((r) => ({ symbol: null, name: r.sector as string, price: null, change: null, changePct: finite(r.averageChange), unit: "pct_change" as const, extra: { exchange, date } }))211 .sort((a, b) => (b.changePct ?? 0) - (a.changePct ?? 0));212 if (items.length === 0) continue;213 const formingToday = date === today && exchangeOpen === true;214 return {215 id: "sectors",216 title: "Sectors",217 available: true,218 freshness: { kind: formingToday ? "polled" : "eod", asOf: Date.parse(`${date}T00:00:00Z`), provider: "fmp", retrievedAt, note: `Average change of ${exchange}-listed stocks per sector on ${date} (unweighted; not a sector index).${formingToday ? " Session in progress." : ""}` },219 items,220 };221 }222 return unavailable("sectors", "Sectors", new ProviderError("fmp", "not_found", "FMP has no sector snapshot for the last trading days."), retrievedAt);223 } catch (e) {224 return unavailable("sectors", "Sectors", e, retrievedAt);225 }226}227228const TENORS: [field: string, tenor: string, months: number][] = [229 ["month1", "1M", 1],230 ["month2", "2M", 2],231 ["month3", "3M", 3],232 ["month6", "6M", 6],233 ["year1", "1Y", 12],234 ["year2", "2Y", 24],235 ["year3", "3Y", 36],236 ["year5", "5Y", 60],237 ["year7", "7Y", 84],238 ["year10", "10Y", 120],239 ["year20", "20Y", 240],240 ["year30", "30Y", 360],241];242const RATE_ITEMS = ["3M", "2Y", "5Y", "10Y", "30Y"];243type TreasuryRow = Record<string, unknown> & { date?: string };244245const curvePoints = (row: TreasuryRow): CurvePoint[] => TENORS.flatMap(([field, tenor, months]) => (finite(row[field]) === null ? [] : [{ tenor, months, yield: row[field] as number }]));246247/**248 * Yield curve (latest day and the day closest to one month before it) and the headline rates, from daily249 * Treasury par yields. Pure: rows may come in any order.250 */251export function buildRates(rows: TreasuryRow[], retrievedAt: number): { curve: YieldCurve; section: OverviewSection } {252 const days = rows.filter((r) => typeof r.date === "string" && /^\d{4}-\d{2}-\d{2}/.test(r.date) && curvePoints(r).length > 0).sort((a, b) => String(b.date).localeCompare(String(a.date)));253 const note = "US Treasury par yields, daily (FMP); in percent.";254 if (days.length === 0) {255 const freshness: Freshness = { kind: "eod", asOf: null, provider: "fmp", retrievedAt, note: "Unavailable: FMP returned no Treasury rates." };256 return { curve: { date: null, points: [], previous: null, freshness }, section: { id: "rates", title: "Rates", available: false, freshness, items: [] } };257 }258 const latest = days[0];259 const latestDate = String(latest.date).slice(0, 10);260 const asOf = Date.parse(`${latestDate}T00:00:00Z`);261 // "One month ago": the most recent published day at least 28 days before the latest one.262 const monthAgo = days.find((r) => asOf - Date.parse(`${String(r.date).slice(0, 10)}T00:00:00Z`) >= 28 * 86_400_000) ?? null;263 const dayBefore = days[1] ?? null;264 const freshness: Freshness = { kind: "eod", asOf, provider: "fmp", retrievedAt, note };265 const points = curvePoints(latest);266 const items: OverviewItem[] = points267 .filter((p) => RATE_ITEMS.includes(p.tenor))268 .map((p) => {269 const field = TENORS.find((t) => t[1] === p.tenor)![0];270 const prev = dayBefore ? finite(dayBefore[field]) : null;271 return { symbol: `UST${p.tenor}`, name: `US Treasury ${p.tenor}`, price: p.yield, change: prev === null ? null : +(p.yield - prev).toFixed(4), changePct: null, unit: "yield_pct" as const, extra: { months: p.months, previousDate: dayBefore ? String(dayBefore.date).slice(0, 10) : null } };272 });273 const y2 = finite(latest.year2);274 const y10 = finite(latest.year10);275 if (y2 !== null && y10 !== null) {276 const p2 = dayBefore ? finite(dayBefore.year2) : null;277 const p10 = dayBefore ? finite(dayBefore.year10) : null;278 items.push({ symbol: "UST2S10S", name: "10Y − 2Y spread", price: +(y10 - y2).toFixed(4), change: p2 === null || p10 === null ? null : +(y10 - y2 - (p10 - p2)).toFixed(4), changePct: null, unit: "yield_pct", extra: { formula: "year10 − year2 (percentage points)" } });279 }280 return {281 curve: { date: latestDate, points, previous: monthAgo ? { date: String(monthAgo.date).slice(0, 10), points: curvePoints(monthAgo) } : null, freshness },282 section: { id: "rates", title: "Rates", available: true, freshness, items },283 };284}285286async function ratesSection(nowMs: number): Promise<{ curve: YieldCurve; section: OverviewSection }> {287 const retrievedAt = Date.now();288 try {289 const rows = await providerJson<TreasuryRow[]>("fmp", "/treasury-rates", { params: { from: isoDay(nowMs - 50 * 86_400_000), to: isoDay(nowMs) } });290 return buildRates(Array.isArray(rows) ? rows : [], retrievedAt);291 } catch (e) {292 const section = unavailable("rates", "Rates", e, retrievedAt);293 return { section, curve: { date: null, points: [], previous: null, freshness: { ...section.freshness, kind: "eod" } } };294 }295}296297const MOVER_GROUPS: [group: string, path: string][] = [298 ["gainers", "/biggest-gainers"],299 ["losers", "/biggest-losers"],300 ["actives", "/most-actives"],301];302const MOVERS_PER_GROUP = 8;303304async function moversSection(exchangeOpen: boolean | null): Promise<OverviewSection> {305 const retrievedAt = Date.now();306 const settled = await Promise.allSettled(MOVER_GROUPS.map(([, path]) => providerJson<Record<string, unknown>[]>("fmp", path)));307 const items: OverviewItem[] = [];308 const failed: string[] = [];309 settled.forEach((r, i) => {310 const group = MOVER_GROUPS[i][0];311 if (r.status === "rejected") {312 failed.push(`${group}: ${reason(r.reason)}`);313 return;314 }315 for (const m of (Array.isArray(r.value) ? r.value : []).slice(0, MOVERS_PER_GROUP)) {316 if (typeof m.symbol !== "string") continue;317 items.push({ symbol: m.symbol, name: typeof m.name === "string" ? m.name : m.symbol, price: finite(m.price), change: finite(m.change), changePct: finite(m.changesPercentage ?? m.changePercentage), unit: "currency", extra: { group, exchange: typeof m.exchange === "string" ? m.exchange : null } });318 }319 });320 if (items.length === 0) return unavailable("movers", "Movers", new ProviderError("fmp", "upstream", failed.join(" · ") || "FMP returned no movers."), retrievedAt);321 const note = [`US-listed stocks: top ${MOVERS_PER_GROUP} gainers, losers and most active (extra.group), as ranked by FMP${exchangeOpen === false ? " at the last session" : ""}.`, failed.length ? `Unavailable — ${failed.join(" · ")}` : null].filter(Boolean).join(" ");322 return { id: "movers", title: "Movers", available: true, freshness: { kind: exchangeOpen === false ? "eod" : "polled", asOf: null, provider: "fmp", retrievedAt, note }, items };323}324325const CALENDAR_DAYS = 7;326const CALENDAR_MAX = 80;327328/** Scheduled releases, soonest first: high and medium impact (low impact only when there is nothing else). */329export function buildCalendar(rows: Record<string, unknown>[], nowMs: number): CalendarEvent[] {330 const events: CalendarEvent[] = [];331 for (const r of rows) {332 const m = /^(\d{4}-\d{2}-\d{2})[ T](\d{2}:\d{2}:\d{2})/.exec(String(r.date ?? ""));333 if (!m || typeof r.event !== "string") continue;334 const date = `${m[1]}T${m[2]}Z`;335 if (Date.parse(date) < nowMs - 12 * 3_600_000) continue;336 const text = (v: unknown) => (typeof v === "string" && v.trim() !== "" ? v : null);337 events.push({ date, event: r.event, country: text(r.country), currency: text(r.currency), actual: finite(r.actual), estimate: finite(r.estimate), previous: finite(r.previous), impact: text(r.impact), unit: text(r.unit) });338 }339 events.sort((a, b) => a.date.localeCompare(b.date) || a.event.localeCompare(b.event));340 const important = events.filter((e) => e.impact === "High" || e.impact === "Medium");341 return (important.length > 0 ? important : events).slice(0, CALENDAR_MAX);342}343344async function calendar(nowMs: number): Promise<{ events: CalendarEvent[]; freshness: Freshness }> {345 const retrievedAt = Date.now();346 try {347 const rows = await providerJson<Record<string, unknown>[]>("fmp", "/economic-calendar", { params: { from: isoDay(nowMs), to: isoDay(nowMs + CALENDAR_DAYS * 86_400_000) } });348 const events = buildCalendar(Array.isArray(rows) ? rows : [], nowMs);349 return { events, freshness: { kind: "polled", asOf: null, provider: "fmp", retrievedAt, note: `Scheduled releases of the next ${CALENDAR_DAYS} days (high and medium impact); times in UTC as published by FMP. Estimates are consensus figures, not observations.` } };350 } catch (e) {351 return { events: [], freshness: { kind: "polled", asOf: null, provider: "fmp", retrievedAt, note: `Unavailable: ${reason(e)}` } };352 }353}354355// ─── Assembly ────────────────────────────────────────────────────────────────356357async function nyseOpen(): Promise<boolean | null> {358 try {359 const rows = await providerJson<{ isMarketOpen?: boolean }[]>("fmp", "/exchange-market-hours", { params: { exchange: "NYSE" }, timeoutMs: 6_000 });360 const v = Array.isArray(rows) ? rows[0]?.isMarketOpen : undefined;361 return typeof v === "boolean" ? v : null;362 } catch {363 return null;364 }365}366367export async function buildOverview(nowMs = Date.now()): Promise<MarketOverview> {368 const open = await nyseOpen();369 const [quoteSections, sectors, rates, movers, cal] = await Promise.all([Promise.all(QUOTE_SECTIONS.map(quoteSection)), sectorSection(nowMs, open), ratesSection(nowMs), moversSection(open), calendar(nowMs)]);370 const by = new Map<SectionId, OverviewSection>([...quoteSections, sectors, rates.section, movers].map((s) => [s.id, s]));371 const order: SectionId[] = ["indices", "sectors", "rates", "fx", "commodities", "crypto", "volatility", "movers"];372 const sections = order.map((id) => by.get(id)!).filter(Boolean);373 const down = sections.filter((s) => !s.available).map((s) => s.id);374 if (down.length > 0) logger.warn(`[market] overview without ${down.join(", ")}`);375 return { asOf: Date.now(), status: marketStatus(nowMs, open), sections, yieldCurve: rates.curve, calendar: cal.events, calendarFreshness: cal.freshness };376}377378export const OVERVIEW_TTL_MS = 45_000;379const cache = new TtlCache<MarketOverview>(1);380const flights = new SingleFlight<MarketOverview>();381382/** The overview, at most 45 s old; concurrent callers during a refresh share one build. */383export function getMarketOverview(build: () => Promise<MarketOverview> = buildOverview): Promise<MarketOverview> {384 return cachedFlight(cache, flights, "overview", OVERVIEW_TTL_MS, build);385}386387export function registerMarketRoutes(app: Express): void {388 app.get("/api/v2/market/overview", async (_req: Request, res: Response) => {389 res.set("Cache-Control", "private, no-store");390 try {391 res.json(await getMarketOverview());392 } catch (e) {393 const r = dataErrorResponse(e, "overview");394 res.status(r.status).json(r.body);395 }396 });397}398399/** Test hook. */400export function resetMarket(): void {401 cache.clear();402}403