Repository Public MIT
1// @vitest-environment node2/**3 * =============================================================================4 * SP BOUCHER | SOFTWARE & RESEARCH5 * ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING6 * =============================================================================7 *8 * Project : VQuant9 * File : server/next/statements.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 fs from "node:fs";48import path from "node:path";49import { DataParamError, ProviderError, resetDataLayer } from "./dataLayer";50import { buildStatements, getStatements, parseStatementsQuery, resetStatements, type RawStatements, type Row } from "./statements";5152// Recorded from the real FMP stable API (AAPL, 2026-11-20): server/next/__fixtures__/fmp-statements-aapl.json53const fixture = JSON.parse(fs.readFileSync(path.join(__dirname, "__fixtures__", "fmp-statements-aapl.json"), "utf8")) as { annual: RawStatements; quarter: RawStatements };54const row = (rows: Row[], key: string): Row => {55 const r = rows.find((x) => x.key === key);56 if (!r) throw new Error(`row ${key} is missing`);57 return r;58};59const clone = <T>(v: T): T => JSON.parse(JSON.stringify(v)) as T;6061describe("buildStatements (annual, real AAPL response)", () => {62 const s = buildStatements("AAPL", fixture.annual, "annual", 5);63 const inc = fixture.annual.income as Record<string, number>[];64 const bal = fixture.annual.balance as Record<string, number>[];65 const cf = fixture.annual.cashflow as Record<string, number>[];6667 it("normalises periods newest first and keeps the reported values", () => {68 expect(s.currency).toBe("USD");69 expect(s.periods).toHaveLength(5);70 expect(s.periods[0]).toEqual({ date: "2026-09-26", fiscalYear: "2026", period: "FY", filingDate: "2026-11-03" });71 expect(s.periods.map((p) => p.date)).toEqual([...s.periods.map((p) => p.date)].sort().reverse());72 expect(row(s.income, "revenue")).toMatchObject({ label: "Revenue", unit: "currency", values: inc.slice(0, 5).map((r) => r.revenue) });73 expect(row(s.income, "epsDiluted").unit).toBe("per_share");74 expect(row(s.income, "weightedAverageShsOutDil").unit).toBe("count");75 expect(row(s.balance, "totalAssets").values[0]).toBe(404548000000);76 expect(row(s.cashflow, "freeCashFlow").values[0]).toBe(136056000000);77 for (const r of [...s.income, ...s.balance, ...s.cashflow]) {78 expect(r.values).toHaveLength(5);79 expect(r.formula).toBeUndefined(); // reported lines carry no formula80 expect(r.label.length).toBeGreaterThan(2);81 }82 });8384 it("derives margins, returns, leverage and per-share rows with their formula", () => {85 expect(row(s.ratios, "grossMargin")).toMatchObject({ unit: "percent", formula: "grossProfit / revenue" });86 expect(row(s.ratios, "grossMargin").values[0]).toBeCloseTo(233602000000 / 478834000000, 12);87 expect(row(s.ratios, "netMargin").values[0]).toBeCloseTo(132175000000 / 478834000000, 12);88 expect(row(s.ratios, "fcfMargin").values[0]).toBeCloseTo(136056000000 / 478834000000, 12);89 expect(row(s.ratios, "returnOnEquity").values[0]).toBeCloseTo(132175000000 / 112093000000, 12);90 expect(row(s.ratios, "currentRatio").values[0]).toBeCloseTo(173857000000 / 169915000000, 12);91 expect(row(s.ratios, "quickRatio").values[0]).toBeCloseTo((56722000000 + 83713000000) / 169915000000, 12);92 expect(row(s.ratios, "debtToEquity").values[0]).toBeCloseTo(80111000000 / 112093000000, 12);93 expect(row(s.ratios, "netDebtToEbitda").values[0]).toBeCloseTo(43806000000 / 172660000000, 12);94 expect(row(s.ratios, "payoutRatio").values[0]).toBeCloseTo(15721000000 / 132175000000, 12);95 expect(row(s.ratios, "revenuePerShare")).toMatchObject({ unit: "per_share" });96 expect(row(s.ratios, "revenuePerShare").values[0]).toBeCloseTo(478834000000 / 14720306000, 9);97 expect(row(s.ratios, "dividendsPerShare").values[0]).toBeCloseTo(15721000000 / 14661935000, 9);98 const roic = row(s.ratios, "returnOnInvestedCapital").values[0]!;99 expect(roic).toBeCloseTo((159237000000 * (1 - 27062000000 / 159237000000)) / (80111000000 + 112093000000 - 56722000000), 12);100 for (const r of [...s.ratios, ...s.growth, ...s.commonSize.income, ...s.commonSize.balance]) expect(typeof r.formula).toBe("string");101 });102103 it("gives null — not zero, not infinity — when an input is missing or the denominator is zero", () => {104 // AAPL no longer reports interest expense separately: FMP writes 0, so coverage cannot be computed.105 expect(inc[0].interestExpense).toBe(0);106 expect(row(s.ratios, "interestCoverage").values[0]).toBeNull();107 const all = [...s.ratios, ...s.growth, ...s.commonSize.income, ...s.commonSize.balance].flatMap((r) => r.values);108 expect(all.every((v) => v === null || Number.isFinite(v))).toBe(true);109110 const broken = clone(fixture.annual);111 delete (broken.income[0] as Record<string, unknown>).grossProfit;112 (broken.income[1] as Record<string, unknown>).revenue = 0;113 (broken.balance[0] as Record<string, unknown>).totalStockholdersEquity = -5;114 broken.cashflow = broken.cashflow.slice(1); // the latest cash-flow statement is not published yet115 const b = buildStatements("AAPL", broken, "annual", 5);116 expect(row(b.income, "grossProfit").values[0]).toBeNull();117 expect(row(b.ratios, "grossMargin").values[0]).toBeNull();118 expect(row(b.ratios, "grossMargin").values[1]).toBeNull(); // revenue 0119 expect(row(b.ratios, "netMargin").values[1]).toBeNull();120 expect(row(b.ratios, "returnOnEquity").values[0]).toBeNull(); // negative equity121 expect(row(b.ratios, "debtToEquity").values[0]).toBeNull();122 expect(row(b.cashflow, "freeCashFlow").values[0]).toBeNull();123 expect(row(b.ratios, "fcfMargin").values[0]).toBeNull();124 expect(row(b.ratios, "fcfMargin").values[2]).not.toBeNull();125 expect(row(b.growth, "revenueGrowthYoY").values[0]).toBeNull(); // base is 0126 expect(row(b.commonSize.income, "netIncome").values[1]).toBeNull();127 });128129 it("computes year-over-year growth, using the extra period only as a base", () => {130 const g = row(s.growth, "revenueGrowthYoY");131 expect(g.unit).toBe("percent");132 expect(g.values).toHaveLength(5);133 for (let i = 0; i < 5; i++) expect(g.values[i]).toBeCloseTo(inc[i].revenue / inc[i + 1].revenue - 1, 12);134 expect(row(s.growth, "epsDilutedGrowthYoY").values[0]).toBeCloseTo(inc[0].epsDiluted / inc[1].epsDiluted - 1, 12);135 expect(row(s.growth, "freeCashFlowGrowthYoY").values[0]).toBeCloseTo(cf[0].freeCashFlow / cf[1].freeCashFlow - 1, 12);136 // Without the extra period the oldest displayed year has no base.137 const short = buildStatements("AAPL", { income: fixture.annual.income.slice(0, 5), balance: fixture.annual.balance.slice(0, 5), cashflow: fixture.annual.cashflow.slice(0, 5) }, "annual", 5);138 expect(row(short.growth, "revenueGrowthYoY").values[4]).toBeNull();139 expect(s.growth.some((r) => r.key.endsWith("QoQ"))).toBe(false);140 });141142 it("refuses a growth rate over the wrong span or from a negative base", () => {143 const holed = clone(fixture.annual);144 for (const k of ["income", "balance", "cashflow"] as const) holed[k].splice(1, 1); // fiscal 2025 missing everywhere: 2026 would be compared with 2024145 expect(buildStatements("AAPL", holed, "annual", 4).periods.map((p) => p.fiscalYear).slice(0, 2)).toEqual(["2026", "2024"]);146 expect(row(buildStatements("AAPL", holed, "annual", 4).growth, "netIncomeGrowthYoY").values[0]).toBeNull();147 const neg = clone(fixture.annual);148 (neg.income[1] as Record<string, unknown>).netIncome = -1_000;149 expect(row(buildStatements("AAPL", neg, "annual", 4).growth, "netIncomeGrowthYoY").values[0]).toBeNull();150 });151152 it("computes common-size statements", () => {153 expect(row(s.commonSize.income, "costOfRevenue").values[0]).toBeCloseTo(245232000000 / 478834000000, 12);154 expect(row(s.commonSize.balance, "totalLiabilities").values[0]).toBeCloseTo(292455000000 / 404548000000, 12);155 expect(s.commonSize.income.some((r) => r.key === "revenue" || r.key === "epsDiluted")).toBe(false);156 expect(s.commonSize.balance.some((r) => r.key === "totalAssets")).toBe(false);157 // cash flow is sized on revenue (same base as the income statement), and says so158 const fcf = row(s.commonSize.cashflow, "freeCashFlow");159 expect(fcf.values[0]).toBeCloseTo(136056000000 / 478834000000, 12);160 expect(fcf.values[0]).toBeCloseTo(row(s.ratios, "fcfMargin").values[0]!, 12);161 expect(fcf).toMatchObject({ unit: "percent", formula: "freeCashFlow / revenue" });162 expect(s.commonSize.cashflow.map((r) => r.key)).toEqual(s.cashflow.map((r) => r.key));163 expect(row(s.commonSize.cashflow, "capitalExpenditure").values[0]!).toBeLessThan(0);164 expect(row(s.commonSize.balance, "totalStockholdersEquity").values[0]! + row(s.commonSize.balance, "totalLiabilities").values[0]!).toBeCloseTo(1, 9);165 expect(bal[0].totalAssets).toBe(404548000000);166 });167});168169describe("buildStatements (quarterly)", () => {170 const s = buildStatements("AAPL", fixture.quarter, "quarter", 5);171 const inc = fixture.quarter.income as Record<string, number>[];172 it("compares a quarter with the same quarter a year earlier, and with the previous quarter", () => {173 expect(s.periods.map((p) => `${p.fiscalYear}${p.period}`)).toEqual(["2026Q4", "2026Q3", "2026Q2", "2026Q1", "2025Q4"]);174 const yoy = row(s.growth, "revenueGrowthYoY");175 for (let i = 0; i < 5; i++) expect(yoy.values[i]).toBeCloseTo(inc[i].revenue / inc[i + 4].revenue - 1, 12);176 expect(yoy.formula).toMatch(/same quarter one year earlier/);177 const qoq = row(s.growth, "revenueGrowthQoQ");178 expect(qoq.values[0]).toBeCloseTo(inc[0].revenue / inc[1].revenue - 1, 12);179 expect(row(s.ratios, "returnOnEquity").formula).toMatch(/not annualised/);180 });181});182183describe("statements route logic", () => {184 beforeEach(() => {185 process.env.FMP_API_KEY = "fmp-test-key-0123456789";186 resetDataLayer();187 resetStatements();188 });189 afterEach(() => vi.unstubAllGlobals());190191 it("validates the query", () => {192 expect(parseStatementsQuery("aapl", {})).toEqual({ symbol: "AAPL", period: "annual", limit: 8 });193 expect(parseStatementsQuery("AAPL", { period: "quarter", limit: "12" })).toEqual({ symbol: "AAPL", period: "quarter", limit: 12 });194 for (const q of [{ period: "ttm" }, { limit: "0" }, { limit: "41" }, { limit: "x" }]) expect(() => parseStatementsQuery("AAPL", q)).toThrow(DataParamError);195 expect(() => parseStatementsQuery("A B", {})).toThrow(DataParamError);196 });197198 it("fetches one extra period for growth, caches, and reports provenance", async () => {199 const seen: Record<string, string>[] = [];200 const fetchMock = vi.fn(async (input: URL | string) => {201 const url = new URL(String(input));202 seen.push({ path: url.pathname, ...Object.fromEntries(url.searchParams) });203 const key = url.pathname.includes("income") ? "income" : url.pathname.includes("balance") ? "balance" : "cashflow";204 return new Response(JSON.stringify(fixture.annual[key as keyof RawStatements].slice(0, Number(url.searchParams.get("limit")))), { status: 200 });205 });206 vi.stubGlobal("fetch", fetchMock);207 const r = await getStatements("AAPL", "annual", 4);208 expect(seen).toHaveLength(3);209 expect(seen.every((c) => c.limit === "5" && c.period === "annual" && c.symbol === "AAPL")).toBe(true);210 expect(r.periods).toHaveLength(4);211 expect(row(r.growth, "revenueGrowthYoY").values[3]).not.toBeNull();212 expect(r.provenance).toMatchObject({ provider: "fmp", freshness: { kind: "historical", asOf: Date.parse("2026-11-03T00:00:00Z") } });213 await getStatements("AAPL", "annual", 4);214 expect(fetchMock).toHaveBeenCalledTimes(3);215 expect(JSON.stringify(r)).not.toContain("fmp-test-key");216 });217218 it("says plainly when there are no statements (ETF, index…)", async () => {219 vi.stubGlobal("fetch", vi.fn(async () => new Response("[]", { status: 200 })));220 const err = await getStatements("SPY", "annual", 4).catch((e) => e);221 expect(err).toBeInstanceOf(ProviderError);222 expect(err.kind).toBe("not_found");223 });224});225