@gloom-sh/terminal 0.20.4 → 0.20.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (316) hide show
  1. package/README.md +3 -1
  2. package/README.zh-CN.md +1 -1
  3. package/bin/gloom +9 -0
  4. package/bin/without-bun.cjs +98 -0
  5. package/package.json +4 -1
  6. package/src/api-client/data.ts +148 -37
  7. package/src/api-client/hk-tenders.ts +59 -0
  8. package/src/api-client/index.ts +1 -0
  9. package/src/api-client/types/econ.ts +30 -0
  10. package/src/api-client/yield-curves.ts +1 -1
  11. package/src/app/global-shortcuts.ts +4 -1
  12. package/src/app/keybindings/actions.ts +6 -0
  13. package/src/app/keybindings/config.ts +2 -1
  14. package/src/app/keybindings/index.ts +1 -0
  15. package/src/app/keybindings/labels.ts +6 -1
  16. package/src/app/keybindings/resolve.ts +23 -4
  17. package/src/app/keybindings/terminal-keys.ts +35 -0
  18. package/src/app/pane-runtime/index.tsx +2 -2
  19. package/src/app/pane-runtime/ticker-open-runtime.ts +68 -40
  20. package/src/app.tsx +18 -13
  21. package/src/architecture/floating-promise-allowlist.json +313 -0
  22. package/src/architecture/ui-literals-allowlist.json +1 -1
  23. package/src/capabilities/chart-series.ts +27 -1
  24. package/src/cli/commands/keybindings.ts +5 -5
  25. package/src/cli/commands/market.ts +238 -57
  26. package/src/cli/commands/news-search.ts +81 -14
  27. package/src/cli/commands/overview.ts +27 -6
  28. package/src/cli/commands/remote.ts +16 -17
  29. package/src/cli/commands/system.ts +1 -1
  30. package/src/cli/commands/ticker.ts +3 -1
  31. package/src/cli/early-command.ts +2 -0
  32. package/src/cli/errors.ts +10 -1
  33. package/src/cli/fx-forward.ts +89 -7
  34. package/src/cli/fx-pair.ts +1 -1
  35. package/src/cli/fx-quote-rate.ts +23 -0
  36. package/src/cli/glossary.ts +19 -5
  37. package/src/cli/help.ts +1 -0
  38. package/src/cli/history-rows.ts +5 -3
  39. package/src/cli/index-roots.ts +5 -4
  40. package/src/cli/index.ts +40 -3
  41. package/src/cli/known-gaps.ts +38 -9
  42. package/src/cli/listing-arg.ts +17 -5
  43. package/src/cli/name-entries.ts +5 -1
  44. package/src/cli/not-a-ticker.ts +4 -0
  45. package/src/cli/options.ts +52 -3
  46. package/src/cli/output-file.ts +5 -3
  47. package/src/cli/pane-functions/catalog.ts +15 -0
  48. package/src/cli/pane-functions/function-help.ts +4 -4
  49. package/src/cli/pane-functions/headless.ts +9 -4
  50. package/src/cli/pane-functions/index.ts +6 -4
  51. package/src/cli/pane-functions/resolver.ts +2 -2
  52. package/src/cli/result.ts +21 -2
  53. package/src/cli/spreadsheet-hint.ts +7 -3
  54. package/src/cli/treasury-yields.ts +5 -3
  55. package/src/components/chart/composite/legend.tsx +40 -2
  56. package/src/components/command-bar/pane-settings.ts +2 -2
  57. package/src/components/command-bar/routes/root/results.ts +6 -2
  58. package/src/components/command-bar/workflow/tickers.ts +2 -2
  59. package/src/components/data-table/view.tsx +9 -2
  60. package/src/components/input-search-bar.tsx +9 -2
  61. package/src/components/layout/pane/header.tsx +2 -0
  62. package/src/components/layout/shell/pane/capture.ts +4 -1
  63. package/src/components/layout/status-bar.tsx +6 -1
  64. package/src/components/onboarding/first-run-workspace.ts +44 -2
  65. package/src/components/onboarding/onboarding-frame.tsx +11 -2
  66. package/src/components/onboarding/onboarding-keyboard.ts +16 -0
  67. package/src/components/onboarding/onboarding-wizard.tsx +8 -8
  68. package/src/components/onboarding/portfolio-step/positions-panel.tsx +62 -1
  69. package/src/components/onboarding/use-onboarding-progress.ts +12 -4
  70. package/src/components/pane-settings-dialog/desktop.tsx +2 -2
  71. package/src/components/pane-settings-dialog/tui.tsx +2 -2
  72. package/src/components/pane-settings-dialog/value.ts +6 -0
  73. package/src/components/pane-settings-dialog.tsx +3 -3
  74. package/src/components/reader/detail-reader.tsx +4 -0
  75. package/src/components/ui/data-table/opentui/index.tsx +11 -4
  76. package/src/components/ui/data-table/opentui/model.ts +8 -6
  77. package/src/components/ui/data-table/types.ts +6 -1
  78. package/src/components/ui/index.ts +1 -1
  79. package/src/components/ui/page-stack-view.tsx +3 -0
  80. package/src/components/ui/pane-link-chip.tsx +269 -54
  81. package/src/components/ui/query-bar.tsx +2 -1
  82. package/src/components/ui/table-layout.ts +38 -1
  83. package/src/components/ui/tabs.tsx +97 -19
  84. package/src/core/state/app/layout-reducer.ts +7 -0
  85. package/src/core/state/app/layout.ts +44 -7
  86. package/src/core/state/app/state.ts +1 -1
  87. package/src/core/state/app/types.ts +22 -2
  88. package/src/docs/snapshot.json +30 -13
  89. package/src/market-data/depositary-pair.ts +5 -3
  90. package/src/market-data/market/change-basis.ts +9 -5
  91. package/src/market-data/market/dated-previous-close.ts +147 -17
  92. package/src/market-data/market/status.ts +17 -1
  93. package/src/market-data/quotes/contributions.ts +2 -0
  94. package/src/market-data/quotes/listing-enterprise-value.ts +50 -0
  95. package/src/plugins/builtin/alerts/metric-data.ts +15 -2
  96. package/src/plugins/builtin/analytics/risk-client.ts +10 -4
  97. package/src/plugins/builtin/analytics/risk-episodes.ts +5 -4
  98. package/src/plugins/builtin/analytics/risk-headless.ts +4 -2
  99. package/src/plugins/builtin/analytics/risk-sectors.ts +91 -0
  100. package/src/plugins/builtin/awards/index.tsx +1 -1
  101. package/src/plugins/builtin/backtest/headless.ts +1 -1
  102. package/src/plugins/builtin/buildout/index.tsx +1 -0
  103. package/src/plugins/builtin/catalysts/index.tsx +2 -2
  104. package/src/plugins/builtin/cds/headless.ts +4 -0
  105. package/src/plugins/builtin/cds/model.ts +0 -6
  106. package/src/plugins/builtin/chart-composer/formula.ts +16 -3
  107. package/src/plugins/builtin/chart-composer/headless-schema.ts +2 -0
  108. package/src/plugins/builtin/chart-composer/headless.ts +4 -2
  109. package/src/plugins/builtin/chart-composer/index.tsx +1 -0
  110. package/src/plugins/builtin/chart-composer/presets.ts +1 -0
  111. package/src/plugins/builtin/chat/content/composer.tsx +5 -4
  112. package/src/plugins/builtin/chat/content/index.tsx +12 -2
  113. package/src/plugins/builtin/chat/content/layout-metrics.ts +3 -3
  114. package/src/plugins/builtin/chat/content/open-targets.ts +3 -3
  115. package/src/plugins/builtin/chat/layout.ts +5 -2
  116. package/src/plugins/builtin/chat/message/pane-chip.tsx +61 -40
  117. package/src/plugins/builtin/chat/message/terminal.tsx +13 -15
  118. package/src/plugins/builtin/chat/pane-links/previews.ts +51 -5
  119. package/src/plugins/builtin/chat/pane-links/share-card.ts +36 -0
  120. package/src/plugins/builtin/cloud/askg/pane.tsx +55 -13
  121. package/src/plugins/builtin/cloud/askg/tool-display.ts +1 -0
  122. package/src/plugins/builtin/cloud/terminal-relay/redact.ts +5 -3
  123. package/src/plugins/builtin/commodity-balances/index.tsx +1 -0
  124. package/src/plugins/builtin/company-attention/index.tsx +1 -1
  125. package/src/plugins/builtin/company-kpis/headless.ts +3 -1
  126. package/src/plugins/builtin/company-kpis/index.tsx +2 -2
  127. package/src/plugins/builtin/cot/index.tsx +1 -1
  128. package/src/plugins/builtin/cpi/index.tsx +1 -1
  129. package/src/plugins/builtin/credit-boards/cdx-pane.tsx +20 -7
  130. package/src/plugins/builtin/credit-boards/client.ts +8 -0
  131. package/src/plugins/builtin/credit-boards/headless.ts +4 -1
  132. package/src/plugins/builtin/credit-boards/model.ts +58 -4
  133. package/src/plugins/builtin/credit-boards/series.ts +63 -6
  134. package/src/plugins/builtin/credit-boards/sovr-pane.tsx +3 -2
  135. package/src/plugins/builtin/credit-conditions/headless.ts +24 -6
  136. package/src/plugins/builtin/credit-conditions/index.tsx +1 -1
  137. package/src/plugins/builtin/credit-conditions/model.ts +12 -6
  138. package/src/plugins/builtin/credit-conditions/series.ts +2 -1
  139. package/src/plugins/builtin/crypto-board/index.tsx +1 -0
  140. package/src/plugins/builtin/dividend-yield/index.tsx +1 -0
  141. package/src/plugins/builtin/doe/index.tsx +1 -1
  142. package/src/plugins/builtin/earnings-calls/headless.ts +5 -1
  143. package/src/plugins/builtin/earnings-calls/index.tsx +1 -0
  144. package/src/plugins/builtin/econ/calendar-model.ts +115 -8
  145. package/src/plugins/builtin/econ/calendar-source.ts +7 -1
  146. package/src/plugins/builtin/econ/fred-catalog.ts +3 -1
  147. package/src/plugins/builtin/econ/index.tsx +42 -8
  148. package/src/plugins/builtin/econ/types.ts +3 -0
  149. package/src/plugins/builtin/econ-statistics/index.tsx +1 -0
  150. package/src/plugins/builtin/econ-statistics/pane.tsx +6 -0
  151. package/src/plugins/builtin/estimate-revisions/index.tsx +1 -0
  152. package/src/plugins/builtin/executives/index.tsx +1 -0
  153. package/src/plugins/builtin/filing-events/index.tsx +1 -0
  154. package/src/plugins/builtin/fixed-income/index.tsx +3 -0
  155. package/src/plugins/builtin/futures-curve/headless.ts +3 -3
  156. package/src/plugins/builtin/futures-curve/index.tsx +1 -1
  157. package/src/plugins/builtin/futures-curve/model.ts +18 -0
  158. package/src/plugins/builtin/fx-matrix/index.tsx +44 -14
  159. package/src/plugins/builtin/gpu/index.tsx +1 -1
  160. package/src/plugins/builtin/help/functions-table.tsx +1 -1
  161. package/src/plugins/builtin/help/index.tsx +11 -1
  162. package/src/plugins/builtin/help/keybindings-editor.tsx +7 -3
  163. package/src/plugins/builtin/holders/index.tsx +1 -0
  164. package/src/plugins/builtin/holders/report-header.ts +2 -2
  165. package/src/plugins/builtin/insider/index.tsx +1 -0
  166. package/src/plugins/builtin/iv-history/index.tsx +1 -1
  167. package/src/plugins/builtin/jobs/index.tsx +1 -0
  168. package/src/plugins/builtin/macro-day/headless.ts +27 -8
  169. package/src/plugins/builtin/macro-day/index.tsx +1 -1
  170. package/src/plugins/builtin/macro-day/model.ts +19 -3
  171. package/src/plugins/builtin/macro-day/pane.tsx +14 -9
  172. package/src/plugins/builtin/macro-day/releases.ts +25 -7
  173. package/src/plugins/builtin/market-valuation/index.tsx +1 -0
  174. package/src/plugins/builtin/market-valuation/pane.tsx +8 -0
  175. package/src/plugins/builtin/members/index.tsx +1 -1
  176. package/src/plugins/builtin/mna/index.tsx +1 -0
  177. package/src/plugins/builtin/news/index.tsx +1 -0
  178. package/src/plugins/builtin/news/wire/index.tsx +5 -1
  179. package/src/plugins/builtin/news/wire/news/detail-view.tsx +4 -0
  180. package/src/plugins/builtin/news/wire/news/list-search.ts +5 -2
  181. package/src/plugins/builtin/options/index.tsx +1 -0
  182. package/src/plugins/builtin/options-positioning/index.tsx +1 -0
  183. package/src/plugins/builtin/pe-band/index.tsx +1 -1
  184. package/src/plugins/builtin/portfolio-list/cli/portfolio-command.ts +25 -0
  185. package/src/plugins/builtin/portfolio-list/cli/render.ts +20 -3
  186. package/src/plugins/builtin/portfolio-list/cli/watchlist-command.ts +5 -1
  187. package/src/plugins/builtin/portfolio-list/headless.ts +15 -6
  188. package/src/plugins/builtin/power/index.tsx +1 -1
  189. package/src/plugins/builtin/realized-vol/index.tsx +1 -1
  190. package/src/plugins/builtin/research/headless-schema.ts +4 -3
  191. package/src/plugins/builtin/research/headless.ts +10 -4
  192. package/src/plugins/builtin/research/index.tsx +4 -0
  193. package/src/plugins/builtin/research/relative-valuation-columns.ts +145 -47
  194. package/src/plugins/builtin/research/relative-valuation-currency.ts +31 -0
  195. package/src/plugins/builtin/research/relative-valuation-headless.ts +25 -8
  196. package/src/plugins/builtin/research/relative-valuation-model.ts +40 -9
  197. package/src/plugins/builtin/research/relative-valuation-pane.tsx +3 -2
  198. package/src/plugins/builtin/research/relative-valuation-peers.ts +2 -2
  199. package/src/plugins/builtin/research-search/index.tsx +1 -0
  200. package/src/plugins/builtin/research-search/pane.tsx +8 -0
  201. package/src/plugins/builtin/revenue-breakdown/index.tsx +1 -0
  202. package/src/plugins/builtin/reverse-dcf/index.tsx +1 -1
  203. package/src/plugins/builtin/risk-factors/index.tsx +1 -0
  204. package/src/plugins/builtin/scanner/headless.ts +52 -13
  205. package/src/plugins/builtin/seasonality/index.tsx +1 -1
  206. package/src/plugins/builtin/sec/index.tsx +1 -0
  207. package/src/plugins/builtin/series-inventory.ts +1 -1
  208. package/src/plugins/builtin/shared/scanner-capture.ts +11 -3
  209. package/src/plugins/builtin/shared/series-list-detail.tsx +5 -0
  210. package/src/plugins/builtin/short-interest/index.tsx +1 -0
  211. package/src/plugins/builtin/social-mentions/index.tsx +1 -1
  212. package/src/plugins/builtin/supply-chain/index.tsx +1 -0
  213. package/src/plugins/builtin/thirteenf/api.ts +47 -4
  214. package/src/plugins/builtin/thirteenf/data.ts +43 -10
  215. package/src/plugins/builtin/thirteenf/headless.ts +55 -11
  216. package/src/plugins/builtin/thirteenf/model.ts +25 -9
  217. package/src/plugins/builtin/thirteenf/report-notes.ts +27 -6
  218. package/src/plugins/builtin/thirteenf/types.ts +2 -0
  219. package/src/plugins/builtin/ticker-detail/adr-pair/model.ts +1 -1
  220. package/src/plugins/builtin/ticker-detail/data-panes/historical-prices.tsx +8 -7
  221. package/src/plugins/builtin/ticker-detail/data-panes/history-bars.ts +8 -5
  222. package/src/plugins/builtin/ticker-detail/financials/model.ts +18 -2
  223. package/src/plugins/builtin/ticker-detail/financials/ratio-table.tsx +3 -3
  224. package/src/plugins/builtin/ticker-detail/financials/tab.tsx +6 -6
  225. package/src/plugins/builtin/ticker-detail/headless.ts +24 -17
  226. package/src/plugins/builtin/ticker-detail/index.tsx +4 -0
  227. package/src/plugins/builtin/ticker-detail/overview/model.ts +6 -4
  228. package/src/plugins/builtin/ticker-detail/overview-tab.tsx +6 -4
  229. package/src/plugins/builtin/time-sales/client.ts +9 -11
  230. package/src/plugins/builtin/time-sales/index.tsx +1 -1
  231. package/src/plugins/builtin/treasury-auctions/after.ts +267 -0
  232. package/src/plugins/builtin/treasury-auctions/cache.ts +54 -5
  233. package/src/plugins/builtin/treasury-auctions/client.ts +33 -2
  234. package/src/plugins/builtin/treasury-auctions/headless.ts +150 -22
  235. package/src/plugins/builtin/treasury-auctions/hk-headless.ts +126 -0
  236. package/src/plugins/builtin/treasury-auctions/hk-view.tsx +347 -0
  237. package/src/plugins/builtin/treasury-auctions/hk.ts +363 -0
  238. package/src/plugins/builtin/treasury-auctions/index.tsx +27 -4
  239. package/src/plugins/builtin/treasury-auctions/model.ts +264 -28
  240. package/src/plugins/builtin/treasury-auctions/pane.tsx +176 -41
  241. package/src/plugins/builtin/treasury-auctions/treasury-direct.ts +5 -2
  242. package/src/plugins/builtin/treasury-auctions/types.ts +7 -1
  243. package/src/plugins/builtin/vol-surface/index.tsx +1 -1
  244. package/src/plugins/builtin/world-venue-map/index.ts +1 -0
  245. package/src/plugins/builtin/yield-curve/curves.ts +10 -4
  246. package/src/plugins/builtin/yield-curve/headless.ts +6 -2
  247. package/src/plugins/builtin/yield-curve/index.tsx +3 -3
  248. package/src/plugins/builtin/yield-curve/series.ts +10 -0
  249. package/src/plugins/builtin/yield-curve/world.ts +3 -1
  250. package/src/portfolio/collection-name.ts +22 -0
  251. package/src/portfolio/column-values.ts +2 -1
  252. package/src/public/__snapshots__/public-api.test.ts.snap +4 -0
  253. package/src/public/remote.ts +7 -1
  254. package/src/remote/client.ts +191 -11
  255. package/src/remote/controller-utils.ts +13 -1
  256. package/src/remote/controller.ts +88 -26
  257. package/src/remote/endpoint.ts +24 -0
  258. package/src/remote/form.ts +59 -4
  259. package/src/remote/resources.ts +44 -18
  260. package/src/remote/schema.ts +21 -9
  261. package/src/remote/secrets.ts +12 -0
  262. package/src/remote/semantic-tree.tsx +14 -2
  263. package/src/remote/server.ts +2 -1
  264. package/src/remote/surface.tsx +192 -0
  265. package/src/remote/types.ts +5 -0
  266. package/src/renderers/dom/data-table/frozen-column.ts +3 -1
  267. package/src/renderers/dom/data-table/index.tsx +27 -9
  268. package/src/renderers/dom/data-table/row.tsx +2 -0
  269. package/src/renderers/electrobun/bun/desktop/backend.ts +27 -24
  270. package/src/renderers/electrobun/bun/desktop/detached-windows.ts +3 -3
  271. package/src/renderers/electrobun/bun/desktop/snapshot-commit.ts +77 -0
  272. package/src/renderers/electrobun/shared/protocol.ts +4 -0
  273. package/src/renderers/electrobun/view/backend-rpc.ts +3 -0
  274. package/src/renderers/electrobun/view/desktop/window/bridge.ts +3 -0
  275. package/src/renderers/opentui/host.tsx +6 -0
  276. package/src/series/standalone.ts +2 -2
  277. package/src/shares/api.ts +21 -4
  278. package/src/shares/item.ts +73 -0
  279. package/src/shares/pane-item.ts +205 -0
  280. package/src/shares/pane.ts +4 -0
  281. package/src/shares/payload.ts +9 -5
  282. package/src/sources/gloomberb-cloud/news.ts +2 -0
  283. package/src/sources/gloomberb-cloud/normalizers.ts +9 -5
  284. package/src/sources/provider-router/cache.ts +3 -1
  285. package/src/sync/controller.ts +17 -2
  286. package/src/sync/other-window-tabs.ts +32 -1
  287. package/src/sync/react.ts +4 -4
  288. package/src/tickers/renamed-listings.ts +105 -0
  289. package/src/tickers/search/index.ts +103 -16
  290. package/src/time-series/bar-spacing.ts +33 -0
  291. package/src/time-series/base-series.ts +21 -3
  292. package/src/time-series/chart-bounds.ts +31 -0
  293. package/src/time-series/field-catalog.ts +17 -0
  294. package/src/time-series/fundamentals.ts +143 -11
  295. package/src/time-series/ice-credit.ts +32 -6
  296. package/src/time-series/resolve.ts +11 -7
  297. package/src/time-series/session-bar.ts +78 -9
  298. package/src/time-series/studies/formula.ts +53 -10
  299. package/src/time-series/studies/pair.ts +18 -7
  300. package/src/time-series/studies/units.ts +49 -2
  301. package/src/time-series/types.ts +12 -0
  302. package/src/types/desktop-window.ts +2 -0
  303. package/src/types/financials.ts +7 -0
  304. package/src/types/headless.ts +8 -0
  305. package/src/types/plugin-pane-settings.ts +2 -0
  306. package/src/types/plugin-panes.ts +22 -0
  307. package/src/utils/central-banks.ts +86 -1
  308. package/src/utils/cli-output.ts +6 -3
  309. package/src/utils/datetime-format.ts +12 -3
  310. package/src/utils/depositary-receipt.ts +28 -3
  311. package/src/utils/ebitda.ts +128 -0
  312. package/src/utils/format.ts +1 -1
  313. package/src/utils/fundamentals.ts +14 -0
  314. package/src/utils/max-drawdown.ts +97 -16
  315. package/src/utils/shell-word.ts +13 -0
  316. package/src/utils/untrusted-text.ts +29 -0
