@gloom-sh/terminal 0.20.22 → 0.20.23

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 (195) hide show
  1. package/package.json +1 -1
  2. package/src/account/heard-from-question.tsx +6 -4
  3. package/src/account/heard-from.ts +3 -4
  4. package/src/api-client/exchange-announcements.ts +2 -2
  5. package/src/api-client/heard-from.ts +5 -7
  6. package/src/api-client/ownership-disclosures.ts +38 -5
  7. package/src/api-client/types/ticker-data.ts +3 -1
  8. package/src/architecture/dom-cell-metrics-allowlist.json +2 -2
  9. package/src/cli/commands/market.ts +5 -3
  10. package/src/cli/commands/overview.ts +7 -9
  11. package/src/cli/listing-arg.ts +45 -18
  12. package/src/cli/pane-functions/catalog-snapshot.json +2 -2
  13. package/src/cli/pane-functions/data.ts +3 -1
  14. package/src/cli/pane-functions/freshness.ts +6 -1
  15. package/src/cli/pane-functions/function-help.ts +0 -2
  16. package/src/cli/pane-functions/market-session.ts +12 -2
  17. package/src/cli/pane-functions/screenshot-payload.ts +3 -1
  18. package/src/cli/symbol-list.ts +52 -14
  19. package/src/cli/ticker-resolution.ts +133 -38
  20. package/src/components/chart/composite/composite-chart.tsx +12 -0
  21. package/src/components/chart/composite/types.ts +18 -0
  22. package/src/components/chart/composite/use-composite-chart-keyboard.ts +38 -15
  23. package/src/components/chart-table/header.tsx +11 -5
  24. package/src/components/chart-table/selection.ts +20 -1
  25. package/src/components/data-table/view.tsx +2 -0
  26. package/src/components/feed-data-table/stack-view.tsx +85 -5
  27. package/src/components/layout/pane/header.tsx +12 -30
  28. package/src/components/ticker/badge/index.tsx +9 -4
  29. package/src/components/ticker/badge/list.tsx +3 -1
  30. package/src/components/ui/data-table/index.tsx +7 -1
  31. package/src/components/ui/data-table/muted-row.tsx +47 -0
  32. package/src/components/ui/data-table/opentui/index.tsx +42 -11
  33. package/src/components/ui/data-table/spill.ts +36 -0
  34. package/src/components/ui/data-table/types.ts +17 -1
  35. package/src/components/ui/data-table/use-column-order.ts +11 -0
  36. package/src/components/ui/icon.tsx +50 -3
  37. package/src/components/ui/list-view.tsx +2 -2
  38. package/src/components/ui/table-layout.ts +32 -0
  39. package/src/components/ui/terminal-hover-label.tsx +49 -0
  40. package/src/components/use-pinned-moment.ts +222 -13
  41. package/src/core/state/app/state.ts +11 -2
  42. package/src/core/state/app/types.ts +2 -1
  43. package/src/data/sqlite/access.ts +14 -1
  44. package/src/data/sqlite/checkpointer.ts +2 -2
  45. package/src/data/sqlite/database.ts +4 -0
  46. package/src/docs/snapshot.json +180 -26
  47. package/src/i18n/es.ts +1 -0
  48. package/src/i18n/ja.ts +1 -0
  49. package/src/i18n/ko.ts +1 -0
  50. package/src/i18n/zh-cn.ts +1 -0
  51. package/src/i18n/zh-tw.ts +1 -0
  52. package/src/market-data/market/freshness.ts +2 -2
  53. package/src/market-data/market/globex-day.ts +14 -0
  54. package/src/market-data/published-us-sessions.ts +3 -2
  55. package/src/market-data/quotes/live-valuation.ts +4 -2
  56. package/src/market-data/quotes/metadata.ts +48 -5
  57. package/src/market-data/quotes/regular-session-valuation.ts +12 -1
  58. package/src/plugins/builtin/alerts/history-pane.tsx +19 -3
  59. package/src/plugins/builtin/broker-trading/orders.tsx +4 -2
  60. package/src/plugins/builtin/chat/attachments/desktop.tsx +46 -12
  61. package/src/plugins/builtin/chat/channels.ts +5 -2
  62. package/src/plugins/builtin/chat/content/composer-runtime.ts +64 -65
  63. package/src/plugins/builtin/chat/content/footer.tsx +17 -7
  64. package/src/plugins/builtin/chat/content/index.tsx +108 -36
  65. package/src/plugins/builtin/chat/content/new-dm-dialog.tsx +21 -8
  66. package/src/plugins/builtin/chat/content/selection-runtime.ts +16 -0
  67. package/src/plugins/builtin/chat/content/shortcuts.ts +3 -0
  68. package/src/plugins/builtin/chat/content/snapshot.ts +37 -13
  69. package/src/plugins/builtin/chat/content/transcript.tsx +12 -0
  70. package/src/plugins/builtin/chat/content/types.ts +2 -0
  71. package/src/plugins/builtin/chat/controller/channels.ts +15 -15
  72. package/src/plugins/builtin/chat/controller/index.ts +140 -34
  73. package/src/plugins/builtin/chat/controller/lifecycle.ts +8 -12
  74. package/src/plugins/builtin/chat/controller/persistence.ts +32 -4
  75. package/src/plugins/builtin/chat/controller/send.ts +41 -17
  76. package/src/plugins/builtin/chat/controller/session-runtime.ts +28 -27
  77. package/src/plugins/builtin/chat/controller/state.ts +17 -8
  78. package/src/plugins/builtin/chat/controller/storage.ts +41 -4
  79. package/src/plugins/builtin/chat/controller/view.ts +6 -3
  80. package/src/plugins/builtin/chat/index.tsx +1 -1
  81. package/src/plugins/builtin/chat/layout.ts +8 -1
  82. package/src/plugins/builtin/chat/message/desktop.tsx +15 -11
  83. package/src/plugins/builtin/chat/message/header.tsx +112 -30
  84. package/src/plugins/builtin/chat/message/reactions.tsx +10 -11
  85. package/src/plugins/builtin/chat/message/render-state.ts +4 -2
  86. package/src/plugins/builtin/chat/message/terminal.tsx +13 -15
  87. package/src/plugins/builtin/chat/message/types.ts +5 -0
  88. package/src/plugins/builtin/cloud-tweets/table.tsx +25 -2
  89. package/src/plugins/builtin/company-kpis/model.ts +11 -3
  90. package/src/plugins/builtin/correlation/compute.ts +6 -1
  91. package/src/plugins/builtin/custom-view/loader.ts +95 -34
  92. package/src/plugins/builtin/custom-view/pane.tsx +31 -41
  93. package/src/plugins/builtin/custom-view/table.ts +201 -0
  94. package/src/plugins/builtin/dividend-yield/client.ts +14 -17
  95. package/src/plugins/builtin/dividend-yield/headless.ts +0 -1
  96. package/src/plugins/builtin/dividend-yield/model.ts +45 -6
  97. package/src/plugins/builtin/dividend-yield/pane.tsx +70 -7
  98. package/src/plugins/builtin/dividend-yield/types.ts +2 -3
  99. package/src/plugins/builtin/dividend-yield/view.ts +22 -2
  100. package/src/plugins/builtin/econ/calendar-model.ts +135 -0
  101. package/src/plugins/builtin/econ/columns.ts +132 -0
  102. package/src/plugins/builtin/econ/index.tsx +25 -65
  103. package/src/plugins/builtin/holders/disclosures-view.tsx +9 -6
  104. package/src/plugins/builtin/holders/disclosures.ts +20 -6
  105. package/src/plugins/builtin/holders/headless.ts +2 -2
  106. package/src/plugins/builtin/ipo-calendar/model.ts +30 -1
  107. package/src/plugins/builtin/ipo-calendar/pane.tsx +7 -3
  108. package/src/plugins/builtin/kelly-sizer/headless.ts +9 -4
  109. package/src/plugins/builtin/kelly-sizer/pane.tsx +19 -9
  110. package/src/plugins/builtin/kelly-sizer/units.ts +26 -0
  111. package/src/plugins/builtin/market-halts/pane.tsx +14 -2
  112. package/src/plugins/builtin/news/wire/news/row.ts +5 -12
  113. package/src/plugins/builtin/news/wire/news/table.tsx +32 -41
  114. package/src/plugins/builtin/pe-band/headless.ts +1 -1
  115. package/src/plugins/builtin/pe-band/model.ts +41 -18
  116. package/src/plugins/builtin/pe-band/pane.tsx +6 -5
  117. package/src/plugins/builtin/perps/equity-row.tsx +4 -6
  118. package/src/plugins/builtin/perps/markets-section.tsx +19 -15
  119. package/src/plugins/builtin/perps/model.ts +10 -2
  120. package/src/plugins/builtin/portfolio-list/cli/import-positions.ts +6 -18
  121. package/src/plugins/builtin/portfolio-list/cli/portfolio-command.ts +1 -1
  122. package/src/plugins/builtin/portfolio-list/pane/purchase-date-fx.ts +1 -1
  123. package/src/plugins/builtin/portfolio-list/positions-import/index.tsx +1 -1
  124. package/src/plugins/builtin/portfolio-list/positions-import/lookup.ts +28 -57
  125. package/src/plugins/builtin/research/event-data.ts +3 -1
  126. package/src/plugins/builtin/research/event-model.ts +17 -15
  127. package/src/plugins/builtin/research/relative-valuation-columns.ts +19 -6
  128. package/src/plugins/builtin/research/relative-valuation-headless.ts +1 -1
  129. package/src/plugins/builtin/scanner/flow-pane.tsx +10 -0
  130. package/src/plugins/builtin/sec/exchange-filings.ts +32 -7
  131. package/src/plugins/builtin/sec/headless.ts +8 -8
  132. package/src/plugins/builtin/sec/index.tsx +69 -29
  133. package/src/plugins/builtin/shared/report-freshness.ts +4 -1
  134. package/src/plugins/builtin/ticker-detail/financials/aggregation.ts +1 -2
  135. package/src/plugins/builtin/ticker-detail/financials/exchange-table.tsx +61 -0
  136. package/src/plugins/builtin/ticker-detail/financials/model.ts +38 -4
  137. package/src/plugins/builtin/ticker-detail/financials/ratio-table.tsx +9 -2
  138. package/src/plugins/builtin/ticker-detail/financials/tab.tsx +68 -39
  139. package/src/plugins/builtin/ticker-detail/headless.ts +4 -1
  140. package/src/plugins/builtin/ticker-detail/overview/model.ts +61 -15
  141. package/src/plugins/builtin/ticker-detail/overview-tab.tsx +5 -0
  142. package/src/plugins/builtin/time-sales/model.ts +16 -9
  143. package/src/plugins/builtin/time-sales/pane.tsx +27 -24
  144. package/src/plugins/builtin/treasury-daily/client.ts +43 -9
  145. package/src/plugins/builtin/treasury-daily/pane.tsx +48 -27
  146. package/src/plugins/builtin/treasury-daily/resource.ts +33 -0
  147. package/src/portfolio/positions-import/parse.ts +14 -6
  148. package/src/portfolio/positions-import/plan.ts +3 -2
  149. package/src/react/async-resource.ts +3 -1
  150. package/src/renderers/dom/data-table/index.tsx +40 -0
  151. package/src/renderers/dom/data-table/row.tsx +39 -3
  152. package/src/renderers/dom/desktop/icons.tsx +147 -3
  153. package/src/renderers/dom/desktop/popover.tsx +2 -2
  154. package/src/renderers/dom/host/media-surface.tsx +204 -45
  155. package/src/renderers/dom/host/tabs.tsx +1 -0
  156. package/src/renderers/dom/styles.css +14 -2
  157. package/src/renderers/electrobun/bun/desktop/backend.ts +2 -0
  158. package/src/renderers/electrobun/bun/desktop/rpc-timing.ts +9 -3
  159. package/src/renderers/electrobun/shared/protocol.ts +2 -0
  160. package/src/renderers/electrobun/view/backend-rpc.ts +5 -2
  161. package/src/renderers/electrobun/view/rpc-timeout.ts +44 -3
  162. package/src/sources/gloomberb-cloud/index.ts +8 -7
  163. package/src/sources/gloomberb-cloud/normalizers.ts +7 -2
  164. package/src/sources/listing-symbols.ts +7 -1
  165. package/src/sources/provider-router/cache.ts +5 -4
  166. package/src/sources/provider-router/financials.ts +40 -18
  167. package/src/state/app/tab-cursor.ts +47 -6
  168. package/src/telemetry/stall-clocks.ts +3 -0
  169. package/src/telemetry/stall-reports.ts +12 -3
  170. package/src/telemetry/windows-process-activity.ts +41 -0
  171. package/src/telemetry/windows-time.ts +32 -0
  172. package/src/test-support/scoped-earnings.ts +24 -0
  173. package/src/tickers/terminal-codes.ts +1 -6
  174. package/src/time-series/daily-valuation.ts +13 -6
  175. package/src/time-series/filed-trailing-eps.ts +16 -3
  176. package/src/time-series/fundamentals/current-valuation.ts +8 -0
  177. package/src/time-series/fundamentals/historical-valuation.ts +20 -0
  178. package/src/time-series/fundamentals/series.ts +13 -1
  179. package/src/time-series/valuation-currency.ts +2 -0
  180. package/src/types/financials.ts +46 -10
  181. package/src/ui/dialog-context.ts +8 -0
  182. package/src/utils/datetime-format.ts +23 -1
  183. package/src/utils/declared-dividends.ts +12 -2
  184. package/src/utils/exchange-announcements.ts +4 -1
  185. package/src/utils/exchange-notation.generated.ts +3 -1
  186. package/src/utils/exchanges.ts +2 -1
  187. package/src/utils/fundamentals.ts +1 -0
  188. package/src/utils/main-thread-stall.ts +9 -1
  189. package/src/utils/rpc-timeout-error.ts +36 -11
  190. package/src/utils/sec.ts +3 -1
  191. package/src/utils/share-multiples.ts +1 -1
  192. package/src/utils/stall-process-activity.ts +70 -0
  193. package/src/utils/statement-scope.ts +103 -0
  194. package/src/utils/trailing-eps.ts +1 -1
  195. package/src/utils/zoned-date-time.ts +1 -0
