@gloom-sh/terminal 0.20.5 → 0.20.6

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 (127) 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/hk-tenders.ts +59 -0
  6. package/src/api-client/index.ts +1 -0
  7. package/src/api-client/types/econ.ts +20 -2
  8. package/src/app.tsx +18 -13
  9. package/src/architecture/floating-promise-allowlist.json +313 -0
  10. package/src/cli/commands/market.ts +164 -40
  11. package/src/cli/commands/news-search.ts +22 -7
  12. package/src/cli/commands/overview.ts +12 -6
  13. package/src/cli/commands/ticker.ts +3 -1
  14. package/src/cli/early-command.ts +2 -0
  15. package/src/cli/errors.ts +10 -1
  16. package/src/cli/fx-forward.ts +76 -12
  17. package/src/cli/fx-pair.ts +1 -1
  18. package/src/cli/fx-quote-rate.ts +23 -0
  19. package/src/cli/help.ts +1 -0
  20. package/src/cli/index-roots.ts +5 -4
  21. package/src/cli/index.ts +40 -3
  22. package/src/cli/known-gaps.ts +11 -8
  23. package/src/cli/listing-arg.ts +6 -4
  24. package/src/cli/options.ts +52 -3
  25. package/src/cli/output-file.ts +5 -3
  26. package/src/cli/pane-functions/catalog.ts +15 -0
  27. package/src/cli/pane-functions/function-help.ts +4 -4
  28. package/src/cli/pane-functions/headless.ts +9 -4
  29. package/src/cli/pane-functions/index.ts +6 -4
  30. package/src/cli/pane-functions/resolver.ts +2 -2
  31. package/src/cli/result.ts +21 -2
  32. package/src/cli/spreadsheet-hint.ts +7 -3
  33. package/src/cli/treasury-yields.ts +5 -3
  34. package/src/components/chart/composite/legend.tsx +40 -2
  35. package/src/components/command-bar/workflow/tickers.ts +2 -2
  36. package/src/components/data-table/view.tsx +9 -2
  37. package/src/components/ui/data-table/opentui/index.tsx +11 -4
  38. package/src/components/ui/data-table/opentui/model.ts +8 -6
  39. package/src/components/ui/data-table/types.ts +6 -1
  40. package/src/components/ui/table-layout.ts +38 -1
  41. package/src/docs/snapshot.json +3 -3
  42. package/src/market-data/market/change-basis.ts +9 -5
  43. package/src/market-data/market/dated-previous-close.ts +57 -6
  44. package/src/market-data/quotes/contributions.ts +2 -0
  45. package/src/market-data/quotes/listing-enterprise-value.ts +50 -0
  46. package/src/plugins/builtin/alerts/metric-data.ts +15 -2
  47. package/src/plugins/builtin/backtest/headless.ts +1 -1
  48. package/src/plugins/builtin/cds/model.ts +0 -6
  49. package/src/plugins/builtin/chart-composer/formula.ts +16 -3
  50. package/src/plugins/builtin/chart-composer/headless-schema.ts +2 -0
  51. package/src/plugins/builtin/chart-composer/headless.ts +2 -1
  52. package/src/plugins/builtin/chart-composer/presets.ts +1 -0
  53. package/src/plugins/builtin/cloud/askg/pane.tsx +55 -13
  54. package/src/plugins/builtin/credit-boards/cdx-pane.tsx +20 -7
  55. package/src/plugins/builtin/credit-boards/client.ts +8 -0
  56. package/src/plugins/builtin/credit-boards/headless.ts +4 -1
  57. package/src/plugins/builtin/credit-boards/model.ts +58 -4
  58. package/src/plugins/builtin/credit-boards/series.ts +63 -6
  59. package/src/plugins/builtin/credit-boards/sovr-pane.tsx +3 -2
  60. package/src/plugins/builtin/credit-conditions/headless.ts +24 -6
  61. package/src/plugins/builtin/credit-conditions/index.tsx +1 -1
  62. package/src/plugins/builtin/credit-conditions/model.ts +12 -6
  63. package/src/plugins/builtin/credit-conditions/series.ts +2 -1
  64. package/src/plugins/builtin/econ/calendar-model.ts +41 -7
  65. package/src/plugins/builtin/econ/calendar-source.ts +7 -1
  66. package/src/plugins/builtin/econ/index.tsx +41 -8
  67. package/src/plugins/builtin/econ/types.ts +3 -0
  68. package/src/plugins/builtin/fixed-income/index.tsx +2 -0
  69. package/src/plugins/builtin/fx-matrix/index.tsx +44 -14
  70. package/src/plugins/builtin/help/keybindings-editor.tsx +6 -2
  71. package/src/plugins/builtin/portfolio-list/cli/render.ts +20 -3
  72. package/src/plugins/builtin/portfolio-list/cli/watchlist-command.ts +5 -1
  73. package/src/plugins/builtin/research/headless-schema.ts +4 -3
  74. package/src/plugins/builtin/research/relative-valuation-columns.ts +145 -47
  75. package/src/plugins/builtin/research/relative-valuation-currency.ts +31 -0
  76. package/src/plugins/builtin/research/relative-valuation-headless.ts +25 -8
  77. package/src/plugins/builtin/research/relative-valuation-model.ts +40 -9
  78. package/src/plugins/builtin/research/relative-valuation-pane.tsx +3 -2
  79. package/src/plugins/builtin/research/relative-valuation-peers.ts +2 -2
  80. package/src/plugins/builtin/thirteenf/api.ts +47 -4
  81. package/src/plugins/builtin/ticker-detail/data-panes/historical-prices.tsx +8 -7
  82. package/src/plugins/builtin/ticker-detail/data-panes/history-bars.ts +8 -5
  83. package/src/plugins/builtin/ticker-detail/financials/model.ts +6 -2
  84. package/src/plugins/builtin/ticker-detail/financials/tab.tsx +1 -1
  85. package/src/plugins/builtin/ticker-detail/headless.ts +6 -4
  86. package/src/plugins/builtin/treasury-auctions/cache.ts +36 -2
  87. package/src/plugins/builtin/treasury-auctions/headless.ts +42 -4
  88. package/src/plugins/builtin/treasury-auctions/hk-headless.ts +126 -0
  89. package/src/plugins/builtin/treasury-auctions/hk-view.tsx +347 -0
  90. package/src/plugins/builtin/treasury-auctions/hk.ts +363 -0
  91. package/src/plugins/builtin/treasury-auctions/index.tsx +14 -1
  92. package/src/plugins/builtin/treasury-auctions/model.ts +16 -8
  93. package/src/plugins/builtin/treasury-auctions/pane.tsx +45 -21
  94. package/src/portfolio/collection-name.ts +22 -0
  95. package/src/renderers/dom/data-table/frozen-column.ts +3 -1
  96. package/src/renderers/dom/data-table/index.tsx +27 -9
  97. package/src/renderers/dom/data-table/row.tsx +2 -0
  98. package/src/renderers/electrobun/bun/desktop/backend.ts +27 -24
  99. package/src/renderers/electrobun/bun/desktop/detached-windows.ts +3 -3
  100. package/src/renderers/electrobun/bun/desktop/snapshot-commit.ts +77 -0
  101. package/src/renderers/electrobun/shared/protocol.ts +4 -0
  102. package/src/renderers/electrobun/view/backend-rpc.ts +3 -0
  103. package/src/renderers/electrobun/view/desktop/window/bridge.ts +3 -0
  104. package/src/sources/gloomberb-cloud/normalizers.ts +9 -5
  105. package/src/sources/provider-router/cache.ts +3 -1
  106. package/src/sync/controller.ts +17 -2
  107. package/src/sync/other-window-tabs.ts +32 -1
  108. package/src/sync/react.ts +4 -4
  109. package/src/time-series/bar-spacing.ts +33 -0
  110. package/src/time-series/base-series.ts +21 -3
  111. package/src/time-series/chart-bounds.ts +31 -0
  112. package/src/time-series/field-catalog.ts +17 -0
  113. package/src/time-series/fundamentals.ts +143 -11
  114. package/src/time-series/ice-credit.ts +32 -6
  115. package/src/time-series/resolve.ts +9 -5
  116. package/src/time-series/session-bar.ts +78 -9
  117. package/src/time-series/studies/formula.ts +53 -10
  118. package/src/time-series/studies/pair.ts +18 -7
  119. package/src/time-series/studies/units.ts +49 -2
  120. package/src/time-series/types.ts +12 -0
  121. package/src/types/desktop-window.ts +2 -0
  122. package/src/types/financials.ts +6 -0
  123. package/src/types/headless.ts +8 -0
  124. package/src/utils/cli-output.ts +6 -3
  125. package/src/utils/ebitda.ts +128 -0
  126. package/src/utils/format.ts +1 -1
  127. package/src/utils/shell-word.ts +13 -0
