@gloom-sh/terminal 0.20.8 → 0.20.10

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 (165) hide show
  1. package/package.json +1 -1
  2. package/src/api-client/auth.ts +6 -0
  3. package/src/api-client/data.ts +1 -0
  4. package/src/api-client/earnings.ts +15 -0
  5. package/src/api-client/futures-curve.ts +5 -1
  6. package/src/api-client/index.ts +14 -3
  7. package/src/api-client/types/account.ts +10 -0
  8. package/src/api-client/types/billing.ts +10 -0
  9. package/src/api-client/types/econ.ts +19 -7
  10. package/src/api-client/types/market.ts +7 -0
  11. package/src/api-client/types/screener.ts +2 -0
  12. package/src/cli/commands/market.ts +18 -8
  13. package/src/cli/commands/overview.ts +28 -7
  14. package/src/cli/commands/ticker.ts +40 -15
  15. package/src/cli/desktop-pane-shot.ts +39 -0
  16. package/src/cli/errors.ts +20 -3
  17. package/src/cli/fx-pair.ts +11 -2
  18. package/src/cli/history-rows.ts +34 -3
  19. package/src/cli/index.ts +1 -1
  20. package/src/cli/listing-arg.ts +51 -13
  21. package/src/cli/pane-functions/data.ts +3 -2
  22. package/src/cli/pane-functions/headless.ts +5 -2
  23. package/src/cli/pane-functions/index.ts +1 -0
  24. package/src/cli/pane-functions/resolver.ts +2 -1
  25. package/src/cli/pane-functions/screenshot-assessment.ts +73 -5
  26. package/src/cli/pane-functions/screenshot-types.ts +4 -0
  27. package/src/cli/symbol-cells.ts +6 -0
  28. package/src/cli/symbol-list.ts +14 -6
  29. package/src/cli/symbol-rows.ts +12 -5
  30. package/src/components/chart/composite/chart-layout.ts +7 -4
  31. package/src/components/chart/composite/composite-chart.tsx +6 -16
  32. package/src/components/chart/composite/toolbar.tsx +258 -82
  33. package/src/components/chart/composite/use-composite-chart-keyboard.ts +5 -6
  34. package/src/components/command-bar/list/model.ts +13 -0
  35. package/src/components/command-bar/routes/ticker-search/actions.ts +2 -0
  36. package/src/components/command-bar/routes/ticker-search/results.ts +15 -8
  37. package/src/components/command-bar/surface/index.tsx +10 -5
  38. package/src/components/command-bar/workflow/alert.ts +21 -7
  39. package/src/components/data-table/table-pane.ts +3 -1
  40. package/src/components/layout/pane/footer/model.ts +26 -1
  41. package/src/components/metric-treemap/heat-surface.tsx +2 -1
  42. package/src/components/metric-treemap/index.tsx +3 -2
  43. package/src/components/ui/confirm-dialog.tsx +253 -7
  44. package/src/components/ui/data-table/index.tsx +1 -1
  45. package/src/components/ui/data-table/types.ts +7 -0
  46. package/src/components/ui/list-view.tsx +4 -3
  47. package/src/components/ui/page-stack-view.tsx +24 -6
  48. package/src/components/ui/status.tsx +9 -6
  49. package/src/docs/snapshot.json +36 -0
  50. package/src/i18n/es.ts +12 -0
  51. package/src/i18n/ja.ts +12 -0
  52. package/src/i18n/ko.ts +12 -0
  53. package/src/i18n/zh-cn.ts +12 -0
  54. package/src/i18n/zh-tw.ts +12 -0
  55. package/src/market-data/futures-roll-returns.ts +226 -0
  56. package/src/market-data/fx-closes.ts +14 -2
  57. package/src/market-data/market/change-basis.ts +35 -1
  58. package/src/market-data/market/session-close-note.ts +41 -4
  59. package/src/market-data/market/status.ts +37 -0
  60. package/src/market-data/performance.ts +4 -1
  61. package/src/market-data/quotes/listing-enterprise-value.ts +8 -4
  62. package/src/market-data/quotes/live-valuation.ts +25 -2
  63. package/src/market-data/realized-volatility.ts +3 -0
  64. package/src/market-data/us-bond-market.ts +115 -0
  65. package/src/plugins/builtin/account-management/invite-row.tsx +54 -0
  66. package/src/plugins/builtin/account-management/keyboard.ts +3 -0
  67. package/src/plugins/builtin/account-management/model.ts +1 -0
  68. package/src/plugins/builtin/account-management/pane.tsx +51 -5
  69. package/src/plugins/builtin/account-management/trial-cancel.ts +32 -7
  70. package/src/plugins/builtin/backtest/client.ts +9 -2
  71. package/src/plugins/builtin/backtest/pane.tsx +1 -1
  72. package/src/plugins/builtin/backtest/report.ts +22 -6
  73. package/src/plugins/builtin/backtest/window.ts +17 -9
  74. package/src/plugins/builtin/cloud/askg/pane-session.ts +94 -0
  75. package/src/plugins/builtin/cloud/askg/pane.tsx +40 -83
  76. package/src/plugins/builtin/congress-trades/pane.tsx +8 -2
  77. package/src/plugins/builtin/correlation/compute.ts +4 -3
  78. package/src/plugins/builtin/correlation/headless.ts +6 -2
  79. package/src/plugins/builtin/correlation/index.tsx +7 -3
  80. package/src/plugins/builtin/correlation/matrix/model.ts +15 -1
  81. package/src/plugins/builtin/correlation/relationship/model.ts +15 -1
  82. package/src/plugins/builtin/correlation/relationship/pane.tsx +4 -2
  83. package/src/plugins/builtin/earnings/board-model.ts +33 -0
  84. package/src/plugins/builtin/earnings/board-table.ts +50 -11
  85. package/src/plugins/builtin/earnings/board.tsx +29 -13
  86. package/src/plugins/builtin/earnings/calendar.tsx +15 -3
  87. package/src/plugins/builtin/earnings/client.ts +4 -1
  88. package/src/plugins/builtin/earnings/headless.ts +27 -14
  89. package/src/plugins/builtin/econ/calendar-source.ts +3 -0
  90. package/src/plugins/builtin/futures-curve/headless.ts +4 -1
  91. package/src/plugins/builtin/futures-curve/model.ts +24 -0
  92. package/src/plugins/builtin/help/index.tsx +1 -1
  93. package/src/plugins/builtin/ipo-calendar/model.ts +3 -3
  94. package/src/plugins/builtin/iv-history/headless.ts +12 -10
  95. package/src/plugins/builtin/kelly-sizer/headless.ts +2 -2
  96. package/src/plugins/builtin/kelly-sizer/history.ts +10 -3
  97. package/src/plugins/builtin/kelly-sizer/pane.tsx +2 -2
  98. package/src/plugins/builtin/kelly-sizer/sections.tsx +1 -1
  99. package/src/plugins/builtin/macro-day/headless.ts +15 -5
  100. package/src/plugins/builtin/macro-day/model.ts +17 -4
  101. package/src/plugins/builtin/macro-day/releases.ts +36 -15
  102. package/src/plugins/builtin/market-halts/model.ts +3 -2
  103. package/src/plugins/builtin/market-movers/headless.ts +2 -1
  104. package/src/plugins/builtin/market-movers/index.tsx +3 -2
  105. package/src/plugins/builtin/market-movers/model.ts +75 -22
  106. package/src/plugins/builtin/market-movers/screener.ts +2 -1
  107. package/src/plugins/builtin/market-movers/table.ts +7 -5
  108. package/src/plugins/builtin/pe-band/model.ts +4 -0
  109. package/src/plugins/builtin/portfolio-list/cell-version.ts +4 -4
  110. package/src/plugins/builtin/portfolio-list/cli/render.ts +9 -4
  111. package/src/plugins/builtin/portfolio-list/pane/index.tsx +2 -1
  112. package/src/plugins/builtin/portfolio-list/summary/index.tsx +24 -7
  113. package/src/plugins/builtin/portfolio-list/summary/totals.ts +40 -11
  114. package/src/plugins/builtin/portfolio-list/table.tsx +13 -1
  115. package/src/plugins/builtin/realized-vol/headless.ts +11 -6
  116. package/src/plugins/builtin/realized-vol/model.ts +14 -6
  117. package/src/plugins/builtin/realized-vol/pane.tsx +2 -1
  118. package/src/plugins/builtin/realized-vol/settings.ts +2 -1
  119. package/src/plugins/builtin/research/analyst-headless.ts +9 -1
  120. package/src/plugins/builtin/research/analyst-pane.tsx +10 -4
  121. package/src/plugins/builtin/research/client.ts +25 -1
  122. package/src/plugins/builtin/research/corporate-actions-pane.tsx +2 -1
  123. package/src/plugins/builtin/research/event-model.ts +3 -13
  124. package/src/plugins/builtin/research/event-sources.ts +3 -1
  125. package/src/plugins/builtin/seasonality/client.ts +66 -17
  126. package/src/plugins/builtin/seasonality/headless.ts +7 -2
  127. package/src/plugins/builtin/seasonality/model.ts +12 -3
  128. package/src/plugins/builtin/seasonality/pane.tsx +4 -2
  129. package/src/plugins/builtin/shared/use-quote-board.ts +28 -6
  130. package/src/plugins/builtin/short-interest/headless.ts +2 -0
  131. package/src/plugins/builtin/short-interest/publications-headless.ts +2 -0
  132. package/src/plugins/builtin/short-interest/watch-headless.ts +1 -0
  133. package/src/plugins/builtin/yield-curve/headless.ts +5 -1
  134. package/src/plugins/builtin/yield-curve/index.tsx +5 -0
  135. package/src/portfolio/column-values.ts +47 -14
  136. package/src/portfolio/return-metrics.ts +4 -2
  137. package/src/renderers/dom/desktop/controls.tsx +1 -1
  138. package/src/renderers/dom/host/image-surface.tsx +19 -9
  139. package/src/renderers/dom/host/input.tsx +4 -0
  140. package/src/renderers/dom/styles.css +7 -4
  141. package/src/renderers/electrobun/view/cli-pane-shot-entry.tsx +23 -1
  142. package/src/renderers/opentui/box-width.ts +30 -0
  143. package/src/sources/gloomberb-cloud/normalizers.ts +2 -0
  144. package/src/sources/provider-errors.ts +12 -0
  145. package/src/sources/provider-router/index.ts +12 -4
  146. package/src/state/pane-session.ts +145 -0
  147. package/src/tickers/search/home-listing.ts +44 -1
  148. package/src/tickers/search/index.ts +5 -2
  149. package/src/tickers/search/ranking.ts +7 -7
  150. package/src/tickers/us-listing.ts +11 -5
  151. package/src/time-series/base-series.ts +7 -1
  152. package/src/time-series/fundamentals/current-valuation.ts +8 -0
  153. package/src/time-series/fundamentals/series.ts +6 -0
  154. package/src/time-series/resolve.ts +1 -0
  155. package/src/types/financials.ts +36 -3
  156. package/src/types/headless.ts +15 -0
  157. package/src/ui/host.tsx +2 -0
  158. package/src/utils/exchanges.ts +13 -8
  159. package/src/utils/fundamentals.ts +49 -8
  160. package/src/utils/price-earnings.ts +17 -10
  161. package/src/utils/price-history-integrity.ts +15 -0
  162. package/src/utils/reason-codes.ts +79 -0
  163. package/src/utils/share-multiples.cases.json +889 -0
  164. package/src/utils/share-multiples.ts +254 -0
  165. package/src/utils/untrusted-text.ts +11 -0