@@ -1,5 +1,5 @@
1
1
  import { MISSING_VALUE } from "../../../../../utils/format";
2
- import { useCallback, useEffect, useMemo, useRef, type ReactNode, type RefObject } from "react";
2
+ import { useCallback, useEffect, useMemo, type ReactNode, type RefObject } from "react";
3
3
  import type { ScrollBoxRenderable } from "../../../../../ui";
4
4
  import {
5
5
  DataTableStackView,
@@ -20,7 +20,7 @@ import { nextHeaderSort } from "../../../../../utils/sort-values";
20
20
  import { localTimeZoneShortName } from "../../../../../utils/datetime-format";
21
21
  import { formatNewsCategoryForColumn } from "../categories";
22
22
  import { useOpenTickerChoice } from "../../../shared/ticker-choice";
23
- import { usePinnedMoment } from "../../../../../components/use-pinned-moment";
23
+ import { usePinnedList } from "../../../../../components/use-pinned-moment";
24
24
  import { MIN_HEADLINE_WIDTH, NEWS_SOURCE_WIDTH, NEWS_TIME_WIDTH, newsHeadlineCell, newsSourceCell, newsTimeCell } from "./row";
25
25
 
26
26
  export type NewsColumnId =
@@ -75,6 +75,9 @@ interface NewsArticleStackBaseProps {
75
75
  onBodyScrollActivity?: () => void;
76
76
  }
77
77
 
78
+ const articleId = (article: MarketNewsItem) => article.id;
79
+ const articleMoment = (article: MarketNewsItem) => article.publishedAt.getTime();
80
+
78
81
  function compareText(a: string, b: string): number {
79
82
  return a.localeCompare(b, "en-US", { sensitivity: "base" });
80
83
  }
@@ -295,35 +298,28 @@ export function NewsArticleStackView({
295
298
  }, [loadNewsStory]);
296
299
 
297
300
  // A crosshair pinned in the tab picks the newest story out by then, and
298
- // mutes the ones published after it. The selection follows the pin when it
299
- // moves, not when a story streams in, so a row the user picked stays put.
300
- const pinnedAt = usePinnedMoment("news-table:pin", { enabled: !detailOpen });
301
- const pinnedArticleId = useMemo(() => {
302
- if (pinnedAt === null) return null;
303
- let newest: MarketNewsItem | null = null;
304
- for (const article of sortedArticles) {
305
- const at = article.publishedAt.getTime();
306
- if (at <= pinnedAt && (!newest || at > newest.publishedAt.getTime())) newest = article;
307
- }
308
- return newest?.id ?? null;
309
- }, [pinnedAt, sortedArticles]);
310
- const followedPinRef = useRef<number | null>(null);
311
- useEffect(() => {
312
- if (pinnedAt === null) followedPinRef.current = null;
313
- if (pinnedAt === null || pinnedArticleId === null || followedPinRef.current === pinnedAt) return;
314
- followedPinRef.current = pinnedAt;
315
- setSelectedArticleId(pinnedArticleId);
316
- }, [pinnedAt, pinnedArticleId, setSelectedArticleId]);
301
+ // mutes the ones published after it, badges and all. The selection follows
302
+ // the pin when it moves, not when a story streams in, so a row the user
303
+ // picked stays put.
304
+ const { pinnedRow, isAfterPin } = usePinnedList<MarketNewsItem>("news-table:pin", {
305
+ enabled: !detailOpen,
306
+ rows: sortedArticles,
307
+ getId: articleId,
308
+ moment: articleMoment,
309
+ selectedId: selectedArticleId,
310
+ select: setSelectedArticleId,
311
+ });
312
+ const fallbackArticleId = pinnedRow?.id ?? sortedArticles[0]?.id ?? null;
317
313
 
318
314
  useEffect(() => {
319
- if (sortedArticles.length === 0) {
315
+ if (fallbackArticleId === null) {
320
316
  if (selectedArticleId !== null) setSelectedArticleId(null);
321
317
  return;
322
318
  }
323
319
  if (selectedArticleId === null || selectedIdx < 0) {
324
- setSelectedArticleId(sortedArticles[0]!.id);
320
+ setSelectedArticleId(fallbackArticleId);
325
321
  }
326
- }, [selectedArticleId, selectedIdx, setSelectedArticleId, sortedArticles]);
322
+ }, [fallbackArticleId, selectedArticleId, selectedIdx, setSelectedArticleId]);
327
323
 
