SPB Git

Repository Public MIT

dataLayer.test.ts 30.2 KB 549 lines typescript

1// @vitest-environment node2/**3 * =============================================================================4 *                  SP BOUCHER | SOFTWARE & RESEARCH5 *             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING6 * =============================================================================7 *8 * Project          : VQuant9 * File             : server/next/dataLayer.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 {48  DataParamError,49  NoDataError,50  ProviderError,51  SingleFlight,52  TtlCache,53  aggregateBars,54  cachedFlight,55  classifyBarsFreshness,56  classifyQuoteFreshness,57  detectGaps,58  getBars,59  getQuotes,60  guessAssetClass,61  parseBarsQuery,62  parseSymbolList,63  providerJson,64  providerStats,65  quoteFromFmp,66  getBarsBatch,67  parseBarsBatchQuery,68  resetDataLayer,69  usSessionBucket,70  zonedToEpochSec,71  type Bar,72} from "./dataLayer";7374const FMP_KEY = "fmp-test-key-0123456789";75const FD_KEY = "findata-test-key-0123456789";7677type Handler = (url: URL, init?: RequestInit) => unknown | Promise<unknown>;78/** Replaces fetch: `routes` maps a path fragment to its JSON answer (or a function, or a Response). */79function mockFetch(routes: Record<string, Handler | unknown>) {80  const calls: { host: string; path: string; params: Record<string, string>; body?: string }[] = [];81  const fn = vi.fn(async (input: URL | string, init?: RequestInit) => {82    const url = new URL(String(input));83    calls.push({ host: url.host, path: url.pathname, params: Object.fromEntries(url.searchParams), body: typeof init?.body === "string" ? init.body : undefined });84    const key = Object.keys(routes).find((k) => (url.host + url.pathname).includes(k));85    if (!key) return new Response(JSON.stringify([]), { status: 200 });86    const h = routes[key];87    const out = typeof h === "function" ? await (h as Handler)(url, init) : h;88    return out instanceof Response ? out : new Response(JSON.stringify(out), { status: 200 });89  });90  vi.stubGlobal("fetch", fn);91  return calls;92}9394const weekdays = (from: string, to: string): string[] => {95  const out: string[] = [];96  for (let t = Date.parse(`${from}T00:00:00Z`); t <= Date.parse(`${to}T00:00:00Z`); t += 86_400_000) {97    const dow = new Date(t).getUTCDay();98    if (dow !== 0 && dow !== 6) out.push(new Date(t).toISOString().slice(0, 10));99  }100  return out;101};102103beforeEach(() => {104  process.env.FMP_API_KEY = FMP_KEY;105  process.env.FINDATA_API_KEY = FD_KEY;106  delete process.env.EODHD_API_KEY;107  resetDataLayer();108});109afterEach(() => {110  vi.unstubAllGlobals();111  vi.useRealTimers();112});113114describe("TtlCache / SingleFlight", () => {115  it("expires entries after their own TTL and evicts the least recently used", () => {116    let now = 1_000;117    const c = new TtlCache<number>(2, () => now);118    c.set("a", 1, 100);119    c.set("b", 2, 1_000);120    expect(c.get("a")).toBe(1); // a is now the most recently used121    c.set("c", 3, 1_000); // evicts b122    expect(c.get("b")).toBeUndefined();123    expect(c.get("a")).toBe(1);124    now += 150;125    expect(c.get("a")).toBeUndefined(); // expired126    expect(c.get("c")).toBe(3);127    expect(c.size).toBe(1);128  });129130  it("runs one execution for concurrent callers and none while the value is cached", async () => {131    const cache = new TtlCache<number>(10);132    const flights = new SingleFlight<number>();133    let runs = 0;134    let release!: (v: number) => void;135    const slow = () => new Promise<number>((r) => ((runs++), (release = r)));136    const all = Promise.all([cachedFlight(cache, flights, "k", 1_000, slow), cachedFlight(cache, flights, "k", 1_000, slow), cachedFlight(cache, flights, "k", 1_000, slow)]);137    await Promise.resolve();138    await Promise.resolve();139    expect(runs).toBe(1);140    release(42);141    expect(await all).toEqual([42, 42, 42]);142    expect(await cachedFlight(cache, flights, "k", 1_000, slow)).toBe(42);143    expect(runs).toBe(1);144    expect(flights.inFlight).toBe(0);145  });146147  it("does not cache a failure", async () => {148    const cache = new TtlCache<number>(10);149    const flights = new SingleFlight<number>();150    let n = 0;151    const flaky = async () => {152      if (n++ === 0) throw new Error("boom");153      return 7;154    };155    await expect(cachedFlight(cache, flights, "k", 1_000, flaky)).rejects.toThrow("boom");156    expect(await cachedFlight(cache, flights, "k", 1_000, flaky)).toBe(7);157  });158});159160describe("parameter validation", () => {161  const now = Date.parse("2026-11-20T15:00:00Z");162  it("applies defaults", () => {163    expect(parseBarsQuery("aapl", {}, now)).toEqual({ symbol: "AAPL", interval: "1d", from: "2025-11-20", to: "2026-11-20", explicitFrom: false, adjust: "split_div", limit: 5000 });164    expect(parseBarsQuery("^GSPC", { interval: "5m" }, now).from).toBe("2026-11-10");165    expect(parseBarsQuery("RY.TO", { interval: "1h", from: "2026-01-02", to: "2026-03-01", adjust: "none", limit: "250" }, now)).toMatchObject({ symbol: "RY.TO", from: "2026-01-02", to: "2026-03-01", adjust: "none", limit: 250, explicitFrom: true });166  });167  it.each([168    ["AAPL; DROP", {}],169    ["", {}],170    ["AAPL", { interval: "2m" }],171    ["AAPL", { interval: "1w" }],172    ["AAPL", { adjust: "total_return" }],173    ["AAPL", { from: "2026-13-01" }],174    ["AAPL", { from: "20260101" }],175    ["AAPL", { from: "2026-02-30" }],176    ["AAPL", { from: "2026-06-01", to: "2026-01-01" }],177    ["AAPL", { limit: "0" }],178    ["AAPL", { limit: "1.5" }],179    ["AAPL", { limit: "50001" }],180    ["AAPL", { limit: "abc" }],181  ])("rejects %s %j", (symbol, q) => {182    expect(() => parseBarsQuery(symbol, q, now)).toThrow(DataParamError);183  });184  it("caps a `to` in the future instead of failing", () => {185    expect(parseBarsQuery("AAPL", { to: "2030-01-01" }, now).to).toBe("2026-11-21");186  });187  it("parses symbol lists", () => {188    expect(parseSymbolList("aapl, msft;AAPL ^gspc")).toEqual(["AAPL", "MSFT", "^GSPC"]);189    expect(() => parseSymbolList("")).toThrow(DataParamError);190    expect(() => parseSymbolList("AAPL,<script>")).toThrow(DataParamError);191    expect(() => parseSymbolList(Array.from({ length: 61 }, (_, i) => `S${i}`).join(","))).toThrow(/At most 60/);192  });193  it("guesses an asset class from the shape of a symbol", () => {194    expect([guessAssetClass("^VIX"), guessAssetClass("EURUSD"), guessAssetClass("BTCUSD"), guessAssetClass("GCUSD"), guessAssetClass("AAPL"), guessAssetClass("RY.TO")]).toEqual(["index", "fx", "crypto", "commodity", "equity", "equity"]);195  });196});197198describe("time zones", () => {199  it("converts New York wall-clock times across daylight saving", () => {200    expect(zonedToEpochSec("2026-11-20 14:40:00", "America/New_York")).toBe(Date.parse("2026-11-20T19:40:00Z") / 1000); // EST201    expect(zonedToEpochSec("2026-07-01 09:30:00", "America/New_York")).toBe(Date.parse("2026-07-01T13:30:00Z") / 1000); // EDT202    expect(zonedToEpochSec("2026-03-09 09:30:00", "America/New_York")).toBe(Date.parse("2026-03-09T13:30:00Z") / 1000); // day after the switch203    expect(zonedToEpochSec("2026-03-06 15:55:00", "America/New_York")).toBe(Date.parse("2026-03-06T20:55:00Z") / 1000);204    expect(Number.isNaN(zonedToEpochSec("garbage", "America/New_York"))).toBe(true);205  });206});207208describe("gap detection", () => {209  it("finds no gap in a complete week and ignores the weekend", () => {210    const g = detectGaps(weekdays("2026-11-09", "2026-11-20"), { mode: "weekdays" });211    expect(g.missingSessions).toBe(0);212    expect(g.note).toMatch(/weekdays only/);213  });214  it("reports missing sessions between the first and the last bar only", () => {215    const dates = weekdays("2026-11-02", "2026-11-20").filter((d) => d !== "2026-11-11" && d !== "2026-11-12");216    const g = detectGaps(dates, { mode: "weekdays" });217    expect(g.missingSessions).toBe(2);218    expect(g.missingDates).toEqual(["2026-11-11", "2026-11-12"]);219    expect(g.checkedFrom).toBe("2026-11-02");220    expect(g.checkedTo).toBe("2026-11-20");221  });222  it("does not count an exchange holiday as missing, and counts it when no calendar is available", () => {223    const dates = weekdays("2026-11-23", "2026-11-30").filter((d) => d !== "2026-11-26"); // Thanksgiving224    const withCalendar = detectGaps(dates, { mode: "exchange", holidays: new Set(["2026-11-26"]), coveredYears: new Set([2026]), label: "NYSE" });225    expect(withCalendar.missingSessions).toBe(0);226    expect(withCalendar.note).toMatch(/NYSE trading calendar/);227    const without = detectGaps(dates, { mode: "weekdays" });228    expect(without.missingSessions).toBe(1);229    expect(without.note).toMatch(/holidays count as missing/);230  });231  it("says which years have no holiday list", () => {232    const dates = [...weekdays("1999-12-27", "1999-12-31"), ...weekdays("2000-01-03", "2000-01-07")];233    const g = detectGaps(dates, { mode: "exchange", holidays: new Set(), coveredYears: new Set([2000]), label: "NYSE" });234    expect(g.note).toMatch(/No holiday list for 1999/);235  });236  it("flags a bar dated on a closed day", () => {237    const g = detectGaps(["2026-11-20", "2026-11-21", "2026-11-23"], { mode: "weekdays" });238    expect(g.unexpectedSessions).toBe(1);239    expect(g.unexpectedDates).toEqual(["2026-11-21"]);240    expect(detectGaps(["2026-11-20", "2026-11-22", "2026-11-23"], { mode: "weekdays", weekendBarsExpected: true }).unexpectedSessions).toBe(0);241  });242  it("expects every calendar day for a market that never closes", () => {243    const g = detectGaps(["2026-11-06", "2026-11-09"], { mode: "every_day" });244    expect(g.missingDates).toEqual(["2026-11-07", "2026-11-08"]);245  });246  it("handles an empty series", () => {247    expect(detectGaps([], { mode: "weekdays" })).toMatchObject({ missingSessions: 0, checkedFrom: null });248  });249});250251describe("freshness", () => {252  const now = Date.parse("2026-11-20T19:45:00Z");253  const sec = (iso: string) => Date.parse(iso) / 1000;254  it("never says live: a quote is polled, with a note when its stamp is old", () => {255    const fresh = classifyQuoteFreshness("fmp", now - 30_000, now);256    expect(fresh).toMatchObject({ kind: "polled", asOf: now - 30_000, provider: "fmp", note: null });257    const stale = classifyQuoteFreshness("fmp", now - 3 * 3_600_000, now);258    expect(stale.kind).toBe("polled");259    expect(stale.note).toMatch(/3 h ago/);260    expect(classifyQuoteFreshness("eodhd", now - 60_000, now).kind).toBe("delayed");261    expect(classifyQuoteFreshness("fmp", null, now).note).toMatch(/no timestamp/);262    for (const p of ["fmp", "findata", "eodhd"] as const) expect(JSON.stringify(classifyQuoteFreshness(p, now, now))).not.toMatch(/live|real-?time/i);263  });264  it("classifies daily series", () => {265    const base = { interval: "1d" as const, nowMs: now, todayInZone: "2026-11-20" };266    expect(classifyBarsFreshness({ ...base, lastBarSec: sec("2026-11-20T00:00:00Z"), provider: "fmp", sessionOpen: true }).kind).toBe("polled");267    expect(classifyBarsFreshness({ ...base, lastBarSec: sec("2026-11-20T00:00:00Z"), provider: "fmp", sessionOpen: false }).kind).toBe("eod");268    expect(classifyBarsFreshness({ ...base, lastBarSec: sec("2026-11-19T00:00:00Z"), provider: "findata", sessionOpen: null })).toMatchObject({ kind: "eod", note: expect.stringMatching(/after each session/) });269    expect(classifyBarsFreshness({ ...base, lastBarSec: sec("2026-11-13T00:00:00Z"), provider: "findata", sessionOpen: null }).kind).toBe("historical");270    expect(classifyBarsFreshness({ ...base, lastBarSec: sec("2020-09-04T00:00:00Z"), provider: "fmp", sessionOpen: true }).kind).toBe("historical");271    expect(classifyBarsFreshness({ ...base, lastBarSec: null, provider: "fmp", sessionOpen: null })).toMatchObject({ kind: "historical", asOf: null });272  });273  it("classifies intraday series", () => {274    const base = { interval: "5m" as const, nowMs: now, todayInZone: "2026-11-20", sessionOpen: true };275    const polled = classifyBarsFreshness({ ...base, lastBarSec: sec("2026-11-20T19:40:00Z"), provider: "fmp" });276    expect(polled).toMatchObject({ kind: "polled", asOf: Date.parse("2026-11-20T19:45:00Z") });277    expect(classifyBarsFreshness({ ...base, lastBarSec: sec("2026-11-19T20:55:00Z"), provider: "fmp" }).kind).toBe("eod");278    expect(classifyBarsFreshness({ ...base, lastBarSec: sec("2026-11-20T19:40:00Z"), provider: "findata" }).kind).toBe("eod");279    expect(classifyBarsFreshness({ ...base, lastBarSec: sec("2026-10-01T19:40:00Z"), provider: "fmp" }).kind).toBe("historical");280  });281});282283describe("aggregation", () => {284  it("builds session-anchored hourly bars from 5-minute bars and drops extended hours", () => {285    const start = Date.parse("2026-11-18T14:30:00Z") / 1000; // 09:30 New York286    const fine: Bar[] = [];287    fine.push([start - 300, 1, 1, 1, 1, 999]); // 09:25 pre-market288    for (let i = 0; i < 78; i++) fine.push([start + i * 300, 100 + i, 101 + i, 99 + i, 100.5 + i, 10]);289    fine.push([start + 78 * 300, 5, 5, 5, 5, 999]); // 16:00 after hours290    const hourly = aggregateBars(fine, usSessionBucket(3600));291    expect(hourly).toHaveLength(7); // 09:30 … 15:30292    expect(hourly[0]).toEqual([start, 100, 112, 99, 111.5, 120]);293    expect(hourly[6][0]).toBe(start + 6 * 3600);294    expect(hourly[6][5]).toBe(60); // the last bucket is half an hour295    const four = aggregateBars(fine, usSessionBucket(14_400));296    expect(four.map((b) => b[0])).toEqual([start, start + 14_400]);297  });298});299300describe("providerJson", () => {301  it("classifies refusals and never leaks the key or the URL", async () => {302    mockFetch({ "/stable/premium": () => new Response(JSON.stringify({ "Error Message": `Exclusive Endpoint: upgrade at https://site.example/pricing?apikey=${FMP_KEY}` }), { status: 402 }) });303    const err = await providerJson("fmp", "/premium").catch((e) => e);304    expect(err).toBeInstanceOf(ProviderError);305    expect(err.kind).toBe("plan");306    expect(err.message).not.toContain(FMP_KEY);307    expect(err.message).not.toMatch(/https?:/);308    expect(providerStats().fmp).toMatchObject({ calls: 1, errors: 1 });309    expect(providerStats().fmp.lastError).not.toContain(FMP_KEY);310  });311  it("maps statuses", async () => {312    mockFetch({313      "/stable/a": () => new Response("Not found", { status: 404 }),314      "/stable/b": () => new Response("{}", { status: 429 }),315      "/stable/c": () => new Response("oops", { status: 500 }),316      "/stable/d": () => new Response("<html>", { status: 200 }),317      "/stable/e": { "Error Message": "Limit Reach." },318    });319    const kind = async (p: string) => (await providerJson("fmp", p).catch((e) => e)).kind;320    expect([await kind("/a"), await kind("/b"), await kind("/c"), await kind("/d"), await kind("/e")]).toEqual(["not_found", "rate_limit", "upstream", "bad_response", "upstream"]);321  });322  it("reports a timeout and an unconfigured provider", async () => {323    vi.stubGlobal("fetch", vi.fn((_u: URL, init?: RequestInit) => new Promise((_r, reject) => init?.signal?.addEventListener("abort", () => reject(Object.assign(new Error("timed out"), { name: "TimeoutError" }))))));324    const err = await providerJson("fmp", "/slow", { timeoutMs: 20 }).catch((e) => e);325    expect(err.kind).toBe("timeout");326    process.env.FMP_API_KEY = "";327    expect((await providerJson("fmp", "/x").catch((e) => e)).kind).toBe("not_configured");328  });329  it("does not move the counters for a health probe", async () => {330    mockFetch({ "/stable/quote": [{ symbol: "AAPL", price: 1 }] });331    await providerJson("fmp", "/quote", { track: false });332    expect(providerStats().fmp.calls).toBe(0);333  });334});335336/** An FMP that serves daily rows for business days, newest first, 5 000 per request, honouring from/to. */337function fmpDailyRoutes(allDates: string[], extra: Record<string, Handler | unknown> = {}) {338  const page = (url: URL, adjusted: boolean) => {339    const from = url.searchParams.get("from") ?? "0000";340    const to = url.searchParams.get("to") ?? "9999";341    return allDates342      .filter((d) => d >= from && d <= to)343      .reverse()344      .slice(0, 5000)345      .map((d, i) => (adjusted ? { symbol: "AAPL", date: d, adjOpen: 10, adjHigh: 12, adjLow: 9, adjClose: 11, volume: 1000 + i } : { symbol: "AAPL", date: d, open: 20, high: 22, low: 19, close: 21, volume: 1000 + i }));346  };347  return {348    "/stable/quote": [{ symbol: "AAPL", name: "Apple Inc.", price: 100, exchange: "NASDAQ", timestamp: 1795203878 }],349    "/stable/profile": [{ symbol: "AAPL", currency: "USD", exchange: "NASDAQ", isEtf: false }],350    "/stable/all-exchange-market-hours": [{ exchange: "NASDAQ", timezone: "America/New_York", isMarketOpen: false }],351    "/stable/holidays-by-exchange": [{ exchange: "NYSE", date: "2026-11-26", name: "Thanksgiving Day", isClosed: true }, { exchange: "NYSE", date: "2026-11-27", name: "Early close", isClosed: null }],352    "/historical-price-eod/dividend-adjusted": (url: URL) => page(url, true),353    "/historical-price-eod/non-split-adjusted": (url: URL) => page(url, true),354    "/historical-price-eod/full": (url: URL) => page(url, false),355    ...extra,356  };357}358359describe("getBars", () => {360  const now = Date.parse("2026-11-30T22:00:00Z");361362  it("serves a daily series from FMP with provenance and calendar-based gaps", async () => {363    const dates = weekdays("2026-11-02", "2026-11-30").filter((d) => d !== "2026-11-26" && d !== "2026-11-12"); // holiday (fine) + one real hole364    const calls = mockFetch(fmpDailyRoutes(dates));365    const r = await getBars(parseBarsQuery("AAPL", { from: "2026-11-01", to: "2026-11-30" }, now), now);366    expect(r.bars[0]).toEqual([Date.parse("2026-11-02T00:00:00Z") / 1000, 10, 12, 9, 11, expect.any(Number)]);367    expect(r.bars.map((b) => b[0])).toEqual([...r.bars.map((b) => b[0])].sort((a, b) => a - b));368    expect(r.provenance).toMatchObject({ provider: "fmp", adjust: "split_div", adjustRequested: "split_div", currency: "USD", timezone: "America/New_York", assetClass: "equity", observations: dates.length, firstDate: "2026-11-02", lastDate: "2026-11-30", truncated: false });369    expect(r.provenance.fallbackFrom).toBeUndefined();370    expect(r.provenance.gaps).toMatchObject({ calendar: "exchange", missingSessions: 1, missingDates: ["2026-11-12"], unexpectedSessions: 0 });371    // Never mixed: FinData was not asked for anything.372    expect(calls.some((c) => c.host.includes("findata"))).toBe(false);373    // Served from the cache the second time.374    const before = calls.length;375    await getBars(parseBarsQuery("AAPL", { from: "2026-11-01", to: "2026-11-30" }, now), now);376    expect(calls.length).toBe(before);377  });378379  it("uses the endpoint of the requested adjustment", async () => {380    const calls = mockFetch(fmpDailyRoutes(weekdays("2026-11-02", "2026-11-06")));381    const paths = async (adjust: string) => {382      const r = await getBars(parseBarsQuery("AAPL", { from: "2026-11-02", to: "2026-11-06", adjust }, now), now);383      return [calls.filter((c) => c.path.includes("historical-price-eod")).pop()!.path.split("/").pop(), r.bars[0][4], r.provenance.adjust];384    };385    expect(await paths("split")).toEqual(["full", 21, "split"]);386    expect(await paths("none")).toEqual(["non-split-adjusted", 11, "none"]);387    expect(await paths("split_div")).toEqual(["dividend-adjusted", 11, "split_div"]);388  });389390  it("pages backwards when FMP caps a request at 5 000 rows", async () => {391    const dates = weekdays("1990-01-01", "2026-11-30"); // ≈ 9 630 business days392    const calls = mockFetch(fmpDailyRoutes(dates, { "/stable/holidays-by-exchange": [] }));393    const r = await getBars(parseBarsQuery("AAPL", { from: "1990-01-01", to: "2026-11-30", limit: 50000 }, now), now);394    const pages = calls.filter((c) => c.path.includes("dividend-adjusted"));395    expect(pages.length).toBe(2);396    expect(pages[1].params.to < pages[0].params.to).toBe(true);397    expect(r.bars.length).toBe(dates.length);398    expect(new Set(r.bars.map((b) => b[0])).size).toBe(dates.length);399    expect(r.provenance.firstDate).toBe("1990-01-01");400    expect(r.provenance.gaps.calendar).toBe("weekdays"); // no holiday list → weekdays, and the note says so401    expect(r.provenance.gaps.note).toMatch(/weekdays only/);402  });403404  it("keeps the most recent bars when the range holds more than `limit`", async () => {405    mockFetch(fmpDailyRoutes(weekdays("2026-01-01", "2026-11-30")));406    const r = await getBars(parseBarsQuery("AAPL", { from: "2026-01-01", to: "2026-11-30", limit: 10 }, now), now);407    expect(r.bars).toHaveLength(10);408    expect(r.provenance.lastDate).toBe("2026-11-30");409    expect(r.provenance.truncated).toBe(true);410  });411412  it("falls back to FinData for the whole series when FMP refuses, and says so", async () => {413    const fdDates = weekdays("2026-11-02", "2026-11-13");414    const calls = mockFetch({415      ...fmpDailyRoutes([]),416      "/historical-price-eod/dividend-adjusted": () => new Response(JSON.stringify({ "Error Message": "Premium endpoint" }), { status: 402 }),417      "/api/v1/instruments/AAPL": { instrument: { asset_class: "stock", currency: "USD" } },418      "/api/v1/market/bars": { data: fdDates.map((d) => ({ timestamp_utc: `${d}T05:00:00Z`, session_date: d, open: 1, high: 2, low: 0.5, close: 1.5, volume: 10 })), next_cursor: null },419    });420    const r = await getBars(parseBarsQuery("AAPL", { from: "2026-11-01", to: "2026-11-30" }, now), now);421    expect(r.provenance).toMatchObject({ provider: "findata", fallbackFrom: "fmp", observations: fdDates.length, lastDate: "2026-11-13" });422    expect(r.provenance.fallbackReason).toMatch(/not included in the current plan/);423    expect(r.provenance.freshness.kind).toBe("historical");424    expect(r.bars.every((b) => b[4] === 1.5)).toBe(true); // one provider only425    const fd = calls.find((c) => c.path.endsWith("/market/bars"))!;426    expect(fd.params).toMatchObject({ symbol: "AAPL", interval: "1d", adjustment: "split_div" });427  });428429  it("falls back when FMP has nothing, naming crypto by its base asset for FinData", async () => {430    const calls = mockFetch({431      "/stable/quote": [{ symbol: "BTCUSD", name: "Bitcoin USD", exchange: "CRYPTO", price: 1 }],432      "/historical-price-eod/full": [],433      "/api/v1/query": { rows: [{ t: "2026-11-12T00:00:00+00:00", session_date: "2026-11-12", open: 1, high: 2, low: 1, close: 2, volume: 5 }, { t: "2026-11-11T00:00:00+00:00", session_date: "2026-11-11", open: 1, high: 2, low: 1, close: 2, volume: 5 }], meta: { truncated: false } },434    });435    const r = await getBars(parseBarsQuery("BTCUSD", { from: "2026-11-01", to: "2026-11-30" }, now), now);436    expect(r.provenance).toMatchObject({ provider: "findata", fallbackFrom: "fmp", assetClass: "crypto", currency: "USD", adjust: "none" });437    expect(r.provenance.gaps.calendar).toBe("every_day");438    const sql = JSON.parse(calls.find((c) => c.path.endsWith("/query"))!.body!).sql as string;439    expect(sql).toContain("market_bars_crypto_1d_raw");440    expect(sql).toContain("symbol = 'BTC'");441    expect(sql).not.toContain("BTCUSD");442    expect(calls.some((c) => c.path.includes("/instruments/"))).toBe(false); // BTC is also an ETF ticker there: never resolved by name443  });444445  it("does not ask FinData for a listing outside its catalogue and reports both reasons", async () => {446    const calls = mockFetch({ "/stable/quote": [{ symbol: "RY.TO", exchange: "TSX", price: 1 }], "/stable/profile": [{ symbol: "RY.TO", currency: "CAD", exchange: "TSX" }], "/historical-price-eod": [] });447    const err = await getBars(parseBarsQuery("RY.TO", { from: "2026-11-01", to: "2026-11-30" }, now), now).catch((e) => e);448    expect(err).toBeInstanceOf(NoDataError);449    expect(err.upstream).toBe(false);450    expect(err.attempts.map((a: { provider: string }) => a.provider)).toEqual(["fmp", "findata"]);451    expect(err.attempts[1].reason).toMatch(/US stocks and ETFs/);452    expect(calls.some((c) => c.host.includes("findata"))).toBe(false);453  });454455  it("converts FMP intraday stamps from New York time and flags the real adjustment", async () => {456    mockFetch({457      ...fmpDailyRoutes([]),458      "/historical-chart/5min": [459        { date: "2026-11-20 14:40:00", open: 3, high: 4, low: 2, close: 3.5, volume: 7 },460        { date: "2026-11-20 14:35:00", open: 1, high: 2, low: 1, close: 2, volume: 5 },461        { date: "2026-11-20 14:35:00", open: 1, high: 2, low: 1, close: 2, volume: 5 },462      ],463    });464    const at = Date.parse("2026-11-20T19:46:00Z");465    const r = await getBars(parseBarsQuery("AAPL", { interval: "5m" }, at), at);466    expect(r.bars.map((b) => b[0])).toEqual([Date.parse("2026-11-20T19:35:00Z") / 1000, Date.parse("2026-11-20T19:40:00Z") / 1000]);467    expect(r.provenance.adjust).toBe("split");468    expect(r.provenance.notes.join(" ")).toMatch(/split-adjusted only/);469    expect(r.provenance.gaps.calendar).toBe("none");470  });471});472473describe("batch of daily series (sparklines)", () => {474  const now = Date.parse("2026-11-30T22:00:00Z");475476  it("validates: symbols required, at most 30, daily only, bounded limit, no range parameters", () => {477    expect(parseBarsBatchQuery({ symbols: "aapl, msft" })).toEqual({ symbols: ["AAPL", "MSFT"], interval: "1d", limit: 30 });478    expect(parseBarsBatchQuery({ symbols: "AAPL,AAPL", limit: "60", interval: "1d" })).toEqual({ symbols: ["AAPL"], interval: "1d", limit: 60 });479    expect(() => parseBarsBatchQuery({})).toThrow(DataParamError);480    expect(() => parseBarsBatchQuery({ symbols: Array.from({ length: 31 }, (_, i) => `S${i}`).join(",") })).toThrow(/At most 30/);481    expect(() => parseBarsBatchQuery({ symbols: "AAPL", interval: "5m" })).toThrow(/daily bars only/);482    expect(() => parseBarsBatchQuery({ symbols: "AAPL", limit: "261" })).toThrow(DataParamError);483    expect(() => parseBarsBatchQuery({ symbols: "AAPL", limit: "0" })).toThrow(DataParamError);484    expect(() => parseBarsBatchQuery({ symbols: "AAPL", from: "2026-01-01" })).toThrow(/from is not accepted/);485  });486487  it("answers one series per symbol, each with its own provenance, in the order asked", async () => {488    mockFetch(fmpDailyRoutes(weekdays("2026-01-01", "2026-11-30")));489    const r = await getBarsBatch(parseBarsBatchQuery({ symbols: "MSFT,AAPL", limit: 5 }), now);490    expect(r.interval).toBe("1d");491    expect(r.limit).toBe(5);492    expect(r.failed).toEqual([]);493    expect(r.series.map((x) => x.symbol)).toEqual(["MSFT", "AAPL"]);494    for (const x of r.series) {495      expect(x.bars).toHaveLength(5);496      expect(x.bars[4][0]).toBe(Date.parse("2026-11-30T00:00:00Z") / 1000);497      expect(x.provenance).toMatchObject({ provider: "fmp", adjust: "split_div", observations: 5, lastDate: "2026-11-30", truncated: true });498    }499  });500501  it("shares the cache with the single-symbol route", async () => {502    const calls = mockFetch(fmpDailyRoutes(weekdays("2026-01-01", "2026-11-30")));503    await getBars(parseBarsQuery("AAPL", { interval: "1d", limit: 30 }, now), now);504    const before = calls.length;505    const r = await getBarsBatch(parseBarsBatchQuery({ symbols: "AAPL" }), now);506    expect(r.series[0].bars).toHaveLength(30);507    expect(calls.length).toBe(before);508  });509510  it("a symbol without data does not fail the batch", async () => {511    mockFetch(fmpDailyRoutes(weekdays("2026-01-01", "2026-11-30"), {512      "/historical-price-eod/dividend-adjusted": (url: URL) => (url.searchParams.get("symbol") === "NOPE" ? [] : weekdays("2026-11-02", "2026-11-30").reverse().map((d) => ({ symbol: "AAPL", date: d, adjOpen: 10, adjHigh: 12, adjLow: 9, adjClose: 11, volume: 1 }))),513    }));514    const r = await getBarsBatch(parseBarsBatchQuery({ symbols: "AAPL,NOPE", limit: 3 }), now);515    expect(r.series.map((x) => x.symbol)).toEqual(["AAPL"]);516    expect(r.failed).toHaveLength(1);517    expect(r.failed[0]).toMatchObject({ symbol: "NOPE" });518    expect([404, 502]).toContain(r.failed[0].status);519    expect(r.failed[0].error).not.toMatch(/apikey|fmp-test-key/i);520  });521});522523describe("quotes", () => {524  it("maps an FMP quote without inventing values", () => {525    const now = 1795203900_000;526    const q = quoteFromFmp({ symbol: "^GSPC", name: "S&P 500", price: 6976.39, changePercentage: -2.78, change: -199.44, volume: 0, marketCap: 0, exchange: "INDEX", timestamp: 1795203878 }, { assetClass: "index", currency: null }, now);527    expect(q).toMatchObject({ symbol: "^GSPC", price: 6976.39, changePct: -2.78, marketCap: null, volume: null, currency: null, dayLow: null, providerTimestamp: 1795203878_000, provider: "fmp", freshness: "polled" });528  });529530  it("answers a batch with one FMP call, reports unknown symbols as missing and stamps the provider time", async () => {531    const calls = mockFetch({532      "/stable/batch-quote": [533        { symbol: "AAPL", name: "Apple Inc.", price: 344.87, changePercentage: -1.24, change: -4.33, exchange: "NASDAQ", marketCap: 5e12, timestamp: Math.floor(Date.now() / 1000) - 5 },534        { symbol: "EURUSD", name: "EUR/USD", price: 1.097, changePercentage: -0.02, change: -0.0002, exchange: "FOREX", marketCap: null, timestamp: Math.floor(Date.now() / 1000) - 9 },535      ],536      "/stable/profile": [{ symbol: "AAPL", currency: "USD", exchange: "NASDAQ" }],537      "/stable/all-exchange-market-hours": [{ exchange: "NASDAQ", timezone: "America/New_York", isMarketOpen: true }],538    });539    const r = await getQuotes(["AAPL", "EURUSD", "NOPE"]);540    expect(calls.filter((c) => c.path.endsWith("/batch-quote"))).toHaveLength(1);541    expect(r.quotes.map((q) => [q.symbol, q.currency, q.assetClass])).toEqual([["AAPL", "USD", "equity"], ["EURUSD", "USD", "fx"]]);542    expect(r.missing).toEqual(["NOPE"]);543    expect(r.freshness.kind).toBe("polled");544    expect(r.freshness.asOf).toBe(r.quotes[0].providerTimestamp);545    expect(r.freshness.note).toMatch(/not streamed/);546    expect(JSON.stringify(r)).not.toMatch(/"live"/);547  });548});549
Files main
Menu

Theme