Repository Public MIT
1/**2 * =============================================================================3 * SP BOUCHER | SOFTWARE & RESEARCH4 * ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5 * =============================================================================6 *7 * Project : VQuant8 * File : server/next/statements.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 * Financial statements, normalized (contract: docs/next/CONTRACT.md §3).47 *48 * GET /api/v2/data/statements/:symbol?period=annual|quarter&limit=849 *50 * The three statements come from FMP as reported; every other number (margins, returns, leverage, per-share51 * figures, growth, common-size) is computed here, and each derived row carries the `formula` that produced it.52 * A derived value is null whenever one of its inputs is missing or its denominator is zero or not meaningful53 * (negative equity, negative base of a growth rate): it is never replaced by a zero.54 *55 * Conventions: periods are newest first, and `values[i]` belongs to `periods[i]`; a `percent` or `ratio` is a56 * fraction (0.25 = 25 %); amounts are in the reporting currency, not scaled.57 */58import type { Express, Request, Response } from "express";59import { DataParamError, ProviderError, SingleFlight, TtlCache, cachedFlight, dataErrorResponse, parseSymbol, providerJson, type Freshness } from "./dataLayer";6061export type Unit = "currency" | "ratio" | "percent" | "per_share" | "count";62export interface Row {63 key: string;64 label: string;65 unit: Unit;66 values: (number | null)[];67 formula?: string;68}69export type PeriodKind = "annual" | "quarter";70type Raw = Record<string, unknown>;71export interface RawStatements {72 income: Raw[];73 balance: Raw[];74 cashflow: Raw[];75}7677type Line = [key: string, label: string, unit?: Unit];7879// Lines in the order a reader expects them. Keys are FMP's field names (kept so a number can be traced back).80const INCOME: Line[] = [81 ["revenue", "Revenue"],82 ["costOfRevenue", "Cost of revenue"],83 ["grossProfit", "Gross profit"],84 ["researchAndDevelopmentExpenses", "Research and development"],85 ["sellingGeneralAndAdministrativeExpenses", "Selling, general and administrative"],86 ["otherExpenses", "Other operating expenses"],87 ["operatingExpenses", "Operating expenses"],88 ["operatingIncome", "Operating income"],89 ["interestIncome", "Interest income"],90 ["interestExpense", "Interest expense"],91 ["totalOtherIncomeExpensesNet", "Other income (expense), net"],92 ["incomeBeforeTax", "Income before tax"],93 ["incomeTaxExpense", "Income tax expense"],94 ["netIncome", "Net income"],95 ["depreciationAndAmortization", "Depreciation and amortization"],96 ["ebitda", "EBITDA"],97 ["ebit", "EBIT"],98 ["eps", "EPS (basic)", "per_share"],99 ["epsDiluted", "EPS (diluted)", "per_share"],100 ["weightedAverageShsOut", "Weighted average shares (basic)", "count"],101 ["weightedAverageShsOutDil", "Weighted average shares (diluted)", "count"],102];103104const BALANCE: Line[] = [105 ["cashAndCashEquivalents", "Cash and cash equivalents"],106 ["shortTermInvestments", "Short-term investments"],107 ["cashAndShortTermInvestments", "Cash and short-term investments"],108 ["netReceivables", "Receivables, net"],109 ["inventory", "Inventory"],110 ["otherCurrentAssets", "Other current assets"],111 ["totalCurrentAssets", "Total current assets"],112 ["propertyPlantEquipmentNet", "Property, plant and equipment, net"],113 ["goodwill", "Goodwill"],114 ["intangibleAssets", "Intangible assets"],115 ["longTermInvestments", "Long-term investments"],116 ["otherNonCurrentAssets", "Other non-current assets"],117 ["totalNonCurrentAssets", "Total non-current assets"],118 ["totalAssets", "Total assets"],119 ["accountPayables", "Accounts payable"],120 ["shortTermDebt", "Short-term debt"],121 ["deferredRevenue", "Deferred revenue"],122 ["otherCurrentLiabilities", "Other current liabilities"],123 ["totalCurrentLiabilities", "Total current liabilities"],124 ["longTermDebt", "Long-term debt"],125 ["otherNonCurrentLiabilities", "Other non-current liabilities"],126 ["totalNonCurrentLiabilities", "Total non-current liabilities"],127 ["totalLiabilities", "Total liabilities"],128 ["commonStock", "Common stock"],129 ["retainedEarnings", "Retained earnings"],130 ["accumulatedOtherComprehensiveIncomeLoss", "Accumulated other comprehensive income"],131 ["totalStockholdersEquity", "Total stockholders' equity"],132 ["minorityInterest", "Minority interest"],133 ["totalEquity", "Total equity"],134 ["totalDebt", "Total debt"],135 ["netDebt", "Net debt"],136];137138const CASHFLOW: Line[] = [139 ["netIncome", "Net income"],140 ["depreciationAndAmortization", "Depreciation and amortization"],141 ["stockBasedCompensation", "Stock-based compensation"],142 ["deferredIncomeTax", "Deferred income tax"],143 ["changeInWorkingCapital", "Change in working capital"],144 ["otherNonCashItems", "Other non-cash items"],145 ["operatingCashFlow", "Cash from operating activities"],146 ["capitalExpenditure", "Capital expenditure"],147 ["acquisitionsNet", "Acquisitions, net"],148 ["purchasesOfInvestments", "Purchases of investments"],149 ["salesMaturitiesOfInvestments", "Sales and maturities of investments"],150 ["netCashProvidedByInvestingActivities", "Cash from investing activities"],151 ["netDebtIssuance", "Debt issued (repaid), net"],152 ["commonStockRepurchased", "Common stock repurchased"],153 ["commonDividendsPaid", "Dividends paid"],154 ["netCashProvidedByFinancingActivities", "Cash from financing activities"],155 ["netChangeInCash", "Net change in cash"],156 ["freeCashFlow", "Free cash flow"],157];158159const num = (v: unknown): number | null => (typeof v === "number" && Number.isFinite(v) ? v : null);160/** a / b, null when either is missing or b is zero. */161const div = (a: number | null, b: number | null): number | null => (a === null || b === null || b === 0 ? null : a / b);162/** a / b where b must be strictly positive to mean something (equity, EBITDA, pre-tax income, a growth base). */163const divPos = (a: number | null, b: number | null): number | null => (b !== null && b > 0 ? div(a, b) : null);164const add = (...xs: (number | null)[]): number | null => (xs.some((x) => x === null) ? null : (xs as number[]).reduce((s, x) => s + x, 0));165const sub = (a: number | null, b: number | null): number | null => (a === null || b === null ? null : a - b);166const abs = (a: number | null): number | null => (a === null ? null : Math.abs(a));167168interface PeriodInfo {169 date: string;170 fiscalYear: string | null;171 period: string | null;172 filingDate: string | null;173}174175export interface StatementsResult {176 symbol: string;177 currency: string | null;178 period: PeriodKind;179 periods: PeriodInfo[];180 income: Row[];181 balance: Row[];182 cashflow: Row[];183 ratios: Row[];184 growth: Row[];185 commonSize: { income: Row[]; balance: Row[]; cashflow: Row[] };186 provenance: { provider: "fmp"; retrievedAt: number; freshness: Freshness; endpoints: string[]; notes: string[] };187}188189const daysBetween = (a: string, b: string): number => Math.abs(Date.parse(a) - Date.parse(b)) / 86_400_000;190191/**192 * Pure normalisation and derivations. `raw` may hold more periods than `limit`: the extra ones are only used as193 * the base of growth rates (previous year, previous quarter).194 */195export function buildStatements(symbol: string, raw: RawStatements, kind: PeriodKind, limit: number): Omit<StatementsResult, "provenance"> & { latestFiling: string | null } {196 const dateOf = (r: Raw) => String(r.date ?? "").slice(0, 10);197 const index = (rows: Raw[]) => new Map(rows.filter((r) => /^\d{4}-\d{2}-\d{2}$/.test(dateOf(r))).map((r) => [dateOf(r), r]));198 const inc = index(raw.income);199 const bal = index(raw.balance);200 const cf = index(raw.cashflow);201 // Period ends of the three statements, newest first: a statement that lacks one of them gets nulls there.202 const allDates = [...new Set([...inc.keys(), ...bal.keys(), ...cf.keys()])].sort().reverse();203 const shown = allDates.slice(0, limit);204205 const series = (m: Map<string, Raw>, key: string): (number | null)[] => allDates.map((d) => num(m.get(d)?.[key]));206 const cut = (xs: (number | null)[]) => xs.slice(0, shown.length);207 const rows = (m: Map<string, Raw>, lines: Line[]): Row[] => lines.map(([key, label, unit]) => ({ key, label, unit: unit ?? "currency", values: cut(series(m, key)) }));208209 const I = (k: string) => series(inc, k);210 const B = (k: string) => series(bal, k);211 const C = (k: string) => series(cf, k);212 const each = (fn: (i: number) => number | null): (number | null)[] => shown.map((_, i) => fn(i));213 const flowNote = kind === "quarter" ? " (quarterly flows, not annualised)" : "";214215 const revenue = I("revenue");216 const netIncome = I("netIncome");217 const equity = B("totalStockholdersEquity");218 const assets = B("totalAssets");219 const sharesDil = I("weightedAverageShsOutDil");220 const sharesBasic = I("weightedAverageShsOut");221 const fcf = C("freeCashFlow");222 const ocf = C("operatingCashFlow");223 const dividends = C("commonDividendsPaid");224225 const derived = (key: string, label: string, unit: Unit, formula: string, fn: (i: number) => number | null): Row => ({ key, label, unit, values: each(fn), formula });226227 const ratios: Row[] = [228 derived("grossMargin", "Gross margin", "percent", "grossProfit / revenue", (i) => div(I("grossProfit")[i], revenue[i])),229 derived("operatingMargin", "Operating margin", "percent", "operatingIncome / revenue", (i) => div(I("operatingIncome")[i], revenue[i])),230 derived("ebitdaMargin", "EBITDA margin", "percent", "ebitda / revenue", (i) => div(I("ebitda")[i], revenue[i])),231 derived("netMargin", "Net margin", "percent", "netIncome / revenue", (i) => div(netIncome[i], revenue[i])),232 derived("fcfMargin", "Free cash flow margin", "percent", "freeCashFlow / revenue", (i) => div(fcf[i], revenue[i])),233 derived("effectiveTaxRate", "Effective tax rate", "percent", "incomeTaxExpense / incomeBeforeTax (null when pre-tax income ≤ 0)", (i) => divPos(I("incomeTaxExpense")[i], I("incomeBeforeTax")[i])),234 derived("returnOnEquity", "Return on equity", "percent", `netIncome / totalStockholdersEquity at period end (null when equity ≤ 0)${flowNote}`, (i) => divPos(netIncome[i], equity[i])),235 derived("returnOnAssets", "Return on assets", "percent", `netIncome / totalAssets at period end${flowNote}`, (i) => divPos(netIncome[i], assets[i])),236 derived(237 "returnOnInvestedCapital",238 "Return on invested capital",239 "percent",240 `ebit × (1 − incomeTaxExpense / incomeBeforeTax) / (totalDebt + totalStockholdersEquity − cashAndShortTermInvestments)${flowNote}`,241 (i) => {242 const tax = divPos(I("incomeTaxExpense")[i], I("incomeBeforeTax")[i]);243 const ebit = I("ebit")[i];244 const invested = sub(add(B("totalDebt")[i], equity[i]), B("cashAndShortTermInvestments")[i]);245 return tax === null || ebit === null ? null : divPos(ebit * (1 - tax), invested);246 },247 ),248 derived("assetTurnover", "Asset turnover", "ratio", `revenue / totalAssets at period end${flowNote}`, (i) => divPos(revenue[i], assets[i])),249 derived("currentRatio", "Current ratio", "ratio", "totalCurrentAssets / totalCurrentLiabilities", (i) => divPos(B("totalCurrentAssets")[i], B("totalCurrentLiabilities")[i])),250 derived("quickRatio", "Quick ratio", "ratio", "(cashAndShortTermInvestments + netReceivables) / totalCurrentLiabilities", (i) => divPos(add(B("cashAndShortTermInvestments")[i], B("netReceivables")[i]), B("totalCurrentLiabilities")[i])),251 derived("debtToEquity", "Debt to equity", "ratio", "totalDebt / totalStockholdersEquity (null when equity ≤ 0)", (i) => divPos(B("totalDebt")[i], equity[i])),252 derived("netDebtToEbitda", "Net debt to EBITDA", "ratio", `netDebt / ebitda (null when EBITDA ≤ 0)${flowNote}`, (i) => divPos(B("netDebt")[i], I("ebitda")[i])),253 derived("interestCoverage", "Interest coverage", "ratio", "operatingIncome / interestExpense (null when no interest expense is reported)", (i) => divPos(I("operatingIncome")[i], I("interestExpense")[i])),254 derived("payoutRatio", "Dividend payout ratio", "percent", "|commonDividendsPaid| / netIncome (null when net income ≤ 0)", (i) => divPos(abs(dividends[i]), netIncome[i])),255 derived("revenuePerShare", "Revenue per share", "per_share", "revenue / weightedAverageShsOutDil", (i) => divPos(revenue[i], sharesDil[i])),256 derived("operatingCashFlowPerShare", "Operating cash flow per share", "per_share", "operatingCashFlow / weightedAverageShsOutDil", (i) => divPos(ocf[i], sharesDil[i])),257 derived("freeCashFlowPerShare", "Free cash flow per share", "per_share", "freeCashFlow / weightedAverageShsOutDil", (i) => divPos(fcf[i], sharesDil[i])),258 derived("bookValuePerShare", "Book value per share", "per_share", "totalStockholdersEquity / weightedAverageShsOutDil (weighted average diluted shares of the period, not the period-end count)", (i) => divPos(equity[i], sharesDil[i])),259 derived("dividendsPerShare", "Dividends per share", "per_share", "|commonDividendsPaid| / weightedAverageShsOut", (i) => divPos(abs(dividends[i]), sharesBasic[i])),260 ];261262 // Growth: the base period must really be one year (or one quarter) earlier — a hole in the series gives null,263 // not a rate over the wrong span — and must be positive for the rate to mean anything.264 const yoyLag = kind === "quarter" ? 4 : 1;265 const growthOf = (xs: (number | null)[], lag: number, minDays: number, maxDays: number) => (i: number): number | null => {266 const j = i + lag;267 if (j >= allDates.length) return null;268 const gap = daysBetween(allDates[i], allDates[j]);269 if (gap < minDays || gap > maxDays) return null;270 const base = xs[j];271 const cur = xs[i];272 return cur === null || base === null || base <= 0 ? null : cur / base - 1;273 };274 const GROWTH: [string, string, (number | null)[]][] = [275 ["revenue", "Revenue", revenue],276 ["grossProfit", "Gross profit", I("grossProfit")],277 ["operatingIncome", "Operating income", I("operatingIncome")],278 ["ebitda", "EBITDA", I("ebitda")],279 ["netIncome", "Net income", netIncome],280 ["epsDiluted", "EPS (diluted)", I("epsDiluted")],281 ["operatingCashFlow", "Operating cash flow", ocf],282 ["freeCashFlow", "Free cash flow", fcf],283 ];284 const growth: Row[] = [];285 for (const [key, label, xs] of GROWTH) {286 const lagText = kind === "quarter" ? "same quarter one year earlier" : "previous fiscal year";287 growth.push(derived(`${key}GrowthYoY`, `${label} growth, year over year`, "percent", `${key}[t] / ${key}[${lagText}] − 1 (null when the base is ≤ 0 or missing)`, growthOf(xs, yoyLag, 330, 400)));288 }289 if (kind === "quarter") {290 for (const [key, label, xs] of GROWTH) {291 growth.push(derived(`${key}GrowthQoQ`, `${label} growth, quarter over quarter`, "percent", `${key}[t] / ${key}[previous quarter] − 1 (null when the base is ≤ 0 or missing; not seasonally adjusted)`, growthOf(xs, 1, 60, 125)));292 }293 }294295 const commonSize = (m: Map<string, Raw>, lines: Line[], baseKey: string, base: (number | null)[]): Row[] =>296 lines297 .filter(([key, , unit]) => (unit ?? "currency") === "currency" && key !== baseKey)298 .map(([key, label]) => {299 const xs = series(m, key);300 return derived(key, label, "percent", `${key} / ${baseKey}`, (i) => divPos(xs[i], base[i]));301 });302303 const periods: PeriodInfo[] = shown.map((d) => {304 const r = inc.get(d) ?? bal.get(d) ?? cf.get(d) ?? {};305 return { date: d, fiscalYear: r.fiscalYear ? String(r.fiscalYear) : null, period: r.period ? String(r.period) : null, filingDate: r.filingDate ? String(r.filingDate).slice(0, 10) : null };306 });307 const first = raw.income[0] ?? raw.balance[0] ?? raw.cashflow[0];308 return {309 symbol,310 currency: first?.reportedCurrency ? String(first.reportedCurrency) : null,311 period: kind,312 periods,313 income: rows(inc, INCOME),314 balance: rows(bal, BALANCE),315 cashflow: rows(cf, CASHFLOW),316 ratios,317 growth,318 // Cash-flow lines are sized on revenue too, so they read against the income statement's margins (capex / revenue,319 // free cash flow / revenue…); the formula of each row says so.320 commonSize: { income: commonSize(inc, INCOME, "revenue", revenue), balance: commonSize(bal, BALANCE, "totalAssets", assets), cashflow: commonSize(cf, CASHFLOW, "revenue", revenue) },321 latestFiling: periods[0]?.filingDate ?? null,322 };323}324325export function parseStatementsQuery(symbol: unknown, q: Record<string, unknown>): { symbol: string; period: PeriodKind; limit: number } {326 const sym = parseSymbol(symbol);327 const period = String(q.period ?? "annual").trim().toLowerCase();328 if (period !== "annual" && period !== "quarter") throw new DataParamError("period must be annual or quarter.");329 let limit = 8;330 if (q.limit !== undefined && q.limit !== null && q.limit !== "") {331 const n = Number(q.limit);332 if (!Number.isInteger(n) || n < 1 || n > 40) throw new DataParamError("limit must be an integer between 1 and 40.");333 limit = n;334 }335 return { symbol: sym, period, limit };336}337338const cache = new TtlCache<StatementsResult>(200);339const flights = new SingleFlight<StatementsResult>();340const ENDPOINTS = ["/income-statement", "/balance-sheet-statement", "/cash-flow-statement"];341342/** Statements of a company with derived rows. Statements change a few times a year: cached six hours. */343export function getStatements(symbol: string, period: PeriodKind, limit: number): Promise<StatementsResult> {344 return cachedFlight(cache, flights, `${symbol}|${period}|${limit}`, 6 * 3_600_000, async () => {345 // Extra periods so the oldest displayed one still has its growth base.346 const fetchLimit = limit + (period === "quarter" ? 4 : 1);347 const [income, balance, cashflow] = await Promise.all(ENDPOINTS.map((path) => providerJson<Raw[]>("fmp", path, { params: { symbol, period, limit: fetchLimit } })));348 const raw: RawStatements = { income: Array.isArray(income) ? income : [], balance: Array.isArray(balance) ? balance : [], cashflow: Array.isArray(cashflow) ? cashflow : [] };349 if (raw.income.length + raw.balance.length + raw.cashflow.length === 0) {350 throw new ProviderError("fmp", "not_found", `FMP has no financial statements for ${symbol} (statements exist for operating companies, not for ETFs, indices, pairs or crypto).`);351 }352 const retrievedAt = Date.now();353 const { latestFiling, ...built } = buildStatements(symbol, raw, period, limit);354 const asOf = latestFiling ? Date.parse(`${latestFiling}T00:00:00Z`) : built.periods[0] ? Date.parse(`${built.periods[0].date}T00:00:00Z`) : null;355 const notes = [356 "Statement lines are as reported by FMP, in the reporting currency. FMP writes 0 for a line a company does not report separately.",357 "Derived rows are computed by VQuant from those lines (see each row's formula); a derived value is null when an input is missing.",358 "percent and ratio values are fractions (0.25 = 25 %).",359 ];360 if (built.periods.length < limit) notes.push(`FMP returned ${built.periods.length} period(s); ${limit} were asked.`);361 return {362 ...built,363 provenance: { provider: "fmp", retrievedAt, freshness: { kind: "historical", asOf, provider: "fmp", retrievedAt, note: latestFiling ? `Latest period filed on ${latestFiling}.` : null }, endpoints: ENDPOINTS, notes },364 };365 });366}367368export function registerStatementRoutes(app: Express): void {369 app.get("/api/v2/data/statements/:symbol", async (req: Request, res: Response) => {370 res.set("Cache-Control", "private, no-store");371 try {372 const q = parseStatementsQuery(req.params.symbol, req.query as Record<string, unknown>);373 res.json(await getStatements(q.symbol, q.period, q.limit));374 } catch (e) {375 const r = dataErrorResponse(e, "statements");376 res.status(r.status).json(r.body);377 }378 });379}380381/** Test hook. */382export function resetStatements(): void {383 cache.clear();384}385