328
324
  // [t]icker opens a company the cursor row mentions, as clicking its badge does.
329
325
  // An open story registers its own.
@@ -342,21 +338,17 @@ export function NewsArticleStackView({
342
338
  index: number,
343
339
  rowState: { selected: boolean },
344
340
  ): DataTableCell => {
345
- // A story out after the pinned moment reads muted and plain throughout,
346
- // as rows that no longer apply do elsewhere (an exited holder).
347
- const later = pinnedAt !== null && item.publishedAt.getTime() > pinnedAt;
348
- const tone = (color: string) => later ? colors.textMuted : color;
349
341
  switch (column.id) {
350
342
  case "rank":
351
- return { text: String(index + 1), color: tone(colors.textDim) };
343
+ return { text: String(index + 1), color: colors.textDim };
352
344
  case "time":
353
- return { ...newsTimeCell(item, { later }), value: item.publishedAt };
345
+ return { ...newsTimeCell(item), value: item.publishedAt };
354
346
  case "source":
355
347
  return newsSourceCell(item);
356
348
  case "title":
357
349
  // Unclipped: the table fits it to the width the column really gets,
358
350
  // which on desktop is wider than the width it was laid out at.
359
- return newsHeadlineCell(item, { later, read: readArticleIds?.has(item.id), title: titleForArticle?.(item) });
351
+ return newsHeadlineCell(item, { read: readArticleIds?.has(item.id), title: titleForArticle?.(item) });
360
352
  case "tickers": {
361
353
  const tickers = fitTickerSymbols(collectNewsDisplayTickers(item.tickers), column.width);
362
354
  return {
@@ -376,29 +368,27 @@ export function NewsArticleStackView({
376
368
  return {
377
369
  text: category && category === impliedCategory ? "" : category || MISSING_VALUE,
378
370
  ...(category && category === impliedCategory ? { value: category } : {}),
379
- color: tone(colors.textDim),
371
+ color: colors.textDim,
380
372
  };
381
373
  }
382
374
  case "sentiment": {
383
375
  const sentiment = item.sentiment;
384
376
  return {
385
377
  text: sentiment ? sentiment.slice(0, 3) : MISSING_VALUE,
386
- color: tone(
387
- sentiment === "positive"
388
- ? colors.positive
389
- : sentiment === "negative"
390
- ? colors.negative
391
- : colors.textDim
392
- ),
378
+ color: sentiment === "positive"
379
+ ? colors.positive
380
+ : sentiment === "negative"
381
+ ? colors.negative
382
+ : colors.textDim,
393
383
  };
394
384
  }
395
385
  case "importance":
396
386
  return {
397
387
  text: String(item.importance),
398
- color: tone(item.importance >= 80 ? colors.positive : colors.textDim),
388
+ color: item.importance >= 80 ? colors.positive : colors.textDim,
399
389
  };
400
390
  }
401
- }, [impliedCategory, pinnedAt, readArticleIds, titleForArticle]);
391
+ }, [impliedCategory, readArticleIds, titleForArticle]);
402
392
 
403
393
  return (
404
394
  <DataTableStackView<MarketNewsItem, NewsTableColumn>
@@ -427,6 +417,7 @@ export function NewsArticleStackView({
427
417
  }))}
