gloomberb 0.20.6 → 0.20.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (67) hide show
  1. package/package.json +1 -1
  2. package/src/api-client/fund-facts.ts +20 -4
  3. package/src/api-client/socket.ts +4 -4
  4. package/src/architecture/shortcut-labels-allowlist.json +1 -0
  5. package/src/cli/commands/market.ts +33 -17
  6. package/src/cli/commands/search.ts +19 -3
  7. package/src/cli/desktop-pane-shot.ts +61 -0
  8. package/src/cli/pane-functions/dom.ts +4 -4
  9. package/src/cli/pane-functions/freshness.ts +38 -5
  10. package/src/cli/pane-functions/screenshot-assessment.ts +16 -4
  11. package/src/cli/quote-answer.ts +57 -1
  12. package/src/cli/result.ts +17 -0
  13. package/src/docs/snapshot.json +55 -16
  14. package/src/i18n/es.ts +2 -0
  15. package/src/i18n/ja.ts +2 -0
  16. package/src/i18n/ko.ts +2 -0
  17. package/src/i18n/zh-cn.ts +2 -0
  18. package/src/i18n/zh-tw.ts +2 -0
  19. package/src/market-data/market/change-basis.ts +49 -8
  20. package/src/market-data/market/dated-previous-close.ts +133 -10
  21. package/src/market-data/market/freshness.ts +18 -6
  22. package/src/market-data/market/status.ts +9 -1
  23. package/src/market-data/published-nse-sessions.ts +16 -1
  24. package/src/market-data/quotes/freshness.ts +15 -0
  25. package/src/plugins/builtin/alerts/alert-engine.ts +15 -0
  26. package/src/plugins/builtin/alerts/cli.ts +22 -9
  27. package/src/plugins/builtin/alerts/headless.ts +1 -1
  28. package/src/plugins/builtin/alerts/index.tsx +5 -1
  29. package/src/plugins/builtin/alerts/metric-command.ts +1 -1
  30. package/src/plugins/builtin/holders/fund-holders.ts +22 -1
  31. package/src/plugins/builtin/holders/headless.ts +5 -4
  32. package/src/plugins/builtin/holders/pane.tsx +7 -3
  33. package/src/plugins/builtin/holders/report-header.ts +23 -0
  34. package/src/plugins/builtin/members/client.ts +1 -1
  35. package/src/plugins/builtin/members/headless.ts +2 -0
  36. package/src/plugins/builtin/members/model.ts +10 -8
  37. package/src/plugins/builtin/members/pane.tsx +4 -1
  38. package/src/plugins/builtin/portfolio-list/cli/portfolio-command.ts +5 -2
  39. package/src/plugins/builtin/portfolio-list/cli/render.ts +66 -23
  40. package/src/plugins/builtin/portfolio-list/headless.ts +2 -1
  41. package/src/plugins/builtin/portfolio-list/income.ts +46 -22
  42. package/src/plugins/builtin/portfolio-list/pane/data.ts +16 -6
  43. package/src/plugins/builtin/portfolio-list/pane/index.tsx +5 -4
  44. package/src/plugins/builtin/portfolio-list/use-throttled-ticker-order.ts +40 -3
  45. package/src/plugins/builtin/sec/fund-facts.ts +25 -5
  46. package/src/plugins/builtin/shared/report-freshness.ts +15 -6
  47. package/src/plugins/builtin/supply-chain/model.ts +18 -6
  48. package/src/portfolio/column-values.ts +3 -0
  49. package/src/portfolio/valuation-basis.ts +23 -1
  50. package/src/state/hooks/quote-streaming.ts +14 -6
  51. package/src/tickers/instrument-kind.ts +22 -1
  52. package/src/tickers/search/index.ts +5 -0
  53. package/src/tickers/terminal-codes.ts +17 -5
  54. package/src/time-series/fundamentals/current-valuation.ts +244 -0
  55. package/src/time-series/fundamentals/historical-valuation.ts +99 -0
  56. package/src/time-series/fundamentals/metric-ids.ts +61 -0
  57. package/src/time-series/fundamentals/period-points.ts +104 -0
  58. package/src/time-series/fundamentals/quarterly-ttm.ts +220 -0
  59. package/src/time-series/fundamentals/series.ts +164 -0
  60. package/src/time-series/fundamentals/source-statements.ts +177 -0
  61. package/src/time-series/fundamentals/statement-fields.ts +154 -0
  62. package/src/time-series/fundamentals/statement-merge.ts +124 -0
  63. package/src/time-series/fundamentals/statement.ts +114 -0
  64. package/src/time-series/fundamentals/valuation-multiples.ts +50 -0
  65. package/src/time-series/fundamentals.ts +18 -1407
  66. package/src/types/financials.ts +9 -0
  67. package/src/utils/debug-log.ts +29 -0
