gloomberb 0.20.8 → 0.20.9

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 (42) hide show
  1. package/package.json +1 -1
  2. package/src/api-client/futures-curve.ts +5 -1
  3. package/src/cli/commands/overview.ts +2 -0
  4. package/src/cli/pane-functions/data.ts +3 -2
  5. package/src/cli/pane-functions/headless.ts +1 -0
  6. package/src/cli/symbol-cells.ts +6 -0
  7. package/src/cli/symbol-list.ts +14 -6
  8. package/src/cli/symbol-rows.ts +12 -5
  9. package/src/components/ui/page-stack-view.tsx +24 -6
  10. package/src/market-data/futures-roll-returns.ts +226 -0
  11. package/src/market-data/market/session-close-note.ts +41 -4
  12. package/src/market-data/quotes/listing-enterprise-value.ts +8 -4
  13. package/src/plugins/builtin/backtest/client.ts +9 -2
  14. package/src/plugins/builtin/backtest/pane.tsx +1 -1
  15. package/src/plugins/builtin/backtest/report.ts +22 -6
  16. package/src/plugins/builtin/backtest/window.ts +17 -9
  17. package/src/plugins/builtin/correlation/headless.ts +6 -2
  18. package/src/plugins/builtin/correlation/index.tsx +7 -3
  19. package/src/plugins/builtin/correlation/matrix/model.ts +15 -1
  20. package/src/plugins/builtin/correlation/relationship/model.ts +15 -1
  21. package/src/plugins/builtin/correlation/relationship/pane.tsx +4 -2
  22. package/src/plugins/builtin/futures-curve/headless.ts +4 -1
  23. package/src/plugins/builtin/futures-curve/model.ts +24 -0
  24. package/src/plugins/builtin/kelly-sizer/headless.ts +2 -2
  25. package/src/plugins/builtin/kelly-sizer/history.ts +10 -3
  26. package/src/plugins/builtin/kelly-sizer/pane.tsx +2 -2
  27. package/src/plugins/builtin/kelly-sizer/sections.tsx +1 -1
  28. package/src/plugins/builtin/realized-vol/headless.ts +11 -6
  29. package/src/plugins/builtin/realized-vol/model.ts +14 -6
  30. package/src/plugins/builtin/realized-vol/pane.tsx +2 -1
  31. package/src/plugins/builtin/realized-vol/settings.ts +2 -1
  32. package/src/plugins/builtin/seasonality/client.ts +66 -17
  33. package/src/plugins/builtin/seasonality/headless.ts +7 -2
  34. package/src/plugins/builtin/seasonality/model.ts +12 -3
  35. package/src/plugins/builtin/seasonality/pane.tsx +4 -2
  36. package/src/plugins/builtin/shared/use-quote-board.ts +28 -6
  37. package/src/renderers/dom/desktop/controls.tsx +1 -1
  38. package/src/renderers/dom/styles.css +7 -4
  39. package/src/renderers/opentui/box-width.ts +30 -0
  40. package/src/types/financials.ts +16 -3
  41. package/src/types/headless.ts +6 -0
  42. package/src/utils/fundamentals.ts +49 -8
@@ -1,6 +1,7 @@
1
1
  import { unavailableText } from "../../../components/ui/status";
2
2
  import { getSharedMarketDataCoordinator, MarketDataCoordinator, resolveEntryValue } from "../../../market-data/coordinator";
3
- import type { InstrumentRef } from "../../../market-data/request-types";
3
+ import { isContinuousFuture, rollAdjustedHistory } from "../../../market-data/futures-roll-returns";
4
+ import type { ChartRequest, InstrumentRef } from "../../../market-data/request-types";
4
5
  import type { ManualChartResolution } from "../../../time-series/resolution";
5
6
  import type { DataProvider } from "../../../types/data-provider";
6
7
  import type { PricePoint } from "../../../types/financials";
@@ -12,6 +13,14 @@ export interface SeasonalityHistory {
12
13
  stale: boolean;
13
14
  error: string | null;
14
15
  fetchedAt: number;
16
+ /** A continuous future's returns, read within one contract at each roll: "rolls back-adjusted" (rollAdjustedHistory). */
17
+ rollNote?: string;
18
+ /**
19
+ * The bars as served and their size, what a capture hands the pane to read
20
+ * again: a continuous future's daily bars before their rolls were closed,
21
+ * anything else's `history` itself.
22
+ */
23
+ served: { points: PricePoint[]; resolution: ManualChartResolution };
15
24
  }
16
25
 
17
26
  /** Monthly closes for the Returns and Overlay tabs, daily closes for Weekdays. */
@@ -19,27 +28,63 @@ export type SeasonalityCadence = "monthly" | "daily";
19
28
 
20
29
  const CANCELLED = "Seasonality history load was cancelled";
21
30
  /** The cadence each tab reads, and so the cadence a screenshot of it captures. */