@@ -17,9 +17,10 @@ const SAME_CLOSE_RELATIVE = 1e-5;
17
17
  */
18
18
  const SAME_INDEX_CLOSE_RELATIVE = 1e-4;
19
19
  /**
20
- * How long a reading that named no day, or corrected an index's close,
21
- * stands before the closes are read again: a history a session behind
22
- * catches up, a failed read is retried, a correction is checked again.
20
+ * How long a reading that named no day, corrected an index's close, or found
21
+ * no official close yet for a closed B3 session stands before the closes are
22
+ * read again: a history a session behind catches up, a failed read is
23
+ * retried, a correction is checked again.
23
24
  */
24
25
  const UNDATED_RETRY_MS = 10 * 60_000;
25
26
  /** Readings kept at once; the oldest goes first. */
@@ -49,7 +50,7 @@ export interface DatedCloseListing {
49
50
 
50
51
  /** A listing's recent daily closes (a month is enough), with the flags that say a bar had not closed yet. */
51
52
  export type ReadDailyCloses = (listing: DatedCloseListing) => Promise<readonly DailyClose[]>;
52
- type DailyClose = Pick<PricePoint, "date" | "close" | "partial" | "unsettled">;
53
+ type DailyClose = Pick<PricePoint, "date" | "close" | "partial" | "unsettled"> & { volume?: number };
53
54
 
54
55
  export interface PreviousCloseDatesOptions {
55
56
  /** Called with the latest copy of a quote, dated, when a read lands that names its day. */
@@ -61,6 +62,8 @@ export interface PreviousCloseDatesOptions {
61
62
  indexWaitMs?: number;
62
63
  }
63
64
 
65
+ type ReadingFields = Pick<Reading, "date" | "close" | "sessionClose" | "awaitsSessionClose" | "untraded">;
66
+
64
67
  interface Reading {
65
68
  date: string | null;
66
69
  /**
@@ -68,9 +71,47 @@ interface Reading {
68
71
  * disagrees with it: an index's, whose move is then measured from it.
69
72
  */
70
73
  close?: number;
74
+ /** The official close of the quote's own session, from its daily bar, where the quote ends on a later print (B3). */
75
+ sessionClose?: number;
76
+ /** A closed quote on such a venue whose session's bar was not in the history yet: read again until it lands. */
77
+ awaitsSessionClose?: boolean;
78
+ /**
79
+ * A thin listing that did not trade in the session its venue's calendar
80
+ * puts before the move's, whose earlier closes do not hold its previous
81
+ * close either (ThinPreviousTrade): no day can be named for it.
82
+ */
83
+ untraded?: boolean;
71
84
  at: number;
72
85
  }
73
86
 
87
+ /**
88
+ * Venues whose quoted previous close is the exchange's official close, not
89
+ * the last trade its daily bar closes on, with how far apart the two can be:
90
+ * the BMV's closing auction gave WALMEX 53.57 on Thu 5 Nov 2026 beside a
91
+ * 53.68 last trade. The bar of the trading weekday right before the move's
92
+ * session still dates it, when the two are that close.
93
+ */
94
+ const OFFICIAL_PREVIOUS_CLOSE_VENUES: ReadonlyMap<string, number> = new Map([["BMV", 0.01]]);
95
+
96
+ /**
97
+ * Venues whose closed quote can end on a print after the closing call while
98
+ * the daily bar is the official close, as history and the portfolio read it:
99
+ * B3's PETR4 quoted R$45.36 on Fri 6 Nov 2026 beside a R$45.30 close.
100
+ */
101
+ export const DAILY_BAR_CLOSE_VENUES: ReadonlySet<string> = new Set(["B3"]);
102
+
103
+ /**
104
+ * A session volume below which a share or fund on a venue whose calendar
105
+ * dates its moves may not have traded in the session before: its daily closes
106
+ * are read to find its previous trade (thinPreviousTrade). B95 on SGX traded
107
+ * 3,661 units on Fri 6 Nov 2026 and last before that on 22 Oct, while the
108
+ * calendar put its move "vs Thu 5 Nov".
109
+ */
110
+ const THIN_SESSION_VOLUME = 50_000;
111
+
112
+ /** A close this far from the quote's price is another unit's or another listing's, never the session's. */
113
+ const MAX_SESSION_CLOSE_MOVE = 0.25;
114
+
74
115
  /** One listing whatever spelling of its exchange a request used. */
75
116
  export function datedCloseListingKey(listing: DatedCloseListing): string {
76
117
  return `${listing.symbol.trim().toUpperCase()}|${canonicalExchange(listing.exchange)}`;
@@ -94,16 +135,33 @@ function readingKey(quote: Quote | null | undefined, listing: DatedCloseListing,
94
135
  // An index's dated close is checked against its daily close of that day as well (indexCloseOn), but for a Cboe
95
136
  // index's, which Gloom Cloud checks against Cboe's own closes.
96
137
  if (datedIndexClose(quote)) return calendarVenue(quote) === "CBOE" ? null : datedReadingKey(quote, listing);
97
- if (isChangeBasisDatedWithoutCloses(quote, now)) return null;
138
+ if (isChangeBasisDatedWithoutCloses(quote, now)) return thinListingCalendarDate(quote) ? `${datedReadingKey(quote, listing)}|thin` : null;
98
139
  if (quoteChangeBasis(quote)?.kind !== "previous close") return null;
99
140
  return datedReadingKey(quote, listing);
100
141
  }
101
142
 
143
+ /**
144
+ * The session a venue's calendar puts before a thin listing's move, for a
145
+ * share or fund whose completed session traded under THIN_SESSION_VOLUME:
146
+ * such a listing may not have traded in it, which only its daily closes say.
147
+ * Null for any other quote, so a board of busy listings reads no history.
148
+ */
149
+ function thinListingCalendarDate(quote: Quote): string | null {
150
+ const kind = classifyInstrumentType(quote.instrumentType);
151
+ if (kind !== "equity" && kind !== "fund") return null;
152
+ if (quote.marketState === "REGULAR" || quote.previousCloseDate) return null;
153
+ if (!(typeof quote.volume === "number" && quote.volume >= 0 && quote.volume < THIN_SESSION_VOLUME)) return null;
154
+ const basis = quoteChangeBasis(quote);
155
+ return basis?.kind === "close" && basis.venue ? basis.date : null;
156
+ }
157
+
102
158
  function datedReadingKey(quote: Quote, listing: DatedCloseListing): string | null {
103
159
  const previousClose = quote.previousClose;
104
160
  const sessionDate = changeBasisSessionDate(quote);
105
161
  if (previousClose == null || !Number.isFinite(previousClose) || !sessionDate) return null;
106
- return `${datedCloseListingKey(listing)}|${sessionDate}|${previousClose}`;
162
+ // A session read while it traded has no close yet: once closed it is read again for its official close.
163
+ const closed = DAILY_BAR_CLOSE_VENUES.has(calendarVenue(quote)) && quote.marketState === "CLOSED" ? "|closed" : "";
164
+ return `${datedCloseListingKey(listing)}|${sessionDate}|${previousClose}${closed}`;
107
165
  }
108
166
 
109
167
  /**
@@ -133,7 +191,37 @@ function latestCloseBefore(points: readonly DailyClose[], quote: Quote): string
133
191
  .filter((point) => point.date < sessionDate)
134
192
  .sort((left, right) => left.date.localeCompare(right.date))
135
193
  .at(-1);
136
- return before && sameClose(before.close, quote.previousClose!) ? before.date : null;
194
+ if (!before) return null;
195
+ if (sameClose(before.close, quote.previousClose!)) return before.date;
196
+ const apart = OFFICIAL_PREVIOUS_CLOSE_VENUES.get(calendarVenue(quote));
197
+ return apart != null && before.date === weekdayBefore(sessionDate)
198
+ && Math.abs(before.close - quote.previousClose!) <= before.close * apart ? before.date : null;
199
+ }
200
+
201
+ /** The weekday before a local `YYYY-MM-DD`: Friday for a Monday. */
202
+ function weekdayBefore(date: string): string {
203
+ const day = new Date(`${date}T00:00:00Z`);
204
+ do day.setUTCDate(day.getUTCDate() - 1);
205
+ while (day.getUTCDay() === 0 || day.getUTCDay() === 6);
206
+ return day.toISOString().slice(0, 10);
207
+ }
208
+
209
+ /**
210
+ * The official close of a closed quote's own session on a venue whose quote
211
+ * can end on a later print (DAILY_BAR_CLOSE_VENUES): the session's finished
212
+ * daily bar, when it differs from the quote's price; undefined when it does
213
+ * not. `awaits` when the history has no finished bar of that session yet.
214
+ */
215
+ function sessionCloseOf(points: readonly DailyClose[], quote: Quote): { close?: number; awaits?: true } {
216
+ if (quote.marketState !== "CLOSED" || !DAILY_BAR_CLOSE_VENUES.has(calendarVenue(quote))) return {};
217
+ if (typeof quote.regularClose === "number" && quote.regularClose > 0) return {};
218
+ const sessionDate = changeBasisSessionDate(quote);
219
+ if (!sessionDate) return {};
220
+ const bar = closedBars(points, quote).findLast((point) => point.date === sessionDate && point.close > 0);
221
+ if (!bar) return { awaits: true };
222
+ if (!(quote.price > 0) || sameClose(bar.close, quote.price)) return {};
223
+ const close = cleanFloat32Price(bar.close);
224
+ return Math.abs(close / quote.price - 1) <= MAX_SESSION_CLOSE_MOVE ? { close } : {};
137
225
  }
138
226
 
139
227
  /**
@@ -164,9 +252,35 @@ function indexCloseOn(points: readonly DailyClose[], quote: Quote, date: string)
164
252
  return Math.abs(previousClose - close) <= close * SAME_INDEX_CLOSE_RELATIVE ? { date } : { date, close };
165
253
  }
166
254
 
167
- function readingOf(points: readonly DailyClose[], quote: Quote): { date: string | null; close?: number } {
255
+ /**
256
+ * A thin listing's previous trade, where it is earlier than the session its
257
+ * venue's calendar puts before the move's: the day of its latest daily close
258
+ * before the move's session that traded, when that close is its previous
259
+ * close. When it traded in the calendar's session the calendar stands
260
+ * (date null); when its closes hold neither, the day is unknown (`untraded`).
261
+ */
262
+ function thinPreviousTrade(points: readonly DailyClose[], quote: Quote, calendarDate: string): ReadingFields {
263
+ const sessionDate = changeBasisSessionDate(quote)!;
264
+ const traded = new Set(points.filter((point) => point.volume == null || point.volume > 0).map((point) => point.date.valueOf()));
265
+ const before = closedBars(points.filter((point) => traded.has(point.date.valueOf())), quote)
266
+ .filter((point) => point.date < sessionDate)
267
+ .sort((left, right) => left.date.localeCompare(right.date))
268
+ .at(-1);
269
+ if (!before || before.date >= calendarDate) return { date: null };
270
+ return sameClose(before.close, quote.previousClose!) ? { date: before.date } : { date: null, untraded: true };
271
+ }
272
+
273
+ function readingOf(points: readonly DailyClose[], quote: Quote): ReadingFields {
168
274
  const indexDate = datedIndexClose(quote);
169
- return indexDate ? indexCloseOn(points, quote, indexDate) : { date: latestCloseBefore(points, quote) };
275
+ if (indexDate) return indexCloseOn(points, quote, indexDate);
276
+ const calendarDate = thinListingCalendarDate(quote);
277
+ if (calendarDate) return thinPreviousTrade(points, quote, calendarDate);
278
+ const session = sessionCloseOf(points, quote);
279
+ return {
280
+ date: latestCloseBefore(points, quote),
281
+ ...session.close != null ? { sessionClose: session.close } : {},
282
+ ...session.awaits ? { awaitsSessionClose: true } : {},
283
+ };
170
284
  }
171
285
 
172
286
  function withDate<T extends Quote | null | undefined>(quote: T, date: string | null | undefined): T {
@@ -174,7 +288,21 @@ function withDate<T extends Quote | null | undefined>(quote: T, date: string | n
174
288
  }
175
289
 
176
290
  /** The quote as a reading has it: dated, and for an index measured from that day's close when its own disagrees. */
177
- function withReading<T extends Quote | null | undefined>(quote: T, reading: Pick<Reading, "date" | "close"> | undefined): T {
291
+ function withReading<T extends Quote | null | undefined>(quote: T, reading: Pick<Reading, "date" | "close" | "sessionClose" | "untraded"> | undefined): T {
292
+ if (!quote || !reading) return quote;
293
+ if (reading.untraded) return { ...quote, previousCloseUndated: true };
294
+ const closed = withSessionClose(quote, reading.sessionClose);
295
+ return closed === quote ? withDatedReading(quote, reading) : withDatedReading(closed as T, reading);
296
+ }
297
+
298
+ /** A closed quote that ended on a later print headlines its session's official close, as history and the portfolio read it. */
299
+ function withSessionClose<T extends Quote>(quote: T, close: number | undefined): T {
300
+ const sessionDate = close != null && quote.marketState === "CLOSED" && !(typeof quote.regularClose === "number" && quote.regularClose > 0)
301
+ ? changeBasisSessionDate(quote) : null;
302
+ return sessionDate ? { ...quote, regularClose: close, regularCloseSessionDate: sessionDate } : quote;
303
+ }
304
+
305
+ function withDatedReading<T extends Quote | null | undefined>(quote: T, reading: Pick<Reading, "date" | "close"> | undefined): T {
178
306
  if (!quote || !reading?.date) return quote;
179
307
  if (reading.close == null) return withDate(quote, reading.date);
180
308
  const close = reading.close;
@@ -204,7 +332,7 @@ function withReading<T extends Quote | null | undefined>(quote: T, reading: Pick
204
332
  */
205
333
  export class PreviousCloseDates {
206
334
  private readonly readings = new Map<string, Reading>();
207
- private readonly pending = new Map<string, Promise<Pick<Reading, "date" | "close">>>();
335
+ private readonly pending = new Map<string, Promise<ReadingFields>>();
208
336
  /** The latest copy of each quote a read is pending for, which the read dates when it lands. */
209
337
  private readonly latestCopies = new Map<string, { quote: Quote; listing: DatedCloseListing }>();
210
338
  /** Dating reads and index checks queue apart, so neither waits behind the other. */
@@ -268,21 +396,23 @@ export class PreviousCloseDates {
268
396
  * Whether a reading answers without another read: a day it named that
269
397
  * agreed with the quote's close, or any other reading taken lately. A
270
398
  * correction (an index's close the quote disagreed with) is read again as
271
- * an undated one is, so a wrong close cannot stand for the session.
399
+ * an undated one is, so a wrong close cannot stand for the session, and so
400
+ * is a closed B3 quote's whose session's official close had not landed.
272
401
  */
273
402
  private stands(reading: Reading | undefined): boolean {
274
- return !!reading && ((!!reading.date && reading.close == null) || this.now() - reading.at < UNDATED_RETRY_MS);
403
+ return !!reading && ((!!reading.date && reading.close == null && !reading.awaitsSessionClose)
404
+ || this.now() - reading.at < UNDATED_RETRY_MS);
275
405
  }
276
406
 
277
- private start(key: string, quote: Quote, listing: DatedCloseListing): Promise<Pick<Reading, "date" | "close">> {
407
+ private start(key: string, quote: Quote, listing: DatedCloseListing): Promise<ReadingFields> {
278
408
  this.latestCopies.set(key, { quote, listing });
279
409
  return this.pending.get(key) ?? this.read(key, quote, listing);
280
410
  }
281
411
 
282
- private read(key: string, quote: Quote, listing: DatedCloseListing): Promise<Pick<Reading, "date" | "close">> {
412
+ private read(key: string, quote: Quote, listing: DatedCloseListing): Promise<ReadingFields> {
283
413
  const read = this.inSlot(datedIndexClose(quote) ? "index" : "dating", () => withDeadline(Promise.resolve().then(() => this.readCloses(listing)), this.readDeadlineMs, "Reading daily closes timed out"))
284
414
  .then((points) => readingOf(points, quote))
285
- .catch(logFailure("market-data.dated-previous-close", "Read daily closes failed", { date: null }))
415
+ .catch(logFailure("market-data.dated-previous-close", "Read daily closes failed", { date: null } as ReadingFields))
286
416
  .then((reading) => {
287
417
  this.pending.delete(key);
288
418
  this.readings.delete(key);
@@ -290,7 +420,7 @@ export class PreviousCloseDates {
290
420
  this.readings.set(key, { ...reading, at: this.now() });
291
421
  const latest = this.latestCopies.get(key);
292
422
  this.latestCopies.delete(key);
293
- if (reading.date && latest && this.options.onDated) {
423
+ if ((reading.date || reading.sessionClose != null || reading.untraded) && latest && this.options.onDated) {
294
424
  try {
295
425
  this.options.onDated(latest.listing, withReading(latest.quote, reading));
296
426
  } catch (error) {
@@ -89,9 +89,25 @@ export function quoteBookSessionLabel(quote: Quote): string | null {
89
89
  if (extended) return extended;
90
90
  const day = quoteTradingDay(quote);
91
91
  const date = day ? new Date(`${day}T00:00:00Z`) : null;
92
- return date && Number.isFinite(date.getTime())
92
+ const label = date && Number.isFinite(date.getTime())
93
93
  ? `last quote, ${WEEKDAYS[date.getUTCDay()]} ${date.getUTCDate()} ${MONTHS[date.getUTCMonth()]}`
94
94
  : "last quote";
95
+ return offMarketBook(quote) ? `${label}, off-market` : label;
96
+ }
97
+
98
+ /** Past this share of the last price, a closed market's bid or ask is no market for it. */
99
+ const OFF_MARKET_SHARE = 0.05;
100
+
101
+ /**
102
+ * Whether a closed market's last bid or ask is more than 5% off the last
103
+ * price: FMX's $118.00 / $135.00 around a $129.85 close on 6 Nov 2026 is a
104
+ * book left after the close, not where it trades.
105
+ */
106
+ function offMarketBook(quote: Pick<Quote, "price" | "bid" | "ask">): boolean {
107
+ const last = quote.price;
108
+ if (typeof last !== "number" || !Number.isFinite(last) || last <= 0) return false;
109
+ return [quote.bid, quote.ask].some((side) =>
110
+ typeof side === "number" && Number.isFinite(side) && side > 0 && Math.abs(side - last) / last > OFF_MARKET_SHARE);
95
111
  }
96
112
 
97
113
  /** `Thu close`: the weekday of the session whose close a quote still stands at. */
@@ -251,6 +251,8 @@ export function mergeQuoteContribution(
251
251
  delete merged.previousCloseDate;
252
252
  }
253
253
  }
254
+ // So is a close its daily closes could not date: the next reading says it again.
255
+ if (next.previousCloseUndated === undefined) delete merged.previousCloseUndated;
254
256
 
255
257
  if (isOtherTradingDay(current, next)) {
256
258
  const record = merged as unknown as Record<string, unknown>;
@@ -0,0 +1,50 @@
1
+ import type { EnterpriseValueCheck, TickerFinancials } from "../../types/financials";
2
+ import {
3
+ enterpriseValueCheck, enterpriseValueNotMeaningful, enterpriseValueWithdrawn, reportedEnterpriseValue, withBankEnterpriseValue,
4
+ } from "../../utils/fundamentals";
5
+ import { atRegularSessionPrice } from "./regular-session-valuation";
6
+
7
+ export type ListingEnterpriseValue =
8
+ | {
9
+ kind: "value";
10
+ value: number;
11
+ currency: string;
12
+ /** `computed`: market cap + total debt - cash, standing in for a provider figure Gloom Cloud withdrew. */
13
+ basis: "served" | "computed";
14
+ /** The withdrawn check a computed EV comes from, which names its balance sheet and rate. */
15
+ check?: EnterpriseValueCheck;
16
+ /**
17
+ * The rate the EV's balance sheet check converted the statements' currency
18
+ * at (an ADR's EUR or TWD into its USD EV), from any check that names one.
19
+ */
20
+ fx?: { from: string; rate: number };
21
+ }
22
+ | { kind: "not-meaningful"; reason: string }
23
+ | { kind: "unavailable" };
24
+
25
+ const finite = (value: unknown): value is number => typeof value === "number" && Number.isFinite(value);
26
+
27
+ /**
28
+ * The enterprise value every surface divides, at the regular session price:
29
+ * the one Gloom Cloud serves (`valuation`'s EV, RV's EV/S, the screener's
30
+ * EV/EBITDA), or, where it withdrew the provider's figure against the balance
31
+ * sheet, the market cap + total debt - cash it checked that figure against.
32
+ * Not meaningful at or below zero and for a bank.
33
+ */
34
+ export function listingEnterpriseValue(financials: Pick<TickerFinancials, "quote" | "fundamentals" | "profile">): ListingEnterpriseValue {
35
+ const priced = atRegularSessionPrice({ quote: financials.quote, fundamentals: withBankEnterpriseValue(financials.fundamentals, financials.profile) });
36
+ const fundamentals = priced.fundamentals;
37
+ const notMeaningful = enterpriseValueNotMeaningful(fundamentals);
38
+ if (notMeaningful) return { kind: "not-meaningful", reason: notMeaningful };
39
+ const check = enterpriseValueCheck(fundamentals);
40
+ const served = reportedEnterpriseValue(fundamentals);
41
+ const currency = check?.currency ?? fundamentals?.marketCapCurrency ?? priced.quote?.currency;
42
+ const fx = check?.fx && check.fx.from && finite(check.fx.rate) && check.fx.rate > 0 ? { fx: check.fx } : {};
43
+ if (served != null) return currency ? { kind: "value", value: served, currency, basis: "served", ...fx } : { kind: "unavailable" };
44
+ if (enterpriseValueWithdrawn(fundamentals) && check?.status === "withdrawn" && finite(check.computed) && check.currency) {
45
+ return check.computed > 0
46
+ ? { kind: "value", value: check.computed, currency: check.currency, basis: "computed", check, ...fx }
47
+ : { kind: "not-meaningful", reason: "Cash and short-term investments exceed market cap + total debt" };
48
+ }
49
+ return { kind: "unavailable" };
50
+ }
@@ -1,5 +1,5 @@
1
1
  import type { AssetDataProvider } from "../../../types/data-provider";
2
- import type { TickerFinancials } from "../../../types/financials";
2
+ import type { Quote, TickerFinancials } from "../../../types/financials";
3
3
  import { liveMarketCapitalization, liveTrailingPE } from "../../../market-data/quotes/live-valuation";
4
4
  import { comparablePriceEarnings } from "../../../utils/price-earnings";
5
5
  import { canonicalExchange } from "../../../utils/exchanges";
@@ -68,6 +68,7 @@ export function metricReadings(provider: AssetDataProvider, now = Date.now()) {
68
68
  dailyCaches.set(provider, daily);
69
69
  const financials = new Map<string, Promise<TickerFinancials>>();
70
70
  const history = new Map<string, Promise<Awaited<ReturnType<AssetDataProvider["getPriceHistory"]>> >>();
71
+ const quotes = new Map<string, Promise<Quote | null>>();
71
72
  return async (rule: AlertRule): Promise<MetricReading> => {
72
73
  const m = rule.metric!;
73
74
  const key = `${rule.symbol}|${rule.exchange ?? ""}`;
@@ -99,8 +100,20 @@ export function metricReadings(provider: AssetDataProvider, now = Date.now()) {
99
100
  const request = history.get(listing) ?? load(symbol, venue);
100
101
  history.set(listing, request);
101
102
  // Final as `history` shows it: a close it prints without `partial` is one the rule may judge.
103
+ // A bar the source still marks partial once its session has settled is final at the session's quote,
104
+ // as `history` makes it; the quote is read only then, and one that fails leaves the rule waiting.
102
105
  // Bars read back from the saved cache carry their dates as text.
103
- return finalDailyBars(await request, { now, venue }).map(point => ({ date: barSessionDay(getPricePointTimestamp(point), venue), close: point.close }));
106
+ const served = await request;
107
+ let quote: Promise<Quote | null> | null = null;
108
+ if (served.at(-1)?.partial) {
109
+ quote = quotes.get(listing) ?? provider.getQuote(symbol, venue).catch(() => {
110
+ // Intentional ignore: the bar stays partial and the rule keeps waiting; the next pass reads the quote again.
111
+ return null;
112
+ });
113
+ quotes.set(listing, quote);
114
+ }
115
+ return finalDailyBars(served, { now, venue }, await quote)
116
+ .map(point => ({ date: barSessionDay(getPricePointTimestamp(point), venue), close: point.close }));
104
117
  };
105
118
  const bars = await completed(rule.symbol, exchange);
106
119
  // RS ratios and RRG quadrants read the benchmark's own completed bars, never a quote.
@@ -83,15 +83,20 @@ export interface RiskMarketSnapshot {
83
83
  }
84
84
  /**
85
85
  * The most holdings one load requests daily history for, largest current USD
86
- * value first. Each holding costs one Cloud request of up to 18 months of
87
- * closes, four in flight, again after every two-minute cache expiry, and the
86
+ * value first. Each holding costs one read of up to 18 months of closes,
87
+ * sixteen to a batch request, again after every two-minute cache expiry, and the
88
88
  * correlation view pairs every basket holding with every other. See
89
89
  * docs/research-data.md for the measured cost behind the number.
90
90
  */
91
91
  export const RISK_HISTORY_LIMIT = 150;
92
92
  /** Holdings quoted in one load, 50 to a batch request. */
93
93
  const RISK_QUOTE_LIMIT = 500;
94
- const HISTORY_CONCURRENCY = 4;
94
+ /**
95
+ * Histories asked at once. They go out sixteen to a batch request, side by
96
+ * side (getCloudHistory's `batch`): a 60-holding book is four requests, where
97
+ * four single reads at a time took about 6 s.
98
+ */
99
+ const HISTORY_CONCURRENCY = 64;
95
100
  const MAX_FX_CURRENCIES = 24;
96
101
  export const BEYOND_SIZE_REASON = `Beyond the supported size: only the ${RISK_HISTORY_LIMIT} largest holdings by value are modelled`;
97
102
  // Listing venues as the quotes report them; MTUM and QUAL list on Cboe BZX, not Arca.
@@ -402,7 +407,8 @@ export async function fetchPortfolioRiskMarket(
402
407
  const key = `${canonicalExchange(exchange)}:${normalizeSymbol(symbol)}`;
403
408
  let loading = dailyHistories.get(key);
404
409
  if (!loading) {
405
- dailyHistories.set(key, loading = client.getCloudHistory(symbol, exchange, historyParams, signal ? { signal } : undefined));
410
+ // Read over the window every holding shares, so they go out together; the signal stops the wait, not a batch others share.
411
+ dailyHistories.set(key, loading = client.getCloudHistory(symbol, exchange, historyParams, { batch: true, sharedWindow: true, ...(signal ? { signal } : {}) }));
406
412
  loading.catch(() => {
407
413
  // Intentional ignore: the failure is raised where the history is read.
408
414
  });
@@ -72,7 +72,8 @@ export interface RiskEpisodeTarget {
72
72
  const DAY_MS = 86_400_000;
73
73
  /** A boundary close may be this many days before its date: a weekend, a holiday or a market's own closure. */
74
74
  const BOUNDARY_DAYS = 7;
75
- const EPISODE_CONCURRENCY = 4;
75
+ /** Reads asked at once; they go out sixteen to a batch request over the episodes' one window. */
76
+ const EPISODE_CONCURRENCY = 64;
76
77
  const SPY = RISK_FACTOR_INSTRUMENTS[0]!;
77
78
 
78
79
  /** The one window every episode fits in, with room for a start date's close a holiday before it. */
@@ -149,12 +150,12 @@ export function cloudEpisodeReader(client: EpisodeClient = apiClient): EpisodeRe
149
150
  const params = { interval: "1day", ...episodeSpan(), outputsize: 1500 } as const;
150
151
  return {
151
152
  async instrument(instrument, signal) {
152
- return episodeCloses(dailyCloses(await client.getCloudHistory(instrument.symbol, instrument.exchange, params, signal ? { signal } : undefined)));
153
+ return episodeCloses(dailyCloses(await client.getCloudHistory(instrument.symbol, instrument.exchange, params, { batch: true, sharedWindow: true, ...(signal ? { signal } : {}) })));
153
154
  },
154
155
  async currency(currency, signal) {
155
156
  const leg = riskConversion(currency)?.leg;
156
157
  if (!leg) throw new Error(`No daily FX pair for ${currency}`);
157
- const points = dailyCloses(await client.getCloudHistory(leg.instrument.symbol, leg.instrument.exchange ?? "", params, signal ? { signal } : undefined));
158
+ const points = dailyCloses(await client.getCloudHistory(leg.instrument.symbol, leg.instrument.exchange ?? "", params, { batch: true, sharedWindow: true, ...(signal ? { signal } : {}) }));
158
159
  return episodeCloses(points.map((point) => ({ ...point, close: leg.invert ? 1 / point.close : point.close })));
159
160
  },
160
161
  };
@@ -181,7 +182,7 @@ export function onceEpisodeReader(reader: EpisodeReader): EpisodeReader {
181
182
  /**
182
183
  * The closes the episode replays read: SPY's, every target's, and the daily
183
184
  * FX closes of each currency a target quotes in and of a non-USD account,
184
- * four reads at a time. A read that fails is named in `errors`, and the
185
+ * all asked at once, sixteen to a batch request. A read that fails is named in `errors`, and the
185
186
  * replays move that holding by proxy; the signal stops the load.
186
187
  */
187
188
  export async function fetchRiskEpisodeHistory(
@@ -1,3 +1,4 @@
1
+ import { portfolioSectorReport } from "./risk-sectors";
1
2
  import { loadPortfolioOptionBook } from "./risk-options";
2
3
  import type { HeadlessPaneDefinition } from "../../../types/plugin";
3
4
  import { fetchPortfolioRiskMarket, RISK_HISTORY_LIMIT } from "./risk-client";
@@ -188,8 +189,8 @@ export const portfolioRiskHeadless: HeadlessPaneDefinition<"bundle"> = {
188
189
  type: "enum",
189
190
  settingKey: "riskView",
190
191
  // No default: left out, the report prints every view.
191
- values: RISK_VIEWS.map((value) => ({ value })),
192
- description: "One portfolio risk view; every view when left out.",
192
+ values: [...RISK_VIEWS, "sectors"].map((value) => ({ value })),
193
+ description: "One portfolio risk view; sectors compares direct company sector weights, cash and unclassified holdings against SPY (S&P 500) in percentage points. Every standard risk view when left out.",
193
194
  },
194
195
  {
195
196
  key: "since",
@@ -262,6 +263,7 @@ export const portfolioRiskHeadless: HeadlessPaneDefinition<"bundle"> = {
262
263
  describe: (args, result) =>
263
264
  `Portfolio risk | ${reportPortfolioName(result?.metadata) || args.rawArgument || "local portfolio"}`,
264
265
  async load(args, ctx) {
266
+ if (args.options.view === "sectors") return portfolioSectorReport(args, ctx);
265
267
  // The host reads the argument by id or name, in any case; everything after goes by the configured id.
266
268
  const requested = args.rawArgument.trim() || ctx.config.portfolios[0]?.id;
267
269
  if (!requested || !ctx.resolvePortfolio)
@@ -0,0 +1,91 @@
1
+ import type { HeadlessBundleResult, HeadlessPaneContext, HeadlessPaneLoadArgs, HeadlessPaneRow } from "../../../types/headless";
2
+ import { canonicalTickerKey } from "../../../utils/exchanges";
3
+ import { formatNumber } from "../../../utils/format";
4
+ import { CASH_SYMBOL } from "../../../portfolio/allocation";
5
+ import type { FundMembersPayload } from "../../../api-client/members";
6
+ import { collectionHoldingsHeadless } from "../portfolio-list/headless";
7
+
8
+ const SECTOR_NAMES: Record<string, string> = {
9
+ technology: "Information Technology", "information technology": "Information Technology",
10
+ "financial services": "Financials", financials: "Financials", "health care": "Health Care", healthcare: "Health Care",
11
+ "consumer cyclical": "Consumer Discretionary", "consumer discretionary": "Consumer Discretionary",
12
+ "consumer defensive": "Consumer Staples", "consumer staples": "Consumer Staples",
13
+ "basic materials": "Materials", materials: "Materials", "communication services": "Communication Services", communication: "Communication Services",
14
+ "cash and/or derivatives": "Cash", cash: "Cash",
15
+ energy: "Energy", industrials: "Industrials", "real estate": "Real Estate", utilities: "Utilities",
16
+ };
17
+ const sectorName = (value: unknown) => typeof value === "string" ? SECTOR_NAMES[value.trim().toLowerCase()] ?? null : null;
18
+
19
+ /** Signed positions as a share of net liquidation, including cash. Unknowns stay in the denominator. */
20
+ export function comparePortfolioSectors(positions: HeadlessPaneRow[], total: number, benchmark: FundMembersPayload,
21
+ sectors: ReadonlyMap<string, string | null>) {
22
+ if (!Number.isFinite(total) || total <= 0) throw new Error("Sector comparison needs positive net liquidation.");
23
+ const book = new Map<string, number>(), index = new Map<string, number>();
24
+ const unknown: HeadlessPaneRow[] = [];
25
+ for (const member of benchmark.members) {
26
+ const sector = sectorName(member.sector) ?? "Unknown benchmark sector";
27
+ if (member.weight != null && Number.isFinite(member.weight)) index.set(sector, (index.get(sector) ?? 0) + member.weight * 100);
28
+ }
29
+ if (![...index.values()].some(weight => weight > 0)) throw new Error("No benchmark sector weights are available.");
30
+ for (const position of positions) {
31
+ const symbol = String(position.symbol);
32
+ const sector = symbol === CASH_SYMBOL ? "Cash" : sectorName(sectors.get(canonicalTickerKey(symbol, typeof position.exchange === "string" ? position.exchange : undefined))) ?? "Unclassified / funds";
33
+ const value = position.marketValue;
34
+ if (typeof value !== "number" || !Number.isFinite(value)) {
35
+ unknown.push({ symbol, reason: "Position has no market value", weightPercent: null });
36
+ continue;
37
+ }
38
+ const weight = 100 * value / total;
39
+ book.set(sector, (book.get(sector) ?? 0) + weight);
40
+ if (sector === "Unclassified / funds") unknown.push({ symbol, reason: "No company sector; funds are not looked through", weightPercent: weight });
41
+ }
42
+ const rows = [...new Set([...book.keys(), ...index.keys()])].map(sector => ({ sector,
43
+ portfolioWeightPercent: book.get(sector) ?? 0, benchmarkWeightPercent: index.get(sector) ?? 0,
44
+ activeWeightPp: (book.get(sector) ?? 0) - (index.get(sector) ?? 0),
45
+ })).sort((a, b) => b.activeWeightPp - a.activeWeightPp || a.sector.localeCompare(b.sector));
46
+ return { rows, unknown };
47
+ }
48
+
49
+ export async function portfolioSectorReport(args: HeadlessPaneLoadArgs, ctx: HeadlessPaneContext): Promise<HeadlessBundleResult> {
50
+ const [holdings, benchmark] = await Promise.all([
51
+ collectionHoldingsHeadless.load({ ...args, options: { limit: 200, close: false } }, ctx),
52
+ ctx.apiClient.getFundMembers("SPY"),
53
+ ]);
54
+ const rows = holdings.rows;
55
+ const metadata = holdings.metadata ?? {};
56
+ const total = (metadata.totals as { total?: number } | undefined)?.total;
57
+ if (typeof total !== "number") throw new Error("Sector comparison needs portfolio holdings with net liquidation.");
58
+ const sectors = new Map<string, string | null>();
59
+ const missing = rows.filter(row => row.symbol !== CASH_SYMBOL);
60
+ // The batch preserves exact listing keys; membership under a matching bare ticker never classifies a namesake abroad.
61
+ if (missing.length && ctx.marketData.getTickerFinancialsBatch) {
62
+ for (let offset = 0; offset < missing.length; offset += 50) {
63
+ const chunk = missing.slice(offset, offset + 50);
64
+ const loaded = await ctx.marketData.getTickerFinancialsBatch(chunk.map(row => ({ symbol: String(row.symbol), exchange: String(row.exchange ?? "") })));
65
+ loaded.forEach(result => {
66
+ const financials = result.financials;
67
+ const fund = /ETF|FUND|MUTUAL/i.test(financials?.quote?.instrumentType ?? "");
68
+ sectors.set(canonicalTickerKey(result.target.symbol, result.target.exchange), fund ? null : financials?.profile?.sector ?? null);
69
+ });
70
+ }
71
+ }
72
+ ctx.signal.throwIfAborted();
73
+ const comparison = comparePortfolioSectors(rows, total, benchmark, sectors);
74
+ const truncated = typeof metadata.positions === "number" && metadata.positions > missing.length;
75
+ const unknownBenchmark = comparison.rows.some(row => row.sector === "Unknown benchmark sector");
76
+ return {
77
+ sections: [
78
+ { title: `Sectors vs S&P 500 (${benchmark.fund.ticker} holdings)`, columns: [
79
+ { key: "sector", header: "Sector" }, { key: "portfolioWeightPercent", header: "Book %", align: "right", format: value => formatNumber(Number(value), 2) },
80
+ { key: "benchmarkWeightPercent", header: `${benchmark.fund.ticker} %`, align: "right", format: value => formatNumber(Number(value), 2) }, { key: "activeWeightPp", header: "Active pp", align: "right", format: value => formatNumber(Number(value), 2) },
81
+ ], rows: comparison.rows },
82
+ { title: "Unclassified holdings", columns: [{ key: "symbol", header: "Ticker" }, { key: "weightPercent", header: "Book %" }, { key: "reason", header: "Reason" }], rows: comparison.unknown },
83
+ ],
84
+ complete: holdings.complete !== false && !truncated && !benchmark.stale && comparison.unknown.length === 0 && !unknownBenchmark,
85
+ notes: ["Signed market values / net liquidation, cash included; active weights are percentage points. Direct company sectors; funds are not looked through. Unknown weights remain in the denominator.",
86
+ `Benchmark: ${benchmark.fund.ticker} holdings as of ${benchmark.asOf}.`],
87
+ errors: [...(holdings.errors ?? []), ...(truncated ? ["Portfolio list exceeds 200 rows; the comparison covers only those returned."] : []),
88
+ ...(benchmark.stale ? ["Benchmark holdings are stale."] : [])],
89
+ metadata: { portfolio: metadata.collection, currency: metadata.currency, netLiquidation: total, benchmark: benchmark.fund.ticker, benchmarkAsOf: benchmark.asOf },
90
+ };
91
+ }
@@ -8,7 +8,7 @@ export const awardsModule: PluginModule = {
8
8
  setup(ctx) { awardsCache.attach(ctx.persistence); awardDetailCache.attach(ctx.persistence); },
9
9
  dispose() { awardsCache.reset(); awardDetailCache.reset(); },
10
10
  panes: [{ id: "awards", name: "Government Awards", icon: "A", get component(): typeof import("./pane").AwardsPane { const { AwardsPane } = require("./pane"); return AwardsPane; }, defaultPosition: "right", defaultMode: "floating",
11
- defaultFloatingSize: { width: 132, height: 34 }, tickerFollower: true, instruments: ["equity"], tableExport: true, headless: awardsHeadless,
11
+ defaultFloatingSize: { width: 132, height: 34 }, shareItem: { ticker: true }, tickerFollower: true, instruments: ["equity"], tableExport: true, headless: awardsHeadless,
12
12
  quickSettings: [{ type: "toggle", key: "awardAlerts", icon: "zap", label: "New awards above 1% of annual revenue" }],
13
13
  settings: { title: "Government awards", fields: [{ type: "toggle", key: "awardAlerts", label: "New awards above 1% of annual revenue", description: "Notify while this pane is visible. Starts with the next refresh; historical backfills are excluded." }] } }],
14
14
  paneTemplates: [{ id: "awards-pane", paneId: "awards", label: "Government Awards", description: "Pro: government awards, company history, agency concentration and revenue exposure with source evidence.",
@@ -50,7 +50,7 @@ export const backtestHeadless: HeadlessPaneDefinition<"bundle"> = {
50
50
  normalize: (value) => isoDateOption(value, "end") },
51
51
  { key: "include-partial", settingKey: "includePartial", type: "boolean", defaultValue: false,
52
52
  description: "Keep a session still forming (partial), which is left out by default because its close moves until the day ends" },
53
- { key: "equity", shot: { reportOnly: "prints the daily equity curve in place of the summary" }, type: "boolean", defaultValue: false, example: "--csv --equity > curve.csv",
53
+ { key: "equity", shot: { reportOnly: "prints the daily equity curve in place of the summary" }, type: "boolean", defaultValue: false, example: "--csv --equity --output curve.csv",
54
54
  description: "Report the daily curve instead: date, close in the listing's currency, position (1 long, 0 flat), strategy and"
55
55
  + " buy-and-hold growth of 1 on the price alone (distributions not included) and drawdown in percent, every digit in --csv and --json" },
56
56
  { key: "tab", type: "enum", defaultValue: "summary", values: [{ value: "summary" }, { value: "trades" }], description: "Initial view",
@@ -47,6 +47,7 @@ export const buildoutModule: PluginModule = {
47
47
  defaultPosition: "right",
48
48
  defaultMode: "floating",
49
49
  defaultFloatingSize: { width: 120, height: 32 },
50
+ shareItem: { ticker: true },
50
51
  tickerFollower: true,
51
52
  instruments: ["equity"],
52
53
  reportOptions: [COMPANY_TAB_OPTION],
@@ -17,8 +17,8 @@ export const catalystsModule: PluginModule = {
17
17
  },
18
18
  dispose() { catalystCache.reset(); catalystDetailCache.reset(); },
19
19
  panes: [
20
- { id: "catalysts", name: "Catalysts", icon: "C", component: CatalystsPane, defaultPosition: "right", tickerFollower: true, instruments: ["equity"], defaultMode: "floating", defaultFloatingSize: { width: 130, height: 32 }, tableExport: true, headless: catalystsHeadless },
21
- { id: "litigation", name: "Litigation", icon: "L", component: LitigationPane, defaultPosition: "right", defaultMode: "floating", defaultFloatingSize: { width: 120, height: 30 }, tickerFollower: true,
20
+ { id: "catalysts", name: "Catalysts", icon: "C", component: CatalystsPane, defaultPosition: "right", shareItem: { ticker: true }, tickerFollower: true, instruments: ["equity"], defaultMode: "floating", defaultFloatingSize: { width: 130, height: 32 }, tableExport: true, headless: catalystsHeadless },
21
+ { id: "litigation", name: "Litigation", icon: "L", component: LitigationPane, defaultPosition: "right", defaultMode: "floating", defaultFloatingSize: { width: 120, height: 30 }, shareItem: { ticker: true }, tickerFollower: true,
22
22
  // A fund's trust can be a party (a sponsor's case against the SEC); an index or a pair never is.
23
23
  instruments: ["equity", "fund"], tableExport: true, headless: litigationHeadless },
24
24
  ],
@@ -273,6 +273,10 @@ function projectCdsHeadless({ activity, history, levels, sort, days = DAILY_DAYS
273
273
  // The 5Y figures are dated by their level's day, each trade and each daily level by its own.
274
274
  const levelDate = line ? spreadSummary(line)?.date : undefined;
275
275
  const sections: HeadlessBundleSection[] = [
276
+ ...(!entries.length ? [{ title: "Level coverage", columns: [
277
+ { key: "issuer", header: "Issuer" }, { key: "tenor", header: "Tenor" }, { key: "status", header: "Status" }, { key: "reason", header: "Reason" },
278
+ ], rows: [{ issuer: name, tenor: "5Y", status: history instanceof Error ? "check-failed" : unmatched ? "not-covered" : why ? "not-derivable" : "no-traded-level",
279
+ spreadBp: null, reason: history instanceof Error ? "The spread history check failed." : unmatched ? empty : why ?? `No traded 5Y level on file for ${name} in the last two years.` }] }] : []),
276
280
  ...(entries.length ? [{ title: name, entries, symbol: name, ...(levelDate ? { asOf: levelDate } : {}) }] : []),
277
281
  {
278
282
  title: "Trades",