@@ -1,1407 +1,18 @@
1
- import type {
2
- FinancialStatement,
3
- TickerFinancials,
4
- } from "../types/financials";
5
- import { areNearbyFinancialPeriodEnds, completeAvailability, statementFieldAvailability } from "../utils/financial-statements";
6
- import { copyIncomeField, incomeFieldKnowledgeDate, incomeFieldOwner, isIncomeStatementField } from "../utils/income-statement";
7
- import { fiscalPeriodLabel, fiscalYearEndMonth, ttmPeriodLabel } from "../utils/fiscal-period";
8
- import { hasStatementGap, mergeStatementGaps } from "../utils/statement-gaps";
9
- import { trailingEpsAcrossFiscalYearEnd } from "../utils/trailing-eps";
10
- import { canonicalTimeSeriesFieldId, getTimeSeriesField } from "./field-catalog";
11
- import { dailyForwardPeHistory, forwardPeHistory, realizedNtmPeHistory } from "./forward-valuation";
12
- import { dailyValuationHistory, type DailyValuationBasis } from "./daily-valuation";
13
- import { statementAtRelease } from "./valuation-releases";
14
- import { reportingCurrencySeries } from "./reporting-currency";
15
- import { createValuationCurrencyContext, type ValuationCurrencyContext } from "./valuation-currency";
16
- import { currentValuationPrice, valuationPriceAtOrBefore, valuationQuoteIssue, type ValuationPriceIssue } from "./valuation-price";
17
- import type { SecuritySeriesSource, SeriesPeriod, TimeSeriesPoint } from "./types";
18
- import { isFiniteNumber } from "../utils/guards";
19
- import { liveForwardPE, liveTrailingPE } from "../market-data/quotes/live-valuation";
20
- import { listingEnterpriseValue } from "../market-data/quotes/listing-enterprise-value";
21
- import { BANK_OR_INSURER_EBITDA, isBankOrInsurerIndustry } from "../utils/ebitda";
22
- import { comparablePriceEarnings } from "../utils/price-earnings";
23
-
24
- type NumericStatementField =
25
- | "totalRevenue"
26
- | "grossProfit"
27
- | "operatingIncome"
28
- | "netIncome"
29
- | "netIncomeIncludingNoncontrollingInterests"
30
- | "netIncomeCommonStockholders"
31
- | "ebitda"
32
- | "depreciationAndAmortization"
33
- | "operatingCashFlow"
34
- | "capitalExpenditure"
35
- | "freeCashFlow"
36
- | "eps"
37
- | "totalAssets"
38
- | "cashAndCashEquivalents"
39
- | "cashCashEquivalentsAndShortTermInvestments"
40
- | "totalDebt"
41
- | "totalEquity"
42
- | "basicShares"
43
- | "dilutedShares"
44
- | "shareIssued"
45
- | "ordinarySharesNumber";
46
-
47
- type InternalStatement = FinancialStatement & {
48
- __timeSeriesDerivedFields?: NumericStatementField[];
49
- __timeSeriesTtm?: boolean;
50
- __timeSeriesIncompleteCommonIncome?: boolean;
51
- __timeSeriesIncompleteAverageShares?: boolean;
52
- };
53
-
54
- const DAY_MS = 24 * 60 * 60 * 1_000;
55
-
56
- const QUARTERLY_FLOW_FIELDS: readonly NumericStatementField[] = [
57
- "totalRevenue",
58
- "grossProfit",
59
- "operatingIncome",
60
- "netIncome",
61
- "netIncomeIncludingNoncontrollingInterests",
62
- "ebitda",
63
- "depreciationAndAmortization",
64
- "operatingCashFlow",
65
- "capitalExpenditure",
66
- "freeCashFlow",
67
- ];
68
-
69
- const QUARTERLY_SNAPSHOT_FIELDS: readonly NumericStatementField[] = [
70
- "totalAssets",
71
- "cashAndCashEquivalents",
72
- "cashCashEquivalentsAndShortTermInvestments",
73
- "totalDebt",
74
- "totalEquity",
75
- "shareIssued",
76
- "ordinarySharesNumber",
77
- ];
78
-
79
- const QUARTERLY_AVERAGE_FIELDS: readonly NumericStatementField[] = ["basicShares", "dilutedShares"];
80
- // Reported common-income allocations and EPS may be summed for TTM, but
81
- // independently determined annual values cannot establish a missing quarter.
82
- // A trailing year across a fiscal Q4 without EPS reads that year's own EPS.
83
- const TTM_SUM_FIELDS: readonly NumericStatementField[] = [...QUARTERLY_FLOW_FIELDS, "netIncomeCommonStockholders", "eps"];
84
-
85
- const NUMERIC_STATEMENT_FIELDS: readonly NumericStatementField[] = [
86
- ...QUARTERLY_FLOW_FIELDS,
87
- ...QUARTERLY_SNAPSHOT_FIELDS,
88
- ...QUARTERLY_AVERAGE_FIELDS,
89
- "netIncomeCommonStockholders",
90
- "eps",
91
- ];
92
-
93
- const FUNDAMENTAL_IDS = new Set([
94
- "totalRevenue",
95
- "grossProfit",
96
- "grossMargin",
97
- "operatingIncome",
98
- "operatingMargin",
99
- "netIncome",
100
- "netMargin",
101
- "ebitda",
102
- "depreciationAndAmortization",
103
- "operatingCashFlow",
104
- "freeCashFlow",
105
- "freeCashFlowMargin",
106
- "totalAssets",
107
- "totalDebt",
108
- "totalEquity",
109
- "eps",
110
- ]);
111
-
112
- const VALUATION_IDS = new Set([
113
- "trailingPE",
114
- "forwardPE",
115
- "realizedNtmPE",
116
- "pegRatio",
117
- "priceSales",
118
- "evSales",
119
- "evEbitda",
120
- "priceFcf",
121
- ]);
122
-
123
- /** Statement-based multiples whose latest point is the regular session price over the latest trailing period. */
124
- const QUOTE_DERIVED_VALUATION_IDS = new Set([
125
- "trailingPE",
126
- "priceSales",
127
- "evSales",
128
- "evEbitda",
129
- "priceFcf",
130
- ]);
131
-
132
- /** Multiples priced from history at each observation date; forward P/E also ends on the live quote. */
133
- const PRICE_HISTORY_VALUATION_IDS = new Set([
134
- ...QUOTE_DERIVED_VALUATION_IDS,
135
- "forwardPE",
136
- "realizedNtmPE",
137
- ]);
138
-
139
- function validDate(value: unknown): Date | null {
140
- if (value instanceof Date) {
141
- return Number.isFinite(value.getTime()) ? new Date(value.getTime()) : null;
142
- }
143
- if (typeof value !== "string" && typeof value !== "number") return null;
144
- const parsed = new Date(value);
145
- return Number.isFinite(parsed.getTime()) ? parsed : null;
146
- }
147
-
148
- function statementTime(statement: FinancialStatement): number {
149
- return Date.parse(statement.date);
150
- }
151
-
152
- function statementNumber(statement: FinancialStatement, field: NumericStatementField): number | null {
153
- if (field === "eps" && statement.epsBasis?.status === "unresolved") return null;
154
- const value = statement[field];
155
- return isFiniteNumber(value) ? value : null;
156
- }
157
-
158
- function setStatementNumber(
159
- statement: InternalStatement,
160
- field: NumericStatementField,
161
- value: number,
162
- availableAt?: string,
163
- ): void {
164
- (statement as unknown as Record<string, unknown>)[field] = value;
165
- statement.__timeSeriesDerivedFields = [
166
- ...new Set([...(statement.__timeSeriesDerivedFields ?? []), field]),
167
- ];
168
- statement.fieldAvailability = { ...statement.fieldAvailability };
169
- if (availableAt) statement.fieldAvailability[field] = availableAt;
170
- else delete statement.fieldAvailability[field];
171
- }
172
-
173
- function completeStatementAvailability(statement: InternalStatement): string | undefined {
174
- return completeAvailability(NUMERIC_STATEMENT_FIELDS
175
- .filter((field) => statementNumber(statement, field) !== null)
176
- .map((field) => statementFieldAvailability(statement, field)));
177
- }
178
-
179
- /** Internal calendar bucket for selecting adjacent inputs, not an issuer fiscal label. */
180
- function calendarQuarterBucket(date: string): string {
181
- const parsedYear = Number(date.slice(0, 4));
182
- let year = Number.isFinite(parsedYear) ? parsedYear : 0;
183
-
184
- let month = Number(date.slice(5, 7));
185
- const day = Number(date.slice(8, 10));
186
- if (Number.isFinite(month) && Number.isFinite(day) && day <= 7 && (month - 1) % 3 === 0) {
187
- month -= 1;
188
- if (month === 0) {
189
- month = 12;
190
- year -= 1;
191
- }
192
- }
193
- const quarter = Number.isFinite(month) && month > 0 ? Math.ceil(month / 3) : 0;
194
- return quarter > 0 && year > 0 ? `${year} Q${quarter}` : date;
195
- }
196
-
197
- function statementAvailabilityScore(statement: FinancialStatement): number {
198
- return Object.values(statement.fieldAvailability ?? {})
199
- .filter((value) => Number.isFinite(Date.parse(value)))
200
- .length + (Number.isFinite(Date.parse(statement.availableAt ?? "")) ? 1 : 0);
201
- }
202
-
203
- interface StatementFieldCandidate {
204
- statement: InternalStatement;
205
- value: number;
206
- availableAt?: string;
207
- derived: boolean;
208
- }
209
-
210
- function selectFieldCandidate(candidates: StatementFieldCandidate[]): StatementFieldCandidate {
211
- const reported = candidates.filter((candidate) => !candidate.derived);
212
- const qualityCandidates = reported.length > 0 ? reported : candidates;
213
- const dated = qualityCandidates.filter((candidate) => (
214
- Number.isFinite(Date.parse(candidate.availableAt ?? ""))
215
- ));
216
- const chronological = [...(dated.length > 0 ? dated : qualityCandidates)].sort((left, right) => (
217
- Date.parse(left.availableAt ?? "") - Date.parse(right.availableAt ?? "")
218
- || left.statement.date.localeCompare(right.statement.date)
219
- ));
220
- let selected = chronological[0]!;
221
- for (const candidate of chronological.slice(1)) {
222
- if (!Object.is(candidate.value, selected.value)) selected = candidate;
223
- }
224
- return selected;
225
- }
226
-
227
- function periodDateSource(statements: readonly InternalStatement[]): InternalStatement {
228
- return [...statements].sort((left, right) => {
229
- const availabilityDifference = statementAvailabilityScore(right) - statementAvailabilityScore(left);
230
- return availabilityDifference || left.date.localeCompare(right.date);
231
- })[0]!;
232
- }
233
-
234
- function mergeStatementPeriodGroup(statements: readonly InternalStatement[]): InternalStatement {
235
- const dateSource = periodDateSource(statements);
236
- const merged: InternalStatement = { date: dateSource.date, currency: dateSource.currency };
237
- const compatibleStatements = statements.filter((statement) => statement.currency === dateSource.currency);
238
- const derivedFields: NumericStatementField[] = [];
239
- const fieldAvailability: Record<string, string> = {};
240
- const record = merged as unknown as Record<string, unknown>;
241
-
242
- for (const field of NUMERIC_STATEMENT_FIELDS) {
243
- // A gap declared for the period is never filled from another report.
244
- if (!isIncomeStatementField(field) && compatibleStatements.some((statement) => hasStatementGap(statement, field))) continue;
245
- if (isIncomeStatementField(field)) {
246
- const qualified = compatibleStatements.filter(statement => statement.date === dateSource.date && incomeFieldOwner(field, statement));
247
- if (qualified.length) {
248
- const owner = [...qualified].sort((left, right) => incomeFieldKnowledgeDate(right, field).localeCompare(incomeFieldKnowledgeDate(left, field)))[0]!;
249
- copyIncomeField(merged, owner, field);
250
- const availability = statementFieldAvailability(owner, field);
251
- if (typeof merged[field] === "number" && availability) fieldAvailability[field] = availability;
252
- continue;
253
- }
254
- }
255
- const candidates = compatibleStatements.flatMap((statement): StatementFieldCandidate[] => {
256
- if (isIncomeStatementField(field) && statement.date !== dateSource.date
257
- && incomeFieldOwner(field, statement)) return [];
258
- const value = statementNumber(statement, field);
259
- if (value === null) return [];
260
- return [{
261
- statement,
262
- value,
263
- availableAt: statementFieldAvailability(statement, field),
264
- derived: statement.__timeSeriesDerivedFields?.includes(field) === true,
265
- }];
266
- });
267
- const verifiedEps = field === "eps" ? candidates.filter((candidate) => candidate.statement.epsBasis?.status === "split-adjusted") : [];
268
- const unresolvedEps = field === "eps" ? compatibleStatements.find((statement) => statement.epsBasis?.status === "unresolved") : undefined;
269
- if (unresolvedEps && verifiedEps.length === 0) {
270
- merged.epsBasis = unresolvedEps.epsBasis;
271
- continue;
272
- }
273
- if (candidates.length === 0) continue;
274
- const selected = selectFieldCandidate(verifiedEps.length ? verifiedEps : candidates);
275
- record[field] = selected.value;
276
- if (field === "eps" && selected.statement.epsBasis) merged.epsBasis = selected.statement.epsBasis;
277
- if (selected.availableAt) fieldAvailability[field] = selected.availableAt;
278
- if (selected.derived) derivedFields.push(field);
279
- }
280
-
281
- mergeStatementGaps(merged, compatibleStatements);
282
- merged.fieldAvailability = fieldAvailability;
283
- merged.availableAt = completeStatementAvailability(merged);
284
- if (NUMERIC_STATEMENT_FIELDS.every(field => statementNumber(merged, field) === null)) {
285
- // Even an empty statement can establish when a missing period became
286
- // known. Its empty field map still cannot date any numeric metric.
287
- merged.availableAt = completeAvailability([dateSource.availableAt]);
288
- }
289
- if (derivedFields.length > 0) merged.__timeSeriesDerivedFields = derivedFields;
290
- return merged;
291
- }
292
-
293
- function mergeStatementsByPeriod(
294
- statements: readonly FinancialStatement[],
295
- ): InternalStatement[] {
296
- const groups: InternalStatement[][] = [];
297
- const sorted = [...statements].sort((left, right) => left.date.localeCompare(right.date));
298
- for (const statement of sorted) {
299
- const lastGroup = groups.at(-1);
300
- if (lastGroup && areNearbyFinancialPeriodEnds(lastGroup[0]!.date, statement.date)) {
301
- lastGroup.push(statement as InternalStatement);
302
- } else groups.push([statement as InternalStatement]);
303
- }
304
- return groups
305
- .map(mergeStatementPeriodGroup)
306
- .sort((left, right) => left.date.localeCompare(right.date));
307
- }
308
-
309
- interface PrecedingQuarterInput {
310
- date: string;
311
- time: number;
312
- value: number;
313
- availableAt?: string;
314
- }
315
-
316
- function precedingQuarterInputs(
317
- quarterlyStatements: readonly FinancialStatement[],
318
- annualStatement: FinancialStatement,
319
- field: NumericStatementField,
320
- ): PrecedingQuarterInput[] {
321
- const annualTime = statementTime(annualStatement);
322
- if (!Number.isFinite(annualTime)) return [];
323
-
324
- const annualCategory = calendarQuarterBucket(annualStatement.date);
325
- const byCategory = new Map<string, PrecedingQuarterInput>();
326
- for (const statement of quarterlyStatements) {
327
- if (statement.currency !== annualStatement.currency) continue;
328
- const time = statementTime(statement);
329
- if (!Number.isFinite(time) || time >= annualTime || annualTime - time > 370 * DAY_MS) continue;
330
- const category = calendarQuarterBucket(statement.date);
331
- if (category === annualCategory) continue;
332
- const value = statementNumber(statement, field);
333
- if (value === null) continue;
334
- const previous = byCategory.get(category);
335
- if (!previous || statement.date.localeCompare(previous.date) > 0) {
336
- byCategory.set(category, {
337
- date: statement.date,
338
- time,
339
- value,
340
- availableAt: statementFieldAvailability(statement, field),
341
- });
342
- }
343
- }
344
-
345
- return [...byCategory.values()]
346
- .sort((left, right) => right.time - left.time)
347
- .slice(0, 3)
348
- .sort((left, right) => left.time - right.time);
349
- }
350
-
351
- /**
352
- * Completes additive fiscal Q4 flows from the annual total and three reported
353
- * quarters. EPS and weighted-average shares require reported quarter values;
354
- * neither is an additive flow. Snapshots come from the annual balance sheet. Derived
355
- * values become available only after the annual total and every quarterly
356
- * input used in the derivation are public.
357
- */
358
- export function deriveQuarterlyStatements(
359
- quarterlyStatements: readonly FinancialStatement[],
360
- annualStatements: readonly FinancialStatement[],
361
- ): FinancialStatement[] {
362
- const mergedQuarterly = mergeStatementsByPeriod(quarterlyStatements);
363
- const byDate = new Map(mergedQuarterly.map((statement) => [statement.date, { ...statement }]));
364
-
365
- for (const annualStatement of mergeStatementsByPeriod(annualStatements)) {
366
- let target: InternalStatement = byDate.get(annualStatement.date) ?? { date: annualStatement.date, currency: annualStatement.currency };
367
- if (target.currency !== annualStatement.currency) continue;
368
- let changed = false;
369
-
370
- for (const field of QUARTERLY_FLOW_FIELDS) {
371
- // A line unavailable for the fourth quarter stays a gap: the full year
372
- // minus the other quarters would recreate the value a source withheld.
373
- if (hasStatementGap(target, field) || mergedQuarterly.some((statement) => (
374
- areNearbyFinancialPeriodEnds(statement.date, annualStatement.date) && hasStatementGap(statement, field)
375
- ))) continue;
376
- if (statementNumber(target, field) !== null) continue;
377
- const annualValue = statementNumber(annualStatement, field);
378
- if (annualValue === null) continue;
379
- const previousInputs = precedingQuarterInputs(mergedQuarterly, annualStatement, field);
380
- if (previousInputs.length !== 3) continue;
381
- const inputTimes = [...previousInputs.map((input) => input.time), statementTime(annualStatement)];
382
- if (inputTimes.some((time, index) => index > 0 && (time - inputTimes[index - 1]! < 60 * DAY_MS || time - inputTimes[index - 1]! > 120 * DAY_MS))) continue;
383
- const derived = annualValue - previousInputs.reduce((sum, input) => sum + input.value, 0);
384
- if (!Number.isFinite(derived)) continue;
385
- const availableAt = completeAvailability([
386
- statementFieldAvailability(annualStatement, field),
387
- ...previousInputs.map((input) => input.availableAt),
388
- ]);
389
- setStatementNumber(target, field, derived, availableAt);
390
- changed = true;
391
- }
392
-
393
- for (const field of QUARTERLY_SNAPSHOT_FIELDS) {
394
- if (statementNumber(target, field) !== null) continue;
395
- const annualValue = statementNumber(annualStatement, field);
396
- if (annualValue === null) continue;
397
- const availableAt = statementFieldAvailability(annualStatement, field);
398
- setStatementNumber(target, field, annualValue, availableAt);
399
- changed = true;
400
- }
401
-
402
- if (changed) {
403
- target.availableAt = completeStatementAvailability(target);
404
- byDate.set(target.date, target);
405
- }
406
- }
407
-
408
- return mergeStatementsByPeriod([...byDate.values()]);
409
- }
410
-
411
- function buildTtmStatements(
412
- statements: readonly FinancialStatement[],
413
- annualStatements: readonly FinancialStatement[],
414
- ): InternalStatement[] {
415
- const sorted = mergeStatementsByPeriod(statements);
416
- const annual = mergeStatementsByPeriod(annualStatements);
417
- const result: InternalStatement[] = [];
418
- for (let index = 3; index < sorted.length; index += 1) {
419
- const window = sorted.slice(index - 3, index + 1);
420
- const latest = window.at(-1)!;
421
- const times = window.map(statementTime);
422
- if (new Set(window.map((statement) => statement.currency)).size > 1
423
- || times.some((time, index) => !Number.isFinite(time) || (index > 0 && (time - times[index - 1]! < 60 * DAY_MS || time - times[index - 1]! > 120 * DAY_MS)))) {
424
- // Retain the known period as a gap. Removing an incomplete window joins
425
- // the last usable TTM observation to the first recovered one.
426
- result.push({ date: latest.date, currency: latest.currency, availableAt: latest.availableAt,
427
- __timeSeriesTtm: true });
428
- continue;
429
- }
430
-
431
- const ttm: InternalStatement = {
432
- date: latest.date,
433
- currency: latest.currency,
434
- fieldAvailability: {},
435
- __timeSeriesTtm: true,
436
- __timeSeriesDerivedFields: [],
437
- };
438
- const unresolvedEps = window.find((statement) => statement.epsBasis?.status === "unresolved");
439
- if (unresolvedEps) ttm.epsBasis = unresolvedEps.epsBasis;
440
- const commonIncomeCount = window.filter((statement) => isFiniteNumber(statement.netIncomeCommonStockholders)).length;
441
- // Known common claims in some quarters cannot be ignored by substituting
442
- // aggregate income for the entire window or only its missing quarters.
443
- if ((commonIncomeCount > 0 && commonIncomeCount < window.length)
444
- || window.some(statement => statement.unavailableFields?.includes("netIncomeCommonStockholders"))) ttm.__timeSeriesIncompleteCommonIncome = true;
445
- const hasAverageShareInputs = window.some(statement => QUARTERLY_AVERAGE_FIELDS
446
- .some(field => statementNumber(statement, field) !== null));
447
- const hasCompleteAverageShares = QUARTERLY_AVERAGE_FIELDS.some(field => window.every(statement => {
448
- const value = statementNumber(statement, field);
449
- return value !== null && value > 0;
450
- }));
451
- // A missing quarter cannot replace a known weighted-period denominator
452
- // with a year-end ordinary/issued-share snapshot. Capitalization may still
453
- // use the snapshot; this guard is specific to the fallback earnings ratio.
454
- if (hasAverageShareInputs && !hasCompleteAverageShares) ttm.__timeSeriesIncompleteAverageShares = true;
455
-
456
- for (const field of [...TTM_SUM_FIELDS, ...QUARTERLY_AVERAGE_FIELDS]) {
457
- const values = window.map((statement) => statementNumber(statement, field));
458
- if (!values.every((value): value is number => value !== null)) continue;
459
- if (QUARTERLY_AVERAGE_FIELDS.includes(field) && !values.every(value => value > 0)) continue;
460
- (ttm as unknown as Record<string, unknown>)[field] = values.reduce((sum, value) => sum + value, 0)
461
- / (QUARTERLY_AVERAGE_FIELDS.includes(field) ? 4 : 1);
462
- ttm.__timeSeriesDerivedFields!.push(field);
463
- const availableAt = completeAvailability(window.map((statement) => (
464
- statementFieldAvailability(statement, field)
465
- )));
466
- if (availableAt) ttm.fieldAvailability![field] = availableAt;
467
- }
468
- // A fiscal Q4 the 10-K reports only inside its year: the year's EPS plus the quarters since, less the same quarters a year earlier.
469
- const acrossYearEnd = statementNumber(ttm, "eps") === null && !unresolvedEps
470
- ? trailingEpsAcrossFiscalYearEnd(window, sorted, annual, "eps") : null;
471
- if (acrossYearEnd) {
472
- ttm.eps = acrossYearEnd.value;
473
- ttm.__timeSeriesDerivedFields!.push("eps");
474
- const availableAt = completeAvailability(acrossYearEnd.inputs.map((statement) => statementFieldAvailability(statement, "eps")));
475
- if (availableAt) ttm.fieldAvailability!.eps = availableAt;
476
- }
477
-
478
- for (const field of QUARTERLY_SNAPSHOT_FIELDS) {
479
- const value = statementNumber(latest, field);
480
- if (value === null) continue;
481
- (ttm as unknown as Record<string, unknown>)[field] = value;
482
- const availableAt = statementFieldAvailability(latest, field);
483
- if (availableAt) ttm.fieldAvailability![field] = availableAt;
484
- }
485
- ttm.availableAt = completeStatementAvailability(ttm) ?? latest.availableAt;
486
- result.push(ttm);
487
- }
488
- return result;
489
- }
490
-
491
- /**
492
- * A split restates EPS onto the new share count, and SEC history dates the
493
- * restated figure by the filing that evidenced the split. The earnings were
494
- * known at the original filing; price history is split-adjusted the same way,
495
- * so a multiple of the restated figure steps when it was first filed. The
496
- * EPS series itself keeps the restatement's date: its value is the restated one.
497
- */
498
- export function knownWhenFiled(row: FinancialStatement): FinancialStatement {
499
- const filed = row.epsBasis?.status === "split-adjusted" ? row.epsBasis.originalFiled : undefined;
500
- if (!filed || !Number.isFinite(Date.parse(filed))) return row;
501
- const current = statementFieldAvailability(row, "eps");
502
- if (current && Date.parse(current) <= Date.parse(filed)) return row;
503
- return { ...row, fieldAvailability: { ...row.fieldAvailability, eps: filed } };
504
- }
505
-
506
- /** The statements a multiple is priced from, each restated EPS dated by its first filing. */
507
- function valuationStatements(financials: TickerFinancials): { quarterly: FinancialStatement[]; annual: FinancialStatement[] } {
508
- return { quarterly: financials.quarterlyStatements.map(knownWhenFiled), annual: financials.annualStatements.map(knownWhenFiled) };
509
- }
510
-
511
- /**
512
- * A fiscal fourth quarter's EPS stated without a filing date of its own (a
513
- * 10-K states the year, the results release the quarter) was public once its
514
- * year's filing was, so it is dated by that filing. The daily P/E of the
515
- * quarters after it then sums the same four quarters PEB and the headline EPS
516
- * (TTM) sum (time-series/filed-trailing-eps), rather than reading the quarter
517
- * from the year and landing a cent of rounding away from them. The window that
518
- * ends with the year takes the year's own EPS (fiscalYearEpsAtYearEnd).
519
- */
520
- function fourthQuarterEpsAtYearFiling(row: FinancialStatement, annual: readonly FinancialStatement[]): FinancialStatement {
521
- if (!isFiniteNumber(row.eps) || hasStatementGap(row, "eps") || statementFieldAvailability(row, "eps")) return row;
522
- const year = annual.find((candidate) => candidate.currency === row.currency && areNearbyFinancialPeriodEnds(candidate.date, row.date));
523
- const filed = year && isFiniteNumber(year.eps) ? statementFieldAvailability(year, "eps") : undefined;
524
- return filed ? { ...row, fieldAvailability: { ...row.fieldAvailability, eps: filed } } : row;
525
- }
526
-
527
- /**
528
- * At a fiscal year end the filed year's diluted EPS is the daily trailing
529
- * figure, as PEB and the headline EPS (TTM) read it (filed-trailing-eps): four
530
- * quarters need not add up to their year (3.90 for the year beside four
531
- * quarters of 1.00), so their sum stands only where the year gives no dated EPS.
532
- */
533
- function fiscalYearEpsAtYearEnd(statements: readonly InternalStatement[], annual: readonly FinancialStatement[]): InternalStatement[] {
534
- return statements.map((statement) => {
535
- const year = annual.find((row) => row.currency === statement.currency && areNearbyFinancialPeriodEnds(row.date, statement.date));
536
- const eps = year && !hasStatementGap(year, "eps") ? statementNumber(year, "eps") : null;
537
- if (!year || eps === null) return statement;
538
- const { epsBasis: _sum, ...rest } = statement;
539
- const fieldAvailability = { ...statement.fieldAvailability };
540
- const filed = statementFieldAvailability(year, "eps");
541
- if (filed) fieldAvailability.eps = filed;
542
- else delete fieldAvailability.eps;
543
- const next: InternalStatement = {
544
- ...rest, eps, fieldAvailability, ...(year.epsBasis ? { epsBasis: year.epsBasis } : {}),
545
- __timeSeriesDerivedFields: [...new Set([...(statement.__timeSeriesDerivedFields ?? []), "eps" as const])],
546
- };
547
- next.availableAt = completeStatementAvailability(next) ?? statement.availableAt;
548
- return next;
549
- });
550
- }
551
-
552
- /** An undated vendor value cannot block a derivation from dated filings. */
553
- function datedValuationStatement(statement: FinancialStatement): FinancialStatement {
554
- const dated = { ...statement };
555
- for (const field of NUMERIC_STATEMENT_FIELDS) {
556
- if (!statementFieldAvailability(statement, field)) delete dated[field];
557
- }
558
- return dated;
559
- }
560
-
561
- function normalizeFundamentalPeriod(period: SeriesPeriod | undefined): "annual" | "quarterly" | "ttm" | "auto" {
562
- return period === "annual" || period === "quarterly" || period === "ttm" ? period : "auto";
563
- }
564
-
565
- function sourceStatements(
566
- financials: TickerFinancials,
567
- period: SeriesPeriod | undefined,
568
- valuationMetric?: string,
569
- exchange?: string,
570
- ): { statements: InternalStatement[]; period: "annual" | "quarterly" | "ttm" } {
571
- const normalized = normalizeFundamentalPeriod(period);
572
- let known = valuationMetric
573
- ? valuationStatements(financials)
574
- : { quarterly: financials.quarterlyStatements, annual: financials.annualStatements };
575
- if (period === "daily" && valuationMetric) {
576
- const releases = financials.earningsReleases ?? [];
577
- const venue = financials.quote?.listingExchangeName || financials.quote?.exchangeName || exchange;
578
- known = { quarterly: known.quarterly.map(row => statementAtRelease(row, releases, venue)),
579
- annual: known.annual.map(row => statementAtRelease(row, releases, venue)) };
580
- const annualRows = known.annual;
581
- known = { ...known, quarterly: known.quarterly.map((row) => fourthQuarterEpsAtYearFiling(row, annualRows)) };
582
- known = { quarterly: known.quarterly.map(datedValuationStatement), annual: known.annual.map(datedValuationStatement) };
583
- // A later comparative quarter may repeat a year-end balance sheet that
584
- // the annual filing already published. Only identical, same-currency
585
- // snapshots can inherit that earlier evidence; changed values cannot.
586
- known.quarterly = known.quarterly.map((statement) => {
587
- const dated = { ...statement, fieldAvailability: Object.fromEntries(NUMERIC_STATEMENT_FIELDS.flatMap((field) => {
588
- const availableAt = statementFieldAvailability(statement, field);
589
- return availableAt ? [[field, availableAt]] : [];
590
- })) };
591
- for (const annual of known.annual) {
592
- if (annual.currency !== dated.currency || !areNearbyFinancialPeriodEnds(annual.date, dated.date)) continue;
593
- for (const field of QUARTERLY_SNAPSHOT_FIELDS) {
594
- const value = statementNumber(dated, field);
595
- const earlier = statementFieldAvailability(annual, field);
596
- const current = statementFieldAvailability(dated, field);
597
- if (value !== null && value === statementNumber(annual, field) && earlier
598
- && (!current || Date.parse(earlier) < Date.parse(current))) {
599
- dated.fieldAvailability[field] = earlier;
600
- }
601
- }
602
- }
603
- return dated;
604
- });
605
- }
606
- const quarterly = deriveQuarterlyStatements(known.quarterly, known.annual);
607
- if (period === "daily" && valuationMetric) {
608
- // Sparse or loss-making quarters are gaps, not permission to substitute
609
- // an older annual denominator. Annual-only issuers retain their years.
610
- if (!known.quarterly.length) return { statements: mergeStatementsByPeriod(known.annual), period: "annual" };
611
- const statements = fiscalYearEpsAtYearEnd(buildTtmStatements(quarterly, known.annual), known.annual);
612
- // Capitalization uses the latest reported share count, not an average
613
- // of four quarters. Keep TTM average shares for the income/EPS fallback.
614
- if (valuationMetric !== "trailingPE") for (const statement of statements) {
615
- const latest = quarterly.find((row) => row.date === statement.date);
616
- const year = known.annual.find((row) => areNearbyFinancialPeriodEnds(row.date, statement.date));
617
- const shareRow = latest && selectedShares(latest) ? latest : year;
618
- for (const field of ["dilutedShares", "basicShares", "ordinarySharesNumber", "shareIssued"] as const) {
619
- delete statement[field];
620
- delete statement.fieldAvailability?.[field];
621
- if (shareRow?.[field] !== undefined) {
622
- statement[field] = shareRow[field];
623
- const availableAt = statementFieldAvailability(shareRow, field);
624
- if (availableAt) (statement.fieldAvailability ??= {})[field] = availableAt;
625
- }
626
- }
627
- }
628
- return { statements, period: "ttm" };
629
- }
630
- if (normalized === "annual") {
631
- return { statements: mergeStatementsByPeriod(known.annual), period: "annual" };
632
- }
633
- if (normalized === "ttm" || valuationMetric) {
634
- const ttm = buildTtmStatements(quarterly, known.annual);
635
- if (normalized === "ttm" && ttm.length > 0) return { statements: ttm, period: "ttm" };
636
- if (valuationMetric && ttm.some((statement) => hasValuationInputs(statement, valuationMetric))) {
637
- return { statements: ttm, period: "ttm" };
638
- }
639
- if (normalized === "ttm") return { statements: [], period: "ttm" };
640
- if (valuationMetric) {
641
- return { statements: mergeStatementsByPeriod(known.annual), period: "annual" };
642
- }
643
- }
644
- if (normalized === "quarterly" || (normalized === "auto" && quarterly.length > 0)) {
645
- return { statements: quarterly, period: "quarterly" };
646
- }
647
- return { statements: mergeStatementsByPeriod(known.annual), period: "annual" };
648
- }
649
-
650
- function ratio(numerator: unknown, denominator: unknown): number | null {
651
- return isFiniteNumber(numerator) && isFiniteNumber(denominator) && denominator !== 0
652
- ? numerator / denominator
653
- : null;
654
- }
655
-
656
- function freeCashFlow(statement: FinancialStatement): { value: number | null; derived: boolean } {
657
- if (isFiniteNumber(statement.freeCashFlow)) return { value: statement.freeCashFlow, derived: false };
658
- if (isFiniteNumber(statement.operatingCashFlow) && isFiniteNumber(statement.capitalExpenditure)) {
659
- return { value: statement.operatingCashFlow + statement.capitalExpenditure, derived: true };
660
- }
661
- return { value: null, derived: false };
662
- }
663
-
664
- type SelectedStatementField = {
665
- field: NumericStatementField;
666
- value: number;
667
- };
668
-
669
- function selectStatementField(
670
- statement: FinancialStatement,
671
- fields: readonly NumericStatementField[],
672
- accepts: (value: number) => boolean = () => true,
673
- ): SelectedStatementField | null {
674
- for (const field of fields) {
675
- const value = statementNumber(statement, field);
676
- if (value !== null && accepts(value)) return { field, value };
677
- }
678
- return null;
679
- }
680
-
681
- function selectedShares(statement: FinancialStatement): SelectedStatementField | null {
682
- return selectStatementField(
683
- statement,
684
- ["dilutedShares", "basicShares", "ordinarySharesNumber", "shareIssued"],
685
- (value) => value > 0,
686
- );
687
- }
688
-
689
- function selectedCash(statement: FinancialStatement): SelectedStatementField | null {
690
- return selectStatementField(statement, [
691
- "cashCashEquivalentsAndShortTermInvestments",
692
- "cashAndCashEquivalents",
693
- ]);
694
- }
695
-
696
- function selectedEps(
697
- statement: InternalStatement,
698
- ): { value: number; dependencies: NumericStatementField[] } | null {
699
- if (statement.epsBasis?.status === "unresolved" || hasStatementGap(statement, "eps")) return null;
700
- if (isFiniteNumber(statement.eps)) {
701
- return { value: statement.eps, dependencies: ["eps"] };
702
- }
703
- if (statement.__timeSeriesIncompleteCommonIncome || statement.__timeSeriesIncompleteAverageShares
704
- || statement.unavailableFields?.includes("netIncomeCommonStockholders")) return null;
705
- const shares = selectedShares(statement);
706
- const income = selectStatementField(statement, ["netIncomeCommonStockholders", "netIncome"]);
707
- if (!shares || !income) return null;
708
- return {
709
- value: income.value / shares.value,
710
- dependencies: [income.field, shares.field],
711
- };
712
- }
713
-
714
- function uniqueDependencies(
715
- fields: Array<NumericStatementField | null | undefined>,
716
- ): NumericStatementField[] {
717
- return [...new Set(fields.filter((field): field is NumericStatementField => !!field))];
718
- }
719
-
720
- function metricDependencies(metric: string, statement: FinancialStatement): NumericStatementField[] {
721
- if (metric === "grossMargin") return ["grossProfit", "totalRevenue"];
722
- if (metric === "operatingMargin") return ["operatingIncome", "totalRevenue"];
723
- if (metric === "netMargin") return ["netIncome", "totalRevenue"];
724
- if (metric === "freeCashFlowMargin") {
725
- return isFiniteNumber(statement.freeCashFlow)
726
- ? ["freeCashFlow", "totalRevenue"]
727
- : ["operatingCashFlow", "capitalExpenditure", "totalRevenue"];
728
- }
729
- if (metric === "freeCashFlow") {
730
- return isFiniteNumber(statement.freeCashFlow)
731
- ? ["freeCashFlow"]
732
- : ["operatingCashFlow", "capitalExpenditure"];
733
- }
734
- if (metric === "trailingPE") return selectedEps(statement)?.dependencies ?? ["eps"];
735
- if (metric === "priceSales") {
736
- return uniqueDependencies(["totalRevenue", selectedShares(statement)?.field]);
737
- }
738
- if (metric === "evSales") {
739
- return uniqueDependencies([
740
- "totalRevenue",
741
- selectedShares(statement)?.field,
742
- "totalDebt",
743
- selectedCash(statement)?.field,
744
- ]);
745
- }
746
- if (metric === "evEbitda") {
747
- return uniqueDependencies([
748
- "ebitda",
749
- selectedShares(statement)?.field,
750
- "totalDebt",
751
- selectedCash(statement)?.field,
752
- ]);
753
- }
754
- if (metric === "priceFcf") {
755
- return uniqueDependencies([
756
- ...(isFiniteNumber(statement.freeCashFlow)
757
- ? ["freeCashFlow" as const]
758
- : ["operatingCashFlow" as const, "capitalExpenditure" as const]),
759
- selectedShares(statement)?.field,
760
- ]);
761
- }
762
- return [metric as NumericStatementField];
763
- }
764
-
765
- function metricAvailability(statement: FinancialStatement, metric: string): string | undefined {
766
- const dependencies = metricDependencies(metric, statement);
767
- return completeAvailability(dependencies.map((field) => statementFieldAvailability(statement, field)));
768
- }
769
-
770
- function fundamentalValue(
771
- statement: InternalStatement,
772
- metric: string,
773
- ): { value: number | null; derived: boolean } {
774
- if (metric === "grossMargin") {
775
- const value = ratio(statement.grossProfit, statement.totalRevenue);
776
- return { value: value === null ? null : value * 100, derived: true };
777
- }
778
- if (metric === "operatingMargin") {
779
- const value = ratio(statement.operatingIncome, statement.totalRevenue);
780
- return { value: value === null ? null : value * 100, derived: true };
781
- }
782
- if (metric === "netMargin") {
783
- const value = ratio(statement.netIncome, statement.totalRevenue);
784
- return { value: value === null ? null : value * 100, derived: true };
785
- }
786
- if (metric === "freeCashFlow" || metric === "freeCashFlowMargin") {
787
- const fcf = freeCashFlow(statement);
788
- if (metric === "freeCashFlow") return fcf;
789
- const value = ratio(fcf.value, statement.totalRevenue);
790
- return { value: value === null ? null : value * 100, derived: true };
791
- }
792
- const value = statementNumber(statement, metric as NumericStatementField);
793
- const derived = statement.__timeSeriesTtm === true
794
- || statement.__timeSeriesDerivedFields?.includes(metric as NumericStatementField) === true;
795
- return { value, derived };
796
- }
797
-
798
- function pointForStatement(
799
- statement: FinancialStatement,
800
- metric: string,
801
- value: number | null,
802
- period: "annual" | "quarterly" | "ttm",
803
- timestampMode: SecuritySeriesSource["timestampMode"],
804
- derived: boolean,
805
- /** The month the issuer's fiscal year ends; null names the period by its end date. */
806
- yearEndMonth: number | null,
807
- ): TimeSeriesPoint | null {
808
- const observedAt = validDate(statement.date);
809
- if (!observedAt) return null;
810
- // A missing metric is known to be unavailable with its statement. It has
811
- // no metric-specific publication date to substitute for that boundary.
812
- const availableAtString = metricAvailability(statement, metric)
813
- ?? (value === null ? statement.availableAt : undefined);
814
- const availableAt = validDate(availableAtString);
815
- const date = timestampMode !== "period-end" && availableAt ? availableAt : observedAt;
816
- return {
817
- date,
818
- observedAt,
819
- availableAt: availableAt ?? undefined,
820
- value,
821
- // Providers do not supply a reliable issuer fiscal-year/quarter identity.
822
- // Calendar-month numbering would mislabel non-calendar fiscal years.
823
- periodLabel: `${period === "annual" ? "Year" : period === "ttm" ? "TTM" : "Quarter"} ended ${statement.date}`,
824
- // The period as FA's columns name it (`Q3 FY26`), which the legend prints beside the value.
825
- fiscalPeriod: period === "ttm" ? ttmPeriodLabel(statement.date, yearEndMonth) : fiscalPeriodLabel(statement.date, period, yearEndMonth),
826
- provenance: {
827
- quality: derived || (metric === "eps" && statement.epsBasis?.factor !== undefined && statement.epsBasis.factor !== 1) ? "derived" : "reported",
828
- ...((metric === "eps" || metric === "trailingPE") && statement.epsBasis ? { secEpsBasis: statement.epsBasis } : {}),
829
- ...((metric === "eps" || metric === "trailingPE") && hasStatementGap(statement, "eps")
830
- ? { unavailableEarnings: ["eps" as const] } : {}),
831
- currency: statement.currency,
832
- },
833
- };
834
- }
835
-
836
- function historicalValuation(
837
- financials: TickerFinancials,
838
- statement: FinancialStatement,
839
- metric: string,
840
- currencies: ValuationCurrencyContext,
841
- ) {
842
- // A price failure cannot make absent financial inputs appear available.
843
- if (currencies.priceInStatementUnits(statement, 1) === null || valuationAtPrice(statement, metric, 1, true) === null) return null;
844
- const priceDate = metricAvailability(statement, metric) ?? statement.date;
845
- const price = valuationPriceAtOrBefore(financials.priceHistory, priceDate);
846
- if (!price) return null;
847
- const comparablePrice = price.price === null ? null : currencies.priceInStatementUnits(statement, price.price);
848
- return { value: comparablePrice === null ? null : valuationAtPrice(statement, metric, comparablePrice), integrity: price.integrity, issue: price.issue };
849
- }
850
-
851
- function hasValuationInputs(statement: InternalStatement, metric: string): boolean {
852
- if (metric === "trailingPE") {
853
- return hasStatementGap(statement, "eps") || statement.epsBasis?.status === "unresolved"
854
- || statement.__timeSeriesIncompleteCommonIncome === true
855
- || statement.__timeSeriesIncompleteAverageShares === true
856
- || selectedEps(statement) !== null;
857
- }
858
- if (!selectedShares(statement)) return false;
859
- if (metric === "priceSales") return isFiniteNumber(statement.totalRevenue);
860
- if (metric === "priceFcf") return freeCashFlow(statement).value !== null;
861
- if (!isFiniteNumber(statement.totalDebt) || !selectedCash(statement)) return false;
862
- return metric === "evSales" ? isFiniteNumber(statement.totalRevenue)
863
- : metric === "evEbitda" && isFiniteNumber(statement.ebitda);
864
- }
865
-
866
- function valuationAtPrice(
867
- statement: FinancialStatement,
868
- metric: string,
869
- price: number,
870
- checkingInputs = false,
871
- ): number | null {
872
- const shares = selectedShares(statement);
873
- const marketCap = shares ? price * shares.value : null;
874
- const cash = selectedCash(statement)?.value;
875
- const debt = statement.totalDebt;
876
- // Unknown balance-sheet inputs are not zero balances. Avoid manufacturing
877
- // an EV multiple from market capitalization alone when coverage is sparse.
878
- const enterpriseValue = marketCap !== null && isFiniteNumber(debt) && isFiniteNumber(cash)
879
- ? marketCap + debt - cash
880
- : null;
881
- if (metric === "trailingPE") {
882
- const eps = selectedEps(statement)?.value;
883
- return eps && eps > 0 ? price / eps : null;
884
- }
885
- if (metric === "priceSales") return ratio(marketCap, statement.totalRevenue);
886
- // The probe at price=1 checks input coverage, not the historical EV sign.
887
- if (!checkingInputs && enterpriseValue !== null && enterpriseValue < 0 && (metric === "evSales" || metric === "evEbitda")) return null;
888
- if (metric === "evSales") return ratio(enterpriseValue, statement.totalRevenue);
889
- // Over EBITDA at or below zero the multiple means nothing (N/M), as a P/E over a loss.
890
- if (metric === "evEbitda") return isFiniteNumber(statement.ebitda) && statement.ebitda > 0 ? ratio(enterpriseValue, statement.ebitda) : null;
891
- if (metric === "priceFcf") return ratio(marketCap, freeCashFlow(statement).value);
892
- return null;
893
- }
894
-
895
- function dailyStatementValuation(financials: TickerFinancials, metric: string, exchange?: string): TimeSeriesPoint[] {
896
- const earningsMetric = metric === "pegRatio" ? "trailingPE" : metric;
897
- const selected = sourceStatements(financials, "daily", earningsMetric, exchange);
898
- const currencies = createValuationCurrencyContext(financials);
899
- const yearEndMonth = fiscalYearEndMonth(financials.annualStatements);
900
- const bases: DailyValuationBasis[] = selected.statements.flatMap((statement) => {
901
- const usable = valuationAtPrice(statement, earningsMetric, 1, true) !== null;
902
- // Missing dates cannot put information at the period end: until its
903
- // publication is known there is no historical denominator to use.
904
- let publication = metricAvailability(statement, earningsMetric)
905
- ?? (!usable ? statement.availableAt : undefined);
906
- let growth: number | null = null;
907
- if (metric === "pegRatio") {
908
- const prior = selected.statements.find((candidate) => {
909
- const days = (statementTime(statement) - statementTime(candidate)) / DAY_MS;
910
- return days >= 330 && days <= 400;
911
- });
912
- const currentEps = selectedEps(statement)?.value;
913
- const previousEps = prior ? selectedEps(prior)?.value : null;
914
- if (prior && currentEps != null && currentEps > 0 && previousEps != null && previousEps > 0) {
915
- publication = completeAvailability([publication, metricAvailability(prior, "trailingPE")]);
916
- const change = (currentEps / previousEps - 1) * 100;
917
- if (change > 0) growth = change;
918
- }
919
- }
920
- const observedAt = validDate(statement.date);
921
- if (!observedAt) return [];
922
- const availableAt = validDate(publication);
923
- if (availableAt && availableAt < observedAt) publication = undefined;
924
- const point = pointForStatement(statement, earningsMetric, null, selected.period, "available-at", true, yearEndMonth);
925
- return [{
926
- availableAt: publication,
927
- observedAt,
928
- periodLabel: point?.periodLabel,
929
- atPrice: (price: number) => {
930
- // An undated newer period must stop the previous TTM from continuing.
931
- // Its period end only bounds the gap; it never publishes a value.
932
- if (!publication || !availableAt) return null;
933
- const comparable = currencies.priceInStatementUnits(statement, price);
934
- if (comparable === null) return null;
935
- const value = valuationAtPrice(statement, earningsMetric, comparable);
936
- // Negative cash flow, revenue or EBITDA cannot produce a meaningful
937
- // multiple. Explicit period views retain their historical behavior.
938
- const denominator = earningsMetric === "priceFcf" ? freeCashFlow(statement).value
939
- : earningsMetric === "evEbitda" ? statement.ebitda
940
- : earningsMetric === "priceSales" || earningsMetric === "evSales" ? statement.totalRevenue : 1;
941
- if (denominator == null || denominator <= 0 || value === null) return null;
942
- return metric === "pegRatio" ? growth === null ? null : value / growth : value;
943
- },
944
- }];
945
- });
946
- const points = dailyValuationHistory(financials.priceHistory, bases, financials.quote?.listingExchangeName || financials.quote?.exchangeName || exchange);
947
- return points.some((point) => point.value !== null) ? points : [];
948
- }
949
-
950
- /** A daily history cannot be dated at all, but the issuer still has reported figures. */
951
- export function dailyValuationFallbackPeriod(financials: TickerFinancials, source: SecuritySeriesSource): "annual" | "quarterly" | "ttm" | null {
952
- if (source.period !== "daily") return null;
953
- const [namespace, metric = ""] = canonicalTimeSeriesFieldId(source.fieldId).split(".");
954
- const inputMetric = metric === "pegRatio" ? "trailingPE" : metric;
955
- if (namespace !== "valuation" || !QUOTE_DERIVED_VALUATION_IDS.has(inputMetric)) return null;
956
- const daily = sourceStatements(financials, "daily", inputMetric, source.instrument.exchange);
957
- if (daily.statements.some(row => metricAvailability(row, inputMetric))) return null;
958
- const annual = sourceStatements(financials, "annual", inputMetric);
959
- if (annual.statements.some(row => valuationAtPrice(row, inputMetric, 1, true) !== null)) return "annual";
960
- const reported = sourceStatements(financials, "auto", inputMetric);
961
- return reported.statements.some(row => valuationAtPrice(row, inputMetric, 1, true) !== null) ? reported.period : null;
962
- }
963
-
964
- function providerCurrentValuationPoint(
965
- financials: TickerFinancials,
966
- metric: string,
967
- ): TimeSeriesPoint | null {
968
- // A forward P/E is measured at the regular session price, as `valuation` reads it; PEG stays as served.
969
- const value = metric === "forwardPE"
970
- ? comparablePriceEarnings(liveForwardPE(financials.quote, financials.fundamentals))
971
- : metric === "pegRatio"
972
- ? financials.fundamentals?.pegRatio
973
- : undefined;
974
- if (!isFiniteNumber(value) || (metric === "forwardPE" && value <= 0)) return null;
975
- const quoteTime = financials.quote?.lastUpdated;
976
- const quoteDate = validDate(isFiniteNumber(quoteTime) && quoteTime > 0 ? quoteTime : null);
977
- if (!quoteDate) return null;
978
- const date = metric === "forwardPE" ? currentValuationPrice(financials.quote)?.date ?? quoteDate : quoteDate;
979
- return {
980
- date,
981
- observedAt: date,
982
- availableAt: date,
983
- value,
984
- periodLabel: "Current",
985
- provenance: {
986
- providerId: financials.quote?.providerId,
987
- quality: "estimated",
988
- },
989
- };
990
- }
991
-
992
- /**
993
- * The trailing P/E `valuation`, DES and the portfolio columns show: the served
994
- * one at the regular session price, over positive EPS.
995
- */
996
- function servedTrailingPE(financials: TickerFinancials): number | null {
997
- return comparablePriceEarnings(liveTrailingPE(financials.quote, financials.fundamentals));
998
- }
999
-
1000
- /**
1001
- * A current EV multiple over the listing's enterprise value, the one
1002
- * `valuation` and RV show (listingEnterpriseValue): EV/EBITDA and EV/S then
1003
- * read one EV on every surface. A statement in another currency than the EV
1004
- * (an ADR's EUR or TWD statements) is converted at the rate the EV's balance
1005
- * sheet check was, as RV's EV/S converts revenue. Undefined to read the
1006
- * statement's own (shares times the price, plus debt, less cash) where the
1007
- * listing has none or no rate; null where it is not meaningful.
1008
- */
1009
- function listingEnterpriseMultiple(financials: TickerFinancials, statement: FinancialStatement, metric: string): number | null | undefined {
1010
- if (metric !== "evEbitda" && metric !== "evSales") return undefined;
1011
- if (metric === "evEbitda" && isBankOrInsurerIndustry(financials.profile?.industry)) return null;
1012
- const listing = listingEnterpriseValue(financials);
1013
- if (listing.kind === "not-meaningful") return null;
1014
- if (listing.kind !== "value") return undefined;
1015
- const rate = listingStatementRate(listing, statement.currency ?? financials.financialCurrency);
1016
- if (rate === null) return undefined;
1017
- const denominator = metric === "evEbitda" ? statement.ebitda : statement.totalRevenue;
1018
- if (metric === "evEbitda" && !(isFiniteNumber(denominator) && denominator > 0)) return null;
1019
- return ratio(listing.value, isFiniteNumber(denominator) ? denominator * rate : denominator);
1020
- }
1021
-
1022
- /** Units of the listing EV's currency per unit of the statement's: 1 in its own, the check's rate from another, null without one. */
1023
- function listingStatementRate(listing: Extract<ReturnType<typeof listingEnterpriseValue>, { kind: "value" }>, currency: string | undefined): number | null {
1024
- if (!currency || currency === listing.currency) return 1;
1025
- return listing.fx && listing.fx.from === currency && isFiniteNumber(listing.fx.rate) && listing.fx.rate > 0 ? listing.fx.rate : null;
1026
- }
1027
-
1028
- /**
1029
- * The rate a current EV multiple converted the statement at
1030
- * (listingEnterpriseMultiple): `{ from: "EUR", rate: 1.133 }` for an ADR's
1031
- * EUR statements under its USD EV; null in the EV's own currency.
1032
- */
1033
- export function listingStatementConversion(financials: TickerFinancials, statement: FinancialStatement): { from: string; rate: number; to: string } | null {
1034
- const listing = listingEnterpriseValue(financials);
1035
- const currency = statement.currency ?? financials.financialCurrency;
1036
- if (listing.kind !== "value" || !currency || currency === listing.currency) return null;
1037
- const rate = listingStatementRate(listing, currency);
1038
- return rate === null ? null : { from: currency, rate, to: listing.currency };
1039
- }
1040
-
1041
- /**
1042
- * The latest value of a statement-based multiple and the period it reads:
1043
- * the regular session price (after the close, the close, dated by it) over
1044
- * the latest period known when the quote was observed. The statements decide
1045
- * whether there is one; a trailing P/E then takes the served one at that
1046
- * price where there is one, so the chart ends on the P/E `valuation` prints,
1047
- * and an EV multiple divides the listing's EV. `value` null where that period
1048
- * gives none (a loss, EBITDA at or below zero, a missing line); null where
1049
- * there is no period or price to read.
1050
- */
1051
- function currentDerivedValuation(
1052
- financials: TickerFinancials,
1053
- statements: readonly FinancialStatement[],
1054
- metric: string,
1055
- currencies: ValuationCurrencyContext,
1056
- ): { value: number | null; date: Date; statement: FinancialStatement } | null {
1057
- const quote = financials.quote;
1058
- if (valuationQuoteIssue(quote)) return null;
1059
- const quoteDate = validDate(quote?.lastUpdated);
1060
- if (!quoteDate || !isFiniteNumber(quote?.price) || quote.price <= 0) return null;
1061
- const current = currentValuationPrice(quote);
1062
- if (!current) return null;
1063
- const quoteTime = quoteDate.getTime();
1064
- // Select the latest known period first. Missing inputs, a loss or incompatible
1065
- // currency cannot make an older period's denominator current again.
1066
- const statement = statements
1067
- .flatMap((candidate) => {
1068
- const availableAt = validDate(metricAvailability(candidate, metric) ?? candidate.date);
1069
- const observedAt = validDate(candidate.date);
1070
- if (!availableAt || !observedAt || availableAt.getTime() > quoteTime) return [];
1071
- return [{ candidate, observedAt: observedAt.getTime(), availableAt: availableAt.getTime() }];
1072
- })
1073
- .sort((left, right) => (
1074
- left.observedAt - right.observedAt || left.availableAt - right.availableAt
1075
- ))
1076
- .at(-1)?.candidate;
1077
- if (!statement) return null;
1078
- // The listing's EV needs no price in the statement's currency: an ADR's converts the statement instead.
1079
- const listing = listingEnterpriseMultiple(financials, statement, metric);
1080
- if (listing !== undefined) return { value: listing, date: current.date, statement };
1081
- const comparablePrice = currencies.priceInStatementUnits(statement, current.price);
1082
- if (comparablePrice === null) return null;
1083
- const value = valuationAtPrice(statement, metric, comparablePrice);
1084
- if (value === null) return { value: null, date: current.date, statement };
1085
- return { value: (metric === "trailingPE" ? servedTrailingPE(financials) : null) ?? value, date: current.date, statement };
1086
- }
1087
-
1088
- /**
1089
- * Why a current EV/EBITDA is N/M where the statement it reads has an EBITDA:
1090
- * a bank's or an insurer's, or EBITDA at or below zero. Undefined otherwise.
1091
- */
1092
- function ebitdaNotMeaningful(financials: TickerFinancials, statement: FinancialStatement): string | undefined {
1093
- if (isBankOrInsurerIndustry(financials.profile?.industry)) return BANK_OR_INSURER_EBITDA;
1094
- return isFiniteNumber(statement.ebitda) && statement.ebitda <= 0 ? "Trailing EBITDA is not positive" : undefined;
1095
- }
1096
-
1097
- function currentDerivedValuationPoint(
1098
- financials: TickerFinancials,
1099
- statements: readonly FinancialStatement[],
1100
- metric: string,
1101
- currencies: ValuationCurrencyContext,
1102
- ): TimeSeriesPoint | null {
1103
- const current = currentDerivedValuation(financials, statements, metric, currencies);
1104
- if (!current || current.value === null) return null;
1105
- return {
1106
- date: current.date,
1107
- observedAt: current.date,
1108
- availableAt: current.date,
1109
- value: current.value,
1110
- periodLabel: "Current",
1111
- provenance: {
1112
- providerId: financials.quote?.providerId,
1113
- quality: "derived",
1114
- },
1115
- };
1116
- }
1117
-
1118
- /**
1119
- * The value GE's trailing-twelve-months series of a statement multiple ends
1120
- * on, and the quarter its period ends with: the figure RV's added EV/EBITDA
1121
- * column shows, so the two never disagree. `value` null with the reason where
1122
- * it is not meaningful (`notMeaningful`, GE's N/M); null where GE draws no
1123
- * current point and has no reason for it.
1124
- */
1125
- export function currentTrailingValuation(
1126
- financials: TickerFinancials,
1127
- metric: "evEbitda" | "evSales",
1128
- ): { value: number | null; notMeaningful?: string; periodEnd: string; statement: FinancialStatement } | null {
1129
- const current = currentValuation(financials, "ttm", metric);
1130
- if (!current) return null;
1131
- const dated = { periodEnd: current.statement.date.slice(0, 10), statement: current.statement };
1132
- if (current.value !== null) return { value: current.value, ...dated };
1133
- const notMeaningful = metric === "evEbitda" ? ebitdaNotMeaningful(financials, current.statement) : undefined;
1134
- return notMeaningful ? { value: null, notMeaningful, ...dated } : null;
1135
- }
1136
-
1137
- function currentValuation(financials: TickerFinancials, period: SeriesPeriod | undefined, metric: string) {
1138
- const selected = sourceStatements(financials, period, metric);
1139
- return currentDerivedValuation(financials, currentValuationStatements(financials, selected, metric), metric,
1140
- createValuationCurrencyContext(financials));
1141
- }
1142
-
1143
- /**
1144
- * Why a valuation series ends on no value: EV/EBITDA is N/M for a bank or an
1145
- * insurer, and over EBITDA at or below zero, as RV reads it. The period the
1146
- * series would end on dates it. Undefined for any other series, or where its
1147
- * current value is there.
1148
- */
1149
- export function valuationNotMeaningful(financials: TickerFinancials, source: SecuritySeriesSource): { reason: string; asOf: string } | undefined {
1150
- const [namespace, metric = ""] = canonicalTimeSeriesFieldId(source.fieldId).split(".");
1151
- if (namespace !== "valuation" || metric !== "evEbitda") return undefined;
1152
- // A daily series ends on the trailing twelve months, as its current point does.
1153
- const period = source.period === "daily" || source.period === "auto" || !source.period ? "ttm" : source.period;
1154
- const current = currentValuation(financials, period, metric);
1155
- if (current) {
1156
- const reason = current.value === null ? ebitdaNotMeaningful(financials, current.statement) : undefined;
1157
- return reason ? { reason, asOf: current.statement.date.slice(0, 10) } : undefined;
1158
- }
1159
- if (!isBankOrInsurerIndustry(financials.profile?.industry)) return undefined;
1160
- const latest = sourceStatements(financials, period).statements.at(-1);
1161
- return latest ? { reason: BANK_OR_INSURER_EBITDA, asOf: latest.date.slice(0, 10) } : undefined;
1162
- }
1163
-
1164
- /**
1165
- * The trailing twelve months of a statement line the way GE's `ttm` series
1166
- * reads it (four consecutive quarters, a fiscal fourth quarter completed from
1167
- * its year): the latest one, or null when the latest window is incomplete.
1168
- */
1169
- export function latestTrailingStatement(financials: TickerFinancials): FinancialStatement | null {
1170
- const selected = sourceStatements(financials, "ttm");
1171
- return selected.statements.at(-1) ?? null;
1172
- }
1173
-
1174
- /**
1175
- * The periods a Current multiple is read from: the selected ones, and beside
1176
- * fiscal years the trailing twelve months the quarters after them sum to, so a
1177
- * fiscal year's EPS never prices today once later quarters are reported. A
1178
- * fiscal year is itself a trailing twelve months at its end.
1179
- */
1180
- function currentValuationStatements(
1181
- financials: TickerFinancials,
1182
- selected: ReturnType<typeof sourceStatements>,
1183
- metric: string,
1184
- ): InternalStatement[] {
1185
- if (selected.period !== "annual") return selected.statements;
1186
- const known = valuationStatements(financials);
1187
- const trailing = buildTtmStatements(deriveQuarterlyStatements(known.quarterly, known.annual), known.annual)
1188
- .filter((statement) => hasValuationInputs(statement, metric));
1189
- return [...selected.statements, ...trailing];
1190
- }
1191
-
1192
- /** Whether a valuation field derives a current point from the latest quote. */
1193
- export function valuationSeriesUsesLiveQuote(fieldId: string): boolean {
1194
- const [namespace, metric = ""] = canonicalTimeSeriesFieldId(fieldId).split(".");
1195
- return namespace === "valuation" && (QUOTE_DERIVED_VALUATION_IDS.has(metric) || metric === "forwardPE");
1196
- }
1197
-
1198
- /** Whether a valuation field needs the full price history to date its observations. */
1199
- export function valuationSeriesUsesPriceHistory(fieldId: string, period?: SeriesPeriod): boolean {
1200
- const [namespace, metric = ""] = canonicalTimeSeriesFieldId(fieldId).split(".");
1201
- return namespace === "valuation" && (PRICE_HISTORY_VALUATION_IDS.has(metric) || (metric === "pegRatio" && period === "daily"));
1202
- }
1203
-
1204
- function preferredPeriodPoint(
1205
- existing: TimeSeriesPoint,
1206
- candidate: TimeSeriesPoint,
1207
- ): TimeSeriesPoint {
1208
- if (existing.provenance?.quality !== candidate.provenance?.quality) {
1209
- return candidate.provenance?.quality === "reported" ? candidate : existing;
1210
- }
1211
- const existingAvailableAt = existing.availableAt?.getTime();
1212
- const candidateAvailableAt = candidate.availableAt?.getTime();
1213
- const existingHasAvailability = Number.isFinite(existingAvailableAt);
1214
- const candidateHasAvailability = Number.isFinite(candidateAvailableAt);
1215
- if (existingHasAvailability !== candidateHasAvailability) {
1216
- return candidateHasAvailability ? candidate : existing;
1217
- }
1218
- if (
1219
- existingHasAvailability
1220
- && candidateHasAvailability
1221
- && candidateAvailableAt! !== existingAvailableAt!
1222
- ) {
1223
- const preferLater = !Object.is(existing.value, candidate.value);
1224
- const candidateWins = preferLater
1225
- ? candidateAvailableAt! > existingAvailableAt!
1226
- : candidateAvailableAt! < existingAvailableAt!;
1227
- return candidateWins ? candidate : existing;
1228
- }
1229
- return candidate.observedAt.getTime() < existing.observedAt.getTime()
1230
- ? candidate
1231
- : existing;
1232
- }
1233
-
1234
- /**
1235
- * Provider snapshots can contain both an issuer fiscal-period row and a
1236
- * calendar-normalized row for the same observation. Their period ends and
1237
- * display timestamps differ slightly, so timestamp-only deduplication renders
1238
- * paired bars. A financial period is the observation identity; publication
1239
- * time only decides when that observation became available.
1240
- */
1241
- function dedupeFundamentalPeriods(points: readonly TimeSeriesPoint[]): TimeSeriesPoint[] {
1242
- const groups: TimeSeriesPoint[][] = [];
1243
- const sorted = [...points].sort((left, right) => (
1244
- left.observedAt.getTime() - right.observedAt.getTime()
1245
- ));
1246
- for (const point of sorted) {
1247
- const lastGroup = groups.at(-1);
1248
- if (lastGroup && areNearbyFinancialPeriodEnds(lastGroup[0]!.observedAt, point.observedAt)
1249
- && (lastGroup[0]!.observedAt.getTime() === point.observedAt.getTime()
1250
- || ![point, ...lastGroup].some(item => item.provenance?.unavailableEarnings?.length))) {
1251
- lastGroup.push(point);
1252
- } else groups.push([point]);
1253
- }
1254
- return groups
1255
- .map((group) => group.slice(1).reduce(preferredPeriodPoint, group[0]!))
1256
- .sort((left, right) => (
1257
- left.date.getTime() - right.date.getTime()
1258
- || left.observedAt.getTime() - right.observedAt.getTime()
1259
- ));
1260
- }
1261
-
1262
- /** Extracts the selected statement snapshot, retaining known availability dates without reconstructing prior vintages. */
1263
- export function extractFundamentalSeries(
1264
- financials: TickerFinancials | null,
1265
- source: SecuritySeriesSource,
1266
- ): TimeSeriesPoint[] {
1267
- if (!financials) return [];
1268
- const canonicalId = canonicalTimeSeriesFieldId(source.fieldId);
1269
- const [namespace, metric = ""] = canonicalId.split(".");
1270
- if (namespace === "fundamental" && FUNDAMENTAL_IDS.has(metric)) {
1271
- const selected = sourceStatements(financials, source.period);
1272
- const yearEndMonth = fiscalYearEndMonth(financials.annualStatements);
1273
- let hasObservation = false;
1274
- const points = selected.statements.flatMap((statement) => {
1275
- const result = fundamentalValue(statement, metric);
1276
- if (result.value !== null) hasObservation = true;
1277
- const point = pointForStatement(
1278
- statement,
1279
- metric,
1280
- result.value,
1281
- selected.period,
1282
- source.timestampMode,
1283
- result.derived,
1284
- yearEndMonth,
1285
- );
1286
- return point ? [point] : [];
1287
- });
1288
- if (!hasObservation) return [];
1289
- const deduped = dedupeFundamentalPeriods(points);
1290
- return getTimeSeriesField(canonicalId)?.unit.startsWith("currency")
1291
- ? reportingCurrencySeries(deduped, financials.financialCurrency).points : deduped;
1292
- }
1293
-
1294
- if (namespace !== "valuation" || !VALUATION_IDS.has(metric)) return [];
1295
- // A bank's or an insurer's EBITDA measures nothing: its EV/EBITDA is N/M throughout (valuationNotMeaningful).
1296
- if (metric === "evEbitda" && isBankOrInsurerIndustry(financials.profile?.industry)) return [];
1297
- const fallback = dailyValuationFallbackPeriod(financials, source);
1298
- if (fallback) return extractFundamentalSeries(financials, { ...source, period: fallback });
1299
- if (source.period === "daily" && metric !== "realizedNtmPE") {
1300
- if (metric !== "forwardPE") return dailyStatementValuation(financials, metric, source.instrument.exchange);
1301
- const points = dailyForwardPeHistory(financials, createValuationCurrencyContext(financials), source.instrument.exchange);
1302
- if (points.some((point) => point.value !== null)) return points;
1303
- const current = providerCurrentValuationPoint(financials, metric);
1304
- return current ? [current] : [];
1305
- }
1306
- if (metric === "forwardPE") {
1307
- const points = forwardPeHistory(financials, createValuationCurrencyContext(financials));
1308
- if (points.length > 0) return points;
1309
- // Without an estimate history the provider's own figure is all there is.
1310
- const current = providerCurrentValuationPoint(financials, metric);
1311
- return current ? [current] : [];
1312
- }
1313
- if (metric === "realizedNtmPE") {
1314
- return realizedNtmPeHistory(financials, createValuationCurrencyContext(financials));
1315
- }
1316
- if (metric === "pegRatio") {
1317
- const current = providerCurrentValuationPoint(financials, metric);
1318
- return current ? [current] : [];
1319
- }
1320
-
1321
- const selected = sourceStatements(financials, source.period, metric);
1322
- const currencies = createValuationCurrencyContext(financials);
1323
- const yearEndMonth = fiscalYearEndMonth(financials.annualStatements);
1324
- let hasHistoricalObservation = false;
1325
- const historical = selected.statements.flatMap((statement) => {
1326
- const historical = historicalValuation(financials, statement, metric, currencies);
1327
- if (historical !== null) hasHistoricalObservation = true;
1328
- const point = pointForStatement(
1329
- statement,
1330
- metric,
1331
- historical?.value ?? null,
1332
- selected.period,
1333
- source.timestampMode,
1334
- true,
1335
- yearEndMonth,
1336
- );
1337
- if (point && historical?.integrity) point.provenance = { ...point.provenance, priceHistoryIntegrity: historical.integrity };
1338
- if (point && historical?.issue) point.provenance = { ...point.provenance,
1339
- valuationPriceIssues: [{ ...historical.issue, affectedAt: point.date.toISOString() }] };
1340
- return point ? [point] : [];
1341
- });
1342
- const current = currentDerivedValuationPoint(financials, currentValuationStatements(financials, selected, metric), metric, currencies);
1343
- if (!hasHistoricalObservation && !current) return [];
1344
- const dedupedHistorical = dedupeFundamentalPeriods(historical);
1345
- // Publication timestamps can be shared by distinct fiscal periods. Their
1346
- // period identities were deduplicated above; a gap must not overwrite a
1347
- // different period's usable observation released on the same date.
1348
- return (current ? [...dedupedHistorical, current] : dedupedHistorical).sort((left, right) => (
1349
- left.date.getTime() - right.date.getTime() || left.observedAt.getTime() - right.observedAt.getTime()
1350
- ));
1351
- }
1352
-
1353
- /**
1354
- * The period a fundamental series asks for that its company reports no figure
1355
- * of, though it reports annual ones: `quarterly` for an issuer that reports
1356
- * twice a year. Null for any other series, and when the annual figures are as
1357
- * missing as the quarterly ones.
1358
- */
1359
- export function unreportedStatementPeriod(
1360
- financials: TickerFinancials,
1361
- source: SecuritySeriesSource,
1362
- ): "quarterly" | null {
1363
- if (source.period !== "quarterly" || !canonicalTimeSeriesFieldId(source.fieldId).startsWith("fundamental.")) return null;
1364
- return extractFundamentalSeries(financials, { ...source, period: "annual" }).length > 0 ? "quarterly" : null;
1365
- }
1366
-
1367
- export function fundamentalSeriesUsesAvailabilityFallback(
1368
- financials: TickerFinancials | null,
1369
- source: SecuritySeriesSource,
1370
- ): boolean {
1371
- if (!financials || source.timestampMode === "period-end") return false;
1372
- // A gap has no value to place, so it has no date to fall back for.
1373
- const points = extractFundamentalSeries(financials, source);
1374
- return points.some((point) => point.value != null && point.availableAt === undefined);
1375
- }
1376
-
1377
- /** Explains withheld currency-dependent values through chart and export metadata. */
1378
- export function valuationCurrencyWarning(financials: TickerFinancials, source: SecuritySeriesSource): string | undefined {
1379
- const [namespace, metric = ""] = canonicalTimeSeriesFieldId(source.fieldId).split(".");
1380
- if (namespace !== "valuation" || !QUOTE_DERIVED_VALUATION_IDS.has(metric)) return undefined;
1381
- const selected = sourceStatements(financials, source.period, metric);
1382
- return createValuationCurrencyContext(financials).warning(selected.statements.filter((row) => (
1383
- valuationAtPrice(row, metric, 1) !== null
1384
- )));
1385
- }
1386
-
1387
- /** Structured failures preserve source values independently of the chart's ratios. */
1388
- export function valuationPriceIssues(financials: TickerFinancials, source: SecuritySeriesSource): ValuationPriceIssue[] {
1389
- if (source.period === "daily" && canonicalTimeSeriesFieldId(source.fieldId).startsWith("valuation.")) {
1390
- return extractFundamentalSeries(financials, source).flatMap((point) => point.provenance?.valuationPriceIssues ?? []);
1391
- }
1392
- if (!valuationSeriesUsesLiveQuote(source.fieldId)) return [];
1393
- const metric = canonicalTimeSeriesFieldId(source.fieldId).split(".")[1]!;
1394
- const currencies = createValuationCurrencyContext(financials);
1395
- const selected = sourceStatements(financials, source.period, metric);
1396
- const rows = selected.statements.filter((row) => (
1397
- currencies.priceInStatementUnits(row, 1) !== null && valuationAtPrice(row, metric, 1) !== null
1398
- ));
1399
- if (!rows.length) return [];
1400
- const quoteIssue = valuationQuoteIssue(financials.quote);
1401
- const issues = rows.flatMap((row) => {
1402
- const price = valuationPriceAtOrBefore(financials.priceHistory, metricAvailability(row, metric) ?? row.date);
1403
- const date = pointForStatement(row, metric, null, selected.period, source.timestampMode, true, null)?.date;
1404
- return price?.issue && date ? [{ ...price.issue, affectedAt: date.toISOString() }] : [];
1405
- });
1406
- return [...(quoteIssue ? [quoteIssue] : []), ...new Map(issues.map((issue) => [JSON.stringify(issue), issue])).values()];
1407
- }
1
+ // The fundamentals series API. The work lives in ./fundamentals/*; importers keep this path.
2
+ export { deriveQuarterlyStatements } from "./fundamentals/quarterly-ttm";
3
+ export { knownWhenFiled } from "./fundamentals/source-statements";
4
+ export { dailyValuationFallbackPeriod } from "./fundamentals/historical-valuation";
5
+ export {
6
+ listingStatementConversion,
7
+ currentTrailingValuation,
8
+ valuationNotMeaningful,
9
+ latestTrailingStatement,
10
+ } from "./fundamentals/current-valuation";
11
+ export { valuationSeriesUsesLiveQuote, valuationSeriesUsesPriceHistory } from "./fundamentals/metric-ids";
12
+ export {
13
+ extractFundamentalSeries,
14
+ unreportedStatementPeriod,
15
+ fundamentalSeriesUsesAvailabilityFallback,
16
+ valuationCurrencyWarning,
17
+ valuationPriceIssues,
18
+ } from "./fundamentals/series";