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
@@ -0,0 +1,244 @@
1
+ // The current point of a valuation series: served, listing-EV and live-quote multiples, and why one is not meaningful.
2
+ import type { FinancialStatement, TickerFinancials } from "../../types/financials";
3
+ import { canonicalTimeSeriesFieldId } from "../field-catalog";
4
+ import { createValuationCurrencyContext, type ValuationCurrencyContext } from "../valuation-currency";
5
+ import { currentValuationPrice, valuationQuoteIssue } from "../valuation-price";
6
+ import type { SecuritySeriesSource, SeriesPeriod, TimeSeriesPoint } from "../types";
7
+ import { isFiniteNumber } from "../../utils/guards";
8
+ import { liveForwardPE, liveTrailingPE } from "../../market-data/quotes/live-valuation";
9
+ import { listingEnterpriseValue } from "../../market-data/quotes/listing-enterprise-value";
10
+ import { BANK_OR_INSURER_EBITDA, isBankOrInsurerIndustry } from "../../utils/ebitda";
11
+ import { comparablePriceEarnings } from "../../utils/price-earnings";
12
+ import { buildTtmStatements, deriveQuarterlyStatements } from "./quarterly-ttm";
13
+ import { sourceStatements, valuationStatements } from "./source-statements";
14
+ import { type InternalStatement, validDate } from "./statement";
15
+ import { metricAvailability, ratio } from "./statement-fields";
16
+ import { hasValuationInputs, valuationAtPrice } from "./valuation-multiples";
17
+
18
+ export function providerCurrentValuationPoint(
19
+ financials: TickerFinancials,
20
+ metric: string,
21
+ ): TimeSeriesPoint | null {
22
+ // A forward P/E is measured at the regular session price, as `valuation` reads it; PEG stays as served.
23
+ const value = metric === "forwardPE"
24
+ ? comparablePriceEarnings(liveForwardPE(financials.quote, financials.fundamentals))
25
+ : metric === "pegRatio"
26
+ ? financials.fundamentals?.pegRatio
27
+ : undefined;
28
+ if (!isFiniteNumber(value) || (metric === "forwardPE" && value <= 0)) return null;
29
+ const quoteTime = financials.quote?.lastUpdated;
30
+ const quoteDate = validDate(isFiniteNumber(quoteTime) && quoteTime > 0 ? quoteTime : null);
31
+ if (!quoteDate) return null;
32
+ const date = metric === "forwardPE" ? currentValuationPrice(financials.quote)?.date ?? quoteDate : quoteDate;
33
+ return {
34
+ date,
35
+ observedAt: date,
36
+ availableAt: date,
37
+ value,
38
+ periodLabel: "Current",
39
+ provenance: {
40
+ providerId: financials.quote?.providerId,
41
+ quality: "estimated",
42
+ },
43
+ };
44
+ }
45
+
46
+ /**
47
+ * The trailing P/E `valuation`, DES and the portfolio columns show: the served
48
+ * one at the regular session price, over positive EPS.
49
+ */
50
+ function servedTrailingPE(financials: TickerFinancials): number | null {
51
+ return comparablePriceEarnings(liveTrailingPE(financials.quote, financials.fundamentals));
52
+ }
53
+
54
+ /**
55
+ * A current EV multiple over the listing's enterprise value, the one
56
+ * `valuation` and RV show (listingEnterpriseValue): EV/EBITDA and EV/S then
57
+ * read one EV on every surface. A statement in another currency than the EV
58
+ * (an ADR's EUR or TWD statements) is converted at the rate the EV's balance
59
+ * sheet check was, as RV's EV/S converts revenue. Undefined to read the
60
+ * statement's own (shares times the price, plus debt, less cash) where the
61
+ * listing has none or no rate; null where it is not meaningful.
62
+ */
63
+ function listingEnterpriseMultiple(financials: TickerFinancials, statement: FinancialStatement, metric: string): number | null | undefined {
64
+ if (metric !== "evEbitda" && metric !== "evSales") return undefined;
65
+ if (metric === "evEbitda" && isBankOrInsurerIndustry(financials.profile?.industry)) return null;
66
+ const listing = listingEnterpriseValue(financials);
67
+ if (listing.kind === "not-meaningful") return null;
68
+ if (listing.kind !== "value") return undefined;
69
+ const rate = listingStatementRate(listing, statement.currency ?? financials.financialCurrency);
70
+ if (rate === null) return undefined;
71
+ const denominator = metric === "evEbitda" ? statement.ebitda : statement.totalRevenue;
72
+ if (metric === "evEbitda" && !(isFiniteNumber(denominator) && denominator > 0)) return null;
73
+ return ratio(listing.value, isFiniteNumber(denominator) ? denominator * rate : denominator);
74
+ }
75
+
76
+ /** 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. */
77
+ function listingStatementRate(listing: Extract<ReturnType<typeof listingEnterpriseValue>, { kind: "value" }>, currency: string | undefined): number | null {
78
+ if (!currency || currency === listing.currency) return 1;
79
+ return listing.fx && listing.fx.from === currency && isFiniteNumber(listing.fx.rate) && listing.fx.rate > 0 ? listing.fx.rate : null;
80
+ }
81
+
82
+ /**
83
+ * The rate a current EV multiple converted the statement at
84
+ * (listingEnterpriseMultiple): `{ from: "EUR", rate: 1.133 }` for an ADR's
85
+ * EUR statements under its USD EV; null in the EV's own currency.
86
+ */
87
+ export function listingStatementConversion(financials: TickerFinancials, statement: FinancialStatement): { from: string; rate: number; to: string } | null {
88
+ const listing = listingEnterpriseValue(financials);
89
+ const currency = statement.currency ?? financials.financialCurrency;
90
+ if (listing.kind !== "value" || !currency || currency === listing.currency) return null;
91
+ const rate = listingStatementRate(listing, currency);
92
+ return rate === null ? null : { from: currency, rate, to: listing.currency };
93
+ }
94
+
95
+ /**
96
+ * The latest value of a statement-based multiple and the period it reads:
97
+ * the regular session price (after the close, the close, dated by it) over
98
+ * the latest period known when the quote was observed. The statements decide
99
+ * whether there is one; a trailing P/E then takes the served one at that
100
+ * price where there is one, so the chart ends on the P/E `valuation` prints,
101
+ * and an EV multiple divides the listing's EV. `value` null where that period
102
+ * gives none (a loss, EBITDA at or below zero, a missing line); null where
103
+ * there is no period or price to read.
104
+ */
105
+ function currentDerivedValuation(
106
+ financials: TickerFinancials,
107
+ statements: readonly FinancialStatement[],
108
+ metric: string,
109
+ currencies: ValuationCurrencyContext,
110
+ ): { value: number | null; date: Date; statement: FinancialStatement } | null {
111
+ const quote = financials.quote;
112
+ if (valuationQuoteIssue(quote)) return null;
113
+ const quoteDate = validDate(quote?.lastUpdated);
114
+ if (!quoteDate || !isFiniteNumber(quote?.price) || quote.price <= 0) return null;
115
+ const current = currentValuationPrice(quote);
116
+ if (!current) return null;
117
+ const quoteTime = quoteDate.getTime();
118
+ // Select the latest known period first. Missing inputs, a loss or incompatible
119
+ // currency cannot make an older period's denominator current again.
120
+ const statement = statements
121
+ .flatMap((candidate) => {
122
+ const availableAt = validDate(metricAvailability(candidate, metric) ?? candidate.date);
123
+ const observedAt = validDate(candidate.date);
124
+ if (!availableAt || !observedAt || availableAt.getTime() > quoteTime) return [];
125
+ return [{ candidate, observedAt: observedAt.getTime(), availableAt: availableAt.getTime() }];
126
+ })
127
+ .sort((left, right) => (
128
+ left.observedAt - right.observedAt || left.availableAt - right.availableAt
129
+ ))
130
+ .at(-1)?.candidate;
131
+ if (!statement) return null;
132
+ // The listing's EV needs no price in the statement's currency: an ADR's converts the statement instead.
133
+ const listing = listingEnterpriseMultiple(financials, statement, metric);
134
+ if (listing !== undefined) return { value: listing, date: current.date, statement };
135
+ const comparablePrice = currencies.priceInStatementUnits(statement, current.price);
136
+ if (comparablePrice === null) return null;
137
+ const value = valuationAtPrice(statement, metric, comparablePrice);
138
+ if (value === null) return { value: null, date: current.date, statement };
139
+ return { value: (metric === "trailingPE" ? servedTrailingPE(financials) : null) ?? value, date: current.date, statement };
140
+ }
141
+
142
+ /**
143
+ * Why a current EV/EBITDA is N/M where the statement it reads has an EBITDA:
144
+ * a bank's or an insurer's, or EBITDA at or below zero. Undefined otherwise.
145
+ */
146
+ function ebitdaNotMeaningful(financials: TickerFinancials, statement: FinancialStatement): string | undefined {
147
+ if (isBankOrInsurerIndustry(financials.profile?.industry)) return BANK_OR_INSURER_EBITDA;
148
+ return isFiniteNumber(statement.ebitda) && statement.ebitda <= 0 ? "Trailing EBITDA is not positive" : undefined;
149
+ }
150
+
151
+ export function currentDerivedValuationPoint(
152
+ financials: TickerFinancials,
153
+ statements: readonly FinancialStatement[],
154
+ metric: string,
155
+ currencies: ValuationCurrencyContext,
156
+ ): TimeSeriesPoint | null {
157
+ const current = currentDerivedValuation(financials, statements, metric, currencies);
158
+ if (!current || current.value === null) return null;
159
+ return {
160
+ date: current.date,
161
+ observedAt: current.date,
162
+ availableAt: current.date,
163
+ value: current.value,
164
+ periodLabel: "Current",
165
+ provenance: {
166
+ providerId: financials.quote?.providerId,
167
+ quality: "derived",
168
+ },
169
+ };
170
+ }
171
+
172
+ /**
173
+ * The value GE's trailing-twelve-months series of a statement multiple ends
174
+ * on, and the quarter its period ends with: the figure RV's added EV/EBITDA
175
+ * column shows, so the two never disagree. `value` null with the reason where
176
+ * it is not meaningful (`notMeaningful`, GE's N/M); null where GE draws no
177
+ * current point and has no reason for it.
178
+ */
179
+ export function currentTrailingValuation(
180
+ financials: TickerFinancials,
181
+ metric: "evEbitda" | "evSales",
182
+ ): { value: number | null; notMeaningful?: string; periodEnd: string; statement: FinancialStatement } | null {
183
+ const current = currentValuation(financials, "ttm", metric);
184
+ if (!current) return null;
185
+ const dated = { periodEnd: current.statement.date.slice(0, 10), statement: current.statement };
186
+ if (current.value !== null) return { value: current.value, ...dated };
187
+ const notMeaningful = metric === "evEbitda" ? ebitdaNotMeaningful(financials, current.statement) : undefined;
188
+ return notMeaningful ? { value: null, notMeaningful, ...dated } : null;
189
+ }
190
+
191
+ function currentValuation(financials: TickerFinancials, period: SeriesPeriod | undefined, metric: string) {
192
+ const selected = sourceStatements(financials, period, metric);
193
+ return currentDerivedValuation(financials, currentValuationStatements(financials, selected, metric), metric,
194
+ createValuationCurrencyContext(financials));
195
+ }
196
+
197
+ /**
198
+ * Why a valuation series ends on no value: EV/EBITDA is N/M for a bank or an
199
+ * insurer, and over EBITDA at or below zero, as RV reads it. The period the
200
+ * series would end on dates it. Undefined for any other series, or where its
201
+ * current value is there.
202
+ */
203
+ export function valuationNotMeaningful(financials: TickerFinancials, source: SecuritySeriesSource): { reason: string; asOf: string } | undefined {
204
+ const [namespace, metric = ""] = canonicalTimeSeriesFieldId(source.fieldId).split(".");
205
+ if (namespace !== "valuation" || metric !== "evEbitda") return undefined;
206
+ // A daily series ends on the trailing twelve months, as its current point does.
207
+ const period = source.period === "daily" || source.period === "auto" || !source.period ? "ttm" : source.period;
208
+ const current = currentValuation(financials, period, metric);
209
+ if (current) {
210
+ const reason = current.value === null ? ebitdaNotMeaningful(financials, current.statement) : undefined;
211
+ return reason ? { reason, asOf: current.statement.date.slice(0, 10) } : undefined;
212
+ }
213
+ if (!isBankOrInsurerIndustry(financials.profile?.industry)) return undefined;
214
+ const latest = sourceStatements(financials, period).statements.at(-1);
215
+ return latest ? { reason: BANK_OR_INSURER_EBITDA, asOf: latest.date.slice(0, 10) } : undefined;
216
+ }
217
+
218
+ /**
219
+ * The trailing twelve months of a statement line the way GE's `ttm` series
220
+ * reads it (four consecutive quarters, a fiscal fourth quarter completed from
221
+ * its year): the latest one, or null when the latest window is incomplete.
222
+ */
223
+ export function latestTrailingStatement(financials: TickerFinancials): FinancialStatement | null {
224
+ const selected = sourceStatements(financials, "ttm");
225
+ return selected.statements.at(-1) ?? null;
226
+ }
227
+
228
+ /**
229
+ * The periods a Current multiple is read from: the selected ones, and beside
230
+ * fiscal years the trailing twelve months the quarters after them sum to, so a
231
+ * fiscal year's EPS never prices today once later quarters are reported. A
232
+ * fiscal year is itself a trailing twelve months at its end.
233
+ */
234
+ export function currentValuationStatements(
235
+ financials: TickerFinancials,
236
+ selected: ReturnType<typeof sourceStatements>,
237
+ metric: string,
238
+ ): InternalStatement[] {
239
+ if (selected.period !== "annual") return selected.statements;
240
+ const known = valuationStatements(financials);
241
+ const trailing = buildTtmStatements(deriveQuarterlyStatements(known.quarterly, known.annual), known.annual)
242
+ .filter((statement) => hasValuationInputs(statement, metric));
243
+ return [...selected.statements, ...trailing];
244
+ }
@@ -0,0 +1,99 @@
1
+ // Valuation multiples at the price of each period or day, and the daily fallback for issuers whose history cannot be dated.
2
+ import type { FinancialStatement, TickerFinancials } from "../../types/financials";
3
+ import { completeAvailability } from "../../utils/financial-statements";
4
+ import { fiscalYearEndMonth } from "../../utils/fiscal-period";
5
+ import { canonicalTimeSeriesFieldId } from "../field-catalog";
6
+ import { dailyValuationHistory, type DailyValuationBasis } from "../daily-valuation";
7
+ import { createValuationCurrencyContext, type ValuationCurrencyContext } from "../valuation-currency";
8
+ import { valuationPriceAtOrBefore } from "../valuation-price";
9
+ import type { SecuritySeriesSource, TimeSeriesPoint } from "../types";
10
+ import { QUOTE_DERIVED_VALUATION_IDS } from "./metric-ids";
11
+ import { pointForStatement } from "./period-points";
12
+ import { sourceStatements } from "./source-statements";
13
+ import { DAY_MS, statementTime, validDate } from "./statement";
14
+ import { freeCashFlow, metricAvailability, selectedEps } from "./statement-fields";
15
+ import { valuationAtPrice } from "./valuation-multiples";
16
+
17
+ export function historicalValuation(
18
+ financials: TickerFinancials,
19
+ statement: FinancialStatement,
20
+ metric: string,
21
+ currencies: ValuationCurrencyContext,
22
+ ) {
23
+ // A price failure cannot make absent financial inputs appear available.
24
+ if (currencies.priceInStatementUnits(statement, 1) === null || valuationAtPrice(statement, metric, 1, true) === null) return null;
25
+ const priceDate = metricAvailability(statement, metric) ?? statement.date;
26
+ const price = valuationPriceAtOrBefore(financials.priceHistory, priceDate);
27
+ if (!price) return null;
28
+ const comparablePrice = price.price === null ? null : currencies.priceInStatementUnits(statement, price.price);
29
+ return { value: comparablePrice === null ? null : valuationAtPrice(statement, metric, comparablePrice), integrity: price.integrity, issue: price.issue };
30
+ }
31
+
32
+ export function dailyStatementValuation(financials: TickerFinancials, metric: string, exchange?: string): TimeSeriesPoint[] {
33
+ const earningsMetric = metric === "pegRatio" ? "trailingPE" : metric;
34
+ const selected = sourceStatements(financials, "daily", earningsMetric, exchange);
35
+ const currencies = createValuationCurrencyContext(financials);
36
+ const yearEndMonth = fiscalYearEndMonth(financials.annualStatements);
37
+ const bases: DailyValuationBasis[] = selected.statements.flatMap((statement) => {
38
+ const usable = valuationAtPrice(statement, earningsMetric, 1, true) !== null;
39
+ // Missing dates cannot put information at the period end: until its
40
+ // publication is known there is no historical denominator to use.
41
+ let publication = metricAvailability(statement, earningsMetric)
42
+ ?? (!usable ? statement.availableAt : undefined);
43
+ let growth: number | null = null;
44
+ if (metric === "pegRatio") {
45
+ const prior = selected.statements.find((candidate) => {
46
+ const days = (statementTime(statement) - statementTime(candidate)) / DAY_MS;
47
+ return days >= 330 && days <= 400;
48
+ });
49
+ const currentEps = selectedEps(statement)?.value;
50
+ const previousEps = prior ? selectedEps(prior)?.value : null;
51
+ if (prior && currentEps != null && currentEps > 0 && previousEps != null && previousEps > 0) {
52
+ publication = completeAvailability([publication, metricAvailability(prior, "trailingPE")]);
53
+ const change = (currentEps / previousEps - 1) * 100;
54
+ if (change > 0) growth = change;
55
+ }
56
+ }
57
+ const observedAt = validDate(statement.date);
58
+ if (!observedAt) return [];
59
+ const availableAt = validDate(publication);
60
+ if (availableAt && availableAt < observedAt) publication = undefined;
61
+ const point = pointForStatement(statement, earningsMetric, null, selected.period, "available-at", true, yearEndMonth);
62
+ return [{
63
+ availableAt: publication,
64
+ observedAt,
65
+ periodLabel: point?.periodLabel,
66
+ atPrice: (price: number) => {
67
+ // An undated newer period must stop the previous TTM from continuing.
68
+ // Its period end only bounds the gap; it never publishes a value.
69
+ if (!publication || !availableAt) return null;
70
+ const comparable = currencies.priceInStatementUnits(statement, price);
71
+ if (comparable === null) return null;
72
+ const value = valuationAtPrice(statement, earningsMetric, comparable);
73
+ // Negative cash flow, revenue or EBITDA cannot produce a meaningful
74
+ // multiple. Explicit period views retain their historical behavior.
75
+ const denominator = earningsMetric === "priceFcf" ? freeCashFlow(statement).value
76
+ : earningsMetric === "evEbitda" ? statement.ebitda
77
+ : earningsMetric === "priceSales" || earningsMetric === "evSales" ? statement.totalRevenue : 1;
78
+ if (denominator == null || denominator <= 0 || value === null) return null;
79
+ return metric === "pegRatio" ? growth === null ? null : value / growth : value;
80
+ },
81
+ }];
82
+ });
83
+ const points = dailyValuationHistory(financials.priceHistory, bases, financials.quote?.listingExchangeName || financials.quote?.exchangeName || exchange);
84
+ return points.some((point) => point.value !== null) ? points : [];
85
+ }
86
+
87
+ /** A daily history cannot be dated at all, but the issuer still has reported figures. */
88
+ export function dailyValuationFallbackPeriod(financials: TickerFinancials, source: SecuritySeriesSource): "annual" | "quarterly" | "ttm" | null {
89
+ if (source.period !== "daily") return null;
90
+ const [namespace, metric = ""] = canonicalTimeSeriesFieldId(source.fieldId).split(".");
91
+ const inputMetric = metric === "pegRatio" ? "trailingPE" : metric;
92
+ if (namespace !== "valuation" || !QUOTE_DERIVED_VALUATION_IDS.has(inputMetric)) return null;
93
+ const daily = sourceStatements(financials, "daily", inputMetric, source.instrument.exchange);
94
+ if (daily.statements.some(row => metricAvailability(row, inputMetric))) return null;
95
+ const annual = sourceStatements(financials, "annual", inputMetric);
96
+ if (annual.statements.some(row => valuationAtPrice(row, inputMetric, 1, true) !== null)) return "annual";
97
+ const reported = sourceStatements(financials, "auto", inputMetric);
98
+ return reported.statements.some(row => valuationAtPrice(row, inputMetric, 1, true) !== null) ? reported.period : null;
99
+ }
@@ -0,0 +1,61 @@
1
+ // Which fundamental and valuation metrics exist, and which of them read the live quote or the price history.
2
+ import { canonicalTimeSeriesFieldId } from "../field-catalog";
3
+ import type { SeriesPeriod } from "../types";
4
+
5
+ export const FUNDAMENTAL_IDS = new Set([
6
+ "totalRevenue",
7
+ "grossProfit",
8
+ "grossMargin",
9
+ "operatingIncome",
10
+ "operatingMargin",
11
+ "netIncome",
12
+ "netMargin",
13
+ "ebitda",
14
+ "depreciationAndAmortization",
15
+ "operatingCashFlow",
16
+ "freeCashFlow",
17
+ "freeCashFlowMargin",
18
+ "totalAssets",
19
+ "totalDebt",
20
+ "totalEquity",
21
+ "eps",
22
+ ]);
23
+
24
+ export const VALUATION_IDS = new Set([
25
+ "trailingPE",
26
+ "forwardPE",
27
+ "realizedNtmPE",
28
+ "pegRatio",
29
+ "priceSales",
30
+ "evSales",
31
+ "evEbitda",
32
+ "priceFcf",
33
+ ]);
34
+
35
+ /** Statement-based multiples whose latest point is the regular session price over the latest trailing period. */
36
+ export const QUOTE_DERIVED_VALUATION_IDS = new Set([
37
+ "trailingPE",
38
+ "priceSales",
39
+ "evSales",
40
+ "evEbitda",
41
+ "priceFcf",
42
+ ]);
43
+
44
+ /** Multiples priced from history at each observation date; forward P/E also ends on the live quote. */
45
+ const PRICE_HISTORY_VALUATION_IDS = new Set([
46
+ ...QUOTE_DERIVED_VALUATION_IDS,
47
+ "forwardPE",
48
+ "realizedNtmPE",
49
+ ]);
50
+
51
+ /** Whether a valuation field derives a current point from the latest quote. */
52
+ export function valuationSeriesUsesLiveQuote(fieldId: string): boolean {
53
+ const [namespace, metric = ""] = canonicalTimeSeriesFieldId(fieldId).split(".");
54
+ return namespace === "valuation" && (QUOTE_DERIVED_VALUATION_IDS.has(metric) || metric === "forwardPE");
55
+ }
56
+
57
+ /** Whether a valuation field needs the full price history to date its observations. */
58
+ export function valuationSeriesUsesPriceHistory(fieldId: string, period?: SeriesPeriod): boolean {
59
+ const [namespace, metric = ""] = canonicalTimeSeriesFieldId(fieldId).split(".");
60
+ return namespace === "valuation" && (PRICE_HISTORY_VALUATION_IDS.has(metric) || (metric === "pegRatio" && period === "daily"));
61
+ }
@@ -0,0 +1,104 @@
1
+ // Turns a statement into a dated series point, and keeps one point per financial period.
2
+ import type { FinancialStatement } from "../../types/financials";
3
+ import { areNearbyFinancialPeriodEnds } from "../../utils/financial-statements";
4
+ import { fiscalPeriodLabel, ttmPeriodLabel } from "../../utils/fiscal-period";
5
+ import { hasStatementGap } from "../../utils/statement-gaps";
6
+ import type { SecuritySeriesSource, TimeSeriesPoint } from "../types";
7
+ import { validDate } from "./statement";
8
+ import { metricAvailability } from "./statement-fields";
9
+
10
+ export function pointForStatement(
11
+ statement: FinancialStatement,
12
+ metric: string,
13
+ value: number | null,
14
+ period: "annual" | "quarterly" | "ttm",
15
+ timestampMode: SecuritySeriesSource["timestampMode"],
16
+ derived: boolean,
17
+ /** The month the issuer's fiscal year ends; null names the period by its end date. */
18
+ yearEndMonth: number | null,
19
+ ): TimeSeriesPoint | null {
20
+ const observedAt = validDate(statement.date);
21
+ if (!observedAt) return null;
22
+ // A missing metric is known to be unavailable with its statement. It has
23
+ // no metric-specific publication date to substitute for that boundary.
24
+ const availableAtString = metricAvailability(statement, metric)
25
+ ?? (value === null ? statement.availableAt : undefined);
26
+ const availableAt = validDate(availableAtString);
27
+ const date = timestampMode !== "period-end" && availableAt ? availableAt : observedAt;
28
+ return {
29
+ date,
30
+ observedAt,
31
+ availableAt: availableAt ?? undefined,
32
+ value,
33
+ // Providers do not supply a reliable issuer fiscal-year/quarter identity.
34
+ // Calendar-month numbering would mislabel non-calendar fiscal years.
35
+ periodLabel: `${period === "annual" ? "Year" : period === "ttm" ? "TTM" : "Quarter"} ended ${statement.date}`,
36
+ // The period as FA's columns name it (`Q3 FY26`), which the legend prints beside the value.
37
+ fiscalPeriod: period === "ttm" ? ttmPeriodLabel(statement.date, yearEndMonth) : fiscalPeriodLabel(statement.date, period, yearEndMonth),
38
+ provenance: {
39
+ quality: derived || (metric === "eps" && statement.epsBasis?.factor !== undefined && statement.epsBasis.factor !== 1) ? "derived" : "reported",
40
+ ...((metric === "eps" || metric === "trailingPE") && statement.epsBasis ? { secEpsBasis: statement.epsBasis } : {}),
41
+ ...((metric === "eps" || metric === "trailingPE") && hasStatementGap(statement, "eps")
42
+ ? { unavailableEarnings: ["eps" as const] } : {}),
43
+ currency: statement.currency,
44
+ },
45
+ };
46
+ }
47
+
48
+ function preferredPeriodPoint(
49
+ existing: TimeSeriesPoint,
50
+ candidate: TimeSeriesPoint,
51
+ ): TimeSeriesPoint {
52
+ if (existing.provenance?.quality !== candidate.provenance?.quality) {
53
+ return candidate.provenance?.quality === "reported" ? candidate : existing;
54
+ }
55
+ const existingAvailableAt = existing.availableAt?.getTime();
56
+ const candidateAvailableAt = candidate.availableAt?.getTime();
57
+ const existingHasAvailability = Number.isFinite(existingAvailableAt);
58
+ const candidateHasAvailability = Number.isFinite(candidateAvailableAt);
59
+ if (existingHasAvailability !== candidateHasAvailability) {
60
+ return candidateHasAvailability ? candidate : existing;
61
+ }
62
+ if (
63
+ existingHasAvailability
64
+ && candidateHasAvailability
65
+ && candidateAvailableAt! !== existingAvailableAt!
66
+ ) {
67
+ const preferLater = !Object.is(existing.value, candidate.value);
68
+ const candidateWins = preferLater
69
+ ? candidateAvailableAt! > existingAvailableAt!
70
+ : candidateAvailableAt! < existingAvailableAt!;
71
+ return candidateWins ? candidate : existing;
72
+ }
73
+ return candidate.observedAt.getTime() < existing.observedAt.getTime()
74
+ ? candidate
75
+ : existing;
76
+ }
77
+
78
+ /**
79
+ * Provider snapshots can contain both an issuer fiscal-period row and a
80
+ * calendar-normalized row for the same observation. Their period ends and
81
+ * display timestamps differ slightly, so timestamp-only deduplication renders
82
+ * paired bars. A financial period is the observation identity; publication
83
+ * time only decides when that observation became available.
84
+ */
85
+ export function dedupeFundamentalPeriods(points: readonly TimeSeriesPoint[]): TimeSeriesPoint[] {
86
+ const groups: TimeSeriesPoint[][] = [];
87
+ const sorted = [...points].sort((left, right) => (
88
+ left.observedAt.getTime() - right.observedAt.getTime()
89
+ ));
90
+ for (const point of sorted) {
91
+ const lastGroup = groups.at(-1);
92
+ if (lastGroup && areNearbyFinancialPeriodEnds(lastGroup[0]!.observedAt, point.observedAt)
93
+ && (lastGroup[0]!.observedAt.getTime() === point.observedAt.getTime()
94
+ || ![point, ...lastGroup].some(item => item.provenance?.unavailableEarnings?.length))) {
95
+ lastGroup.push(point);
96
+ } else groups.push([point]);
97
+ }
98
+ return groups
99
+ .map((group) => group.slice(1).reduce(preferredPeriodPoint, group[0]!))
100
+ .sort((left, right) => (
101
+ left.date.getTime() - right.date.getTime()
102
+ || left.observedAt.getTime() - right.observedAt.getTime()
103
+ ));
104
+ }