22
- export const SEASONALITY_HISTORY_RESOLUTION: Record<SeasonalityCadence, ManualChartResolution> = { monthly: "1mo", daily: "1d" };
31
+ const SEASONALITY_HISTORY_RESOLUTION: Record<SeasonalityCadence, ManualChartResolution> = { monthly: "1mo", daily: "1d" };
23
32
  /** Daily history is served to five years; a longer request can come back as weekly bars. */
24
33
  const BUFFER_RANGE = { monthly: "ALL", daily: "5Y" } as const;
25
34
 
35
+ /**
36
+ * The bars a tab reads: monthly or daily ones, and for a continuous future
37
+ * (NG=F) daily ones either way, the newest a read returns (all of NG=F's,
38
+ * from August 2000), whose rolls are back-adjusted before the months are
39
+ * taken. A lookback reaching before them says where they start
40
+ * (SeasonalityModel.historyStart).
41
+ */
42
+ function seasonalityRequest(instrument: InstrumentRef, cadence: SeasonalityCadence): ChartRequest {
43
+ if (isContinuousFuture(instrument.symbol)) {
44
+ return { instrument, bufferRange: "ALL", granularity: "resolution", resolution: "1d", newestBars: true };
45
+ }
46
+ return { instrument, bufferRange: BUFFER_RANGE[cadence], granularity: "resolution", resolution: SEASONALITY_HISTORY_RESOLUTION[cadence] };
47
+ }
48
+
49
+ /**
50
+ * A continuous future's daily bars with every roll back-adjusted, as the tab
51
+ * reads them: the Weekdays tab the last five years of sessions, the others
52
+ * each month's last close dated by the month's first day, as monthly bars
53
+ * are. Anything else as served.
54
+ */
55
+ function seasonalitySeries(
56
+ bars: readonly PricePoint[], symbol: string, cadence: SeasonalityCadence,
57
+ ): Pick<SeasonalityHistory, "history" | "rollNote" | "served"> {
58
+ if (!isContinuousFuture(symbol)) {
59
+ return { history: [...bars], served: { points: [...bars], resolution: SEASONALITY_HISTORY_RESOLUTION[cadence] } };
60
+ }
61
+ const adjusted = rollAdjustedHistory(bars, symbol);
62
+ const note = { served: { points: [...bars], resolution: "1d" as const }, ...adjusted.note ? { rollNote: adjusted.note } : {} };
63
+ if (cadence === "daily") {
64
+ const from = new Date(adjusted.points.at(-1)?.date ?? 0);
65
+ from.setUTCFullYear(from.getUTCFullYear() - 5);
66
+ return { history: adjusted.points.filter((point) => new Date(point.date).getTime() > from.getTime()), ...note };
67
+ }
68
+ const months = new Map<string, PricePoint>();
69
+ for (const point of adjusted.points) {
70
+ const day = new Date(point.date).toISOString();
71
+ months.set(day.slice(0, 7), { date: new Date(`${day.slice(0, 7)}-01T00:00:00Z`), close: point.close });
72
+ }
73
+ return { history: [...months.values()], ...note };
74
+ }
75
+
26
76
  export function cachedSeasonalityHistory(
27
77
  request: { instrument: InstrumentRef; cadence?: SeasonalityCadence },
28
78
  ): SeasonalityHistory | null {
29
79
  const coordinator = getSharedMarketDataCoordinator();
30
80
  if (!coordinator) return null;
31
81
  const cadence = request.cadence ?? "monthly";
32
- const entry = coordinator.getChartEntry({
33
- instrument: request.instrument,
34
- bufferRange: BUFFER_RANGE[cadence],
35
- granularity: "resolution",
36
- resolution: SEASONALITY_HISTORY_RESOLUTION[cadence],
37
- });
38
- const history = resolveEntryValue(entry);
39
- if (!history?.length) return null;
82
+ const entry = coordinator.getChartEntry(seasonalityRequest(request.instrument, cadence));
83
+ const served = resolveEntryValue(entry);
84
+ if (!served?.length) return null;
40
85
  const now = Date.now();
41
86
  return {
42
- history,
87
+ ...seasonalitySeries(served, request.instrument.symbol, cadence),
43
88
  stale: !!entry.error || (entry.staleAt != null && entry.staleAt <= now),
44
89
  error: entry.error?.message ?? null,
45
90
  fetchedAt: entry.fetchedAt ?? now,
@@ -51,7 +96,9 @@ export function cachedSeasonalityHistory(
51
96
  * refetches. Monthly bars, because daily history is only served to 5Y where
52
97
  * provider support is not known yet, and a longer daily request comes back as
53
98
  * Monday-stamped weeks that file a week's close under the wrong month. The
54
- * Weekdays tab needs sessions, so it reads those five years of daily bars.
99
+ * Weekdays tab needs sessions, so it reads those five years of daily bars. A
100
+ * continuous future reads the newest daily bars a request returns for every
101
+ * tab, so its rolls can be back-adjusted (seasonalitySeries).
55
102
  */
56
103
  export async function loadSeasonalityHistory(
57
104
  request: { instrument: InstrumentRef; cadence?: SeasonalityCadence; signal?: AbortSignal; forceRefresh?: boolean },
@@ -63,14 +110,16 @@ export async function loadSeasonalityHistory(
63
110
  const coordinator = marketData ? new MarketDataCoordinator(marketData) : getSharedMarketDataCoordinator();
64
111
  try {
65
112
  if (!coordinator) throw new Error("Market data coordinator unavailable");
66
- const entry = await abortable(coordinator.loadChart({ instrument: request.instrument, bufferRange: BUFFER_RANGE[cadence],
67
- granularity: "resolution", resolution: SEASONALITY_HISTORY_RESOLUTION[cadence] }, { forceRefresh: request.forceRefresh }), request.signal, CANCELLED);
68
- const history = resolveEntryValue(entry) ?? [];
69
- return { history, stale: !!entry.error || (entry.staleAt != null && entry.staleAt <= now),
113
+ const entry = await abortable(coordinator.loadChart(seasonalityRequest(request.instrument, cadence),
114
+ { forceRefresh: request.forceRefresh }), request.signal, CANCELLED);
115
+ const series = seasonalitySeries(resolveEntryValue(entry) ?? [], request.instrument.symbol, cadence);
116
+ const history = series.history;
117
+ return { ...series, stale: !!entry.error || (entry.staleAt != null && entry.staleAt <= now),
70
118
  error: entry.error?.message ?? (history.length ? null : unavailableText(cadence === "daily" ? "Daily price history" : "Monthly price history")),
71
119
  fetchedAt: entry.fetchedAt ?? now };
72
120
  } catch (error) {
73
121
  if (request.signal?.aborted || (error instanceof Error && error.name === "AbortError")) throw abortError(CANCELLED);
74
- return { history: [], stale: false, error: errorMessage(error), fetchedAt: now };
122
+ return { history: [], stale: false, error: errorMessage(error), fetchedAt: now,
123
+ served: { points: [], resolution: SEASONALITY_HISTORY_RESOLUTION[cadence] } };
75
124
  }
76
125
  }
@@ -26,7 +26,7 @@ export const seasonalityHeadless: HeadlessPaneDefinition<"bundle"> = {
26
26
  const weekdays = args.options.tab === "weekdays";
27
27
  const history = await loadSeasonalityHistory({ instrument, cadence: weekdays ? "daily" : "monthly", signal: ctx.signal }, ctx.marketData);
28
28
  ctx.signal.throwIfAborted();
29
- const common = { errors: history.error ? [history.error] : [] };
29
+ const common = { errors: history.error ? [history.error] : [], ...(history.rollNote ? { notes: [history.rollNote] } : {}) };
30
30
  if (weekdays) {
31
31
  const model = projectWeekdays(history.history, { symbol: instrument.symbol, exchange: instrument.exchange, fetchedAt: history.fetchedAt });
32
32
  const present = model.start != null;
@@ -47,7 +47,11 @@ export const seasonalityHeadless: HeadlessPaneDefinition<"bundle"> = {
47
47
  fetchedAt: history.fetchedAt, methodology: "docs/research-data.md#seasonality" },
48
48
  };
49
49
  }
50
- const model = projectSeasonality(history.history, { symbol: instrument.symbol, lookbackYears: Number(args.options.lookbackYears) || 10 });
50
+ const lookbackYears = Number(args.options.lookbackYears) || 10;
51
+ const model = projectSeasonality(history.history, { symbol: instrument.symbol, lookbackYears });
52
+ // A lookback past the first month on record says where the years it covers start.
53
+ const coverage = model.historyStart
54
+ ? `History starts ${model.historyStart}, so the ${lookbackYears}-year lookback covers ${model.years.length} calendar year${model.years.length === 1 ? "" : "s"}` : null;
51
55
  // Monthly bars are dated by their month's first day, which is no close while the month runs.
52
56
  const bar = model.asOf?.toISOString().slice(0, 10);
53
57
  // The venue whose sessions say whether the month still runs: the key's, or for a bare symbol its quote's.
@@ -66,6 +70,7 @@ export const seasonalityHeadless: HeadlessPaneDefinition<"bundle"> = {
66
70
  complete: !history.stale && !history.error && model.years.length > 0,
67
71
  unavailableSymbols: model.years.length ? [] : [instrument.symbol],
68
72
  ...common,
73
+ ...(coverage ? { notes: [...common.notes ?? [], coverage] } : {}),
69
74
  ...(forming ? { freshness: { periodToDate: forming } } : closed ? { freshness: { asOf: closed } } : {}),
70
75
  metadata: { unit: "decimal return, local-price close to close", asOf: model.asOf?.toISOString() ?? null, stale: history.stale,
71
76
  fetchedAt: history.fetchedAt, averagePath: model.averagePath, methodology: "docs/research-data.md#seasonality" },
@@ -40,6 +40,12 @@ export interface SeasonalityModel {
40
40
  /** Mean of the completed years' paths at each month-end every one of them reached. */
41
41
  averagePath: SeasonalityPathPoint[];
42
42
  asOf: Date | null;
43
+ /**
44
+ * The first month on record ("2000-08") when the lookback reaches before
45
+ * it: a 30-year lookback on NG=F, whose history starts in 2000, covers the
46
+ * years since. Null when the history covers every year asked for.
47
+ */
48
+ historyStart: string | null;
43
49
  }
44
50
 
45
51
  const monthKey = (year: number, month: number) => year * 12 + month;
@@ -79,7 +85,7 @@ export function projectSeasonality(history: readonly PricePoint[], options: { sy
79
85
  const points = medianGapDays(sorted) >= 5 && medianGapDays(sorted) <= 9
80
86
  ? sorted.map((point) => ({ ...point, date: new Date(point.date.getTime() + 4 * DAY_MS) })) : sorted;
81
87
  const last = points.at(-1);
82
- if (!last) return { symbol: options.symbol, years: [], months: [], paths: [], averagePath: [], asOf: null };
88
+ if (!last) return { symbol: options.symbol, years: [], months: [], paths: [], averagePath: [], asOf: null, historyStart: null };
83
89
 
84
90
  const monthEnd = new Map<number, number>();
85
91
  for (const point of points) monthEnd.set(monthKey(point.date.getUTCFullYear(), point.date.getUTCMonth()), point.close);
@@ -89,7 +95,10 @@ export function projectSeasonality(history: readonly PricePoint[], options: { sy
89
95
  // bars are stamped at the month's start, so their date cannot say more.
90
96
  const complete = last.date.getUTCMonth() === 11;
91
97
  const runningMonthKey = complete ? null : monthKey(lastYear, last.date.getUTCMonth());
92
- const firstYear = Math.max(points[0]!.date.getUTCFullYear(), lastYear - Math.max(1, options.lookbackYears) + 1);
98
+ const askedFirstYear = lastYear - Math.max(1, options.lookbackYears) + 1;
99
+ const firstYear = Math.max(points[0]!.date.getUTCFullYear(), askedFirstYear);
100
+ // The asked-for first year's January needs the December before it.
101
+ const historyStart = points[0]!.date.getTime() >= Date.UTC(askedFirstYear, 0, 1) ? points[0]!.date.toISOString().slice(0, 7) : null;
93
102
  const years: SeasonalityYear[] = [];
94
103
  const paths: SeasonalityModel["paths"] = [];
95
104
  /** Per completed year, return since the prior year-end at each month-end. */
@@ -124,7 +133,7 @@ export function projectSeasonality(history: readonly PricePoint[], options: { sy
124
133
  return values.every((value) => value != null) ? [{ date: overlayMonthEnd(month), value: mean(values as number[])! }] : [];
125
134
  })] : [];
126
135
 
127
- return { symbol: options.symbol, years, months, paths, averagePath, asOf: last.date };
136
+ return { symbol: options.symbol, years, months, paths, averagePath, asOf: last.date, historyStart };
128
137
  }
129
138
 
130
139
  /** Monday first; a Saturday or Sunday row appears only for a venue that trades then. */
@@ -177,8 +177,10 @@ export function SeasonalityPane({ width, height, focused }: PaneProps) {
177
177
 
178
178
  usePaneNoticeFooter({ registrationId: "seasonality-notices", focused,
179
179
  notices: [...new Set([identityError, history.error, history.data?.error].filter((value): value is string => !!value))] });
180
- const closes = model?.asOf ? `monthly closes to ${model.asOf.toISOString().slice(0, 7)}`
181
- : weekdayModel?.start ? `daily closes ${weekdayModel.start} to ${weekdayModel.asOf}` : null;
180
+ const rolls = history.data?.rollNote ? ` · ${history.data.rollNote}` : "";
181
+ // From the first month on record when the lookback reaches before it.
182
+ const closes = model?.asOf ? `monthly closes ${model.historyStart ? `${model.historyStart} ` : ""}to ${model.asOf.toISOString().slice(0, 7)}${rolls}`
183
+ : weekdayModel?.start ? `daily closes ${weekdayModel.start} to ${weekdayModel.asOf}${rolls}` : null;
182
184
  usePaneFooter("seasonality", () => ({ info: [
183
185
  ...(history.loading ? [{ id: "loading", parts: [{ text: "loading history", tone: "muted" as const }] }] : []),
184
186
  ...(history.data?.stale ? [{ id: "stale", parts: [{ text: "stale history", tone: "warning" as const }] }] : []),
@@ -100,18 +100,32 @@ function isFlaggedStale(quote: Quote): boolean {
100
100
  return quote.stale === true && !quote.delisting;
101
101
  }
102
102
 
103
+ /**
104
+ * What a load hands the board for a symbol. `interim`: the batch's dated
105
+ * price for a symbol it left to be asked for alone, shown meanwhile only on
106
+ * a row that has no quote yet (mergeQuotes).
107
+ */
108
+ type LoadedQuoteState = BoardQuoteState & { interim?: true };
109
+ type LoadedQuoteMap = Map<string, LoadedQuoteState>;
110
+
103
111
  /**
104
112
  * A failed refresh must not blank a board that was showing prices a second
105
113
  * ago: keep the last good quote and mark it stale instead. A load that
106
114
  * brings only a price flagged stale shows the newer of it and the last one,
107
- * marked stale too.
115
+ * marked stale too. An interim price fills only a row with no quote, which
116
+ * stays loading until its own read answers; a row that has one keeps it as
117
+ * it is, so a background top-up never marks it loading or stale.
108
118
  */
109
- function mergeQuotes(previous: BoardQuoteMap, loaded: BoardQuoteMap): BoardQuoteMap {
119
+ function mergeQuotes(previous: BoardQuoteMap, loaded: LoadedQuoteMap): BoardQuoteMap {
110
120
  const next: BoardQuoteMap = new Map(previous);
111
121
  const now = Date.now();
112
122
  for (const [symbol, state] of loaded) {
113
- const current = state.quote && !isFlaggedStale(state.quote) ? state.quote : null;
114
123
  const kept = previous.get(symbol)?.quote ?? null;
124
+ if (state.interim) {
125
+ if (!kept) next.set(symbol, { ...(previous.get(symbol) ?? EMPTY_STATE), quote: state.quote, loading: true, stale: true });
126
+ continue;
127
+ }
128
+ const current = state.quote && !isFlaggedStale(state.quote) ? state.quote : null;
115
129
  const retained = current ?? (state.quote && (state.quote.lastUpdated ?? 0) >= (kept?.lastUpdated ?? 0) ? state.quote : kept);
116
130
  next.set(symbol, {
117
131
  quote: retained,
@@ -197,7 +211,7 @@ async function requestBoardQuotes(
197
211
  dataProvider: NonNullable<ReturnType<typeof useAssetData>>,
198
212
  subset: readonly string[],
199
213
  forceRefresh: boolean,
200
- apply: (loaded: BoardQuoteMap) => void,
214
+ apply: (loaded: LoadedQuoteMap) => void,
201
215
  timeoutMs?: number,
202
216
  ): Promise<void> {
203
217
  const askAlone = async (symbol: string, context: MarketDataRequestContext | undefined, fallback: Quote | null = null) => {
@@ -215,7 +229,7 @@ async function requestBoardQuotes(
215
229
  if (dataProvider.getQuotesBatch) {
216
230
  const applyBatch = async (results: QuoteBatchResult[]) => {
217
231
  const bySymbol = new Map(results.map((result) => [result.target.symbol, result]));
218
- const answered: BoardQuoteMap = new Map();
232
+ const answered: LoadedQuoteMap = new Map();
219
233
  const followUps: QuoteBatchResult[] = [];
220
234
  for (const symbol of subset) {
221
235
  const result = bySymbol.get(symbol);
@@ -230,6 +244,14 @@ async function requestBoardQuotes(
230
244
  stale: false,
231
245
  });
232
246
  }
247
+ // A symbol asked for again alone shows the batch's dated quote meanwhile on a row with none (a cold board), so
248
+ // what reads its quote (a future's contract month, which FUT's returns read the contract's history by) starts
249
+ // now rather than after a round trip. A row that has a quote keeps it (mergeQuotes).
250
+ for (const result of followUps) {
251
+ if (finitePrice(result.quote ?? null)) {
252
+ answered.set(result.target.symbol, { quote: result.quote!, loading: true, error: null, stale: true, interim: true });
253
+ }
254
+ }
233
255
  if (answered.size > 0) apply(answered);
234
256
  await Promise.all(followUps.map((result) => askAlone(result.target.symbol, { cacheMode: result.followUp }, result.quote)));
235
257
  };
@@ -388,7 +410,7 @@ export function useQuoteBoard(symbols: string[], options: QuoteBoardOptions = {}
388
410
  */
389
411
  const refreshInBatches = useCallback((subset: readonly string[], forceRefresh: boolean, gen: number) => {
390
412
  if (!dataProvider) return;
391
- const apply = (loaded: BoardQuoteMap) => {
413
+ const apply = (loaded: LoadedQuoteMap) => {
392
414
  if (fetchGenRef.current !== gen) return;
393
415
  setSnapshots((prev) => mergeQuotes(prev, loaded));
394
416
  };
@@ -689,7 +689,7 @@ export function WebPageStackView({
689
689
  <WebIcon name="back" size={11} />
690
690
  <span className="gloom-qb-text">{backLabel}</span>
691
691
  </button>
692
- {detailTitle ? <div className="gloom-stack-title">{detailTitle}</div> : <div style={{ flex: 1 }} />}
692
+ {detailTitle ? <div className="gloom-stack-title" title={detailTitle}>{detailTitle}</div> : <div style={{ flex: 1 }} />}
693
693
  {backHint ? <span className="gloom-stack-hint">{backHint}</span> : null}
694
694
  </div>
695
695
  )}
@@ -1320,8 +1320,8 @@ html[data-gloom-screenshot="true"] [data-gloom-role="chart-watermark"] {
1320
1320
 
1321
1321
 
1322
1322
  /* Detail header of a list/detail stack: the same band as the query bar, so
1323
- Back and the item title read as the pane's toolbar. Grows when a long title
1324
- wraps rather than hiding it. */
1323
+ Back and the item title read as the pane's toolbar. The title stays on one
1324
+ line at any width and ends in an ellipsis; the full title is its tooltip. */
1325
1325
  .gloom-stack-bar {
1326
1326
  --qb-hairline: var(--gloom-hairline);
1327
1327
  --qb-fill: var(--gloom-hover-fill);
@@ -1360,7 +1360,9 @@ html[data-gloom-screenshot="true"] [data-gloom-role="chart-watermark"] {
1360
1360
  line-height: var(--cell-h);
1361
1361
  font-weight: var(--gloom-weight-bold);
1362
1362
  color: var(--gloom-text-bright);
1363
- overflow-wrap: break-word;
1363
+ overflow: hidden;
1364
+ text-overflow: ellipsis;
1365
+ white-space: nowrap;
1364
1366
  }
1365
1367
  .gloom-stack-hint { flex: none; align-self: center; padding: 0 var(--gloom-space-sm); color: var(--gloom-text-muted); white-space: nowrap; }
1366
1368
  /* Back and the title when a detail's query bar has taken the stack header. */
@@ -1399,7 +1401,8 @@ html[data-gloom-screenshot="true"] [data-gloom-role="chart-watermark"] {
1399
1401
  [data-gloom-role="pane-header-tabs"] [data-gloom-role="tab-label"],
1400
1402
  [data-gloom-role="pane-stack-tabs"] [data-gloom-role="tab-label"],
1401
1403
  .gloom-qb-title,
1402
- .gloom-qb-meta {
1404
+ .gloom-qb-meta,
1405
+ .gloom-stack-title {
1403
1406
  padding-block: var(--gloom-space-xs);
1404
1407
  margin-block: calc(-1 * var(--gloom-space-xs));
1405
1408
  }
@@ -0,0 +1,30 @@
1
+ import type { BoxRenderable as NativeBoxRenderable } from "@opentui/core";
2
+ import type { BoxRenderable } from "../../ui/host";
3
+
4
+ /**
5
+ * Calls `listener` with a box's laid-out width in cells, now if it has one and
6
+ * after every layout that changes it. For text that has to be cut to the room
7
+ * a flex row gives it, which only the layout knows. Returns the unsubscribe.
8
+ */
9
+ export function observeBoxWidth(
10
+ box: BoxRenderable | null,
11
+ listener: (width: number) => void,
12
+ ): (() => void) | undefined {
13
+ const native = box as NativeBoxRenderable | null;
14
+ if (!native) return;
15
+ const report = () => {
16
+ const width = native.width;
17
+ if (typeof width === "number" && width > 0) listener(width);
18
+ };
19
+ report();
20
+ // Computed layout invokes onSizeChange; keep whoever else listens.
21
+ const previous = native.onSizeChange;
22
+ const handleSizeChange = () => {
23
+ previous?.call(native);
24
+ report();
25
+ };
26
+ native.onSizeChange = handleSizeChange;
27
+ return () => {
28
+ if (native.onSizeChange === handleSizeChange) native.onSizeChange = previous;
29
+ };
30
+ }
@@ -326,7 +326,8 @@ export interface TtmConversion {
326
326
  * served beside it.
327
327
  * `matches` within 5%; `differs` beyond it (or beyond 2% on the other side of the market cap from net debt), within
328
328
  * 0.7x to 1.5x, shown labelled as the provider's; `withdrawn` outside that band, with no EV or EV/revenue; `unchecked`
329
- * without a recent balance sheet carrying both lines. `computed`: an insurer's or a holding company's EV, which is
329
+ * without a recent balance sheet carrying both lines, or where that balance sheet has no minority interest and an
330
+ * earlier one's accounts for the gap (`minorityUnreported`): the provider's figure stands. `computed`: an insurer's or a holding company's EV, which is
330
331
  * `computed` itself, its investment book kept in (`investmentsKept`). `not-meaningful`: the EV comes out at or below
331
332
  * zero, served as no EV or EV/revenue, with `reason`; shown N/M.
332
333
  */
@@ -348,10 +349,17 @@ export interface EnterpriseValueCheck {
348
349
  computed?: number;
349
350
  /**
350
351
  * Minority interest and preferred equity on the same balance sheet (total equity including minority interest less
351
- * common equity), where both lines are there and the difference is positive. `computed` plus this is the EV the
352
- * provider's is checked against and that stands in for it (bridgeEnterpriseValue).
352
+ * common equity, else what the company's filing tags for its date, `minorityFiled`), where it is positive.
353
+ * `computed` plus this is the EV the provider's is checked against and that stands in for it (bridgeEnterpriseValue).
353
354
  */
354
355
  minorityAndPreferred?: number;
356
+ /** `minorityAndPreferred` comes from the company's filing: the balance sheet has no equity lines. */
357
+ minorityFiled?: true;
358
+ /**
359
+ * On an `unchecked` check: the balance sheet and its filing give no minority interest, and this earlier balance sheet's
360
+ * accounts for the provider's EV above `computed`, so the provider's figure stands.
361
+ */
362
+ minorityUnreported?: { balanceSheetDate: string; value: number };
355
363
  /** `cash` is cash and equivalents alone: an insurer's or a holding company's investments stay in its EV. */
356
364
  investmentsKept?: true;
357
365
  /** Why the EV is not meaningful (`not-meaningful`), or why a withdrawn EV no balance sheet checked is withdrawn. */
@@ -1092,6 +1100,11 @@ export interface FinancialStatement {
1092
1100
  totalEquity?: number;
1093
1101
  totalEquityGrossMinorityInterest?: number;
1094
1102
  commonStockEquity?: number;
1103
+ /**
1104
+ * Minority interest and preferred equity as the company's 10-K or 10-Q tags them for the date: on a quarter Gloom
1105
+ * Cloud reads from the filing alone, which has no equity lines.
1106
+ */
1107
+ minorityAndPreferredEquity?: number;
1095
1108
  commonStock?: number;
1096
1109
  capitalStock?: number;
1097
1110
  additionalPaidInCapital?: number;
@@ -500,6 +500,12 @@ interface HeadlessPaneResultBase {
500
500
  unavailableSymbols?: string[];
501
501
  /** Failures: a source that did not answer, or a value that could not be computed. */
502
502
  errors?: string[];
503
+ /**
504
+ * What a report with `complete: false` leaves out, in the few words its
505
+ * status line and `# incomplete` line name it by ("NGZ31 not resolved"),
506
+ * when neither a count asked for nor a symbol without data says it.
507
+ */
508
+ incompleteDetail?: string;
503
509
  /**
504
510
  * Caveats about a report that did load: what it leaves out, what it assumes,
505
511
  * how a value was marked. One sentence each. They never make a report fail;
@@ -215,6 +215,8 @@ export function enterpriseValueComputed(
215
215
  */
216
216
  export function enterpriseValueGapIsLarge(fundamentals: Parameters<typeof enterpriseValueCheck>[0]): boolean {
217
217
  const check = enterpriseValueCheck(fundamentals);
218
+ // The provider's figure shown as it is: what the note says of its inputs is a detail for `ticker`.
219
+ if (check?.status === "matches" || check?.status === "unchecked") return false;
218
220
  const bridge = check ? bridgeEnterpriseValue(check) : undefined;
219
221
  if (check?.status !== "differs" || !finiteNumber(check.source) || bridge === undefined || bridge <= 0) return true;
220
222
  return Math.abs(check.source / bridge - 1) > OVERVIEW_ENTERPRISE_VALUE_GAP;
@@ -227,7 +229,9 @@ const OVERVIEW_ENTERPRISE_VALUE_GAP = 0.1;
227
229
  * and short-term investments 1.25B (balance sheet 2026-06-30), in place of the provider's 61.75B.", "EV N/M: cash and short-term investments
228
230
  * exceed market cap + total debt (balance sheet 2026-06-30)." A balance sheet in another currency names the rate it
229
231
  * was converted at ("balance sheet 2026-06-30, EUR at 0.8614 GBP"). A withdrawn EV no balance sheet checked gives
230
- * Gloom Cloud's reason; one withdrawn without a check, that the source failed validation. Undefined when the EV matches, is unchecked or computed, or has no check. Read it from the
232
+ * Gloom Cloud's reason; one withdrawn without a check, that the source failed validation. A provider's EV that
233
+ * matches or is unchecked has a line only where the balance sheet's minority interest is not on its lines
234
+ * (providerEnterpriseValueNote). Undefined when the EV is computed, or has no check. Read it from the
231
235
  * fundamentals the rows show (atRegularSessionPrice moves the check with the EV and the market cap), so its figures
232
236
  * are theirs.
233
237
  */
@@ -247,8 +251,12 @@ export function enterpriseValueReconciliationNote(
247
251
  if (check?.status === "withdrawn" && !finiteNumber(check.computed) && reason) {
248
252
  return `EV unavailable: ${reason.charAt(0).toLowerCase()}${reason.slice(1)}.`;
249
253
  }
250
- if (!check || !finiteNumber(check.computed) || !finiteNumber(check.source)
251
- || (check.status !== "differs" && check.status !== "withdrawn")) return undefined;
254
+ if (!check || !finiteNumber(check.computed) || !finiteNumber(check.source)) return undefined;
255
+ const otherCurrency = !!currency && !!check.currency && check.currency !== currency;
256
+ if ((check.status === "matches" || check.status === "unchecked") && !otherCurrency) {
257
+ return providerEnterpriseValueNote({ ...check, computed: check.computed, source: check.source }, currency, statements);
258
+ }
259
+ if (check.status !== "differs" && check.status !== "withdrawn") return undefined;
252
260
  const source = `${formatCompact(check.source)} ${check.currency}`;
253
261
  const computed = formatCompact(check.computed);
254
262
  const leases = finiteNumber(check.leases) && check.leases > 0 ? " + leases" : "";
@@ -266,6 +274,30 @@ export function enterpriseValueReconciliationNote(
266
274
  return `EV unavailable: the provider's ${source}${ratio} the ${computed} computed from ${basis}${twice}.`;
267
275
  }
268
276
 
277
+ /**
278
+ * The line under a provider's EV the bridge did not replace, where the balance sheet's minority interest is not on
279
+ * its lines: "EV 26.41B USD is the provider's, within 5% of 27.28B: market cap 6.04B + total debt 9.92B - cash 880M +
280
+ * minority interest and preferred equity 12.21B from the company's filing (balance sheet 2026-09-30).", and where
281
+ * neither the sheet nor its filing gives one, why the provider's figure stands. Undefined for any other check.
282
+ */
283
+ function providerEnterpriseValueNote(
284
+ check: EnterpriseValueCheck & { computed: number; source: number },
285
+ currency: string | undefined,
286
+ statements: BalanceSheets | undefined,
287
+ ): string | undefined {
288
+ const fx = check.fx && finiteNumber(check.fx.rate) ? `, ${check.fx.from} at ${check.fx.rate.toPrecision(4)} ${check.currency}` : "";
289
+ const sheet = check.balanceSheetDate ? ` (balance sheet ${check.balanceSheetDate}${fx})` : "";
290
+ const inputs = enterpriseValueInputs(check, sheet, checkCashBasis(check, statements));
291
+ const provider = `EV ${formatCompact(check.source)} ${check.currency} is the provider's`;
292
+ if (check.status === "matches" && check.minorityFiled && !bridgeStandsIn(check, currency)) {
293
+ return `${provider}, within 5% of ${formatCompact(bridgeEnterpriseValue(check)!)}: ${inputs}.`;
294
+ }
295
+ const earlier = check.minorityUnreported;
296
+ if (check.status !== "unchecked" || !earlier || !finiteNumber(earlier.value)) return undefined;
297
+ return `${provider}: ${inputs} is ${formatCompact(check.computed)} with no minority interest, which that balance sheet does not`
298
+ + ` report (${formatCompact(earlier.value)} on ${earlier.balanceSheetDate}), so the provider's figure stands.`;
299
+ }
300
+
269
301
  /** The balance sheets a note reads to say what a check's cash holds. */
270
302
  type BalanceSheets = Partial<Pick<TickerFinancials, "annualStatements" | "quarterlyStatements">>;
271
303
 
@@ -287,16 +319,25 @@ export function checkCashBasis(
287
319
 
288
320
  /**
289
321
  * "EV 7.48B USD is market cap 8.22B + total debt 864.07M - cash and short-term investments 1.6B (balance sheet
290
- * 2026-06-30)": the bridge with its inputs, each where the check carries it, minority interest and preferred equity
291
- * among them where the balance sheet shows any, and its cash as checkCashBasis reads it.
322
+ * 2026-06-30)": the bridge with its inputs (enterpriseValueInputs).
292
323
  */
293
324
  function computedEnterpriseValueInputs(check: EnterpriseValueCheck, sheet: string, cashBasis: ReturnType<typeof checkCashBasis>): string {
325
+ return `EV ${formatCompact(bridgeEnterpriseValue(check)!)} ${check.currency} is ${enterpriseValueInputs(check, sheet, cashBasis)}`;
326
+ }
327
+
328
+ /**
329
+ * "market cap 8.22B + total debt 864.07M - cash and short-term investments 1.6B (balance sheet 2026-06-30)": what the
330
+ * bridge adds up, each where the check carries it, minority interest and preferred equity among them where the balance
331
+ * sheet shows any (named as the company's filing's where the sheet has no equity lines), and its cash as
332
+ * checkCashBasis reads it.
333
+ */
334
+ function enterpriseValueInputs(check: EnterpriseValueCheck, sheet: string, cashBasis: ReturnType<typeof checkCashBasis>): string {
294
335
  const part = (label: string, value: number | undefined) => finiteNumber(value) ? `${label} ${formatCompact(value)}` : label;
295
336
  const leases = finiteNumber(check.leases) && check.leases > 0 ? ` + ${part("leases", check.leases)}` : "";
296
337
  const minority = minorityAndPreferred(check);
297
- const equity = minority > 0 ? ` + ${part("minority interest and preferred equity", minority)}` : "";
298
- return `EV ${formatCompact(bridgeEnterpriseValue(check)!)} ${check.currency} is ${part("market cap", check.marketCap)} + ${part("total debt", check.totalDebt)}${leases}`
299
- + ` - ${part(cashBasis, check.cash)}${equity}${sheet}`;
338
+ const filed = check.minorityFiled ? " from the company's filing" : "";
339
+ const equity = minority > 0 ? ` + ${part("minority interest and preferred equity", minority)}${filed}` : "";
340
+ return `${part("market cap", check.marketCap)} + ${part("total debt", check.totalDebt)}${leases} - ${part(cashBasis, check.cash)}${equity}${sheet}`;
300
341
  }
301
342
 
302
343
  /**