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