@@ -56,6 +56,7 @@ import { collectCapabilityRouteSources, mergeRouteSourcesById, normalizeRouteSou
56
56
  import type { ProviderRouterCoreDeps } from "./route-types";
57
57
  import { withProviderConnectionHealth } from "./connection-health";
58
58
  import { withFiledTrailingEps } from "../../time-series/filed-trailing-eps";
59
+ import { withShareMultiples } from "../../utils/share-multiples";
59
60
  import {
60
61
  contextFromCachedTarget,
61
62
  getBrokerCandidates,
@@ -66,6 +67,13 @@ import {
66
67
  type BrokerCandidate,
67
68
  } from "./brokers";
68
69
 
70
+ /**
71
+ * One trailing EPS and P/E for every view of a listing: the filed quarters', as PEB and GE read them
72
+ * (withFiledTrailingEps), and none where the price over it is no multiple of the share (withShareMultiples).
73
+ */
74
+ const withTrailingMultiples = <T extends Parameters<typeof withFiledTrailingEps>[0] & Parameters<typeof withShareMultiples>[0]>(financials: T): T =>
75
+ withShareMultiples(withFiledTrailingEps(financials));
76
+
69
77
  const providerLog = debugLog.createLogger("asset-data-router");
70
78
 
71
79
  /**
@@ -216,7 +224,7 @@ export class AssetDataRouter implements DataProvider {
216
224
  for (const target of valid) {
217
225
  const key = target.symbol.toUpperCase();
218
226
  const financials = cached.get(key);
219
- if (financials) cached.set(key, withFiledTrailingEps(this.knownFinancials(financials, listingOf(target, contextFromCachedTarget(target)))));
227
+ if (financials) cached.set(key, withTrailingMultiples(this.knownFinancials(financials, listingOf(target, contextFromCachedTarget(target)))));
220
228
  }
221
229
  return cached;
222
230
  }
@@ -268,7 +276,7 @@ export class AssetDataRouter implements DataProvider {
268
276
  const results = answered.map((result) => {
269
277
  if (!result.financials) return result;
270
278
  const quoted = result.financials.quote ? this.withDatedQuote(result.financials, dated[next++]!, listingOfResult(result)) : result.financials;
271
- const financials = withFiledTrailingEps(quoted);
279
+ const financials = withTrailingMultiples(quoted);
272
280
  return financials === result.financials ? result : { ...result, financials };
273
281
  });
274
282
  const restored = new Map(results.map((result) => {
@@ -283,11 +291,11 @@ export class AssetDataRouter implements DataProvider {
283
291
  const { context, datesChangeBasis } = splitDating(requestContext);
284
292
  exchange = this.resolvePublicExchange(ticker, exchange, context);
285
293
  const financials = await this.financialRoutes.getTickerFinancials(ticker, exchange, context);
286
- if (!financials.quote) return withFiledTrailingEps(financials);
294
+ if (!financials.quote) return withTrailingMultiples(financials);
287
295
  const listing = listingOf({ symbol: ticker, exchange }, context);
288
296
  const [quote] = await this.datedAnswers([{ quote: financials.quote, listing }], datesChangeBasis);
289
297
  // One trailing EPS and P/E for every view of the listing: the filed quarters', as PEB and GE read them.
290
- return withFiledTrailingEps(this.withDatedQuote(financials, quote!, listing));
298
+ return withTrailingMultiples(this.withDatedQuote(financials, quote!, listing));
291
299
  }
292
300
 
293
301
  async getQuote(ticker: string, exchange?: string, requestContext?: MarketDataRequestContext): Promise<Quote> {
@@ -0,0 +1,145 @@
1
+ import {
2
+ useCallback,
3
+ useEffect,
4
+ useMemo,
5
+ useSyncExternalStore,
6
+ type SetStateAction,
7
+ } from "react";
8
+ import { useOptionalPaneInstanceId } from "./app/context";
9
+
10
+ /**
11
+ * Memory a pane keeps for as long as the pane exists, rather than for as long
12
+ * as it is mounted.
13
+ *
14
+ * Docking, floating, stacking or fullscreening a pane draws it in another
15
+ * place in the tree, so its component mounts again. What it shows has to come
16
+ * back on the first frame: a pane that reads it from component state, or has to
17
+ * fetch it again, draws its empty state in between and loses the selection.
18
+ * What the user chose and can save belongs in pane state (`usePluginPaneState`,
19
+ * `usePaneSettingValue`); this holds what cannot be saved or must not be: a
20
+ * live conversation with its answer still coming in, a transcript, a draft.
21
+ * It is in memory only, so a relaunch starts without it, and a shared layout
22
+ * never carries it.
23
+ */
24
+
25
+ /**
26
+ * How long a pane's memory outlives its last mounted view. A move between the
27
+ * dock and a floating window mounts the new view in the commit that unmounts
28
+ * the old one; a closed pane never mounts again, and its memory is released
29
+ * after this.
30
+ */
31
+ export const PANE_SESSION_GRACE_MS = 2_000;
32
+
33
+ interface SessionEntry {
34
+ id: string;
35
+ value: unknown;
36
+ dispose: ((value: never) => void) | undefined;
37
+ holders: number;
38
+ timer: ReturnType<typeof setTimeout> | null;
39
+ }
40
+
41
+ const sessions = new Map<string, SessionEntry>();
42
+
43
+ function scheduleRelease(entry: SessionEntry): void {
44
+ if (entry.timer) clearTimeout(entry.timer);
45
+ entry.timer = setTimeout(() => {
46
+ entry.timer = null;
47
+ if (entry.holders > 0 || sessions.get(entry.id) !== entry) return;
48
+ sessions.delete(entry.id);
49
+ entry.dispose?.(entry.value as never);
50
+ }, PANE_SESSION_GRACE_MS);
51
+ }
52
+
53
+ /** Finds a pane's session or makes it. One a render makes and nothing mounts is released like any other. */
54
+ function acquire<T>(paneId: string, key: string, create: () => T, dispose: ((value: T) => void) | undefined): SessionEntry {
55
+ const id = `${paneId}\u0000${key}`;
56
+ const existing = sessions.get(id);
57
+ if (existing) return existing;
58
+ const entry: SessionEntry = { id, value: create(), dispose: dispose as SessionEntry["dispose"], holders: 0, timer: null };
59
+ sessions.set(id, entry);
60
+ scheduleRelease(entry);
61
+ return entry;
62
+ }
63
+
64
+ /** Test hook: releases every pane's memory now, so one test's panes never start on another's. */
65
+ export function resetPaneSessionsForTests(): void {
66
+ for (const entry of [...sessions.values()]) {
67
+ if (entry.timer) clearTimeout(entry.timer);
68
+ entry.timer = null;
69
+ sessions.delete(entry.id);
70
+ entry.dispose?.(entry.value as never);
71
+ }
72
+ }
73
+
74
+ function useScopedPaneId(paneId?: string): string {
75
+ const contextId = useOptionalPaneInstanceId();
76
+ const scoped = paneId ?? contextId;
77
+ if (!scoped) throw new Error("A pane session requires a pane id or PaneInstanceProvider");
78
+ return scoped;
79
+ }
80
+
81
+ /**
82
+ * An object that lives as long as the pane does: the same one in every view
83
+ * the pane is drawn in, made by `create` the first time. `dispose` runs once
84
+ * the pane has had no mounted view for the grace period (the pane was closed).
85
+ * Read it during render; it never changes identity while the pane exists.
86
+ */
87
+ export function usePaneSession<T>(
88
+ key: string,
89
+ create: () => T,
90
+ dispose?: (value: T) => void,
91
+ paneId?: string,
92
+ ): T {
93
+ const scopedPaneId = useScopedPaneId(paneId);
94
+ const entry = useMemo(() => acquire(scopedPaneId, key, create, dispose), [scopedPaneId, key]);
95
+ useEffect(() => {
96
+ entry.holders += 1;
97
+ if (entry.timer) {
98
+ clearTimeout(entry.timer);
99
+ entry.timer = null;
100
+ }
101
+ return () => {
102
+ entry.holders -= 1;
103
+ if (entry.holders <= 0) scheduleRelease(entry);
104
+ };
105
+ }, [entry]);
106
+ return entry.value as T;
107
+ }
108
+
109
+ interface StateBox<T> {
110
+ value: T;
111
+ listeners: Set<() => void>;
112
+ }
113
+
114
+ /**
115
+ * `useState` for a selection or draft that cannot be saved with the pane: the
116
+ * value is kept for the pane, so the view mounted after a dock change starts on
117
+ * it. A setter held by the view it unmounted still lands, on the value the new
118
+ * view reads. See `usePaneSession` for what belongs here and what belongs in
119
+ * pane state.
120
+ */
121
+ export function usePaneSessionState<T>(
122
+ key: string,
123
+ initial: T | (() => T),
124
+ paneId?: string,
125
+ ): [T, (value: SetStateAction<T>) => void] {
126
+ const box = usePaneSession<StateBox<T>>(key, () => ({
127
+ value: typeof initial === "function" ? (initial as () => T)() : initial,
128
+ listeners: new Set(),
129
+ }), undefined, paneId);
130
+ const subscribe = useCallback((listener: () => void) => {
131
+ box.listeners.add(listener);
132
+ return () => {
133
+ box.listeners.delete(listener);
134
+ };
135
+ }, [box]);
136
+ const getSnapshot = useCallback(() => box.value, [box]);
137
+ const value = useSyncExternalStore(subscribe, getSnapshot, getSnapshot);
138
+ const setValue = useCallback((next: SetStateAction<T>) => {
139
+ const resolved = typeof next === "function" ? (next as (previous: T) => T)(box.value) : next;
140
+ if (Object.is(resolved, box.value)) return;
141
+ box.value = resolved;
142
+ for (const listener of [...box.listeners]) listener();
143
+ }, [box]);
144
+ return [value, setValue];
145
+ }
@@ -1,6 +1,6 @@
1
1
  import { canonicalExchange, isUsListingExchange } from "../../utils/exchanges";
2
2
  import { companyLines, companyNameExtraWords, companyNameMatch, namedByService, type CompanyLineFacts } from "../company-name";
3
- import { answersOnlyByKeyword, isPlaceholderLine, isQualifiedTickerQuery, readsAsUsTicker } from "./ranking";
3
+ import { answersOnlyByKeyword, getIssuerGroupKey, isPlaceholderLine, isQualifiedTickerQuery, normalizeTickerSymbol, readsAsUsTicker } from "./ranking";
4
4
  import type { TickerSearchCandidate } from "./types";
5
5
 
6
6
  /** Venues that only quote shares listed elsewhere: the OTC tiers, Frankfurt's open market and Germany's regional exchanges. */
@@ -187,6 +187,49 @@ export function withHomeListingLead<T extends TickerSearchCandidate>(items: T[],
187
187
  return [...rest.slice(0, after), home, ...rest.slice(after)];
188
188
  }
189
189
 
190
+ /**
191
+ * A US ticker typed that is also a large company's short name leads with the
192
+ * US line, as a bare ticker resolves, then the rows the service marks with
193
+ * the word as typed: the company the word names, ahead of the ticker's other
194
+ * rows. "aia" is the iShares Asia 50 ETF's AIA, then AIA Group's 1299; "byd"
195
+ * is Boyd Gaming's BYD, then BYD Company's 002594 and 1211. Under the
196
+ * ticker, each company's first row then comes before further venues of one
197
+ * already listed (Boyd Gaming's BYD on IEX, the ETF's AIA in Mexico), which
198
+ * would push the other companies out of a short list. A line on a US
199
+ * exchange, a home line and a saved row are no such copies, and a line
200
+ * with no name of its own is no other company. The lead's own
201
+ * home line, which `withHomeListingLead` put right after it, stays there. A
202
+ * name typed as a name (`Aia`) or with its venue (AIA:NASDAQ) asks for
203
+ * something else.
204
+ */
205
+ export function withNamedCompanyAfterUsLead<T extends TickerSearchCandidate>(items: T[], query: string): T[] {
206
+ if (isQualifiedTickerQuery(query) || !readsAsUsTicker(query)) return items;
207
+ const typed = normalizeTickerSymbol(query);
208
+ const exact = (item: T) => normalizeTickerSymbol(item.symbol || item.label) === typed;
209
+ const [lead, next] = items;
210
+ if (!lead || lead.kind !== "search" || !exact(lead) || !isUsListingExchange(candidateExchange(lead))) return items;
211
+ const at = next && !exact(next) && next.result?.homeListing === true ? 2 : 1;
212
+ const named = items.slice(at).filter((item) => item.kind === "search" && !exact(item) && !!item.result && namedByService(query, item.result));
213
+ let rest = items.slice(at).filter((item) => !named.includes(item));
214
+ const companyOf = (item: T) => getIssuerGroupKey(item.detail) || item.id;
215
+ const listed = new Set(items.slice(0, at).filter(exact).map(companyOf));
216
+ const copies = rest.filter((item) => {
217
+ if (!exact(item)) return false;
218
+ const further = listed.has(companyOf(item));
219
+ listed.add(companyOf(item));
220
+ return further && item.kind === "search" && !item.saved && item.result?.homeListing !== true
221
+ && !isUsListingExchange(candidateExchange(item));
222
+ });
223
+ const others = rest.filter((item) => !copies.includes(item));
224
+ // A line with no name of its own (a nameless Buenos Aires DK) is no other company the copies would crowd out.
225
+ const ownName = (item: T) => !!item.result?.name?.trim() && !isPlaceholderLine(item);
226
+ const last = others.findLastIndex((item) => exact(item) && ownName(item));
227
+ const crowding = copies.length > 0 && last >= 0 && rest.indexOf(copies[0]!) < rest.indexOf(others[last]!);
228
+ if (!named.length && !crowding) return items;
229
+ if (crowding) rest = [...others.slice(0, last + 1), ...copies, ...others.slice(last + 1)];
230
+ return [...items.slice(0, at), ...named, ...rest];
231
+ }
232
+
190
233
  /** `items` with `home` moved just ahead of `lead`. */
191
234
  function moveAhead<T>(items: readonly T[], home: T, lead: T): T[] {
192
235
  const rest = items.filter((item) => item !== home);
@@ -41,7 +41,7 @@ import { endsInLegalForm, readNearMissListing, readVenueFirstListing, readTermin
41
41
  import { isProviderBusy, ProviderBusyError, SEARCH_BUSY_MESSAGE } from "../../sources/provider-errors";
42
42
  import { settleWithin } from "../../utils/async-deadline";
43
43
  import { companyNameExtraWords } from "../company-name";
44
- import { withHomeListingLead } from "./home-listing";
44
+ import { withHomeListingLead, withNamedCompanyAfterUsLead } from "./home-listing";
45
45
  import { answeredInFull, rememberSearchAnswer, withKnownListings } from "./listing-index";
46
46
  import { savedAbroadForBareSymbol, savedUsListingOf } from "./bare-symbol";
47
47
  import { delistingLabel, parseListingWithdrawal, withdrawalLabel } from "../../market-data/quotes/delisting";
@@ -356,7 +356,10 @@ export function buildTickerSearchCandidates({
356
356
  query,
357
357
  );
358
358
  const providerItems = createProviderTickerSearchCandidates(filteredProviderResults, tickers, candidateOptions);
359
- const ranked = withHomeListingLead(withSuccessorFirst(rankTickerSearchItems([...localItems, ...providerItems], query), query), query);
359
+ const ranked = withNamedCompanyAfterUsLead(
360
+ withHomeListingLead(withSuccessorFirst(rankTickerSearchItems([...localItems, ...providerItems], query), query), query),
361
+ query,
362
+ );
360
363
  return limitTickerSearchCandidates(companyListingsFirst(assignTickerSearchCategories(ranked, query), query), totalLimit, localLimit);
361
364
  }
362
365
 
@@ -371,17 +371,17 @@ export function rankTickerSearchItems<T extends Pick<TickerSearchRankableItem, "
371
371
  const bIssuerRank = exactIssuerRank.get(exactIssuerKey(b)) ?? Number.POSITIVE_INFINITY;
372
372
  if (aIssuerRank !== bIssuerRank) return aIssuerRank - bIssuerRank;
373
373
  }
374
- if (b.score !== a.score) return b.score - a.score;
375
- const aSaved = isSavedSearchItem(a.item);
376
- const bSaved = isSavedSearchItem(b.item);
377
- if (aSaved !== bSaved) return aSaved ? -1 : 1;
378
- // Rows that answer to the same typed name (GOOGL and GOOG for "Google")
379
- // keep the order the server gave them rather than the shorter symbol first.
380
- if (a.symbolMatchRank === 2) {
374
+ // Rows the server sent for the name as typed (GOOGL and GOOG for "Google"; Microsoft, Micron and
375
+ // Microchip for "micro", largest first) keep its order, rather than the shorter name or symbol first.
376
+ if (a.symbolMatchRank === 2 && !isSavedSearchItem(a.item) && !isSavedSearchItem(b.item)) {
381
377
  const aProviderRank = a.item.providerRank ?? Number.POSITIVE_INFINITY;
382
378
  const bProviderRank = b.item.providerRank ?? Number.POSITIVE_INFINITY;
383
379
  if (aProviderRank !== bProviderRank) return aProviderRank - bProviderRank;
384
380
  }
381
+ if (b.score !== a.score) return b.score - a.score;
382
+ const aSaved = isSavedSearchItem(a.item);
383
+ const bSaved = isSavedSearchItem(b.item);
384
+ if (aSaved !== bSaved) return aSaved ? -1 : 1;
385
385
  if (a.item.label.length !== b.item.label.length) return a.item.label.length - b.item.label.length;
386
386
  return a.index - b.index;
387
387
  };
@@ -1,6 +1,6 @@
1
1
  import { logFailure } from "../utils/log-failure";
2
2
  import type { DataProvider } from "../types/data-provider";
3
- import { canonicalExchange, isUsListingExchange, parsePublicTickerKey } from "../utils/exchanges";
3
+ import { canonicalExchange, isUsListingExchange, isUsOtcVenue, parsePublicTickerKey } from "../utils/exchanges";
4
4
  import { sameCompany } from "./company-name";
5
5
  import { LISTING_SEARCH_LIMIT } from "./search";
6
6
  import { classifyInstrumentKind } from "./search/ranking";
@@ -15,21 +15,27 @@ export interface UsListing {
15
15
  /**
16
16
  * A company's own listing on a US exchange, found by its name: Sanofi's SNY,
17
17
  * Toyota's TM. Funds and contracts that carry its name are not its listing.
18
- * Null when search knows no US line of the company.
18
+ * With `otc`, a line over the counter counts when the company has none on an
19
+ * exchange. Null when search knows no such US line of the company.
19
20
  */
20
21
  export async function findUsListingOfCompany(
21
22
  dataProvider: Pick<DataProvider, "search">,
22
23
  company: string | null | undefined,
24
+ { otc = false }: { otc?: boolean } = {},
23
25
  ): Promise<UsListing | null> {
24
26
  const name = company?.trim();
25
27
  if (!name) return null;
26
28
  const results = await dataProvider.search(name, { limit: LISTING_SEARCH_LIMIT }).catch(logFailure("tickers-us-listing", "Could not search US listing", []));
29
+ let overTheCounter: UsListing | null = null;
27
30
  for (const result of results) {
28
31
  const exchange = canonicalExchange(result.exchange === "SMART" ? result.primaryExchange : result.exchange || result.primaryExchange);
29
32
  const kind = classifyInstrumentKind(result.brokerContract?.secType || result.type);
30
- if (!isUsListingExchange(exchange) || kind === "fund" || kind === "derivative") continue;
33
+ const listed = isUsListingExchange(exchange);
34
+ if (!(listed || (otc && isUsOtcVenue(exchange))) || kind === "fund" || kind === "derivative") continue;
31
35
  if (!sameCompany(result.name, name) || parsePublicTickerKey(result.symbol).exchange) continue;
32
- return { symbol: result.symbol.toUpperCase(), exchange, name: result.name };
36
+ const line = { symbol: result.symbol.toUpperCase(), exchange, name: result.name };
37
+ if (listed) return line;
38
+ overTheCounter ??= line;
33
39
  }
34
- return null;
40
+ return overTheCounter;
35
41
  }
@@ -1,5 +1,6 @@
1
1
  import { resolveAssetDisplayKind } from "../market-data/market/format";
2
2
  import { hasValidQuoteObservationTime } from "../market-data/quotes/freshness";
3
+ import { getActiveQuoteDisplay, getRegularSessionDisplay } from "../market-data/market/status";
3
4
  import type { HistorySession } from "../types/price-history";
4
5
  import { appendLiveQuotePoint, hasUnknownBondHistoryBasis } from "./chart-data";
5
6
  import type { LiveBarAccumulator } from "./live-bars";
@@ -135,6 +136,8 @@ export function baseSecuritySeries(
135
136
  quoteMetadata: QuoteMetadata | null | undefined = financials.quoteMetadata,
136
137
  /** What a futures contract's price counts ("USD / gallon"), from its terms. */
137
138
  contractUnit?: string | null,
139
+ /** The bars run into pre-market and after-hours trading. */
140
+ { extendedHours = false }: { extendedHours?: boolean } = {},
138
141
  ): ResolvedSeries | null {
139
142
  if (spec.source.kind !== "security") return null;
140
143
  const field = getTimeSeriesField(spec.source.fieldId);
@@ -217,10 +220,13 @@ export function baseSecuritySeries(
217
220
  const listingExchange = canonicalExchange(marketExchange) === "SMART" || usOption
218
221
  ? canonicalExchange(sessionExchange) || (routedUsListing ? "NYSE" : marketExchange)
219
222
  : marketExchange;
223
+ // The move of the price the chart ends on: the regular session's, its close
224
+ // once it is over, as `quote` heads Last; the latest print's, an after-hours
225
+ // one included, where the bars run into extended hours.
220
226
  const latestChangePercent = marketField && field.unit.startsWith("currency")
221
227
  && !unknownBondBasis
222
228
  && financials.quote && hasValidQuoteObservationTime(financials.quote)
223
- ? financials.quote.changePercent
229
+ ? (extendedHours ? getActiveQuoteDisplay(financials.quote) : getRegularSessionDisplay(financials.quote))?.changePercent
224
230
  : undefined;
225
231
  const priceIssues = valuationPriceIssues(financials, spec.source);
226
232
  // A source with closes only, such as a generic future, has flat bars (open,
@@ -129,6 +129,8 @@ function currentDerivedValuation(
129
129
  ))
130
130
  .at(-1)?.candidate;
131
131
  if (!statement) return null;
132
+ // A P/E `valuation` withdraws (utils/share-multiples) is withdrawn here too, never read again as the price over EPS.
133
+ if (metric === "trailingPE" && financials.fundamentals?.notMeaningful?.trailingPE) return { value: null, date: current.date, statement };
132
134
  // The listing's EV needs no price in the statement's currency: an ADR's converts the statement instead.
133
135
  const listing = listingEnterpriseMultiple(financials, statement, metric);
134
136
  if (listing !== undefined) return { value: listing, date: current.date, statement };
@@ -202,6 +204,12 @@ function currentValuation(financials: TickerFinancials, period: SeriesPeriod | u
202
204
  */
203
205
  export function valuationNotMeaningful(financials: TickerFinancials, source: SecuritySeriesSource): { reason: string; asOf: string } | undefined {
204
206
  const [namespace, metric = ""] = canonicalTimeSeriesFieldId(source.fieldId).split(".");
207
+ if (namespace === "valuation" && (metric === "trailingPE" || metric === "forwardPE" || metric === "pegRatio")) {
208
+ const reason = financials.fundamentals?.notMeaningful?.[metric];
209
+ const asOf = financials.fundamentals?.trailingEpsPeriodEnd
210
+ ?? [...financials.quarterlyStatements, ...financials.annualStatements].map((row) => row.date).sort().at(-1);
211
+ return reason && asOf ? { reason: reason[0]!.toUpperCase() + reason.slice(1), asOf: asOf.slice(0, 10) } : undefined;
212
+ }
205
213
  if (namespace !== "valuation" || metric !== "evEbitda") return undefined;
206
214
  // A daily series ends on the trailing twelve months, as its current point does.
207
215
  const period = source.period === "daily" || source.period === "auto" || !source.period ? "ttm" : source.period;
@@ -8,6 +8,7 @@ import { createValuationCurrencyContext } from "../valuation-currency";
8
8
  import { valuationPriceAtOrBefore, valuationQuoteIssue, type ValuationPriceIssue } from "../valuation-price";
9
9
  import type { SecuritySeriesSource, TimeSeriesPoint } from "../types";
10
10
  import { isBankOrInsurerIndustry } from "../../utils/ebitda";
11
+ import { notTheShare } from "../../utils/share-multiples";
11
12
  import { currentDerivedValuationPoint, currentValuationStatements, providerCurrentValuationPoint } from "./current-valuation";
12
13
  import { dailyStatementValuation, dailyValuationFallbackPeriod, historicalValuation } from "./historical-valuation";
13
14
  import { FUNDAMENTAL_IDS, QUOTE_DERIVED_VALUATION_IDS, VALUATION_IDS, valuationSeriesUsesLiveQuote } from "./metric-ids";
@@ -16,6 +17,9 @@ import { sourceStatements } from "./source-statements";
16
17
  import { fundamentalValue, metricAvailability } from "./statement-fields";
17
18
  import { valuationAtPrice } from "./valuation-multiples";
18
19
 
20
+ /** The multiples of a share's price over its company's earnings (notTheShare withdraws them). */
21
+ const SHARE_PRICE_EARNINGS = new Set(["trailingPE", "forwardPE", "realizedNtmPE", "pegRatio"]);
22
+
19
23
  /** Extracts the selected statement snapshot, retaining known availability dates without reconstructing prior vintages. */
20
24
  export function extractFundamentalSeries(
21
25
  financials: TickerFinancials | null,
@@ -49,6 +53,8 @@ export function extractFundamentalSeries(
49
53
  }
50
54
 
51
55
  if (namespace !== "valuation" || !VALUATION_IDS.has(metric)) return [];
56
+ // A warrant's, a right's, a unit's or an unratioed receipt's price over its company's EPS is no P/E at any date.
57
+ if (SHARE_PRICE_EARNINGS.has(metric) && notTheShare(financials)) return [];
52
58
  // A bank's or an insurer's EBITDA measures nothing: its EV/EBITDA is N/M throughout (valuationNotMeaningful).
53
59
  if (metric === "evEbitda" && isBankOrInsurerIndustry(financials.profile?.industry)) return [];
54
60
  const fallback = dailyValuationFallbackPeriod(financials, source);
@@ -1033,6 +1033,7 @@ async function resolveChartSpecPass(
1033
1033
  history?.resolution,
1034
1034
  quoteMetadata,
1035
1035
  contractUnit,
1036
+ { extendedHours: history?.extendedHours === true },
1036
1037
  );
1037
1038
  if (!base) throw new Error(`Unknown field ${source.fieldId}.`);
1038
1039
  let result = builtBars ? withBuiltBarSize(base, builtBars) : base;
@@ -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. */
@@ -406,6 +414,12 @@ export interface Fundamentals extends DepositaryReceiptFacts {
406
414
  epsCurrency?: string;
407
415
  /** Set when `trailingPE` divides the price by the trailing EPS converted from another currency. */
408
416
  trailingPEConversion?: TrailingPEConversion;
417
+ /**
418
+ * What the trailing EPS was worked out from where Gloom Cloud did not take
419
+ * its source's: `statements` (net income over shares), `home` (a receipt's
420
+ * home line, per receipt), `cpo` (a CPO line's company, per CPO).
421
+ */
422
+ trailingEpsBasis?: "statements" | "home" | "cpo";
409
423
  /** Provider-reported issuer market cap; marketCapCurrency identifies its units when known. */
410
424
  marketCap?: number;
411
425
  marketCapCurrency?: string;
@@ -467,6 +481,12 @@ export interface Fundamentals extends DepositaryReceiptFacts {
467
481
  */
468
482
  trailingEpsSource?: "filed-quarters" | "served";
469
483
  trailingEpsPeriodEnd?: string;
484
+ /**
485
+ * Why a multiple is withdrawn though its figures are numbers (utils/share-multiples): a warrant's price over its
486
+ * company's EPS, a receipt's with no ratio on record, an EPS that is not net income over the shares. The multiple
487
+ * itself is absent; every view reads it as N/M with this reason.
488
+ */
489
+ notMeaningful?: Partial<Record<"trailingPE" | "forwardPE" | "pegRatio", string>>;
470
490
  operatingMargin?: number;
471
491
  profitMargin?: number;
472
492
  revenueGrowth?: number;
@@ -1092,6 +1112,11 @@ export interface FinancialStatement {
1092
1112
  totalEquity?: number;
1093
1113
  totalEquityGrossMinorityInterest?: number;
1094
1114
  commonStockEquity?: number;
1115
+ /**
1116
+ * Minority interest and preferred equity as the company's 10-K or 10-Q tags them for the date: on a quarter Gloom
1117
+ * Cloud reads from the filing alone, which has no equity lines.
1118
+ */
1119
+ minorityAndPreferredEquity?: number;
1095
1120
  commonStock?: number;
1096
1121
  capitalStock?: number;
1097
1122
  additionalPaidInCapital?: number;
@@ -1157,6 +1182,14 @@ export interface PricePoint {
1157
1182
  rescaled?: number;
1158
1183
  /** A continuous future's bar (NG=F): the contract it closes on (NGZ26). A change from the bar before is a roll. */
1159
1184
  contract?: string;
1185
+ /** A currency pair's daily bar whose source repeated its open as its close: the close is the next session's open. */
1186
+ closeRebuilt?: boolean;
1187
+ /**
1188
+ * A currency pair's daily bar whose source repeated its open as its close, which no next open in its week rebuilds
1189
+ * (none, or one over 5% away): its close is no day's close, and returns leave the bar out
1190
+ * (pricePointCloseCopied).
1191
+ */
1192
+ closeCopied?: boolean;
1160
1193
  }
1161
1194
 
1162
1195
  export interface StatementHistoryAttempt {
@@ -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;
@@ -817,6 +823,15 @@ export interface HeadlessPaneDefinition<Shape extends HeadlessPaneShape = Headle
817
823
  * in the US never shows that company's numbers.
818
824
  */
819
825
  usListingsOnly?: string;
826
+ /**
827
+ * The data covers US over-the-counter lines too (FINRA's short interest
828
+ * and weekly off-exchange volume, the SEC's fails to deliver, daily
829
+ * closes), so a listing abroad is offered its company's OTC line when it
830
+ * has no US exchange listing (Tencent's TCEHY for 0700.HK). Without it
831
+ * only exchange listings are offered, as options, trades and FINRA's
832
+ * daily short volume cover no OTC line.
833
+ */
834
+ usListingsOtc?: boolean;
820
835
  /**
821
836
  * A sentence that answer adds for a listing abroad, after its US listing:
822
837
  * where to read the nearest data the function has for it (time and sales
package/src/ui/host.tsx CHANGED
@@ -204,6 +204,8 @@ export interface InputRenderable {
204
204
  setCursorOffset?(offset: number): void;
205
205
  focus?(): void;
206
206
  blur?(): void;
207
+ /** Whether the field has the keyboard now: the keys typed go to it. */
208
+ readonly focused?: boolean;
207
209
  }
208
210
 
209
211
  export interface TextareaRenderable extends InputRenderable {
@@ -177,21 +177,26 @@ export function usShareClassSpellings(symbol: string, exchange?: string | null):
177
177
  return [`${match[1]}.${match[2]}`, `${match[1]}-${match[2]}`, `${match[1]}/${match[2]}`];
178
178
  }
179
179
 
180
+ /** Canonical US over-the-counter venues: OTC, and the OTC Markets tiers' listing codes. */
181
+ const US_OTC_EXCHANGES: ReadonlySet<string> = new Set(["OTC", "PINK", "PNK", "OQB", "OQX", "OEM", "OBB"]);
182
+
180
183
  /** Canonical US equity venues: the listing exchanges plus other lit and OTC venues. */
181
184
  const US_EQUITY_EXCHANGES: ReadonlySet<string> = new Set([
182
185
  ...US_LISTING_EXCHANGES,
183
186
  "BYX",
184
187
  "IEX",
185
- "OTC",
186
- "PINK",
187
- // Listing codes for the OTC Markets tiers.
188
- "PNK",
189
- "OQB",
190
- "OQX",
191
- "OEM",
192
- "OBB",
188
+ ...US_OTC_EXCHANGES,
193
189
  ]);
194
190
 
191
+ /**
192
+ * A US over-the-counter venue, by its code (OTC, PNK, OQX) or as a quote
193
+ * names it ("OTC MARKETS OTCPK" for TCEHY, "Other OTC").
194
+ */
195
+ export function isUsOtcVenue(value?: string): boolean {
196
+ const venue = canonicalExchange(value);
197
+ return US_OTC_EXCHANGES.has(venue) || /^(?:OTC MARKETS\b|OTCPK$|OTCQX$|OTCQB$|PINX$|OTHER OTC$)/.test(venue);
198
+ }
199
+
195
200
  /** A US venue a stock or fund trades on, listed or over the counter. */
196
201
  export function isUsEquityExchange(value?: string): boolean {
197
202
  return US_EQUITY_EXCHANGES.has(canonicalExchange(value));