@@ -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",
@@ -17,6 +17,8 @@ import { currentValuationPrice, valuationPriceAtOrBefore, valuationQuoteIssue, t
17
17
  import type { SecuritySeriesSource, SeriesPeriod, TimeSeriesPoint } from "./types";
18
18
  import { isFiniteNumber } from "../utils/guards";
19
19
  import { liveForwardPE, liveTrailingPE } from "../market-data/quotes/live-valuation";
20
+ import { listingEnterpriseValue } from "../market-data/quotes/listing-enterprise-value";
21
+ import { BANK_OR_INSURER_EBITDA, isBankOrInsurerIndustry } from "../utils/ebitda";
20
22
  import { comparablePriceEarnings } from "../utils/price-earnings";
21
23
 
22
24
  type NumericStatementField =
@@ -27,6 +29,7 @@ type NumericStatementField =
27
29
  | "netIncomeIncludingNoncontrollingInterests"
28
30
  | "netIncomeCommonStockholders"
29
31
  | "ebitda"
32
+ | "depreciationAndAmortization"
30
33
  | "operatingCashFlow"
31
34
  | "capitalExpenditure"
32
35
  | "freeCashFlow"
@@ -57,6 +60,7 @@ const QUARTERLY_FLOW_FIELDS: readonly NumericStatementField[] = [
57
60
  "netIncome",
58
61
  "netIncomeIncludingNoncontrollingInterests",
59
62
  "ebitda",
63
+ "depreciationAndAmortization",
60
64
  "operatingCashFlow",
61
65
  "capitalExpenditure",
62
66
  "freeCashFlow",
@@ -94,6 +98,8 @@ const FUNDAMENTAL_IDS = new Set([
94
98
  "operatingMargin",
95
99
  "netIncome",
96
100
  "netMargin",
101
+ "ebitda",
102
+ "depreciationAndAmortization",
97
103
  "operatingCashFlow",
98
104
  "freeCashFlow",
99
105
  "freeCashFlowMargin",
@@ -880,7 +886,8 @@ function valuationAtPrice(
880
886
  // The probe at price=1 checks input coverage, not the historical EV sign.
881
887
  if (!checkingInputs && enterpriseValue !== null && enterpriseValue < 0 && (metric === "evSales" || metric === "evEbitda")) return null;
882
888
  if (metric === "evSales") return ratio(enterpriseValue, statement.totalRevenue);
883
- if (metric === "evEbitda") return ratio(enterpriseValue, statement.ebitda);
889
+ // Over EBITDA at or below zero the multiple means nothing (N/M), as a P/E over a loss.
890
+ if (metric === "evEbitda") return isFiniteNumber(statement.ebitda) && statement.ebitda > 0 ? ratio(enterpriseValue, statement.ebitda) : null;
884
891
  if (metric === "priceFcf") return ratio(marketCap, freeCashFlow(statement).value);
885
892
  return null;
886
893
  }
@@ -991,18 +998,62 @@ function servedTrailingPE(financials: TickerFinancials): number | null {
991
998
  }
992
999
 
993
1000
  /**
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.
1001
+ * A current EV multiple over the listing's enterprise value, the one
1002
+ * `valuation` and RV show (listingEnterpriseValue): EV/EBITDA and EV/S then
1003
+ * read one EV on every surface. A statement in another currency than the EV
1004
+ * (an ADR's EUR or TWD statements) is converted at the rate the EV's balance
1005
+ * sheet check was, as RV's EV/S converts revenue. Undefined to read the
1006
+ * statement's own (shares times the price, plus debt, less cash) where the
1007
+ * listing has none or no rate; null where it is not meaningful.
999
1008
  */
1000
- function currentDerivedValuationPoint(
1009
+ function listingEnterpriseMultiple(financials: TickerFinancials, statement: FinancialStatement, metric: string): number | null | undefined {
1010
+ if (metric !== "evEbitda" && metric !== "evSales") return undefined;
1011
+ if (metric === "evEbitda" && isBankOrInsurerIndustry(financials.profile?.industry)) return null;
1012
+ const listing = listingEnterpriseValue(financials);
1013
+ if (listing.kind === "not-meaningful") return null;
1014
+ if (listing.kind !== "value") return undefined;
1015
+ const rate = listingStatementRate(listing, statement.currency ?? financials.financialCurrency);
1016
+ if (rate === null) return undefined;
1017
+ const denominator = metric === "evEbitda" ? statement.ebitda : statement.totalRevenue;
1018
+ if (metric === "evEbitda" && !(isFiniteNumber(denominator) && denominator > 0)) return null;
1019
+ return ratio(listing.value, isFiniteNumber(denominator) ? denominator * rate : denominator);
1020
+ }
1021
+
1022
+ /** Units of the listing EV's currency per unit of the statement's: 1 in its own, the check's rate from another, null without one. */
1023
+ function listingStatementRate(listing: Extract<ReturnType<typeof listingEnterpriseValue>, { kind: "value" }>, currency: string | undefined): number | null {
1024
+ if (!currency || currency === listing.currency) return 1;
1025
+ return listing.fx && listing.fx.from === currency && isFiniteNumber(listing.fx.rate) && listing.fx.rate > 0 ? listing.fx.rate : null;
1026
+ }
1027
+
1028
+ /**
1029
+ * The rate a current EV multiple converted the statement at
1030
+ * (listingEnterpriseMultiple): `{ from: "EUR", rate: 1.133 }` for an ADR's
1031
+ * EUR statements under its USD EV; null in the EV's own currency.
1032
+ */
1033
+ export function listingStatementConversion(financials: TickerFinancials, statement: FinancialStatement): { from: string; rate: number; to: string } | null {
1034
+ const listing = listingEnterpriseValue(financials);
1035
+ const currency = statement.currency ?? financials.financialCurrency;
1036
+ if (listing.kind !== "value" || !currency || currency === listing.currency) return null;
1037
+ const rate = listingStatementRate(listing, currency);
1038
+ return rate === null ? null : { from: currency, rate, to: listing.currency };
1039
+ }
1040
+
1041
+ /**
1042
+ * The latest value of a statement-based multiple and the period it reads:
1043
+ * the regular session price (after the close, the close, dated by it) over
1044
+ * the latest period known when the quote was observed. The statements decide
1045
+ * whether there is one; a trailing P/E then takes the served one at that
1046
+ * price where there is one, so the chart ends on the P/E `valuation` prints,
1047
+ * and an EV multiple divides the listing's EV. `value` null where that period
1048
+ * gives none (a loss, EBITDA at or below zero, a missing line); null where
1049
+ * there is no period or price to read.
1050
+ */
1051
+ function currentDerivedValuation(
1001
1052
  financials: TickerFinancials,
1002
1053
  statements: readonly FinancialStatement[],
1003
1054
  metric: string,
1004
1055
  currencies: ValuationCurrencyContext,
1005
- ): TimeSeriesPoint | null {
1056
+ ): { value: number | null; date: Date; statement: FinancialStatement } | null {
1006
1057
  const quote = financials.quote;
1007
1058
  if (valuationQuoteIssue(quote)) return null;
1008
1059
  const quoteDate = validDate(quote?.lastUpdated);
@@ -1024,23 +1075,102 @@ function currentDerivedValuationPoint(
1024
1075
  ))
1025
1076
  .at(-1)?.candidate;
1026
1077
  if (!statement) return null;
1078
+ // The listing's EV needs no price in the statement's currency: an ADR's converts the statement instead.
1079
+ const listing = listingEnterpriseMultiple(financials, statement, metric);
1080
+ if (listing !== undefined) return { value: listing, date: current.date, statement };
1027
1081
  const comparablePrice = currencies.priceInStatementUnits(statement, current.price);
1028
1082
  if (comparablePrice === null) return null;
1029
1083
  const value = valuationAtPrice(statement, metric, comparablePrice);
1030
- if (value === null) return null;
1084
+ if (value === null) return { value: null, date: current.date, statement };
1085
+ return { value: (metric === "trailingPE" ? servedTrailingPE(financials) : null) ?? value, date: current.date, statement };
1086
+ }
1087
+
1088
+ /**
1089
+ * Why a current EV/EBITDA is N/M where the statement it reads has an EBITDA:
1090
+ * a bank's or an insurer's, or EBITDA at or below zero. Undefined otherwise.
1091
+ */
1092
+ function ebitdaNotMeaningful(financials: TickerFinancials, statement: FinancialStatement): string | undefined {
1093
+ if (isBankOrInsurerIndustry(financials.profile?.industry)) return BANK_OR_INSURER_EBITDA;
1094
+ return isFiniteNumber(statement.ebitda) && statement.ebitda <= 0 ? "Trailing EBITDA is not positive" : undefined;
1095
+ }
1096
+
1097
+ function currentDerivedValuationPoint(
1098
+ financials: TickerFinancials,
1099
+ statements: readonly FinancialStatement[],
1100
+ metric: string,
1101
+ currencies: ValuationCurrencyContext,
1102
+ ): TimeSeriesPoint | null {
1103
+ const current = currentDerivedValuation(financials, statements, metric, currencies);
1104
+ if (!current || current.value === null) return null;
1031
1105
  return {
1032
1106
  date: current.date,
1033
1107
  observedAt: current.date,
1034
1108
  availableAt: current.date,
1035
- value: (metric === "trailingPE" ? servedTrailingPE(financials) : null) ?? value,
1109
+ value: current.value,
1036
1110
  periodLabel: "Current",
1037
1111
  provenance: {
1038
- providerId: quote.providerId,
1112
+ providerId: financials.quote?.providerId,
1039
1113
  quality: "derived",
1040
1114
  },
1041
1115
  };
1042
1116
  }
1043
1117
 
1118
+ /**
1119
+ * The value GE's trailing-twelve-months series of a statement multiple ends
1120
+ * on, and the quarter its period ends with: the figure RV's added EV/EBITDA
1121
+ * column shows, so the two never disagree. `value` null with the reason where
1122
+ * it is not meaningful (`notMeaningful`, GE's N/M); null where GE draws no
1123
+ * current point and has no reason for it.
1124
+ */
1125
+ export function currentTrailingValuation(
1126
+ financials: TickerFinancials,
1127
+ metric: "evEbitda" | "evSales",
1128
+ ): { value: number | null; notMeaningful?: string; periodEnd: string; statement: FinancialStatement } | null {
1129
+ const current = currentValuation(financials, "ttm", metric);
1130
+ if (!current) return null;
1131
+ const dated = { periodEnd: current.statement.date.slice(0, 10), statement: current.statement };
1132
+ if (current.value !== null) return { value: current.value, ...dated };
1133
+ const notMeaningful = metric === "evEbitda" ? ebitdaNotMeaningful(financials, current.statement) : undefined;
1134
+ return notMeaningful ? { value: null, notMeaningful, ...dated } : null;
1135
+ }
1136
+
1137
+ function currentValuation(financials: TickerFinancials, period: SeriesPeriod | undefined, metric: string) {
1138
+ const selected = sourceStatements(financials, period, metric);
1139
+ return currentDerivedValuation(financials, currentValuationStatements(financials, selected, metric), metric,
1140
+ createValuationCurrencyContext(financials));
1141
+ }
1142
+
1143
+ /**
1144
+ * Why a valuation series ends on no value: EV/EBITDA is N/M for a bank or an
1145
+ * insurer, and over EBITDA at or below zero, as RV reads it. The period the
1146
+ * series would end on dates it. Undefined for any other series, or where its
1147
+ * current value is there.
1148
+ */
1149
+ export function valuationNotMeaningful(financials: TickerFinancials, source: SecuritySeriesSource): { reason: string; asOf: string } | undefined {
1150
+ const [namespace, metric = ""] = canonicalTimeSeriesFieldId(source.fieldId).split(".");
1151
+ if (namespace !== "valuation" || metric !== "evEbitda") return undefined;
1152
+ // A daily series ends on the trailing twelve months, as its current point does.
1153
+ const period = source.period === "daily" || source.period === "auto" || !source.period ? "ttm" : source.period;
1154
+ const current = currentValuation(financials, period, metric);
1155
+ if (current) {
1156
+ const reason = current.value === null ? ebitdaNotMeaningful(financials, current.statement) : undefined;
1157
+ return reason ? { reason, asOf: current.statement.date.slice(0, 10) } : undefined;
1158
+ }
1159
+ if (!isBankOrInsurerIndustry(financials.profile?.industry)) return undefined;
1160
+ const latest = sourceStatements(financials, period).statements.at(-1);
1161
+ return latest ? { reason: BANK_OR_INSURER_EBITDA, asOf: latest.date.slice(0, 10) } : undefined;
1162
+ }
1163
+
1164
+ /**
1165
+ * The trailing twelve months of a statement line the way GE's `ttm` series
1166
+ * reads it (four consecutive quarters, a fiscal fourth quarter completed from
1167
+ * its year): the latest one, or null when the latest window is incomplete.
1168
+ */
1169
+ export function latestTrailingStatement(financials: TickerFinancials): FinancialStatement | null {
1170
+ const selected = sourceStatements(financials, "ttm");
1171
+ return selected.statements.at(-1) ?? null;
1172
+ }
1173
+
1044
1174
  /**
1045
1175
  * The periods a Current multiple is read from: the selected ones, and beside
1046
1176
  * fiscal years the trailing twelve months the quarters after them sum to, so a
@@ -1162,6 +1292,8 @@ export function extractFundamentalSeries(
1162
1292
  }
1163
1293
 
1164
1294
  if (namespace !== "valuation" || !VALUATION_IDS.has(metric)) return [];
1295
+ // A bank's or an insurer's EBITDA measures nothing: its EV/EBITDA is N/M throughout (valuationNotMeaningful).
1296
+ if (metric === "evEbitda" && isBankOrInsurerIndustry(financials.profile?.industry)) return [];
1165
1297
  const fallback = dailyValuationFallbackPeriod(financials, source);
1166
1298
  if (fallback) return extractFundamentalSeries(financials, { ...source, period: fallback });
1167
1299
  if (source.period === "daily" && metric !== "realizedNtmPE") {
@@ -1,10 +1,12 @@
1
1
  /**
2
2
  * The ICE BofA credit indexes FRED publishes and Gloom Cloud serves: option
3
- * adjusted spreads by rating and region, and effective yields (US investment
4
- * grade and high yield, investment grade by maturity and by rating), all in
5
- * percent. One list for the CRD board, the data catalog, `fred`'s basis point
6
- * text and FRED's coverage notice. FRED publishes no euro investment grade
7
- * (ICE BofA Euro Corporate) spread, so the euro row is high yield only.
3
+ * adjusted spreads by rating and region (US, euro, and the emerging markets
4
+ * corporate indexes by grade and by region), and effective yields (US
5
+ * investment grade and high yield, investment grade by maturity and by
6
+ * rating), all in percent. One list for the CRD board, the data catalog,
7
+ * `fred`'s basis point text and FRED's coverage notice. FRED publishes no euro
8
+ * investment grade (ICE BofA Euro Corporate) spread, so the euro row is high
9
+ * yield only.
8
10
  */
9
11
  export interface IceCreditSeries {
10
12
  seriesId: string;
@@ -13,7 +15,8 @@ export interface IceCreditSeries {
13
15
  /** The data catalog's name. */
14
16
  name: string;
15
17
  measure: "spread" | "yield";
16
- region: "us" | "euro";
18
+ /** Asia is an emerging markets region too, listed on its own so it can be read alone. */
19
+ region: "us" | "euro" | "em" | "asia";
17
20
  tags: readonly string[];
18
21
  }
19
22
 
@@ -21,6 +24,7 @@ export interface IceCreditSeries {
21
24
  export const ICE_HISTORY_LIMIT_NOTICE = "History limited to 3 years by the publisher.";
22
25
 
23
26
  const HIGH_YIELD = ["high yield", "junk"];
27
+ const EMERGING = ["EM", "emerging markets"];
24
28
 
25
29
  export const ICE_CREDIT_SERIES: readonly IceCreditSeries[] = [
26
30
  { seriesId: "BAMLC0A0CM", label: "US IG", name: "US investment grade corporate OAS", measure: "spread", region: "us", tags: ["IG", "investment grade"] },
@@ -33,6 +37,18 @@ export const ICE_CREDIT_SERIES: readonly IceCreditSeries[] = [
33
37
  { seriesId: "BAMLH0A2HYB", label: "B", name: "Single-B high yield OAS", measure: "spread", region: "us", tags: ["single B", "HY", ...HIGH_YIELD] },
34
38
  { seriesId: "BAMLH0A3HYC", label: "CCC", name: "CCC and lower high yield OAS", measure: "spread", region: "us", tags: ["CCC", "HY", "distressed", ...HIGH_YIELD] },
35
39
  { seriesId: "BAMLHE00EHYIOAS", label: "Euro HY", name: "Euro high yield OAS", measure: "spread", region: "euro", tags: ["euro", "EUR", "Europe", "HY", ...HIGH_YIELD] },
40
+ // ICE BofA's emerging markets Corporate Plus indexes: the whole, by grade, then by region.
41
+ { seriesId: "BAMLEMCBPIOAS", label: "EM Corp", name: "Emerging markets corporate OAS", measure: "spread", region: "em", tags: EMERGING },
42
+ { seriesId: "BAMLEMIBHGCRPIOAS", label: "EM IG", name: "Emerging markets investment grade corporate OAS", measure: "spread", region: "em",
43
+ tags: [...EMERGING, "IG", "investment grade", "high grade"] },
44
+ { seriesId: "BAMLEMHBHYCRPIOAS", label: "EM HY", name: "Emerging markets high yield corporate OAS", measure: "spread", region: "em",
45
+ tags: [...EMERGING, "HY", ...HIGH_YIELD] },
46
+ { seriesId: "BAMLEMRACRPIASIAOAS", label: "Asia EM", name: "Asia emerging markets corporate OAS", measure: "spread", region: "asia",
47
+ tags: [...EMERGING, "Asia", "Asian", "China", "Singapore", "SGD"] },
48
+ { seriesId: "BAMLEMRLCRPILAOAS", label: "LatAm EM", name: "Latin America emerging markets corporate OAS", measure: "spread", region: "em",
49
+ tags: [...EMERGING, "Latin America", "LatAm"] },
50
+ { seriesId: "BAMLEMRECRPIEMEAOAS", label: "EMEA EM", name: "EMEA emerging markets corporate OAS", measure: "spread", region: "em",
51
+ tags: [...EMERGING, "EMEA", "Europe, Middle East and Africa"] },
36
52
  { seriesId: "BAMLC0A0CMEY", label: "US IG yld", name: "US investment grade corporate effective yield", measure: "yield", region: "us", tags: ["IG", "investment grade"] },
37
53
  { seriesId: "BAMLH0A0HYM2EY", label: "US HY yld", name: "US high yield effective yield", measure: "yield", region: "us", tags: ["HY", ...HIGH_YIELD] },
38
54
  // Investment grade by maturity, to read a corporate against the Treasury of its tenor, then by rating.
@@ -55,3 +71,13 @@ export const ICE_CREDIT_SERIES_IDS: ReadonlySet<string> = new Set(ICE_CREDIT_SER
55
71
 
56
72
  /** The option-adjusted spreads, which FRED serves in percentage points. */
57
73
  export const ICE_SPREAD_SERIES: readonly IceCreditSeries[] = ICE_CREDIT_SERIES.filter((series) => series.measure === "spread");
74
+
75
+ const ICE_SPREAD_SERIES_IDS: ReadonlySet<string> = new Set(ICE_SPREAD_SERIES.map((series) => series.seriesId));
76
+
77
+ /**
78
+ * Whether a FRED series is an ICE option-adjusted spread, which every surface
79
+ * shows in basis points (FRED serves 0.93 for 93bp), as credit desks quote it.
80
+ */
81
+ export function isIceSpreadSeries(seriesId: string): boolean {
82
+ return ICE_SPREAD_SERIES_IDS.has(seriesId.trim().toUpperCase());
83
+ }
@@ -107,6 +107,7 @@ import {
107
107
  followLatestMarketObservation,
108
108
  capabilityRequestBounds,
109
109
  endAtNewestObservation,
110
+ startAtOldestObservation,
110
111
  latestSessionView,
111
112
  } from "./chart-bounds";
112
113
  import {
@@ -1067,11 +1068,14 @@ async function resolveChartSpecPass(
1067
1068
  : latestDaily - 7 * CHART_RESOLUTION_STEP_MS["1d"],
1068
1069
  end: latestDaily,
1069
1070
  };
1071
+ // A chart of published series alone (FRED, Gloom Cloud datasets) opens where they start, not on blank years.
1072
+ const publishedOnly = spec.series.length > 0 && spec.series.every(({ source }) => source.kind !== "security");
1073
+ const presetBounds = isDatasetChart(spec)
1074
+ ? endAtNewestObservation(initialVisibleBounds, rawSeries)
1075
+ : followLatestMarketObservation(initialVisibleBounds, rawSeries);
1070
1076
  const bounds = hasExplicitWindow
1071
1077
  ? requestVisibleBounds
1072
- : dailyBounds ?? sessionView?.bounds ?? (isDatasetChart(spec)
1073
- ? endAtNewestObservation(initialVisibleBounds, rawSeries)
1074
- : followLatestMarketObservation(initialVisibleBounds, rawSeries));
1078
+ : dailyBounds ?? sessionView?.bounds ?? (publishedOnly ? startAtOldestObservation(presetBounds, rawSeries) : presetBounds);
1075
1079
  if (sessionView?.priorClose != null && primaryRaw?.transform === "raw"
1076
1080
  && primaryRaw.unitGroup.startsWith("price") && primaryRaw.unitGroup !== "price:unknown") {
1077
1081
  const index = rawSeries.indexOf(primaryRaw);
@@ -1177,8 +1181,8 @@ async function resolveChartSpecPass(
1177
1181
  if (entry.warning) warnings.push(`${entry.label}: ${entry.warning}`);
1178
1182
  if (entry.points.length === 0 && entry.unreportedPeriod) {
1179
1183
  warnings.push(`${entry.label}: no ${entry.unreportedPeriod} figures are reported; annual figures are available.`);
1180
- } else if (entry.points.length === 0 && !entry.warning?.startsWith(VALUATION_CURRENCY_WARNING_PREFIX)) {
1181
- // A currency mismatch already explains an empty valuation series.
1184
+ } else if (entry.points.length === 0 && !entry.notMeaningful && !entry.warning?.startsWith(VALUATION_CURRENCY_WARNING_PREFIX)) {
1185
+ // A currency mismatch or an N/M already explains an empty valuation series.
1182
1186
  warnings.push(`${entry.label}: no observations in the selected date range.`);
1183
1187
  }
1184
1188
  }
@@ -1,11 +1,13 @@
1
1
  import type { PricePoint, Quote } from "../types/financials";
2
2
  import { classifyInstrumentType, kindFromListingSyntax } from "../tickers/instrument-kind";
3
- import { isAlwaysOpenExchange, isRegularSessionTime, sessionCalendarTimeZone } from "../market-data/market/freshness";
3
+ import { isAlwaysOpenExchange, isRegularSessionTime, latestRegularSessionClose, sessionCalendarTimeZone } from "../market-data/market/freshness";
4
+ import { DAILY_BAR_CLOSE_VENUES } from "../market-data/market/dated-previous-close";
4
5
  import { quoteTradingDay } from "../market-data/quotes/day-range";
6
+ import { canonicalExchange } from "../utils/exchanges";
5
7
  import { hasLikelyQuoteUnitMismatch } from "../utils/currency-units";
6
8
  import { pricePointIntegrity } from "../utils/price-history-integrity";
7
9
  import { zonedDateKey } from "../utils/zoned-date-time";
8
- import { barSizeFromGap, medianBarGap } from "./bar-spacing";
10
+ import { barSizeFromGap, medianBarGap, requestedBarSize } from "./bar-spacing";
9
11
  import { calendarBarStart, liveQuoteObservation } from "./chart-data";
10
12
 
11
13
  const DAY_MS = 24 * 60 * 60_000;
@@ -20,8 +22,41 @@ export interface SessionBarOptions {
20
22
  /** The listing's venue, when the caller knows it; otherwise the quote's. */
21
23
  venue?: string;
22
24
  assetCategory?: string;
25
+ /**
26
+ * The bar size the history was asked for or served in, when the caller
27
+ * knows it. Without it the size is read from the bars' spacing, which a
28
+ * thinly traded listing (a trade every week or two) makes look weekly.
29
+ */
30
+ barSize?: "1d" | "1wk" | "1mo";
23
31
  }
24
32
 
33
+ /** The `barSize` option for a history asked for in `resolution` bars: daily or longer ones only. */
34
+ export function dailyOrLongerBarSize(resolution: string | null | undefined): Pick<SessionBarOptions, "barSize"> {
35
+ return resolution === "1d" || resolution === "1wk" || resolution === "1mo" ? { barSize: resolution } : {};
36
+ }
37
+
38
+ /**
39
+ * The bar size withSessionBar is told for bars asked as `requested`: the
40
+ * request, unless the source stated another (`stated`) or the bars' spacing
41
+ * shows them finer, or coarser and starting their periods (requestedBarSize).
42
+ * A 5Y range asks for weekly bars; served daily, Thursday's bar is a day, and
43
+ * Friday's live price is a bar of its own, not Thursday's close.
44
+ */
45
+ export function requestedSessionBarSize(
46
+ points: readonly Pick<PricePoint, "date">[],
47
+ requested: string | null | undefined,
48
+ stated?: string | null,
49
+ ): Pick<SessionBarOptions, "barSize"> {
50
+ const asked = dailyOrLongerBarSize(requested).barSize;
51
+ return asked ? { barSize: requestedBarSize(points.map((point) => new Date(point.date).getTime()), asked, stated) } : {};
52
+ }
53
+
54
+ /**
55
+ * How long after its session closes a day's bar is final: a delayed quote
56
+ * runs up to twenty minutes behind, and a closing auction prints at the bell.
57
+ */
58
+ const SESSION_SETTLE_MS = 30 * 60_000;
59
+
25
60
  function barTime(point: Pick<PricePoint, "date">): number {
26
61
  const date = point.date as Date | string | number;
27
62
  return (date instanceof Date ? date : new Date(date)).getTime();
@@ -95,15 +130,18 @@ export function withSessionBar(
95
130
  options: SessionBarOptions,
96
131
  ): PricePoint[] {
97
132
  const last = points.at(-1);
98
- if (!last || points.length < 2) return points;
133
+ if (!last || (points.length < 2 && !options.barSize)) return points;
99
134
  const times = points.map(barTime);
100
135
  const lastTime = times.at(-1)!;
101
136
  const gap = medianBarGap(times);
102
- if (!Number.isFinite(lastTime) || gap === null || gap < DAILY_BAR_MIN_GAP_MS) return points;
103
- const size = barSizeFromGap(gap);
137
+ if (!Number.isFinite(lastTime) || (!options.barSize && (gap === null || gap < DAILY_BAR_MIN_GAP_MS))) return points;
138
+ // The size asked for, not the spacing: a listing that trades once a fortnight still has daily bars.
139
+ const size = options.barSize ?? barSizeFromGap(gap!);
104
140
  const venue = options.venue || quote?.listingExchangeName || quote?.exchangeName || undefined;
105
141
  if (venue && isAlwaysOpenExchange(venue)) return points;
106
142
  if (quote && !tradesInSessions(quote, venue)) return points;
143
+ const settled = quote ? settledSessionBar(points, last, lastTime, size, quote, venue, options.now) : null;
144
+ if (settled) return settled;
107
145
 
108
146
  // A quote that does not say its session is read by the venue's calendar.
109
147
  const trading = quote?.marketState === "REGULAR" || (quote?.marketState == null && isRegularSessionTime(venue, options.now) === true);
@@ -137,13 +175,44 @@ export function withSessionBar(
137
175
  return points;
138
176
  }
139
177
 
178
+ /**
179
+ * A day's bar the source still marks partial once its session has closed:
180
+ * the session's quote, read after the close, is that day's last price, so
181
+ * the bar takes it (with the day's extremes and volume, which only grow) and
182
+ * is final. A thin listing's Friday bar is no longer partial on Sunday.
183
+ * Null when the bar is not such a bar, or the quote is not from its session,
184
+ * and on a venue whose closed quote can end on a print after its closing call
185
+ * (B3): its official close is the source's bar, which is waited for.
186
+ */
187
+ function settledSessionBar(
188
+ points: PricePoint[],
189
+ last: PricePoint,
190
+ lastTime: number,
191
+ size: "1d" | "1wk" | "1mo",
192
+ quote: Quote,
193
+ venue: string | undefined,
194
+ now: number,
195
+ ): PricePoint[] | null {
196
+ if (size !== "1d" || !last.partial || quote.marketState === "REGULAR" || !positive(quote.price)) return null;
197
+ if (venue && DAILY_BAR_CLOSE_VENUES.has(canonicalExchange(venue))) return null;
198
+ const day = calendarBarStart(lastTime, "1d", venue);
199
+ const closed = latestRegularSessionClose(venue, now - SESSION_SETTLE_MS);
200
+ if (!closed || closed.date < day || quoteTradingDay(quote) !== day) return null;
201
+ if (hasLikelyQuoteUnitMismatch({ currency: quote.currency, price: last.close }, { currency: quote.currency, price: quote.price })) return null;
202
+ const { partial: _partial, ...bar } = sessionBar(last, last.date, quote, quote.price);
203
+ return [...points.slice(0, -1), bar];
204
+ }
205
+
140
206
  /**
141
207
  * The daily bars `history` shows as final, which alerts on a daily close read
142
208
  * too: the bars as served, less the bar of a session still trading
143
209
  * (withSessionBar, which `history` rebuilds from the quote and marks partial)
144
- * and any bar the source marks partial. A close `history` prints without
145
- * `partial` is final here, and one it prints with it is not.
210
+ * and any bar still partial. A bar the source marks partial after its session
211
+ * has settled takes that session's `quote` and is final, as `history` makes
212
+ * it (settledSessionBar); with no quote from its session it stays partial.
213
+ * A close `history` prints without `partial` is final here, and one it prints
214
+ * with it is not.
146
215
  */
147
- export function finalDailyBars(points: PricePoint[], options: SessionBarOptions): PricePoint[] {
148
- return withSessionBar(points, null, options).filter((point) => !point.partial);
216
+ export function finalDailyBars(points: PricePoint[], options: SessionBarOptions, quote?: Quote | null): PricePoint[] {
217
+ return withSessionBar(points, quote ?? null, options).filter((point) => !point.partial);
149
218
  }