@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
package/src/sync/react.ts CHANGED
@@ -54,14 +54,14 @@ export function useCloudSyncRuntime({
54
54
 
55
55
  useEffect(() => {
56
56
  if (!initialized) return;
57
- void cloudSyncController.requestSync({ reason: "startup" });
57
+ cloudSyncController.startSync({ reason: "startup" });
58
58
  }, [initialized, pluginRegistry]);
59
59
 
60
60
  useEffect(() => {
61
61
  if (!initialized || !appActive) return;
62
- void cloudSyncController.requestSync({ reason: "foreground" });
62
+ cloudSyncController.startSync({ reason: "foreground" });
63
63
  const timer = setInterval(() => {
64
- void cloudSyncController.requestSync({ reason: "poll" });
64
+ cloudSyncController.startSync({ reason: "poll" });
65
65
  }, CLOUD_SYNC_POLL_MS);
66
66
  return () => clearInterval(timer);
67
67
  }, [appActive, initialized]);
@@ -70,7 +70,7 @@ export function useCloudSyncRuntime({
70
70
  if (!initialized) return;
71
71
  // Email verification makes the Cloud transport available. Force the first
72
72
  // sync so a workspace completed before verification is uploaded promptly.
73
- void cloudSyncController.requestSync({ reason: "session-verified", force: true });
73
+ cloudSyncController.startSync({ reason: "session-verified", force: true });
74
74
  }, (accountId) => cloudSyncController.resetAccount(accountId),
75
75
  () => cloudSyncController.retireSession()), [initialized]);
76
76
 
@@ -148,6 +148,23 @@ export function isCryptoVenuePerpetual(type: string | null | undefined, name: st
148
148
  return classifyInstrumentType(type) === "crypto" && /\(derivatives\)/i.test(name ?? "");
149
149
  }
150
150
 
151
+ /** An exchange-traded fund's intraday indicative value as an index feed lists it, under the fund's own name: ^ARKK-IV. */
152
+ export function isIndicativeValueListing(symbol: string | null | undefined, type?: string | null): boolean {
153
+ return /^\^[A-Z0-9.]{1,10}-IV$/i.test(parsePublicTickerKey(symbol ?? "").symbol) || normalizeInstrumentType(type) === "INDICATIVEVALUE";
154
+ }
155
+
156
+ /**
157
+ * A crypto venue's copy of a fund's or a company's price: a token on its
158
+ * shares ("... Tokenized ETF (Ondo)", typed as a coin) or a perpetual on it
159
+ * ("... ETF (Derivatives)"). Neither is a listing of the fund or the company.
160
+ * A fund or share whose own name says tokenized is a listing.
161
+ */
162
+ export function isCryptoVenueCopy(type: string | null | undefined, name: string | null | undefined): boolean {
163
+ return normalizeInstrumentType(type) === "TOKENIZEDPRODUCT"
164
+ || (classifyInstrumentType(type) === "crypto" && /\btokeni[sz]ed\b/i.test(name ?? ""))
165
+ || (isCryptoVenuePerpetual(type, name) && /\b(?:ETFS?|ETNS?|FUNDS?|TRUST|SHARES?|STOCK)\b/i.test(name ?? ""));
166
+ }
167
+
151
168
  /**
152
169
  * A quote type's code in the words the other types are written in ("Common
153
170
  * Stock", "Depositary Receipt"), so one search lists one vocabulary. A generic
@@ -173,8 +190,12 @@ const TYPE_CODE_WORDS: Record<string, string> = {
173
190
  export function instrumentTypeLabel(
174
191
  type: string | null | undefined,
175
192
  name: string | null | undefined,
176
- options: { detail?: boolean } = {},
193
+ options: { detail?: boolean; symbol?: string } = {},
177
194
  ): string | undefined {
195
+ if (isIndicativeValueListing(options.symbol, type)) return options.detail ? "Indicative value (the fund's intraday estimate, not a listing)" : "Indicative value";
196
+ if (normalizeInstrumentType(type) !== "TOKENIZEDPRODUCT" && /\btokeni[sz]ed\b/i.test(name ?? "") && classifyInstrumentType(type) === "crypto") {
197
+ return options.detail ? "Tokenized product (a crypto token, not the listing)" : "Tokenized product";
198
+ }
178
199
  if (isCryptoVenuePerpetual(type, name)) {
179
200
  return options.detail ? "Perpetual futures price (24/7 on crypto venues; not the listed future, not spot)" : "Perpetual futures price";
180
201
  }
@@ -35,6 +35,7 @@ import {
35
35
  } from "./result";
36
36
 
37
37
  import { typedPerpetualListing } from "../perpetual-listing";
38
+ import { isCryptoVenueCopy, isIndicativeValueListing } from "../instrument-kind";
38
39
  import { renamedListingFor, renamedListingFormerLine, type RenamedListing } from "../renamed-listings";
39
40
  import { endsInLegalForm, readNearMissListing, readVenueFirstListing, readTerminalListingCode } from "../terminal-codes";
40
41
  import { isProviderBusy, ProviderBusyError, SEARCH_BUSY_MESSAGE } from "../../sources/provider-errors";
@@ -976,6 +977,10 @@ function assignTickerSearchCategories<T extends TickerSearchCandidate>(items: T[
976
977
  if (item.instrumentClass === "fund" || item.instrumentClass === "derivative") {
977
978
  return { ...item, category: "Funds & Derivatives" };
978
979
  }
980
+ // A fund's indicative value (^ARKK-IV) or a crypto venue's token or perpetual on a fund names no listing of its own.
981
+ if (item.kind === "search" && (isIndicativeValueListing(item.symbol, item.result?.type) || isCryptoVenueCopy(item.result?.type, item.result?.name))) {
982
+ return { ...item, category: "Other Matches" };
983
+ }
979
984
  if (!assignedPrimaryListing) {
980
985
  assignedPrimaryListing = true;
981
986
  return { ...item, category: "Primary Listing" };
@@ -438,8 +438,17 @@ export function readLondonDottedSymbol(raw: string): NearMissListing | null {
438
438
 
439
439
  /** `BRK/B`: a US share class after a slash, as a broker writes it. One letter before the slash is a ratio or an abbreviation (P/E, N/A). */
440
440
  const SLASH_CLASS = /^([A-Z]{2,5})\/([A-Z])$/;
441
- /** `700.HK`: a Hong Kong code without its leading zeros. */
442
- const SHORT_HONG_KONG = /^(\d{1,3})\.HK$/;
441
+ /**
442
+ * `700.HK`, `03042.HK`, `00700:HKEX`: a Hong Kong code without its leading
443
+ * zeros, or with the five digits HKEXnews and the Product Key Facts print.
444
+ */
445
+ const HONG_KONG_CODE = /^(\d{1,5})(\.HK|:HKEX)$/;
446
+
447
+ /** A Hong Kong code as the app keys it: four digits at least (0700, 3042, 83042). */
448
+ function hongKongWorkingCode(digits: string): string | null {
449
+ const code = Number(digits);
450
+ return code > 0 ? String(code).padStart(4, "0") : null;
451
+ }
443
452
  /** `6758.JP`, `MC.FP`: a symbol with a Bloomberg market code where a listing suffix goes. */
444
453
  const MARKET_SUFFIX = /^([A-Z0-9]{1,10})\.([A-Z]{2})$/;
445
454
  /**
@@ -454,7 +463,9 @@ const MARKET_SUFFIX_CODES: ReadonlySet<string> = new Set([
454
463
 
455
464
  /**
456
465
  * A symbol written nearly as a listing is (`700.HK`, `6758.JP`, `BRK/B`),
457
- * read as the working form (`0700.HK`, `6758.T`, `BRK-B`). A Bloomberg market
466
+ * read as the working form (`0700.HK`, `6758.T`, `BRK-B`); a Hong Kong code
467
+ * with HKEX's five digits (`03042.HK`, `00700:HKEX`) drops its leading zeros
468
+ * (`3042.HK`, `0700:HKEX`). A Bloomberg market
458
469
  * code after the dot is that market's listing suffix (`MC.FP` is `MC.PA`),
459
470
  * `MARKET_SUFFIX_CODES` only, so `600519.SS` stays Shanghai. Null for
460
471
  * anything else.
@@ -464,8 +475,9 @@ export function readNearMissListing(raw: string): NearMissListing | null {
464
475
  const upper = typed.toUpperCase();
465
476
  const slash = SLASH_CLASS.exec(upper);
466
477
  if (slash) return { typed, symbol: `${slash[1]}-${slash[2]}` };
467
- const hongKong = SHORT_HONG_KONG.exec(upper);
468
- if (hongKong) return { typed, symbol: `${hongKong[1]!.padStart(4, "0")}.HK` };
478
+ const hongKong = HONG_KONG_CODE.exec(upper);
479
+ const code = hongKong ? hongKongWorkingCode(hongKong[1]!) : null;
480
+ if (hongKong) return code && code !== hongKong[1] ? { typed, symbol: `${code}${hongKong[2]}` } : null;
469
481
  const suffixed = MARKET_SUFFIX.exec(upper);
470
482
  if (!suffixed || !MARKET_SUFFIX_CODES.has(suffixed[2]!) || tickerHasListingSuffix(upper)) return null;
471
483
  const venue = BLOOMBERG_MARKETS[suffixed[2]!]!.venues[0]!;
@@ -17,3 +17,36 @@ export function barSizeFromGap(gapMs: number): "1d" | "1wk" | "1mo" {
17
17
  const days = gapMs / DAY_MS;
18
18
  return days >= 25 ? "1mo" : days >= 6 ? "1wk" : "1d";
19
19
  }
20
+
21
+ const BAR_SIZE_ORDER = { "1d": 0, "1wk": 1, "1mo": 2 } as const;
22
+
23
+ /** Whether bars are each the start of a week, all on one weekday, or of a month, in its first week. */
24
+ function startPeriods(times: readonly number[], size: "1wk" | "1mo"): boolean {
25
+ const dates = times.filter(Number.isFinite).map((time) => new Date(time));
26
+ return size === "1wk" ? new Set(dates.map((date) => date.getUTCDay())).size === 1 : dates.every((date) => date.getUTCDate() <= 7);
27
+ }
28
+
29
+ /** Fewer bars than this cannot say they are coarser than asked: three Mondays of a thin listing are no weekly bars. */
30
+ const MIN_COARSER_BARS = 4;
31
+
32
+ type DailyOrLonger = "1d" | "1wk" | "1mo";
33
+
34
+ /**
35
+ * The size of bars asked for as `requested`: the request, not the spacing,
36
+ * unless the source stated the size it served (`stated`). A thinly traded
37
+ * listing's daily bars sit a week or two apart (B95 on SGX traded on 13 Oct,
38
+ * 22 Oct and 6 Nov), which the spacing reads as weekly. Bars the source
39
+ * served finer than asked show it in their spacing; coarser ones only when
40
+ * there are at least four and each starts its period, as weekly and monthly
41
+ * bars do.
42
+ */
43
+ export function requestedBarSize(times: readonly number[], requested: DailyOrLonger, stated?: string | null): DailyOrLonger {
44
+ if (stated === "1d" || stated === "1wk" || stated === "1mo") return stated;
45
+ const gap = medianBarGap(times);
46
+ if (gap == null) return requested;
47
+ const read = barSizeFromGap(gap);
48
+ if (BAR_SIZE_ORDER[read] < BAR_SIZE_ORDER[requested]) return read;
49
+ const bars = new Set(times.filter(Number.isFinite)).size;
50
+ return BAR_SIZE_ORDER[read] > BAR_SIZE_ORDER[requested] && bars >= MIN_COARSER_BARS && startPeriods(times, read as "1wk" | "1mo")
51
+ ? read : requested;
52
+ }
@@ -7,9 +7,12 @@ import { CHART_RESOLUTION_STEP_MS, type ManualChartResolution } from "./resoluti
7
7
  import type { Quote, QuoteMetadata, TickerFinancials } from "../types/financials";
8
8
  import type { FredSeriesLoadResult } from "../sources/gloomberb-cloud/fred-series";
9
9
  import { extractFredSeries } from "./economic";
10
+ import { isIceSpreadSeries } from "./ice-credit";
11
+ import { BASIS_POINT_UNIT, BP_PER_PERCENT } from "./studies/units";
10
12
  import { getTimeSeriesField, isMarketFieldId } from "./field-catalog";
11
13
  import {
12
14
  unreportedStatementPeriod,
15
+ valuationNotMeaningful,
13
16
  dailyValuationFallbackPeriod,
14
17
  valuationCurrencyWarning,
15
18
  valuationPriceIssues,
@@ -122,6 +125,7 @@ export function baseSecuritySeries(
122
125
  const points = extractSecuritySeries(financials, spec.source);
123
126
  const valuationFallback = dailyValuationFallbackPeriod(financials, spec.source);
124
127
  const unreportedPeriod = points.length === 0 ? unreportedStatementPeriod(financials, spec.source) : null;
128
+ const notMeaningful = valuationNotMeaningful(financials, spec.source);
125
129
  const symbol = instrumentLabel(spec.source);
126
130
  const statementCurrency = field.id.startsWith("fundamental.") && field.unit.startsWith("currency")
127
131
  ? reportingCurrencySeries(points, financials.financialCurrency) : null;
@@ -220,11 +224,13 @@ export function baseSecuritySeries(
220
224
  ...(volumeBasis ? { volumeBasis } : {}),
221
225
  ...(priceIssues.length ? { valuationPriceIssues: priceIssues } : {}),
222
226
  warning: [valuationFallback ? "Release dates unavailable; showing reported periods." : undefined,
227
+ notMeaningful ? `N/M: ${notMeaningful.reason} (period to ${notMeaningful.asOf}).` : undefined,
223
228
  field.id === "market.volume" && !volumeUnit && !volumeBasis && points.some((point) => Number.isFinite(point.value) && point.value !== 0)
224
229
  ? "Volume unit unknown." : statementCurrency?.warning ?? valuationCurrencyWarning(financials, spec.source)].filter(Boolean).join(" ") || undefined,
225
230
  nativeFrequency: marketField ? marketSeriesFrequency(spec.source, marketResolution)
226
231
  : valuationFallback ?? (spec.source.period && spec.source.period !== "auto" ? spec.source.period : field.nativeFrequency),
227
232
  ...(unreportedPeriod ? { unreportedPeriod } : {}),
233
+ ...(notMeaningful ? { notMeaningful } : {}),
228
234
  ...(marketField ? { historyResolution: marketResolution } : {}),
229
235
  timestampMode: spec.source.timestampMode,
230
236
  dataShape: field.dataShape,
@@ -278,12 +284,18 @@ export function baseEconomicSeries(
278
284
  const catalogUnit = fredCatalogUnit(units);
279
285
  // "Percent Change from Year Ago" and "Percent per Annum" are percent too.
280
286
  const isPercent = units.toLowerCase().includes("percent");
287
+ // An ICE option-adjusted spread reads in bp, as CRD and `fred` print it and CDX quotes, not FRED's percentage points.
288
+ const basisPoints = isPercent && /^percent$/i.test(units) && isIceSpreadSeries(spec.source.seriesId);
289
+ const points = extractFredSeries(data.observations, { providerId: "fred", timestampMode: "period-end" });
281
290
  return {
282
291
  id: spec.id,
283
292
  label: spec.label?.trim() || data.info?.title?.trim() || spec.source.seriesId,
293
+ expression: `FRED:${spec.source.seriesId}`,
284
294
  color: spec.color ?? SERIES_COLORS[index % SERIES_COLORS.length]!,
285
- unit: isPercent ? "%" : catalogUnit,
286
- unitGroup: isPercent ? "percent" : `economic:${catalogUnit.toLowerCase()}`,
295
+ ...(basisPoints ? BASIS_POINT_UNIT : {
296
+ unit: isPercent ? "%" : catalogUnit,
297
+ unitGroup: isPercent ? "percent" : `economic:${catalogUnit.toLowerCase()}`,
298
+ }),
287
299
  nativeFrequency: "auto",
288
300
  timestampMode: "period-end",
289
301
  dataShape: "scalar",
@@ -292,7 +304,10 @@ export function baseEconomicSeries(
292
304
  axis: spec.axis === "right" ? "right" : "left",
293
305
  panelId: spec.panelId,
294
306
  interpolation: spec.interpolation,
295
- points: extractFredSeries(data.observations, { providerId: "fred", timestampMode: "period-end" }),
307
+ // Rounded off the float's last digits: 0.93 × 100 is 93, not 93.00000000000001.
308
+ points: basisPoints
309
+ ? points.map((point) => typeof point.value === "number" ? { ...point, value: Number((point.value * BP_PER_PERCENT).toPrecision(12)) } : point)
310
+ : points,
296
311
  warning: "FRED vintage dates are unavailable; observations use period dates.",
297
312
  };
298
313
  }
@@ -312,6 +327,9 @@ export function baseCapabilitySeries(
312
327
  ...loaded,
313
328
  id: spec.id,
314
329
  label: spec.label?.trim() || loaded.label || (spec.source.kind === "capability" ? spec.source.seriesId : spec.id),
330
+ // A geographic series writes as GEO:, which only the chart composer spells; it keeps its label.
331
+ ...(spec.source.kind === "capability" && spec.source.capabilityId !== "geo-series"
332
+ ? { expression: `CAP:${spec.source.capabilityId}:${spec.source.seriesId}` } : {}),
315
333
  color: spec.color ?? loaded.color ?? SERIES_COLORS[index % SERIES_COLORS.length]!,
316
334
  style: spec.style,
317
335
  transform: spec.transform,
@@ -288,6 +288,37 @@ export function capabilityRequestBounds(view: DateBounds, range: DateBounds, mov
288
288
  };
289
289
  }
290
290
 
291
+ /** The middle gap between a series' observations, in ms; 0 with fewer than two. */
292
+ function medianStep(times: readonly number[]): number {
293
+ const steps = times.slice(1).map((time, index) => time - times[index]!).sort((left, right) => left - right);
294
+ return steps.length ? steps[Math.floor(steps.length / 2)]! : 0;
295
+ }
296
+
297
+ /**
298
+ * A chart of published series alone (FRED, capability datasets) opens at its oldest observation when
299
+ * every series starts well inside the range: the ICE spreads FRED keeps three
300
+ * years of, on a 5Y chart, would leave two blank years on the left. Well
301
+ * inside is more than two of the series' own steps after the range's start,
302
+ * so a quarterly series whose first quarter in the range falls a month in
303
+ * moves nothing.
304
+ */
305
+ export function startAtOldestObservation(bounds: DateBounds, series: readonly ResolvedSeries[]): DateBounds {
306
+ if (bounds.start === null || bounds.end === null) return bounds;
307
+ let oldest = Number.POSITIVE_INFINITY;
308
+ let step = 0;
309
+ for (const entry of series) {
310
+ const times = entry.points
311
+ .filter((point) => point.value !== null && Number.isFinite(point.date.getTime()))
312
+ .map((point) => point.date.getTime())
313
+ .sort((left, right) => left - right);
314
+ if (times.length < 2) continue;
315
+ oldest = Math.min(oldest, times[0]!);
316
+ step = Math.max(step, medianStep(times));
317
+ }
318
+ if (!Number.isFinite(oldest) || oldest >= bounds.end || oldest - bounds.start <= 2 * step) return bounds;
319
+ return { start: oldest, end: bounds.end };
320
+ }
321
+
291
322
  /**
292
323
  * A chart of capability series alone (CHOKE's vessel transits) ends at its
293
324
  * newest observation, not today: such data is published days late, and an
@@ -156,6 +156,23 @@ const FIELDS = [
156
156
  ...FUNDAMENTAL_PRESENTATION,
157
157
  transforms: RATIO_TRANSFORMS,
158
158
  }),
159
+ // EBITDA is operating income plus D&A (utils/ebitda.ts); both lines chart so a trailing EBITDA can be rebuilt.
160
+ ...([
161
+ ["ebitda", "EBITDA", "EBITDA"],
162
+ ["depreciationAndAmortization", "Depreciation & Amortization", "D&A"],
163
+ ] as const).map(([id, label, shortLabel]) => field({
164
+ id: `fundamental.${id}`,
165
+ label,
166
+ shortLabel,
167
+ sourceKind: "security" as const,
168
+ dataShape: "scalar" as const,
169
+ unit: "currency",
170
+ unitGroup: "currency-total",
171
+ nativeFrequency: "quarterly" as const,
172
+ styles: ["step", "columns", "line", "points"] as SeriesStyle[],
173
+ ...FUNDAMENTAL_PRESENTATION,
174
+ transforms: FUNDAMENTAL_TRANSFORMS,
175
+ })),
159
176
  field({
160
177
  id: "fundamental.operatingCashFlow",
161
178
  label: "Operating Cash Flow",
@@ -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
+ }