428
418
  getItemKey={(item) => item.id}
429
419
  renderCell={renderCell}
420
+ isRowMuted={isAfterPin}
430
421
  selectedTextOverridesCellColor
431
422
  emptyContent={emptyContent}
432
423
  emptyStateTitle={emptyStateTitle}
@@ -25,7 +25,7 @@ export const peBandHeadless: HeadlessPaneDefinition<"bundle"> = {
25
25
  const inputs = await loadPeBandInputs({ instrument, signal: ctx.signal }, ctx.marketData, new MarketDataCoordinator(ctx.marketData), ctx.apiClient);
26
26
  ctx.signal.throwIfAborted();
27
27
  const lookbackYears = Number(args.options.lookbackYears ?? 10);
28
- const model = projectPeBand(inputs.financials, inputs.history, { symbol: instrument.symbol, lookbackYears, reports: inputs.reports,
28
+ const model = projectPeBand(inputs.financials, inputs.history, { symbol: instrument.symbol, exchange: instrument.exchange, lookbackYears, reports: inputs.reports,
29
29
  fx: inputs.fx, fxError: inputs.fxError, daily: inputs.daily });
30
30
  const current = model.current;
31
31
  const conversion = model.conversion;
@@ -1,6 +1,9 @@
1
- import { regularSessionValuationPrice } from "../../../market-data/quotes/regular-session-valuation";
1
+ import { regularSessionValuationPrice, regularSessionValuationTime } from "../../../market-data/quotes/regular-session-valuation";
2
+ import { priceScopedEarnings } from "../../../utils/statement-scope";
2
3
  import { crossFxCloseOnOrBefore, dailyFxLeg, type FxCloses } from "../../../market-data/fx-closes";
3
4
  import { knownWhenFiled } from "../../../time-series/fundamentals";
5
+ import { calendarBarStart } from "../../../time-series/chart-data";
6
+ import { dailyValuationHistory } from "../../../time-series/daily-valuation";
4
7
  import { STALE_TRAILING_EPS_MS, trailingEpsSteps as sharedTrailingEpsSteps, type EpsStep } from "../../../time-series/filed-trailing-eps";
5
8
  import { createValuationCurrencyContext } from "../../../time-series/valuation-currency";
6
9
  import type { FinancialStatement, PricePoint, TickerFinancials } from "../../../types/financials";
@@ -26,11 +29,12 @@ interface PeBandWeek {
26
29
 
27
30
  export interface PeBandRow extends EpsStep {
28
31
  /**
29
- * The close of the day the figure became known (the last session on or
30
- * before it), in price units; before the daily closes on record, the close
31
- * of the weekly bar dated on or before it.
32
+ * In price units: the first eligible close at or after a scoped figure's
33
+ * publication, otherwise the last session on or before it (a weekly close
34
+ * before daily coverage).
32
35
  */
33
36
  price: number | null;
37
+ priceAt?: Date | null;
34
38
  pe: number | null;
35
39
  /** Change from the figure a year earlier in the same currency, when both are positive. */
36
40
  yoy: number | null;
@@ -122,6 +126,7 @@ export function formatEpsFx(from: string, to: string, rate: number): string {
122
126
  export function epsFxCurrencies(financials: TickerFinancials, reports: readonly ReportDate[]): Map<string, string> {
123
127
  const target = resolveCurrencyUnit(financials.quote?.currency).currency;
124
128
  const starts = new Map<string, string>();
129
+ if (financials.statementScope) return starts;
125
130
  if (target !== "USD" && !dailyFxLeg(target)) return starts;
126
131
  for (const step of trailingEpsSteps(financials, reports)) {
127
132
  const source = resolveCurrencyUnit(step.currency).currency;
@@ -184,6 +189,13 @@ function closesOf(history: readonly PricePoint[]): Array<{ date: Date; close: nu
184
189
  .sort((a, b) => a.date.getTime() - b.date.getTime());
185
190
  }
186
191
 
192
+ function scopedBandHistory(history: readonly PricePoint[], step: EpsStep, exchange: string | undefined, now: number) {
193
+ const daily = dailyValuationHistory(history, [{ observedAt: new Date(step.periodEnd), availableAt: step.knownAt.toISOString(), atPrice: price => price }], exchange, now)
194
+ .flatMap(point => point.value === null ? [] : [{ date: point.date, close: point.value }]);
195
+ const weeks = new Map(daily.map(point => [calendarBarStart(point.date.getTime(), "1wk", exchange), point]));
196
+ return { daily, weeks: [...weeks.values()] };
197
+ }
198
+
187
199
  /**
188
200
  * Weekly bars dated by the session their close is from. A bar is dated by
189
201
  * its week's first day, so DWSN's week of 9 Nov 2026 read 9 Nov with the
@@ -226,7 +238,7 @@ export function projectPeBand(
226
238
  financials: TickerFinancials | null,
227
239
  history: readonly PricePoint[],
228
240
  options: {
229
- symbol: string; lookbackYears: number; now?: number; reports?: readonly ReportDate[];
241
+ symbol: string; exchange?: string; lookbackYears: number; now?: number; reports?: readonly ReportDate[];
230
242
  /** Daily FX closes by currency, quoted in USD per unit. */
231
243
  fx?: ReadonlyMap<string, FxCloses>;
232
244
  /** Why a needed FX history is missing, said when it leaves today's EPS unconverted. */
@@ -254,6 +266,7 @@ export function projectPeBand(
254
266
  const quoteUnit = resolveCurrencyUnit(currency);
255
267
  const priced = (step: EpsStep | null): { eps: number; fx: FxClose | null } | null => {
256
268
  if (step?.eps == null) return null;
269
+ if (financials.statementScope) return step.currency === currency ? { eps: step.eps, fx: null } : null;
257
270
  const factor = unitScale(step);
258
271
  if (factor != null) return { eps: step.eps * factor, fx: null };
259
272
  const source = resolveCurrencyUnit(step.currency);
@@ -267,31 +280,38 @@ export function projectPeBand(
267
280
  }
268
281
 
269
282
  const now = options.now ?? Date.now();
283
+ const canPrice = !financials.statementScope || (financials.fundamentals?.scopedEarnings?.priced === true && !financials.fundamentals.notMeaningful?.trailingPE);
284
+ const stepForPrice = (time: number) => financials.statementScope
285
+ ? (latest.knownAt.getTime() <= time && time <= now ? latest : null) : stepAt(allSteps, time);
270
286
  const firstKnown = allSteps.find((step) => step.eps != null)!.knownAt.getTime();
271
287
  const start = Math.max(firstKnown, options.lookbackYears > 0 ? now - options.lookbackYears * YEAR_MS : firstKnown);
272
- const sorted = closesOf(history);
273
- const daily = closesOf(options.daily ?? []);
288
+ const scoped = financials.statementScope ? scopedBandHistory(options.daily?.length ? options.daily : financials.priceHistory,
289
+ latest, financials.quote?.listingExchangeName || financials.quote?.exchangeName || options.exchange, now) : null;
290
+ const sorted = scoped ? [] : closesOf(history);
291
+ const daily = scoped?.daily ?? closesOf(options.daily ?? []);
274
292
  const dailyStart = daily[0]?.date.getTime() ?? Number.POSITIVE_INFINITY;
275
293
  /** A close as the chart reads it: with the EPS in force on its day, and the P/E they make. */
276
294
  const reading = (point: { date: Date; close: number }): PeBandWeek => {
277
- const step = stepAt(allSteps, point.date.getTime());
295
+ const step = stepForPrice(point.date.getTime());
278
296
  const eps = step ? pricedSteps.get(step)?.eps ?? null : null;
279
297
  const positive = eps != null && eps > 0 ? eps : null;
280
- return { date: point.date, close: point.close, eps: positive, pe: positive ? point.close / positive : null };
298
+ return { date: point.date, close: point.close, eps: positive, pe: canPrice && positive ? point.close / positive : null };
281
299
  };
282
- const weeks = closingSessions(sorted, daily).filter((point) => point.date.getTime() >= start).map(reading);
300
+ const weeks = (scoped?.weeks ?? closingSessions(sorted, daily)).filter((point) => point.date.getTime() >= start).map(reading);
283
301
 
284
- /** The close of the day `time` falls on, or the last session before it, where the daily closes reach. */
285
- const dayClose = (time: number) => time >= dailyStart ? daily.findLast((point) => point.date.getTime() <= time) ?? null : null;
286
- const steps = allSteps.filter((step) => step.knownAt.getTime() >= start);
302
+ /** Scoped EPS waits for a close; an ordinary row reads the close on or before its date. */
303
+ const dayClose = (time: number) => scoped ? daily.find(point => point.date.getTime() >= time) ?? null
304
+ : time >= dailyStart ? daily.findLast((point) => point.date.getTime() <= time) ?? null : null;
305
+ const steps = allSteps.filter((step) => step.knownAt.getTime() >= start && (!financials.statementScope || step.knownAt.getTime() <= now));
287
306
  const rows = steps.filter((step) => step.eps != null).map((step): PeBandRow => {
288
307
  const time = step.knownAt.getTime();
289
- const price = (dayClose(time) ?? sorted.findLast((point) => point.date.getTime() <= time))?.close ?? null;
308
+ const bar = dayClose(time) ?? sorted.findLast((point) => point.date.getTime() <= time);
309
+ const price = bar?.close ?? null;
290
310
  const converted = pricedSteps.get(step);
291
311
  const eps = converted?.eps ?? null;
292
312
  const prior = allSteps.find((other) => other.eps != null && other.currency === step.currency
293
313
  && Math.abs(Date.parse(step.periodEnd) - Date.parse(other.periodEnd) - 365 * DAY_MS) <= 20 * DAY_MS);
294
- return { ...step, price, pe: price != null && eps != null && eps > 0 ? price / eps : null, fx: converted?.fx ?? null,
314
+ return { ...step, price, ...(scoped ? { priceAt: bar?.date ?? null } : {}), pe: canPrice && price != null && eps != null && eps > 0 ? price / eps : null, fx: converted?.fx ?? null,
295
315
  yoy: step.eps != null && prior?.eps != null && step.eps > 0 && prior.eps > 0 ? step.eps / prior.eps - 1 : null };
296
316
  }).reverse();
297
317
 
@@ -299,14 +319,17 @@ export function projectPeBand(
299
319
  const pes = ranked.map((week) => week.pe!);
300
320
  const ordered = [...pes].sort((a, b) => a - b);
301
321
  // The regular session's price, as the quote headlines it: after the close, the close rather than an after-hours print.
302
- const price = regularSessionValuationPrice(financials.quote) ?? sorted.at(-1)?.close ?? null;
322
+ const price = regularSessionValuationPrice(financials.quote) ?? (financials.statementScope ? null : sorted.at(-1)?.close ?? null);
303
323
  // Today's figure reads like every week's: one whose newest quarter has no EPS keeps the last figure, dated in the
304
324
  // table, where the headline EPS (TTM) needs that quarter's own (filed-trailing-eps) and shows Gloom Cloud's, labelled.
305
- const currentStep = stepAt(allSteps, now);
325
+ const priceTime = financials.statementScope ? regularSessionValuationTime(financials.quote)?.time : now;
326
+ const currentStep = stepForPrice(priceTime ?? -Infinity);
306
327
  const currentConversion = currentStep ? pricedSteps.get(currentStep) : null;
307
328
  const currentEps = currentConversion?.eps ?? null;
308
329
  const latestFx = currentConversion?.fx;
309
- const currentPe = price != null && currentEps != null && currentEps > 0 ? price / currentEps : null;
330
+ const currentPe = financials.statementScope && financials.fundamentals
331
+ ? priceScopedEarnings(financials.fundamentals, price, financials.quote, priceTime, now).trailingPE ?? null
332
+ : price != null && currentEps != null && currentEps > 0 ? price / currentEps : null;
310
333
  const multiples = chooseMultiples(pes, currentPe);
311
334
  const above = currentPe == null ? undefined : multiples.find((multiple) => multiple >= currentPe);
312
335
  const highestClose = weeks.reduce((max, week) => Math.max(max, week.close), 0);
@@ -106,15 +106,16 @@ export function PeBandPane({ width, height, focused }: PaneProps) {
106
106
 
107
107
  const lookbackYears = Number(lookback);
108
108
  const model = useMemo(() => inputs.data
109
- ? projectPeBand(inputs.data.financials, inputs.data.history, { symbol: symbol ?? "", lookbackYears: Number.isFinite(lookbackYears) ? lookbackYears : 10,
109
+ ? projectPeBand(inputs.data.financials, inputs.data.history, { symbol: symbol ?? "", exchange: instrument?.exchange, lookbackYears: Number.isFinite(lookbackYears) ? lookbackYears : 10,
110
110
  reports: inputs.data.reports, fx: inputs.data.fx, fxError: inputs.data.fxError, daily: inputs.data.daily })
111
- : null, [inputs.data, lookbackYears, symbol]);
111
+ : null, [inputs.data, lookbackYears, symbol, instrument?.exchange]);
112
112
  const rows = model?.rows ?? [];
113
113
  const conversion = model?.conversion ?? null;
114
114
  const showFx = !!conversion || rows.some((row) => row.fx);
115
115
  const columns = useMemo(() => tableColumns(showFx), [showFx]);
116
116
  const series = useMemo(() => model && !model.error ? chartSeries(model, colors) : [], [model, colors]);
117
117
  const currency = model?.currency ?? undefined;
118
+ const scoped = !!inputs.data?.financials?.statementScope;
118
119
  const firstWeek = model?.weeks[0]?.date;
119
120
  const lastWeek = model?.weeks.at(-1)?.date;
120
121
  const sampleStart = model?.sample?.start;
@@ -124,7 +125,7 @@ export function PeBandPane({ width, height, focused }: PaneProps) {
124
125
  ? `${lookbackYears}Y` : `since ${sampleStart.getUTCFullYear()}`;
125
126
 
126
127
  const selected = rows.some((row) => rowKey(row) === selectedId) ? selectedId : rows[0] ? rowKey(rows[0]) : null;
127
- const rowDate = useCallback((row: PeBandRow) => (firstWeek && row.knownAt >= firstWeek ? row.knownAt : null), [firstWeek?.getTime()]);
128
+ const rowDate = useCallback((row: PeBandRow) => row.priceAt !== undefined ? row.priceAt : (firstWeek && row.knownAt >= firstWeek ? row.knownAt : null), [firstWeek?.getTime()]);
128
129
  const link = useChartTableSelection({ rows, getId: rowKey, getDate: rowDate, selectedId: selected, onSelect: setSelectedId, focused });
129
130
 
130
131
  const undatedNotice = model?.undated
@@ -169,12 +170,12 @@ export function PeBandPane({ width, height, focused }: PaneProps) {
169
170
  selection={{ kind: "id", selectedId: selected, getId: rowKey, onChange: (id) => setSelectedId(id) }}
170
171
  selectedTextOverridesCellColor
171
172
  getExportMetadata={() => [["symbol", model.symbol], ["currency", model.currency ?? ""],
172
- ["units", showFx
173
+ ["units", scoped ? "EPS and price in the listing currency; P/E at the first eligible close on or after EPS publication" : showFx
173
174
  ? `EPS as reported; period-end FX to ${model.currency ?? ""}; P/E at the close of the day the EPS became known`
174
175
  : "EPS and price in the listing currency; P/E at the close of the day the EPS became known"]]}
175
176
  renderCell={(row, column) => renderCell(row, column, colors, showFx ? currency : undefined)}
176
177
  rootBefore={<ChartTableHeader width={width} height={height} tableRows={rows.length} tableColumns={columns} query={query} figures={figures}
177
- chart={model.weeks.length >= 2 ? { series, formatValue: formatPrice, formatAxisValue: formatAxis, remoteKind: "pe-band", ...link } : null} />} />
178
+ chart={scoped || model.weeks.length >= 2 ? { series, allowSinglePoint: scoped, formatValue: formatPrice, formatAxisValue: formatAxis, remoteKind: "pe-band", ...link } : null} />} />
178
179
  : null}
179
180
  </PaneStatusBody>
180
181
  </Box>;
@@ -10,7 +10,7 @@ import { perpEquityIdentity } from "./equity-identity";
10
10
  import { perpetualListing } from "../../../tickers/perpetual-listing";
11
11
  import { loadPerpSelection, loadPerpsEquity } from "./client";
12
12
  import { rowReadAt } from "../../../market-data/perpetual-open-interest";
13
- import { compact, percent, perpDescription, price, readingTime } from "./model";
13
+ import { compact, percent, perpDescription, perpMarkText, readingTime, stockPerpPremiumText } from "./model";
14
14
  import { useLivePerpRows } from "./live-rows";
15
15
  import { openPerpLabel, useOpenPerpMarket } from "./open-market";
16
16
  import { mergeVenueMarkets } from "./venue-markets";
@@ -65,12 +65,10 @@ function PerpRow({ row, stale, width, own = false }: { row: PerpBoardRow; stale:
65
65
  usePaneLinkMenuEntry(`function:perps-pane:${row.marketId}`, openPerpLabel(row), open);
66
66
  // Dated by its oldest figure: a streamed mark can sit beside the open interest the last poll read.
67
67
  const read = readingTime(rowReadAt(row));
68
- const staleText = row.stale || stale ? " · stale" : "";
69
- const figures = own
70
- ? row.underlyingPremium != null ? [`${percent(row.underlyingPremium, 2)} vs ${row.underlyingSymbol ?? "underlying"} last${staleText}`] : staleText ? ["stale"] : []
71
- : [`${price(row.markPrice)} ${row.quoteCurrency}`, `${percent(row.underlyingPremium, 2)} vs last${staleText}`];
68
+ const premium = stockPerpPremiumText(row, row.underlyingPremium);
69
+ const figures = [...own ? [] : [perpMarkText(row.markPrice, row.quoteCurrency)], ...premium ? [premium] : [], ...row.stale || stale ? ["stale"] : []];
72
70
  const named = [`${row.baseAsset} · ${perpDescription(row)}`, ...figures].join(" ");
73
- const first = width === undefined || displayWidth(named) <= width ? named : [`${row.baseAsset} perpetual`, ...figures].join(" ");
71
+ const first = width === undefined || displayWidth(named) <= width ? named : fitParts([`${row.baseAsset} perpetual`, ...figures], " ", width);
74
72
  // Funding reads per 8h here as it does in PERP, whatever interval the venue pays on.
75
73
  const second = fitParts([`Funding ${percent(row.fundingRate8h, 4)} per 8 h`, `OI ${compact(row.openInterestUsd)} USD`, `oracle ${percent(row.premium, 2)}`,
76
74
  ...(read ? [`as of ${read}`] : [])], " · ", width);
@@ -1,7 +1,6 @@
1
1
  import { useCallback, useMemo, useState } from "react";
2
2
  import { isAccessDenied } from "../../../api-client/errors";
3
3
  import { usePlanAccess } from "../../../api-client/plan-access";
4
- import type { PerpBoardRow } from "../../../api-client/perps";
5
4
  import { ActionRow, ColumnGrid, SectionHeading, type ColumnGridCell, type ColumnGridColumn } from "../../../components";
6
5
  import { hiddenTableColumnText, markHiddenTableColumns } from "../../../components/ui/table-layout";
7
6
  import { t, tf } from "../../../i18n";
@@ -13,16 +12,16 @@ import { premiumToUnderlying } from "../../../market-data/perpetual-premium";
13
12
  import type { Quote } from "../../../types/financials";
14
13
  import { Box, Text } from "../../../ui";
15
14
  import { isRoundTheClockCoin } from "../../../utils/crypto-pair";
16
- import { displayWidth } from "../../../utils/format";
15
+ import { displayWidth, MISSING_VALUE } from "../../../utils/format";
17
16
  import { parsePublicTickerKey } from "../../../utils/exchanges";
18
17
  import { useResearchCloudSession } from "../shared/research-cloud-session";
19
18
  import { loadPerpsCompare, loadPerpsEquity } from "./client";
20
19
  import { perpEquityIdentity } from "./equity-identity";
21
20
  import { useLivePerpRows } from "./live-rows";
22
- import { compact, perpCell, percent, price, venueName } from "./model";
21
+ import { compact, perpCell, percent, perpMarkText, stockPerpPremiumText, venueName } from "./model";
23
22
  import { openPerpLabel, useOpenPerpMarket } from "./open-market";
24
23
  import { freshnessLine } from "./status-line";
25
- import { contractText, foldSmallMarkets, mergeVenueMarkets, venueMarketsFreshness, withPrimaryReading, type PerpVenueMarket } from "./venue-markets";
24
+ import { contractText, foldSmallMarkets, mergeVenueMarkets, venueMarketsFreshness, withPrimaryReading } from "./venue-markets";
26
25
 
27
26
  const STOCK_TYPES = new Set(["STK", "EQUITY", "STOCK", "COMMON STOCK"]);
28
27
  const COIN_PAIR = /^([A-Z0-9]{1,15})[-/](?:USD|USDT|USDC)$/;
@@ -63,8 +62,8 @@ const DROP_ORDER: readonly Column["id"][] = ["volume", "contract", "premium", "o
63
62
  const GAP = 2;
64
63
  const span = (columns: readonly Column[]) => columns.reduce((sum, column) => sum + column.width, 0) + GAP * (columns.length - 1);
65
64
 
66
- function fitColumns(width: number, venueWidth: number): Column[] {
67
- const original = COLUMNS.map((column) => column.id === "venue" ? { ...column, width: venueWidth } : column);
65
+ function fitColumns(width: number, contentWidths: Partial<Record<Column["id"], number>>): Column[] {
66
+ const original = COLUMNS.map((column) => ({ ...column, width: Math.max(column.width, contentWidths[column.id] ?? 0) }));
68
67
  let columns = original;
69
68
  for (const id of DROP_ORDER) {
70
69
  if (span(columns) <= width) break;
@@ -112,12 +111,18 @@ export function PerpMarketsSection({ symbol, exchange, instrumentType, quote, wi
112
111
  // A streamed reading moves the venue's whole row: its mark, and the open interest and volume counted with it.
113
112
  const rows = visible.map((market, index) => {
114
113
  const row = live.rows[index] ?? market.primary;
115
- return { market: withPrimaryReading(market, row), row };
114
+ const mark = perpMarkText(row.markPrice ?? row.lastPrice, row.quoteCurrency);
115
+ const premium = asset?.kind === "stock" ? premiumToUnderlying(row, quote) : row.premium;
116
+ const premiumText = asset?.kind === "stock" ? stockPerpPremiumText(row, premium) : percent(premium, 2);
117
+ return { market: withPrimaryReading(market, row), row, mark, premium: premiumText ? premium : null, premiumText };
116
118
  });
117
- const premiumLabel = asset?.kind === "stock" ? "vs last" : "Premium";
118
119
  // The venue column fits the longest venue name shown.
119
120
  const venueWidth = Math.min(VENUE_MAX_WIDTH, Math.max(VENUE_MIN_WIDTH, ...visible.map((market) => displayWidth(venueName(market.venue)))));
120
- const columns = fitColumns(width, venueWidth);
121
+ const columns = fitColumns(width, {
122
+ venue: venueWidth,
123
+ mark: Math.max(...rows.map(({ mark }) => displayWidth(mark))),
124
+ premium: Math.max(...rows.map(({ premiumText }) => displayWidth(premiumText ?? ""))),
125
+ });
121
126
  const fixed = span(columns);
122
127
  // The last text column takes what the figures leave, on the desktop too, so a venue keeps its contract beside it.
123
128
  const growing = columns.some((column) => column.id === "contract") ? "contract" : "venue";
@@ -127,17 +132,16 @@ export function PerpMarketsSection({ symbol, exchange, instrumentType, quote, wi
127
132
  gapBefore: index > 0 ? GAP : 0,
128
133
  ...(column.id === growing ? { growFrom: column.width } : {}),
129
134
  }));
130
- const header: ColumnGridCell[] = columns.map((column) => ({ text: t(column.id === "premium" ? premiumLabel : column.label), color: colors.textDim }));
131
- const cell = (column: Column, market: PerpVenueMarket, row: PerpBoardRow): ColumnGridCell => {
135
+ const header: ColumnGridCell[] = columns.map((column) => ({ text: t(column.label), color: colors.textDim }));
136
+ const cell = (column: Column, { market, row, mark, premium, premiumText }: typeof rows[number]): ColumnGridCell => {
132
137
  if (column.id === "venue") {
133
138
  return { text: venueName(market.venue), color: row.stale ? colors.textDim : colors.textBright,
134
139
  link: { label: openPerpLabel(row), onOpen: () => openMarket(row.marketId) } };
135
140
  }
136
141
  if (column.id === "contract") return { text: contractText(market), color: colors.textMuted };
137
- if (column.id === "mark") return { text: price(row.markPrice ?? row.lastPrice), color: colors.text };
142
+ if (column.id === "mark") return { text: mark, color: colors.text };
138
143
  if (column.id === "premium") {
139
- const value = asset?.kind === "stock" ? premiumToUnderlying(row, quote) : row.premium;
140
- return { text: percent(value, 2), color: value == null || value === 0 ? colors.textMuted : value > 0 ? colors.positive : colors.negative };
144
+ return { text: premiumText ?? MISSING_VALUE, color: premium == null || premium === 0 ? colors.textMuted : premium > 0 ? colors.positive : colors.negative };
141
145
  }
142
146
  if (column.id === "funding") {
143
147
  const { text, color } = perpCell(row, "fundingRate8h", colors);
@@ -146,7 +150,7 @@ export function PerpMarketsSection({ symbol, exchange, instrumentType, quote, wi
146
150
  // A venue's open interest and volume are its contracts' together.
147
151
  return { text: compact(column.id === "oi" ? market.openInterestUsd : market.volume24hUsd), color: colors.text };
148
152
  };
149
- const body = rows.map(({ market, row }) => columns.map((column) => cell(column, market, row)));
153
+ const body = rows.map((entry) => columns.map((column) => cell(column, entry)));
150
154
  // Each venue's own time, as PERP's footer gives it: the first form that fits.
151
155
  const status = freshnessLine(venueMarketsFreshness(rows.map(({ market }) => market), { now, streaming: live.liveMarkets, refreshFailed: !!resource.data?.stale }), now);
152
156
  const statusText = status.variants.find((variant) => displayWidth(variant) <= width) ?? status.variants.at(-1);
@@ -238,7 +238,15 @@ export function openInterestFields(row: Pick<PerpBoardRow, "venue" | "baseAsset"
238
238
  }
239
239
 
240
240
  // One text per figure, shared by the pane cells and the text report so the two always agree.
241
- const markText = (row: Pick<PerpBoardRow, "markPrice" | "quoteCurrency">) => row.markPrice == null ? MISSING_VALUE : `${price(row.markPrice)} ${row.quoteCurrency}`;
241
+ export function perpMarkText(value: number | null, currency: string): string {
242
+ return value == null || !currency ? price(value) : `${price(value)} ${currency}`;
243
+ }
244
+
245
+ export function stockPerpPremiumText(row: Pick<PerpBoardRow, "underlying">, premium: number | null): string | null {
246
+ const reference = row.underlying;
247
+ return premium != null && reference?.symbol && reference.currency
248
+ ? `${percent(premium, 2)} vs ${reference.symbol} ${reference.currency}` : null;
249
+ }
242
250
  const fundingPerInterval = (row: Pick<PerpBoardRow, "fundingRate" | "fundingIntervalHours" | "fundingKind">) => row.fundingRate == null ? MISSING_VALUE : `${percent(row.fundingRate, 5)} /${fundingInterval(row)}`;
243
251
  /**
244
252
  * The contract a bare name opens: the one with the largest open interest across venues, among the venues read
@@ -341,7 +349,7 @@ export function perpCellText(row: PerpBoardRow, id: PerpColumnId): string {
341
349
  if (id === "market") return marketLabel(row);
342
350
  if (id === "venue") return venueLabel(row);
343
351
  if (id === "symbol") return row.symbol;
344
- if (id === "markPrice") return markText(row);
352
+ if (id === "markPrice") return perpMarkText(row.markPrice, row.quoteCurrency);
345
353
  if (id === "fundingRate") return fundingPerInterval(row);
346
354
  if (id === "openInterestUsd") return compact(row.openInterestUsd);
347
355
  // A row is dated by its oldest figure: a streamed mark can sit beside the open interest the last poll read.
@@ -2,12 +2,10 @@ import { readFile, stat } from "fs/promises";
2
2
  import { homedir } from "os";
3
3
  import { saveConfig } from "../../../../data/config/store";
4
4
  import { withCollectionMarketData } from "../../../../cli/suffixed-listing-rows";
5
- import { resolveTickersForCli } from "../../../../cli/ticker-resolution";
6
- import { StagedTickerRepository } from "../../../../cli/staged-tickers";
7
5
  import { listingFields, savedListingName } from "../../../../cli/listing-arg";
8
6
  import { cliStyles, renderStats, renderTable } from "../../../../utils/cli-output";
9
7
  import { findNamedCollection } from "../../../../portfolio/collection-name";
10
- import { tickerChangeLine } from "../../../../tickers/ticker-changes";
8
+ import { lookUpPositionSymbols } from "../positions-import/lookup";
11
9
  import { createManualPortfolio, isManualPortfolio } from "../../../../portfolio/mutations";
12
10
  import {
13
11
  decodePositionsFile,
@@ -33,7 +31,6 @@ import {
33
31
  buildPositionsImportPlan,
34
32
  replaceRefusal,
35
33
  summarizePositionsImport,
36
- type ImportSymbolResolution,
37
34
  type PositionsImportMode,
38
35
  type PositionsImportPlan,
39
36
  } from "../../../../portfolio/positions-import/plan";
@@ -49,7 +46,7 @@ export const POSITIONS_IMPORT_HELP = {
49
46
  title: "Importing a broker's positions",
50
47
  lines: [
51
48
  `portfolio import <file> reads the positions export (CSV) a brokerage's positions or holdings page downloads: ${POSITIONS_EXPORT_BROKERS.join(", ")}, or any table with a Symbol (or Ticker) and a Quantity (or Shares) column, and a cost in total (Cost Basis) or per share (Avg Cost, Price Paid), a purchase date (Date Acquired) and a Currency where it has them. US brokers' exports are in USD. A file takes at most ${MAX_IMPORT_POSITIONS.toLocaleString("en-US")} positions; a trade or activity history is refused.`,
52
- "Each symbol becomes a position of shares at its cost per share; rows of one symbol (several accounts or lots) are added up, dated by the earliest. Totals, footers and account headings are left out. Cash and money market sweeps, pending activity, options, bonds and CDs, rows without a ticker and symbols that do not resolve are listed as skipped, each with the reason.",
49
+ "Each symbol becomes a position of shares at its cost per share; rows of one symbol (several accounts or lots) are added up, dated by the earliest. Totals, footers and account headings are left out. Ended listings, unresolved symbols, cash and money market sweeps, pending activity, options, bonds and CDs, and rows without a ticker are listed as skipped, each with the reason.",
53
50
  "The portfolio is named after the broker (or the file) unless --name says otherwise, and is created when it does not exist. One that holds tickers needs --merge (the file's positions replace those of the same listings, a holding's lots becoming one position; the rest stay) or --replace (holdings the file does not list are removed, with their targets). A replace is refused while any of the file's stock or fund rows could not be imported, and never removes a holding the file names on a skipped row. A position the file gives no cost for keeps the holding's own cost, else it has none.",
54
51
  "--dry-run looks every symbol up and prints the same table without saving. In the app, Import Positions… in the PF pane menu shows the same preview before it saves.",
55
52
  ],
@@ -140,18 +137,9 @@ export async function importPositionsFileCommand(
140
137
  const portfolio = existing ?? created!.portfolio;
141
138
 
142
139
  // Looked up as `portfolio add` looks a list up; listings found are kept in memory until the import is saved.
143
- const staged = new StagedTickerRepository(store);
144
- const symbols = file.positions.map((position) => position.symbol);
145
- const lookups = symbols.length > 0
146
- ? await resolveTickersForCli(symbols, staged, dataProvider, undefined, { onRetry: retryNotice(ctx), onProgress: progressNotice(ctx) })
147
- : [];
148
- // A broker's symbols are its own market's listings: a row says only that a symbol changed or stopped trading.
149
- const resolutions = new Map<string, ImportSymbolResolution>(lookups.map((lookup) => [
150
- lookup.input,
151
- lookup.error
152
- ? { error: lookup.error.message }
153
- : { ticker: lookup.ticker, notes: [tickerChangeLine(lookup.change), lookup.ended].filter((note): note is string => !!note) },
154
- ]));
140
+ const symbols = file.positions.map((position) => position.lookupSymbol);
141
+ const { resolutions } = await lookUpPositionSymbols(symbols, { store, dataProvider },
142
+ { onRetry: retryNotice(ctx), onProgress: progressNotice(ctx) });
155
143
  // A portfolio that holds nothing has nothing to replace: the file goes into it either way.
156
144
  const mode = options.mode === "replace" && holdings.length > 0 ? "replace" : "merge";
157
145
  const plan = buildPositionsImportPlan({ file, resolutions, portfolio, holdings, mode, baseCurrency: config.baseCurrency });
@@ -171,7 +159,7 @@ export async function importPositionsFileCommand(
171
159
  }
172
160
 
173
161
  if (!dryRun) {
174
- const latest = new Map<string, TickerRecord>([...lookups.flatMap((lookup) => lookup.ticker ? [lookup.ticker] : []), ...holdings]
162
+ const latest = new Map<string, TickerRecord>([...plan.rows.map((row) => row.ticker), ...holdings]
175
163
  .map((ticker) => [ticker.metadata.ticker, ticker] as const));
176
164
  const applied = applyPositionsImportPlan(plan, {
177
165
  portfolioId: portfolio.id,
@@ -1061,7 +1061,7 @@ const POSITION_HELP = {
1061
1061
  const INCOME_HELP = {
1062
1062
  title: "Income",
1063
1063
  lines: [
1064
- "Income is a year of trailing dividends on the shares held: what each share or fund paid per share over the past twelve months, as DVD reads it, times the shares, in the portfolio's currency. Yield is that over the holding's value; on the TOTAL row, over the whole portfolio, cash included.",
1064
+ "Income is a year of trailing dividends on the shares held: what each share or fund paid per share over the past twelve months, as DVD reads it, times the shares, in the portfolio's currency. Yield is that over the holding's value; on the TOTAL row it is over invested holdings, or gross exposure if the book holds a short. Cash is excluded.",
1065
1065
  `--drip projects reinvested dividends for --years (1 to ${DRIP_MAX_YEARS}, default ${DRIP_DEFAULT_YEARS}), net of --withholding percent (default 0): today's dividends, prices and exchange rates held flat, reinvested once a year.`,
1066
1066
  ],
1067
1067
  };
@@ -17,7 +17,7 @@ const NO_RATES: PurchaseDateCostFx = new Map();
17
17
  */
18
18
  export function usePurchaseDateCostFx(
19
19
  tickers: readonly TickerRecord[],
20
- { enabled, portfolioId, into }: { enabled: boolean; portfolioId: string; into: string },
20
+ { enabled, portfolioId, into }: { enabled: boolean; portfolioId?: string; into: string },
21
21
  ): PurchaseDateCostFx {
22
22
  const key = useMemo(() => enabled ? [...purchaseDatesToRead(tickers, into, portfolioId).keys()].sort().join(",") : "", [enabled, into, portfolioId, tickers]);
23
23
  const tickersRef = useRef(tickers);
@@ -117,7 +117,7 @@ export function usePositionsImport({
117
117
  initialTarget,
118
118
  baseCurrency: config.baseCurrency,
119
119
  };
120
- const symbols = file.positions.map((position) => position.symbol);
120
+ const symbols = file.positions.map((position) => position.lookupSymbol);
121
121
  const lookUp = () => lookUpPositionSymbols(symbols, {
122
122
  tickers: stateRef.current.tickers,
123
123
  store: registry.tickerRepository,