SPB Git

Repository Public MIT

market.test.ts 11.3 KB 206 lines typescript

1// @vitest-environment node2/**3 * =============================================================================4 *                  SP BOUCHER | SOFTWARE & RESEARCH5 *             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING6 * =============================================================================7 *8 * Project          : VQuant9 * File             : server/next/market.test.ts10 * Module           : server11 * Repository       : https://git.spboucher.ai/vquant12 * Project Website  : https://vquant.spboucher.ai13 * Created          : 2026-11-2014 * Last Modified    : 2026-11-2015 *16 * Author           : Simon-Pierre Boucher17 * Position         : Professor of Finance18 * Institution      : Université du Québec en Outaouais (UQO)19 * Organization     : SP Boucher20 * Website          : https://spboucher.ai21 * Git              : https://git.spboucher.ai22 *23 * Preferred Contact: contact@spboucher.ai24 * Development      : dev@spboucher.ai25 * Support          : support@spboucher.ai26 * Security/Admin   : admin@spboucher.ai27 *28 * Copyright (c) 202629 * Simon-Pierre Boucher30 * All rights reserved where applicable. This file is governed by the31 * applicable project license, copyright notices and relevant law.32 * Existing third-party rights and notices remain unaffected.33 *34 * SPDX Identifier  : MIT35 * License          : MIT License36 * License File     : LICENSE37 *38 * Do not embed credentials, private keys, access tokens,39 * certificates or confidential personal information.40 *41 * =============================================================================42 * END OF SP BOUCHER SOURCE HEADER43 * =============================================================================44 */4546import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";47import { resetDataLayer } from "./dataLayer";48import { OVERVIEW_TTL_MS, buildCalendar, buildOverview, buildRates, getMarketOverview, marketStatus, resetMarket, type MarketOverview } from "./market";4950const at = (iso: string) => Date.parse(iso);5152describe("marketStatus", () => {53  it("follows the New York clock, winter and summer", () => {54    expect(marketStatus(at("2026-11-20T15:00:00Z"), true)).toMatchObject({ isOpen: true, session: "regular" }); // 10:00 EST55    expect(marketStatus(at("2026-11-20T13:00:00Z"), false)).toMatchObject({ isOpen: false, session: "pre" }); // 08:00 EST56    expect(marketStatus(at("2026-11-20T22:00:00Z"), false)).toMatchObject({ isOpen: false, session: "post" }); // 17:00 EST57    expect(marketStatus(at("2026-11-21T03:00:00Z"), false)).toMatchObject({ isOpen: false, session: "closed" }); // 22:00 EST58    expect(marketStatus(at("2026-11-21T16:00:00Z"), false)).toMatchObject({ isOpen: false, session: "closed" }); // Saturday59    expect(marketStatus(at("2026-07-01T13:45:00Z"), true)).toMatchObject({ isOpen: true, session: "regular" }); // 09:45 EDT60    expect(marketStatus(at("2026-07-01T13:15:00Z"), false)).toMatchObject({ session: "pre" }); // 09:15 EDT61  });62  it("trusts the provider over the clock on a holiday, and says when only the clock was used", () => {63    const thanksgiving = marketStatus(at("2026-11-26T16:00:00Z"), false); // 11:00 on a Thursday64    expect(thanksgiving).toMatchObject({ isOpen: false, session: "closed" });65    expect(thanksgiving.note).toMatch(/holiday/);66    const blind = marketStatus(at("2026-11-26T16:00:00Z"), null);67    expect(blind).toMatchObject({ isOpen: true, session: "regular" });68    expect(blind.note).toMatch(/holidays and early closes are not checked/);69  });70});7172describe("buildRates", () => {73  const day = (date: string, y2: number, y10: number, extra: Record<string, number> = {}) => ({ date, month1: 4.2, month3: 4.34, year2: y2, year5: 4.86, year10: y10, year30: 5.4, ...extra });74  const rows = [day("2026-11-19", 4.76, 5.04), day("2026-11-18", 4.8, 5.06), day("2026-10-23", 4.66, 4.97), day("2026-10-22", 4.65, 4.96), day("2026-10-21", 4.6, 4.9)];7576  it("builds today's curve and the one a month earlier, whatever the row order", () => {77    const { curve, section } = buildRates([...rows].reverse(), 1);78    expect(curve.date).toBe("2026-11-19");79    expect(curve.points.map((p) => p.tenor)).toEqual(["1M", "3M", "2Y", "5Y", "10Y", "30Y"]);80    expect(curve.points.find((p) => p.tenor === "10Y")).toEqual({ tenor: "10Y", months: 120, yield: 5.04 });81    expect(curve.previous?.date).toBe("2026-10-22"); // the most recent day at least 28 days before82    expect(curve.previous?.points.find((p) => p.tenor === "2Y")?.yield).toBe(4.65);83    expect(curve.freshness).toMatchObject({ kind: "eod", asOf: at("2026-11-19T00:00:00Z"), provider: "fmp" });84    const ten = section.items.find((i) => i.symbol === "UST10Y")!;85    expect(ten).toMatchObject({ price: 5.04, change: -0.02, changePct: null, unit: "yield_pct" });86    const spread = section.items.find((i) => i.symbol === "UST2S10S")!;87    expect(spread.price).toBeCloseTo(0.28, 10);88    expect(spread.change).toBeCloseTo(0.02, 10);89  });90  it("skips tenors the provider did not publish and has no previous curve without a month of history", () => {91    const { curve } = buildRates([{ date: "2026-11-19", year2: 4.76, year10: null as unknown as number }, day("2026-11-10", 4.7, 5)], 1);92    expect(curve.points).toEqual([{ tenor: "2Y", months: 24, yield: 4.76 }]);93    expect(curve.previous).toBeNull();94  });95  it("is explicit when there is nothing", () => {96    const { curve, section } = buildRates([], 1);97    expect(curve).toMatchObject({ date: null, points: [], previous: null });98    expect(section).toMatchObject({ available: false, items: [] });99    expect(section.freshness.note).toMatch(/Unavailable/);100  });101});102103describe("buildCalendar", () => {104  const now = at("2026-11-20T12:00:00Z");105  it("keeps upcoming high and medium impact events, soonest first, with nulls for unpublished figures", () => {106    const events = buildCalendar(107      [108        { date: "2026-11-25 13:30:00", country: "US", event: "GDP Growth Rate QoQ", currency: "USD", previous: 3.1, estimate: 2.8, actual: null, impact: "High", unit: "%" },109        { date: "2026-11-21 09:00:00", country: "DE", event: "Ifo Business Climate", currency: "EUR", previous: 88.4, estimate: null, actual: null, impact: "Medium" },110        { date: "2026-11-22 10:00:00", country: "US", event: "Minor survey", impact: "Low" },111        { date: "2026-11-10 10:00:00", country: "US", event: "Old release", impact: "High" },112        { date: "bad", event: "broken" },113      ],114      now,115    );116    expect(events.map((e) => e.event)).toEqual(["Ifo Business Climate", "GDP Growth Rate QoQ"]);117    expect(events[1]).toEqual({ date: "2026-11-25T13:30:00Z", event: "GDP Growth Rate QoQ", country: "US", currency: "USD", actual: null, estimate: 2.8, previous: 3.1, impact: "High", unit: "%" });118    expect(events[0].estimate).toBeNull();119  });120  it("falls back to low-impact events rather than showing nothing", () => {121    expect(buildCalendar([{ date: "2026-11-22 10:00:00", country: "US", event: "Minor survey", impact: "Low" }], now)).toHaveLength(1);122  });123});124125describe("overview", () => {126  beforeEach(() => {127    process.env.FMP_API_KEY = "fmp-test-key-0123456789";128    resetDataLayer();129    resetMarket();130  });131  afterEach(() => {132    vi.unstubAllGlobals();133    vi.useRealTimers();134  });135136  it("omits a refused section with the reason and keeps the others", async () => {137    const now = at("2026-11-20T15:00:00Z");138    const ts = Math.floor(now / 1000) - 10;139    vi.stubGlobal(140      "fetch",141      vi.fn(async (input: URL | string) => {142        const url = new URL(String(input));143        const p = url.pathname;144        const json = (body: unknown, status = 200) => new Response(JSON.stringify(body), { status });145        if (p.endsWith("/exchange-market-hours")) return json([{ exchange: "NYSE", isMarketOpen: true }]);146        if (p.endsWith("/batch-quote")) {147          const symbols = (url.searchParams.get("symbols") ?? "").split(",");148          if (symbols.includes("BTCUSD")) return json({ "Error Message": "Special Endpoint: not available under your current subscription" }, 402);149          return json(symbols.filter((s) => s !== "^HSI").map((s) => ({ symbol: s, name: `Name of ${s}`, price: 100, change: 1, changePercentage: 1, timestamp: ts })));150        }151        if (p.endsWith("/sector-performance-snapshot")) return json([{ sector: "Energy", averageChange: 0.9 }, { sector: "Technology", averageChange: -2.1 }]);152        if (p.endsWith("/treasury-rates")) return json([{ date: "2026-11-19", year2: 4.76, year10: 5.04 }, { date: "2026-10-20", year2: 4.6, year10: 4.9 }]);153        if (p.endsWith("/biggest-gainers")) return json([{ symbol: "UP", name: "Up Inc.", price: 2, change: 1, changesPercentage: 100, exchange: "NASDAQ" }]);154        if (p.endsWith("/biggest-losers")) return new Response("Forbidden", { status: 403 });155        if (p.endsWith("/most-actives")) return json([]);156        if (p.endsWith("/economic-calendar")) return new Response(JSON.stringify({ "Error Message": "Premium" }), { status: 402 });157        return json([]);158      }),159    );160    const o = await buildOverview(now);161    expect(o.sections.map((s) => s.id)).toEqual(["indices", "sectors", "rates", "fx", "commodities", "crypto", "volatility", "movers"]);162    const by = Object.fromEntries(o.sections.map((s) => [s.id, s]));163    expect(by.crypto).toMatchObject({ available: false, items: [] });164    expect(by.crypto.freshness.note).toMatch(/Unavailable: FMP: not included in the current plan \(402\)/);165    expect(by.indices.available).toBe(true);166    expect(by.indices.items).toHaveLength(10);167    expect(by.indices.freshness).toMatchObject({ kind: "polled", asOf: ts * 1000 });168    expect(by.indices.freshness.note).toMatch(/No quote from FMP for \^HSI/);169    expect(by.sectors.items.map((i) => i.name)).toEqual(["Energy", "Technology"]);170    expect(by.sectors.items[0]).toMatchObject({ symbol: null, price: null, changePct: 0.9, unit: "pct_change" });171    expect(by.rates.items.find((i) => i.symbol === "UST10Y")?.price).toBe(5.04);172    expect(by.movers.items).toHaveLength(1);173    expect(by.movers.freshness.note).toMatch(/losers: FMP: not included in the current plan \(403\)/);174    expect(o.yieldCurve.previous?.date).toBe("2026-10-20");175    expect(o.calendar).toEqual([]);176    expect(o.calendarFreshness.note).toMatch(/Unavailable/);177    expect(o.status).toMatchObject({ isOpen: true, session: "regular" });178    expect(JSON.stringify(o)).not.toContain("fmp-test-key");179    expect(JSON.stringify(o)).not.toMatch(/"kind":"live"/);180  });181182  it("builds once for concurrent clients and again only after 45 s", async () => {183    vi.useFakeTimers({ now: at("2026-11-20T15:00:00Z") });184    let builds = 0;185    let release!: () => void;186    const gate = new Promise<void>((r) => (release = r));187    const build = async (): Promise<MarketOverview> => {188      builds++;189      await gate;190      return { asOf: Date.now(), status: marketStatus(Date.now(), true), sections: [], yieldCurve: buildRates([], 1).curve, calendar: [], calendarFreshness: buildRates([], 1).curve.freshness };191    };192    const pending = Promise.all([getMarketOverview(build), getMarketOverview(build), getMarketOverview(build), getMarketOverview(build)]);193    await vi.advanceTimersByTimeAsync(0);194    expect(builds).toBe(1);195    release();196    const results = await pending;197    expect(new Set(results).size).toBe(1);198    vi.setSystemTime(Date.now() + OVERVIEW_TTL_MS - 1_000);199    await getMarketOverview(build);200    expect(builds).toBe(1);201    vi.setSystemTime(Date.now() + 2_000);202    await getMarketOverview(build);203    expect(builds).toBe(2);204  });205});206
Files main
Menu

Theme