@gloom-sh/terminal 0.20.16 → 0.20.18

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 (345) hide show
  1. package/package.json +3 -1
  2. package/src/account/auth-dialog.tsx +19 -1
  3. package/src/account/billing.ts +2 -1
  4. package/src/account/heard-from-question.tsx +235 -0
  5. package/src/account/heard-from.ts +97 -0
  6. package/src/api-client/data.ts +16 -5
  7. package/src/api-client/heard-from.ts +72 -0
  8. package/src/api-client/index.ts +63 -6
  9. package/src/api-client/mna.ts +18 -0
  10. package/src/api-client/supply-chain.ts +9 -0
  11. package/src/api-client/types/billing.ts +35 -1
  12. package/src/api-client/types/econ.ts +3 -0
  13. package/src/app/global-shortcuts.ts +5 -3
  14. package/src/app/pro-welcome/keys.ts +27 -0
  15. package/src/app/pro-welcome/model.ts +158 -0
  16. package/src/app/pro-welcome/row.tsx +176 -0
  17. package/src/app/pro-welcome/use-pro-welcome.ts +156 -0
  18. package/src/app/runtime/external-profile-changes.ts +135 -0
  19. package/src/app.tsx +33 -2
  20. package/src/architecture/core-builtin-allowlist.json +1 -1
  21. package/src/architecture/floating-promise-allowlist.json +0 -1
  22. package/src/architecture/shortcut-labels-allowlist.json +1 -0
  23. package/src/cli/alert-listing.ts +98 -0
  24. package/src/cli/commands/fred-series.ts +3 -1
  25. package/src/cli/commands/market.ts +138 -22
  26. package/src/cli/commands/overview.ts +72 -14
  27. package/src/cli/commands/plugins.ts +3 -2
  28. package/src/cli/commands/search.ts +30 -6
  29. package/src/cli/context.ts +16 -5
  30. package/src/cli/csv-export.ts +74 -0
  31. package/src/cli/desktop-pane-shot.ts +75 -11
  32. package/src/cli/glossary.ts +64 -10
  33. package/src/cli/help.ts +4 -2
  34. package/src/cli/history-demergers.ts +117 -0
  35. package/src/cli/history-rows.ts +6 -2
  36. package/src/cli/index.ts +1 -0
  37. package/src/cli/known-gaps.ts +16 -0
  38. package/src/cli/known-us-stocks.ts +18 -0
  39. package/src/cli/listing-arg.ts +105 -15
  40. package/src/cli/pane-functions/catalog-snapshot-build.ts +83 -0
  41. package/src/cli/pane-functions/catalog-snapshot.json +866 -0
  42. package/src/cli/pane-functions/catalog-snapshot.ts +62 -0
  43. package/src/cli/pane-functions/catalog.ts +50 -16
  44. package/src/cli/pane-functions/data.ts +16 -4
  45. package/src/cli/pane-functions/dom.ts +24 -6
  46. package/src/cli/pane-functions/freshness.ts +17 -1
  47. package/src/cli/pane-functions/headless.ts +7 -2
  48. package/src/cli/pane-functions/index.ts +102 -44
  49. package/src/cli/pane-functions/resolver.ts +8 -5
  50. package/src/cli/pane-functions/screenshot-assessment.ts +30 -7
  51. package/src/cli/pane-functions/screenshot-bridge.ts +4 -2
  52. package/src/cli/pane-functions/screenshot-payload.ts +21 -0
  53. package/src/cli/pane-functions/screenshot-render.ts +3 -1
  54. package/src/cli/quote-answer.ts +32 -16
  55. package/src/cli/registry.ts +22 -2
  56. package/src/cli/report-tables.ts +17 -3
  57. package/src/cli/result.ts +8 -10
  58. package/src/cli/series-search.ts +45 -6
  59. package/src/cli/shot-temp-dir.ts +4 -9
  60. package/src/components/chart/composite/legend.tsx +80 -25
  61. package/src/components/chart/composite/panel-surface/panel-cursor.tsx +3 -3
  62. package/src/components/chart/composite/price-axis-labels.tsx +7 -5
  63. package/src/components/chart-table/header.tsx +9 -0
  64. package/src/components/chart-table/layout.ts +11 -11
  65. package/src/components/command-bar/pane-templates/items.ts +17 -1
  66. package/src/components/command-bar/routes/root/provider-search.ts +10 -1
  67. package/src/components/command-bar/routes/root/results.ts +34 -2
  68. package/src/components/command-bar/routes/root/runtime.ts +8 -1
  69. package/src/components/command-bar/routes/ticker-search/route.ts +5 -0
  70. package/src/components/command-bar/workflow/alert.ts +19 -8
  71. package/src/components/data-table/view.tsx +15 -2
  72. package/src/components/form-modal/content.tsx +9 -4
  73. package/src/components/index.ts +1 -1
  74. package/src/components/layout/header.tsx +9 -5
  75. package/src/components/layout/pane/capture-status.ts +6 -0
  76. package/src/components/layout/pane/footer/index.tsx +2 -0
  77. package/src/components/layout/pane/footer/model.ts +113 -15
  78. package/src/components/layout/pane/header.tsx +16 -2
  79. package/src/components/market-board/index.tsx +4 -2
  80. package/src/components/onboarding/onboarding-frame.tsx +6 -2
  81. package/src/components/onboarding/onboarding-keyboard.ts +7 -1
  82. package/src/components/onboarding/onboarding-wizard.tsx +3 -1
  83. package/src/components/onboarding/portfolio-step/positions-panel.tsx +24 -15
  84. package/src/components/onboarding/setup-cards.ts +36 -0
  85. package/src/components/onboarding/use-onboarding-progress.ts +22 -1
  86. package/src/components/onboarding/wizard-account.ts +6 -1
  87. package/src/components/onboarding/wizard-model.ts +32 -6
  88. package/src/components/onboarding/wizard-positions.ts +1 -1
  89. package/src/components/sign-in-gate.tsx +3 -1
  90. package/src/components/toggle-list.tsx +6 -8
  91. package/src/components/ui/confirm-dialog.tsx +47 -7
  92. package/src/components/ui/data-table/display-columns.ts +4 -1
  93. package/src/components/ui/data-table/hooks.ts +2 -3
  94. package/src/components/ui/data-table/index.tsx +4 -1
  95. package/src/components/ui/data-table/types.ts +19 -4
  96. package/src/components/ui/data-table/visible-range.ts +11 -1
  97. package/src/components/ui/display.tsx +17 -2
  98. package/src/components/ui/index.ts +1 -1
  99. package/src/components/ui/stat-grid.tsx +4 -0
  100. package/src/components/ui/status.tsx +13 -1
  101. package/src/components/ui/table-layout.ts +2 -1
  102. package/src/components/use-pane-notice-footer.tsx +16 -3
  103. package/src/data/config/store/index.ts +31 -0
  104. package/src/data/config/store/node.ts +61 -11
  105. package/src/data/config/store/normalize.ts +4 -6
  106. package/src/data/config/store/shared-file.ts +309 -0
  107. package/src/data/profile-merge.ts +299 -0
  108. package/src/data/sqlite/checkpointer.ts +11 -1
  109. package/src/data/sqlite/database.ts +1 -1
  110. package/src/data/ticker-repository.ts +134 -10
  111. package/src/data/ticker-store.ts +67 -0
  112. package/src/data/ticker-writes.ts +5 -0
  113. package/src/i18n/es.ts +27 -0
  114. package/src/i18n/ja.ts +27 -0
  115. package/src/i18n/ko.ts +27 -0
  116. package/src/i18n/zh-cn.ts +27 -0
  117. package/src/i18n/zh-tw.ts +27 -0
  118. package/src/layout-marketplace/gallery-desktop.tsx +2 -2
  119. package/src/market-data/ah-pair.ts +103 -0
  120. package/src/market-data/depositary-pair.ts +6 -2
  121. package/src/market-data/hooks.tsx +33 -2
  122. package/src/market-data/market/change-basis.ts +2 -1
  123. package/src/market-data/market/header-market.ts +11 -0
  124. package/src/market-data/split-terms.ts +28 -0
  125. package/src/plugins/builtin/account-management/footer.ts +1 -1
  126. package/src/plugins/builtin/account-management/keyboard.ts +4 -0
  127. package/src/plugins/builtin/account-management/model.ts +1 -0
  128. package/src/plugins/builtin/account-management/pane.tsx +75 -7
  129. package/src/plugins/builtin/account-management/payment-recovery-row.tsx +12 -5
  130. package/src/plugins/builtin/account-management/pro-cancel.tsx +197 -0
  131. package/src/plugins/builtin/account-management/trial-cancel.ts +1 -1
  132. package/src/plugins/builtin/alerts/cli-move.ts +2 -2
  133. package/src/plugins/builtin/alerts/cli.ts +36 -30
  134. package/src/plugins/builtin/alerts/constants.ts +10 -0
  135. package/src/plugins/builtin/alerts/earnings-listing.ts +20 -0
  136. package/src/plugins/builtin/alerts/format.ts +24 -8
  137. package/src/plugins/builtin/alerts/index.tsx +38 -9
  138. package/src/plugins/builtin/alerts/move-checks.ts +7 -0
  139. package/src/plugins/builtin/alerts/pane.tsx +1 -1
  140. package/src/plugins/builtin/alerts/quotes.ts +26 -2
  141. package/src/plugins/builtin/alerts/scheduled.ts +6 -1
  142. package/src/plugins/builtin/alerts/types.ts +7 -0
  143. package/src/plugins/builtin/analytics/manual-value.ts +61 -0
  144. package/src/plugins/builtin/analytics/risk-book.ts +7 -7
  145. package/src/plugins/builtin/analytics/risk-client.ts +26 -13
  146. package/src/plugins/builtin/analytics/risk-headless.ts +13 -8
  147. package/src/plugins/builtin/analytics/risk-model.ts +92 -4
  148. package/src/plugins/builtin/analytics/risk-pane.tsx +85 -38
  149. package/src/plugins/builtin/awards/pane.tsx +7 -3
  150. package/src/plugins/builtin/broker-trading/orders.tsx +2 -2
  151. package/src/plugins/builtin/central-bank-rates/model.ts +8 -2
  152. package/src/plugins/builtin/central-bank-rates/pane.tsx +5 -3
  153. package/src/plugins/builtin/chart-composer/cli-options.ts +4 -2
  154. package/src/plugins/builtin/chart-composer/data-catalog-pane.tsx +2 -6
  155. package/src/plugins/builtin/chart-composer/pane.tsx +9 -3
  156. package/src/plugins/builtin/cloud/auth-actions.tsx +11 -6
  157. package/src/plugins/builtin/cloud/company-picker.tsx +5 -3
  158. package/src/plugins/builtin/cloud/upgrade-command.ts +1 -1
  159. package/src/plugins/builtin/company-kpis/headless.ts +9 -4
  160. package/src/plugins/builtin/company-kpis/latest.ts +45 -0
  161. package/src/plugins/builtin/company-kpis/model.ts +38 -8
  162. package/src/plugins/builtin/company-kpis/pane.tsx +22 -8
  163. package/src/plugins/builtin/composite/alt-data.ts +20 -0
  164. package/src/plugins/builtin/composite/application.ts +14 -0
  165. package/src/plugins/builtin/composite/broker.ts +12 -0
  166. package/src/plugins/builtin/composite/credit.ts +33 -0
  167. package/src/plugins/builtin/composite/crypto.ts +10 -0
  168. package/src/plugins/builtin/composite/earnings.ts +12 -0
  169. package/src/plugins/builtin/composite/filings.ts +13 -0
  170. package/src/plugins/builtin/composite/futures-commodities.ts +23 -0
  171. package/src/plugins/builtin/composite/global-markets.ts +12 -0
  172. package/src/plugins/builtin/composite/options-volatility.ts +23 -0
  173. package/src/plugins/builtin/composite/ownership.ts +23 -0
  174. package/src/plugins/builtin/composite/portfolio.ts +10 -0
  175. package/src/plugins/builtin/composite/quant.ts +15 -0
  176. package/src/plugins/builtin/composite/rates-macro.ts +30 -0
  177. package/src/plugins/builtin/composite/screeners.ts +11 -0
  178. package/src/plugins/builtin/composite/shared.ts +11 -0
  179. package/src/plugins/builtin/composite/ticker-core.ts +36 -0
  180. package/src/plugins/builtin/congress-trades/headless.ts +31 -3
  181. package/src/plugins/builtin/correlation/index.tsx +13 -17
  182. package/src/plugins/builtin/correlation/matrix/model.ts +18 -0
  183. package/src/plugins/builtin/credit-conditions/series.ts +2 -2
  184. package/src/plugins/builtin/dividend-yield/client.ts +57 -16
  185. package/src/plugins/builtin/dividend-yield/headless.ts +17 -11
  186. package/src/plugins/builtin/dividend-yield/model.ts +4 -3
  187. package/src/plugins/builtin/dividend-yield/pane.tsx +22 -18
  188. package/src/plugins/builtin/dividend-yield/ranking.ts +1 -1
  189. package/src/plugins/builtin/dividend-yield/types.ts +4 -0
  190. package/src/plugins/builtin/dividend-yield/view.ts +23 -12
  191. package/src/plugins/builtin/earnings/board-model.ts +12 -0
  192. package/src/plugins/builtin/earnings/board-table.ts +7 -4
  193. package/src/plugins/builtin/earnings/board.tsx +2 -2
  194. package/src/plugins/builtin/earnings/fiscal-quarter.ts +39 -0
  195. package/src/plugins/builtin/earnings/headless.ts +7 -4
  196. package/src/plugins/builtin/earnings/highlight.ts +1 -1
  197. package/src/plugins/builtin/earnings/history-model.ts +6 -4
  198. package/src/plugins/builtin/earnings/history-table.ts +4 -3
  199. package/src/plugins/builtin/earnings-calls/pane.tsx +8 -2
  200. package/src/plugins/builtin/econ/calendar-model.ts +18 -0
  201. package/src/plugins/builtin/econ/fred-catalog.ts +1 -256
  202. package/src/plugins/builtin/econ/index.tsx +3 -0
  203. package/src/plugins/builtin/econ-statistics/cache.ts +1 -1
  204. package/src/plugins/builtin/econ-statistics/client.ts +11 -10
  205. package/src/plugins/builtin/econ-statistics/detail.tsx +1 -0
  206. package/src/plugins/builtin/econ-statistics/headless.ts +42 -6
  207. package/src/plugins/builtin/econ-statistics/index.tsx +1 -0
  208. package/src/plugins/builtin/econ-statistics/pane.tsx +7 -2
  209. package/src/plugins/builtin/econ-statistics/stats.ts +2 -1
  210. package/src/plugins/builtin/econ-statistics/view.ts +9 -3
  211. package/src/plugins/builtin/equity-screener/headless.ts +4 -1
  212. package/src/plugins/builtin/equity-screener/model.ts +7 -6
  213. package/src/plugins/builtin/estimate-revisions/headless.ts +1 -1
  214. package/src/plugins/builtin/exposure/model.ts +10 -0
  215. package/src/plugins/builtin/exposure/pane.tsx +10 -3
  216. package/src/plugins/builtin/fx-matrix/amount.ts +15 -1
  217. package/src/plugins/builtin/fx-matrix/headless.ts +12 -6
  218. package/src/plugins/builtin/fx-matrix/index.tsx +23 -5
  219. package/src/plugins/builtin/fx-matrix/settings.ts +9 -4
  220. package/src/plugins/builtin/kelly-sizer/pane.tsx +9 -4
  221. package/src/plugins/builtin/market-valuation/pane.tsx +22 -10
  222. package/src/plugins/builtin/mna/detail.tsx +67 -6
  223. package/src/plugins/builtin/mna/headless.ts +128 -13
  224. package/src/plugins/builtin/mna/model.ts +219 -16
  225. package/src/plugins/builtin/mna/pane.tsx +34 -6
  226. package/src/plugins/builtin/money-markets/model.ts +14 -5
  227. package/src/plugins/builtin/money-markets/pane.tsx +4 -3
  228. package/src/plugins/builtin/news/wire/news/footer.ts +3 -8
  229. package/src/plugins/builtin/options-scenario/csp-screen-pane.tsx +22 -6
  230. package/src/plugins/builtin/options-scenario/csp-screen.ts +39 -12
  231. package/src/plugins/builtin/options-scenario/strategy-screen.ts +7 -5
  232. package/src/plugins/builtin/pe-band/client.ts +13 -1
  233. package/src/plugins/builtin/pe-band/headless.ts +2 -2
  234. package/src/plugins/builtin/pe-band/model.ts +63 -10
  235. package/src/plugins/builtin/pe-band/pane.tsx +5 -5
  236. package/src/plugins/builtin/portfolio-list/allocation-rows.ts +26 -7
  237. package/src/plugins/builtin/portfolio-list/cli/portfolio-command.ts +66 -13
  238. package/src/plugins/builtin/portfolio-list/cli/render.ts +76 -33
  239. package/src/plugins/builtin/portfolio-list/headless.ts +69 -22
  240. package/src/plugins/builtin/portfolio-list/pane/data.ts +3 -3
  241. package/src/plugins/builtin/portfolio-list/pane/index.tsx +29 -14
  242. package/src/plugins/builtin/portfolio-list/summary/index.tsx +2 -2
  243. package/src/plugins/builtin/relative-rotation/pane.tsx +2 -3
  244. package/src/plugins/builtin/research/corporate-actions-pane.tsx +5 -1
  245. package/src/plugins/builtin/research/event-model.ts +31 -13
  246. package/src/plugins/builtin/research/headless.ts +8 -1
  247. package/src/plugins/builtin/research/relative-valuation-pane.tsx +19 -17
  248. package/src/plugins/builtin/sectors/index.tsx +6 -9
  249. package/src/plugins/builtin/shared/cloud-upgrade.ts +1 -1
  250. package/src/plugins/builtin/shared/earnings-report.ts +19 -4
  251. package/src/plugins/builtin/shared/fred-catalog.ts +256 -0
  252. package/src/plugins/builtin/shared/report-freshness.ts +2 -3
  253. package/src/plugins/builtin/shared/series-cache.ts +3 -0
  254. package/src/plugins/builtin/shared/series-detail-chart.tsx +3 -0
  255. package/src/plugins/builtin/short-interest/watch-pane.tsx +7 -7
  256. package/src/plugins/builtin/supply-chain/client.ts +34 -9
  257. package/src/plugins/builtin/supply-chain/evidence.ts +3 -2
  258. package/src/plugins/builtin/supply-chain/flow.tsx +4 -3
  259. package/src/plugins/builtin/supply-chain/graph-model.ts +14 -7
  260. package/src/plugins/builtin/supply-chain/graph-pane.tsx +3 -1
  261. package/src/plugins/builtin/supply-chain/graph.tsx +6 -3
  262. package/src/plugins/builtin/supply-chain/headless.ts +19 -4
  263. package/src/plugins/builtin/supply-chain/model.ts +50 -6
  264. package/src/plugins/builtin/supply-chain/pane.tsx +76 -16
  265. package/src/plugins/builtin/ticker-detail/adr-pair/ah.ts +62 -0
  266. package/src/plugins/builtin/ticker-detail/adr-pair/headless.ts +119 -20
  267. package/src/plugins/builtin/ticker-detail/adr-pair/model.ts +67 -1
  268. package/src/plugins/builtin/ticker-detail/adr-pair/tab.tsx +31 -16
  269. package/src/plugins/builtin/ticker-detail/overview/model.ts +17 -1
  270. package/src/plugins/builtin/ticker-detail/overview/pane.tsx +4 -0
  271. package/src/plugins/builtin/ticker-detail/overview-tab.tsx +9 -2
  272. package/src/plugins/builtin/ticker-detail/quote-monitor/card.tsx +9 -2
  273. package/src/plugins/builtin/ticker-detail/quote-monitor/index.tsx +5 -2
  274. package/src/plugins/builtin/time-sales/headless.ts +4 -1
  275. package/src/plugins/builtin/time-sales/pane.tsx +2 -0
  276. package/src/plugins/builtin/time-sales/window.ts +12 -0
  277. package/src/plugins/builtin/treasury-auctions/client.ts +4 -0
  278. package/src/plugins/builtin/treasury-auctions/treasury-direct.ts +2 -0
  279. package/src/plugins/builtin/treasury-daily/client.ts +23 -11
  280. package/src/plugins/builtin/volatility/model.ts +17 -0
  281. package/src/plugins/builtin/volatility/pane.tsx +13 -4
  282. package/src/plugins/builtin/world-indices/index.tsx +2 -0
  283. package/src/plugins/builtin/world-indices/table.tsx +15 -0
  284. package/src/plugins/builtin/world-venue-map/evidence.ts +3 -2
  285. package/src/plugins/builtin/world-venue-map/headless.ts +28 -16
  286. package/src/plugins/builtin/world-venue-map/index.ts +19 -6
  287. package/src/plugins/builtin/world-venue-map/layered-pane.tsx +9 -5
  288. package/src/plugins/builtin/world-venue-map/layers.ts +33 -11
  289. package/src/plugins/builtin/world-venue-map/map.tsx +12 -0
  290. package/src/plugins/builtin/world-venue-map/pane.tsx +35 -6
  291. package/src/plugins/builtin/world-venue-map/place.ts +119 -0
  292. package/src/plugins/catalog-data.ts +20 -0
  293. package/src/plugins/catalog-lazy.ts +51 -0
  294. package/src/plugins/catalog-ui.ts +16 -18
  295. package/src/plugins/host-smoke.ts +5 -2
  296. package/src/portfolio/allocation.ts +79 -19
  297. package/src/portfolio/cash-balances.ts +76 -0
  298. package/src/portfolio/mutations.ts +43 -8
  299. package/src/public/__snapshots__/public-api.test.ts.snap +1 -0
  300. package/src/renderers/desktop/window-layouts.ts +14 -0
  301. package/src/renderers/dom/data-table/row.tsx +2 -0
  302. package/src/renderers/dom/host/tabs.tsx +57 -8
  303. package/src/renderers/dom/styles.css +13 -5
  304. package/src/renderers/electrobun/bun/desktop/backend-requests.ts +4 -0
  305. package/src/renderers/electrobun/bun/desktop/backend.ts +22 -1
  306. package/src/renderers/electrobun/bun/window/native-min-size.ts +6 -1
  307. package/src/renderers/electrobun/shared/protocol.ts +4 -0
  308. package/src/renderers/electrobun/view/cli-pane-shot-entry.tsx +2 -0
  309. package/src/renderers/electrobun/view/cli-pane-shot-frame.tsx +50 -12
  310. package/src/renderers/electrobun/view/remote/ticker-repository.ts +10 -0
  311. package/src/series/standalone-catalog.ts +5 -4
  312. package/src/series/standalone.ts +13 -7
  313. package/src/sources/gloomberb-cloud/fred-publisher.ts +25 -0
  314. package/src/sources/gloomberb-cloud/fred-series.ts +1 -1
  315. package/src/sources/gloomberb-cloud/index.ts +14 -3
  316. package/src/sources/gloomberb-cloud/perpetuals.ts +60 -3
  317. package/src/sources/provider-router/financials.ts +20 -13
  318. package/src/sources/provider-router/index.ts +4 -0
  319. package/src/sources/provider-router/search.ts +1 -0
  320. package/src/sync/collections-contributor.ts +3 -1
  321. package/src/sync/config-merge.ts +10 -1
  322. package/src/sync/sanitize.ts +26 -2
  323. package/src/tickers/company-name-listing.ts +16 -2
  324. package/src/tickers/listing-fate.ts +12 -8
  325. package/src/tickers/renamed-listings.ts +43 -10
  326. package/src/tickers/search/home-listing.ts +28 -0
  327. package/src/tickers/search/index.ts +19 -7
  328. package/src/tickers/terminal-codes.ts +11 -1
  329. package/src/time-series/base-series.ts +3 -0
  330. package/src/time-series/ice-credit.ts +1 -0
  331. package/src/time-series/resolve.ts +3 -1
  332. package/src/time-series/spec.ts +2 -2
  333. package/src/time-series/types.ts +2 -1
  334. package/src/types/data-provider.ts +11 -0
  335. package/src/types/financials.ts +39 -3
  336. package/src/types/headless.ts +4 -2
  337. package/src/types/ticker.ts +10 -2
  338. package/src/utils/cli-output.ts +1 -1
  339. package/src/utils/declared-dividends.ts +13 -1
  340. package/src/utils/dividend-cash.ts +5 -1
  341. package/src/utils/forward-dividend.ts +4 -3
  342. package/src/utils/remove-folder.ts +37 -0
  343. package/src/utils/throttled-fetch.ts +15 -1
  344. package/src/utils/trailing-dividend.ts +1 -1
  345. package/src/plugins/builtin/composite-plugins.ts +0 -285
@@ -50,6 +50,8 @@ export interface CspScreenRow {
50
50
  wideSpread: boolean;
51
51
  /** Why the name has no put to rank. */
52
52
  note: string | null;
53
+ /** That reason as its row's few words (`no price`, `no chain`). */
54
+ state: string | null;
53
55
  }
54
56
 
55
57
  export interface CspScreen {
@@ -163,11 +165,33 @@ export async function loadScreenMarket(
163
165
  }
164
166
  const expiration = nearestListedExpiry(first.expirationDates, target);
165
167
  if (expiration == null) {
166
- throw new Error(first.warnings.find((warning) => warning.startsWith("Options chain")) ?? "No listed option expiries");
168
+ throw new ScreenNameError(first.warnings.find((warning) => warning.startsWith("Options chain")) ?? "No listed option expiries", "no chain");
167
169
  }
168
170
  const loaded = first.chain ? [...first.chain.puts, ...first.chain.calls][0]?.expiration : undefined;
169
- return loaded != null && expiryIsoDate(loaded) === expiryIsoDate(expiration)
170
- ? first : await loadScenarioMarket({ instrument, expiration, signal }, dependencies);
171
+ return requireScreenInputs(loaded != null && expiryIsoDate(loaded) === expiryIsoDate(expiration)
172
+ ? first : await loadScenarioMarket({ instrument, expiration, signal }, dependencies));
173
+ }
174
+
175
+ /**
176
+ * Why a screened name has nothing to rank, in full (`note`) and as its row's
177
+ * few words (`state`). The screens type no spot, rate or yield, so a missing
178
+ * one is said as what the market lacks, never as OSA's flag to supply it.
179
+ */
180
+ export class ScreenNameError extends Error {
181
+ constructor(message: string, readonly state: string) {
182
+ super(message);
183
+ }
184
+ }
185
+
186
+ /** The market a name's trade is valued at, or why it cannot be: its chain, price, Treasury rate and dividend yield, in that order. */
187
+ function requireScreenInputs(market: ScenarioMarketSnapshot): ScenarioMarketSnapshot {
188
+ if (!market.chain || market.warnings.includes("Options chain is stale")) {
189
+ throw new ScreenNameError(market.missingExpiry ?? "No current options chain", "no chain");
190
+ }
191
+ if (market.spot == null) throw new ScreenNameError("No current price for the underlying", "no price");
192
+ if (market.rate == null) throw new ScreenNameError("No Treasury rate to value its options at", "no rate");
193
+ if (market.dividendYield == null) throw new ScreenNameError("No dividend yield to value its options at", "no yield");
194
+ return market;
171
195
  }
172
196
 
173
197
  /** One name's put: OSA's csp seed at `--delta` on the listed expiry nearest the target, read as OSA reads it. */
@@ -215,8 +239,8 @@ function screenFreshness(markets: readonly ScenarioMarketSnapshot[], now: number
215
239
  };
216
240
  }
217
241
 
218
- /** One name of a screen: what it found, or why it found nothing, with its IV rank either way. */
219
- interface ScreenedName<T> { symbol: string; ivRank: number | null; value: T | null; note: string | null }
242
+ /** One name of a screen: what it found, or why it found nothing (in full and in a few words), with its IV rank either way. */
243
+ interface ScreenedName<T> { symbol: string; ivRank: number | null; value: T | null; note: string | null; state: string | null }
220
244
 
221
245
  export interface ScreenedNames<T> {
222
246
  names: ScreenedName<T>[];
@@ -229,10 +253,12 @@ export interface ScreenedNames<T> {
229
253
  * Each name screened by `screen`, four at a time: one IV rank request, one
230
254
  * earnings calendar request and one Treasury curve for all of them. A name
231
255
  * `screen` throws on is kept with the error as its note (`fallback` when the
232
- * error has no message). `screen` returns the market that dates its row.
256
+ * error has no message) and its state (a ScreenNameError's, else
257
+ * `fallbackState`). `screen` returns the market that dates its row.
233
258
  */
234
259
  export async function screenNames<T>(
235
- instruments: readonly InstrumentRef[], dependencies: CspScreenDependencies, signal: AbortSignal | undefined, fallback: string,
260
+ instruments: readonly InstrumentRef[], dependencies: CspScreenDependencies, signal: AbortSignal | undefined,
261
+ { fallback, fallbackState }: { fallback: string; fallbackState: string },
236
262
  screen: (instrument: InstrumentRef, earningsDate: string | null, scenario: ScenarioLoaderDependencies) => Promise<{ value: T; market: ScenarioMarketSnapshot }>,
237
263
  ): Promise<ScreenedNames<T>> {
238
264
  const now = dependencies.scenario.now?.() ?? Date.now();
@@ -259,10 +285,11 @@ export async function screenNames<T>(
259
285
  const reason = ivRankReason(ivRow);
260
286
  missingRanks.push(reason ? `${symbol} (${reason})` : symbol);
261
287
  }
262
- return { symbol, ivRank, value: screened.value, note: null };
288
+ return { symbol, ivRank, value: screened.value, note: null, state: null };
263
289
  } catch (error) {
264
290
  if (signal?.aborted) throw error;
265
- return { symbol, ivRank, value: null, note: errorMessage(error) ?? fallback };
291
+ return { symbol, ivRank, value: null, note: errorMessage(error) ?? fallback,
292
+ state: error instanceof ScreenNameError ? error.state : fallbackState };
266
293
  }
267
294
  });
268
295
  return { names, missingRanks: missingRanks.sort(), ivRankError: ivRanks.error, freshness: screenFreshness(markets, now) };
@@ -273,13 +300,13 @@ export async function loadCspScreen(
273
300
  instruments: readonly InstrumentRef[], criteria: CspScreenCriteria, dependencies: CspScreenDependencies, signal?: AbortSignal,
274
301
  ): Promise<CspScreen> {
275
302
  const target = cspTargetDate(criteria, dependencies.scenario.now?.() ?? Date.now());
276
- const screened = await screenNames(instruments, dependencies, signal, "No put to sell", async (instrument, earningsDate, scenario) => {
303
+ const screened = await screenNames(instruments, dependencies, signal, { fallback: "No put to sell", fallbackState: "no put" }, async (instrument, earningsDate, scenario) => {
277
304
  const put = await screenPut(instrument, criteria, scenario, target, earningsDate, signal);
278
305
  return { value: put, market: put.market };
279
306
  });
280
- const rows = screened.names.map(({ symbol, ivRank, value, note }): Omit<CspScreenRow, "rank"> => ({
307
+ const rows = screened.names.map(({ symbol, ivRank, value, note, state }): Omit<CspScreenRow, "rank"> => ({
281
308
  symbol, csp: value?.csp ?? null, delta: value?.delta ?? null, ivRank,
282
- wideSpread: value ? cspWideSpread(value.csp, criteria.maxSpreadPercent) : false, note }));
309
+ wideSpread: value ? cspWideSpread(value.csp, criteria.maxSpreadPercent) : false, note, state }));
283
310
  return { rows: rankCspScreen(rows), criteria, missingRanks: screened.missingRanks, ivRankError: screened.ivRankError,
284
311
  freshness: screened.freshness };
285
312
  }
@@ -9,7 +9,7 @@ import {
9
9
  } from "./client";
10
10
  import { calendarDaysToExpiry, earningsBeforeExpiry, type CspEarnings } from "./csp";
11
11
  import {
12
- cspTargetDate, loadScreenMarket, nearestListedExpiry, readCspScreenCriteria, readNumber, screenNames, supplied,
12
+ cspTargetDate, loadScreenMarket, nearestListedExpiry, readCspScreenCriteria, readNumber, ScreenNameError, screenNames, supplied,
13
13
  type CspScreen, type CspScreenCriteria, type CspScreenDependencies,
14
14
  } from "./csp-screen";
15
15
  import { seededLegQuotes } from "./hedge";
@@ -441,6 +441,8 @@ export interface StrategyScreenRow {
441
441
  wideSpread: boolean;
442
442
  /** Why the name has no trade. */
443
443
  note: string | null;
444
+ /** That reason as its row's few words (`no price`, `no chain`). */
445
+ state: string | null;
444
446
  }
445
447
 
446
448
  export interface StrategyScreen extends Omit<CspScreen, "rows" | "criteria"> {
@@ -489,7 +491,7 @@ async function screenStrategy(
489
491
  if (far == null) throw new Error(`No expiry listed after ${expiryIsoDate(near)} to buy`);
490
492
  const back = await loadScenarioMarket({ instrument, expiration: far, signal }, dependencies);
491
493
  if (!back.chain || back.warnings.includes("Options chain is stale")) {
492
- throw new Error(back.missingExpiry ?? `No current ${expiryIsoDate(far)} chain to buy the calendar on`);
494
+ throw new ScreenNameError(back.missingExpiry ?? `No current ${expiryIsoDate(far)} chain to buy the calendar on`, "no chain");
493
495
  }
494
496
  // The bought contracts by the date they are listed on in the catalogue.
495
497
  const backExpiration = [...back.chain.calls, ...back.chain.puts][0]?.expiration ?? far;
@@ -505,10 +507,10 @@ export async function loadStrategyScreen(
505
507
  instruments: readonly InstrumentRef[], criteria: StrategyScreenCriteria, dependencies: CspScreenDependencies, signal?: AbortSignal,
506
508
  ): Promise<StrategyScreen> {
507
509
  const target = cspTargetDate(criteria, dependencies.scenario.now?.() ?? Date.now());
508
- const screened = await screenNames(instruments, dependencies, signal, "No trade on this chain", async (instrument, earningsDate, scenario) =>
510
+ const screened = await screenNames(instruments, dependencies, signal, { fallback: "No trade on this chain", fallbackState: "no trade" }, async (instrument, earningsDate, scenario) =>
509
511
  screenStrategy(instrument, criteria, scenario, target, earningsDate, signal));
510
- const rows = screened.names.map(({ symbol, ivRank, value, note }): Omit<StrategyScreenRow, "rank"> => ({
511
- symbol, trade: value, ivRank, note,
512
+ const rows = screened.names.map(({ symbol, ivRank, value, note, state }): Omit<StrategyScreenRow, "rank"> => ({
513
+ symbol, trade: value, ivRank, note, state,
512
514
  wideSpread: value?.quote != null && value.quote.spreadOfMid * 100 > criteria.maxSpreadPercent }));
513
515
  return { rows: rankStrategyScreen(rows, criteria.strategy), criteria, missingRanks: screened.missingRanks,
514
516
  ivRankError: screened.ivRankError, freshness: screened.freshness };
@@ -16,6 +16,12 @@ import { reportDatesFrom, type ReportDate } from "./report-dates";
16
16
  export interface PeBandInputs {
17
17
  financials: TickerFinancials | null;
18
18
  history: PricePoint[];
19
+ /**
20
+ * Daily closes as far back as they are served (PE_BAND_DAILY_RANGE): what
21
+ * dates a weekly bar's close and prices a figure on the day it became
22
+ * known. Empty when they failed; the weekly bars stand alone then.
23
+ */
24
+ daily: PricePoint[];
19
25
  stale: boolean;
20
26
  /** Fundamentals failed: there is no EPS to price. */
21
27
  error: string | null;
@@ -33,6 +39,8 @@ export interface PeBandInputs {
33
39
  const CANCELLED = "P/E band load was cancelled";
34
40
  /** Weekly bars: daily history is only served to 5Y, and the band covers every year of statements on record. */
35
41
  const PE_BAND_HISTORY_RESOLUTION: ManualChartResolution = "1wk";
42
+ /** Daily closes are served this far back: a figure known within it is priced at its own day's close. */
43
+ const PE_BAND_DAILY_RANGE = "5Y";
36
44
  /** The most reports the server returns for one company: about ten years of quarters. */
37
45
  const REPORT_LIMIT = 40;
38
46
  /** Report dates only refine the figures' dates, so the pane does not wait longer than this for them. */
@@ -96,7 +104,7 @@ export async function loadPeBandInputs(
96
104
  const { instrument } = request;
97
105
  // Asked alongside the statements when the instrument names a US exchange; otherwise once the quote has said where it lists.
98
106
  const early = isUsListingExchange(instrument.exchange) ? loadReportDates(instrument.symbol, cloud) : null;
99
- const [financials, chart] = await abortable(Promise.allSettled([
107
+ const [financials, chart, dailyChart] = await abortable(Promise.allSettled([
100
108
  marketData.getTickerFinancials(instrument.symbol, instrument.exchange ?? "", {
101
109
  brokerId: instrument.instrument?.brokerId ?? instrument.brokerId,
102
110
  brokerInstanceId: instrument.instrument?.brokerInstanceId ?? instrument.brokerInstanceId,
@@ -106,12 +114,15 @@ export async function loadPeBandInputs(
106
114
  }),
107
115
  coordinator.loadChart({ instrument, bufferRange: "ALL", granularity: "resolution", resolution: PE_BAND_HISTORY_RESOLUTION },
108
116
  { forceRefresh: request.forceRefresh }),
117
+ coordinator.loadChart({ instrument, bufferRange: PE_BAND_DAILY_RANGE, granularity: "resolution", resolution: "1d" },
118
+ { forceRefresh: request.forceRefresh }),
109
119
  ]), request.signal, CANCELLED).catch((error: unknown) => {
110
120
  throw request.signal?.aborted || (error instanceof Error && error.name === "AbortError") ? abortError(CANCELLED) : error;
111
121
  });
112
122
  const value = financials.status === "fulfilled" ? financials.value : null;
113
123
  const entry = chart.status === "fulfilled" ? chart.value : null;
114
124
  const history = entry ? resolveEntryValue(entry) ?? [] : [];
125
+ const daily = dailyChart.status === "fulfilled" && !dailyChart.value.error ? resolveEntryValue(dailyChart.value) ?? [] : [];
115
126
  const quote = value?.quote;
116
127
  const [reports, fx] = await abortable(Promise.all([
117
128
  early ?? (isUsListingExchange(quote?.listingExchangeName ?? quote?.exchangeName ?? quote?.fullExchangeName)
@@ -121,6 +132,7 @@ export async function loadPeBandInputs(
121
132
  return {
122
133
  financials: value,
123
134
  history,
135
+ daily,
124
136
  reports,
125
137
  fx: fx.fx,
126
138
  fxError: fx.error,
@@ -15,7 +15,7 @@ export const peBandHeadless: HeadlessPaneDefinition<"bundle"> = {
15
15
  freshness: { ...DAILY_CLOSES, basis: "daily closes and reported EPS" },
16
16
  describe: (args) => `PEB ${args.symbols[0] ?? ""}`,
17
17
  discovery: { screenshotReadiness: "live-dom", limitations: [
18
- "Weekly closes. EPS reported in another currency than a dollar price is converted at daily FX closes; other currency pairs are not computed.",
18
+ "Weekly closes; each EPS figure is priced at the close of the day it became known where daily closes reach. EPS reported in another currency than a dollar price is converted at daily FX closes; other currency pairs are not computed.",
19
19
  ] },
20
20
  options: [
21
21
  { key: "lookbackYears", type: "integer", minimum: 0, maximum: 30, defaultValue: 10, description: "Years of history; 0 for all on record" },
@@ -26,7 +26,7 @@ export const peBandHeadless: HeadlessPaneDefinition<"bundle"> = {
26
26
  ctx.signal.throwIfAborted();
27
27
  const lookbackYears = Number(args.options.lookbackYears ?? 10);
28
28
  const model = projectPeBand(inputs.financials, inputs.history, { symbol: instrument.symbol, lookbackYears, reports: inputs.reports,
29
- fx: inputs.fx, fxError: inputs.fxError });
29
+ fx: inputs.fx, fxError: inputs.fxError, daily: inputs.daily });
30
30
  const current = model.current;
31
31
  const conversion = model.conversion;
32
32
  const pairQuote = (rate: number) => {
@@ -26,7 +26,11 @@ interface PeBandWeek {
26
26
  }
27
27
 
28
28
  export interface PeBandRow extends EpsStep {
29
- /** The close of the week the figure became known, in price units. */
29
+ /**
30
+ * The close of the day the figure became known (the last session on or
31
+ * before it), in price units; before the daily closes on record, the close
32
+ * of the weekly bar dated on or before it.
33
+ */
30
34
  price: number | null;
31
35
  pe: number | null;
32
36
  /** Change from the figure a year earlier in the same currency, when both are positive. */
@@ -53,7 +57,18 @@ export interface PeBandModel {
53
57
  symbol: string;
54
58
  /** Price currency. */
55
59
  currency: string | null;
60
+ /**
61
+ * The weekly closes the percentile and range rank over, each dated by the
62
+ * session it closed on where the daily closes cover its week (a bar is
63
+ * dated by its first day, its close by its last).
64
+ */
56
65
  weeks: PeBandWeek[];
66
+ /**
67
+ * What the chart draws: the weeks, and the close of each day a figure in
68
+ * the table became known, so selecting its row puts the chart's cursor on
69
+ * that day and the price the row reads.
70
+ */
71
+ points: PeBandWeek[];
57
72
  /** Newest first. */
58
73
  rows: PeBandRow[];
59
74
  multiples: number[];
@@ -176,6 +191,32 @@ export function chooseMultiples(pes: readonly number[], current?: number | null)
176
191
  return [];
177
192
  }
178
193
 
194
+ /** Positive closes in time order; cached history can carry ISO strings for dates. */
195
+ function closesOf(history: readonly PricePoint[]): Array<{ date: Date; close: number }> {
196
+ return history.map((point) => ({ date: new Date(point.date), close: point.close }))
197
+ .filter((point) => Number.isFinite(point.date.getTime()) && Number.isFinite(point.close) && point.close > 0)
198
+ .sort((a, b) => a.date.getTime() - b.date.getTime());
199
+ }
200
+
201
+ /**
202
+ * Weekly bars dated by the session their close is from. A bar is dated by
203
+ * its week's first day, so DWSN's week of 9 Nov 2026 read 9 Nov with the
204
+ * close of Friday the 13th. Where the daily closes cover a week, the bar
205
+ * takes the date of the last daily close before the next bar; elsewhere it
206
+ * keeps its own.
207
+ */
208
+ function closingSessions<T extends { date: Date }>(weekly: readonly T[], daily: readonly { date: Date }[]): T[] {
209
+ let at = 0;
210
+ return weekly.map((bar, index) => {
211
+ const from = bar.date.getTime();
212
+ const until = weekly[index + 1]?.date.getTime() ?? Number.POSITIVE_INFINITY;
213
+ while (at < daily.length && daily[at]!.date.getTime() < from) at += 1;
214
+ let last: { date: Date } | null = null;
215
+ while (at < daily.length && daily[at]!.date.getTime() < until) last = daily[at++]!;
216
+ return last ? { ...bar, date: last.date } : bar;
217
+ });
218
+ }
219
+
179
220
  /** Percent of `values` at or below `value`. */
180
221
  function percentileRank(values: readonly number[], value: number): number | null {
181
222
  return values.length ? 100 * values.filter((other) => other <= value).length / values.length : null;
@@ -204,10 +245,12 @@ export function projectPeBand(
204
245
  fx?: ReadonlyMap<string, FxCloses>;
205
246
  /** Why a needed FX history is missing, said when it leaves today's EPS unconverted. */
206
247
  fxError?: string | null;
248
+ /** Daily closes for the recent years they are served for (see `weeks` and `PeBandRow.price`). */
249
+ daily?: readonly PricePoint[];
207
250
  },
208
251
  ): PeBandModel {
209
252
  const currency = financials?.quote?.currency ?? null;
210
- const empty: PeBandModel = { symbol: options.symbol, currency, weeks: [], rows: [], multiples: [], current: null, range: null, sample: null, bandCeiling: null,
253
+ const empty: PeBandModel = { symbol: options.symbol, currency, weeks: [], points: [], rows: [], multiples: [], current: null, range: null, sample: null, bandCeiling: null,
211
254
  undated: 0, unavailable: 0, conversion: null, error: null, notice: null };
212
255
  if (!financials) return { ...empty, error: "Fundamentals unavailable." };
213
256
  // 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.
@@ -246,22 +289,25 @@ export function projectPeBand(
246
289
  const now = options.now ?? Date.now();
247
290
  const firstKnown = allSteps.find((step) => step.eps != null)!.knownAt.getTime();
248
291
  const start = Math.max(firstKnown, options.lookbackYears > 0 ? now - options.lookbackYears * YEAR_MS : firstKnown);
249
- // Cached history can carry ISO strings for dates.
250
- const sorted = history.map((point) => ({ date: new Date(point.date), close: point.close }))
251
- .filter((point) => Number.isFinite(point.date.getTime()) && Number.isFinite(point.close) && point.close > 0)
252
- .sort((a, b) => a.date.getTime() - b.date.getTime());
253
- const weeks = sorted.filter((point) => point.date.getTime() >= start).map((point): PeBandWeek => {
292
+ const sorted = closesOf(history);
293
+ const daily = closesOf(options.daily ?? []);
294
+ const dailyStart = daily[0]?.date.getTime() ?? Number.POSITIVE_INFINITY;
295
+ /** A close as the chart reads it: with the EPS in force on its day, and the P/E they make. */
296
+ const reading = (point: { date: Date; close: number }): PeBandWeek => {
254
297
  // Converted at the FX close of the bar's date, the same date that picks the EPS in force, so each week's multiple
255
298
  // moves with the price and the currency together rather than with the rate of an old publication date.
256
299
  const eps = priced(stepAt(allSteps, point.date.getTime()), day(point.date))?.eps ?? null;
257
300
  const positive = eps != null && eps > 0 ? eps : null;
258
301
  return { date: point.date, close: point.close, eps: positive, pe: positive ? point.close / positive : null };
259
- });
302
+ };
303
+ const weeks = closingSessions(sorted, daily).filter((point) => point.date.getTime() >= start).map(reading);
260
304
 
305
+ /** The close of the day `time` falls on, or the last session before it, where the daily closes reach. */
306
+ const dayClose = (time: number) => time >= dailyStart ? daily.findLast((point) => point.date.getTime() <= time) ?? null : null;
261
307
  const steps = allSteps.filter((step) => step.knownAt.getTime() >= start);
262
308
  const rows = steps.filter((step) => step.eps != null).map((step): PeBandRow => {
263
309
  const time = step.knownAt.getTime();
264
- const price = sorted.findLast((point) => point.date.getTime() <= time)?.close ?? null;
310
+ const price = (dayClose(time) ?? sorted.findLast((point) => point.date.getTime() <= time))?.close ?? null;
265
311
  // Converted at the FX close of the day it became known.
266
312
  const converted = priced(step, day(step.knownAt));
267
313
  const eps = converted?.eps ?? null;
@@ -286,8 +332,15 @@ export function projectPeBand(
286
332
  const multiples = chooseMultiples(pes, currentPe);
287
333
  const above = currentPe == null ? undefined : multiples.find((multiple) => multiple >= currentPe);
288
334
  const highestClose = weeks.reduce((max, week) => Math.max(max, week.close), 0);
335
+ // Each dated row's day on the chart, the close it reads: its cursor lands there, not on the week around it.
336
+ const rowDays = rows.flatMap((row) => {
337
+ const close = row.dated ? dayClose(row.knownAt.getTime()) : null;
338
+ return close && close.date.getTime() >= start ? [reading(close)] : [];
339
+ });
340
+ const byTime = new Map([...weeks, ...rowDays].map((point) => [point.date.getTime(), point]));
341
+ const points = [...byTime.values()].sort((a, b) => a.date.getTime() - b.date.getTime());
289
342
  return {
290
- ...empty, weeks, rows, multiples,
343
+ ...empty, weeks, points, rows, multiples,
291
344
  conversion: latestFx ? { currency: latestFx.currency, latest: fxCloseOnOrBefore(latestFx, day(now))! } : null,
292
345
  sample: ranked.length ? { start: ranked[0]!.date, weeks: ranked.length } : null,
293
346
  bandCeiling: highestClose > 0 ? Math.max(highestClose * 1.5, above != null && currentEps != null ? above * currentEps : 0) : null,
@@ -68,14 +68,14 @@ function chartSeries(model: PeBandModel, colors: ReturnType<typeof useThemeColor
68
68
  // Cheap multiples toward the positive colour, rich ones toward the negative, both faded so the price stays on top.
69
69
  ...model.multiples.map((value, index) => staticSeries(
70
70
  // Values past the ceiling leave the chart, so a far line cannot stretch the axis away from the price.
71
- model.weeks.map((week) => {
71
+ model.points.map((week) => {
72
72
  const band = week.eps == null ? null : week.eps * value;
73
73
  return scalarPoint(week.date, band != null && model.bandCeiling != null && band > model.bandCeiling ? null : band);
74
74
  }),
75
75
  { id: `x${value}`, label: `${value}x`, calendarSpaced: true, color: blendHex(colors.bg,
76
76
  blendHex(colors.positive, colors.negative, last > 0 ? index / last : 0.5), 0.75) },
77
77
  )),
78
- staticSeries(model.weeks.map((week) => scalarPoint(week.date, week.close)), { id: "price", label: "Price", color: colors.textBright, calendarSpaced: true }),
78
+ staticSeries(model.points.map((week) => scalarPoint(week.date, week.close)), { id: "price", label: "Price", color: colors.textBright, calendarSpaced: true }),
79
79
  ];
80
80
  }
81
81
 
@@ -103,7 +103,7 @@ export function PeBandPane({ width, height, focused }: PaneProps) {
103
103
  const lookbackYears = Number(lookback);
104
104
  const model = useMemo(() => inputs.data
105
105
  ? projectPeBand(inputs.data.financials, inputs.data.history, { symbol: symbol ?? "", lookbackYears: Number.isFinite(lookbackYears) ? lookbackYears : 10,
106
- reports: inputs.data.reports, fx: inputs.data.fx, fxError: inputs.data.fxError })
106
+ reports: inputs.data.reports, fx: inputs.data.fx, fxError: inputs.data.fxError, daily: inputs.data.daily })
107
107
  : null, [inputs.data, lookbackYears, symbol]);
108
108
  const rows = model?.rows ?? [];
109
109
  const conversion = model?.conversion ?? null;
@@ -166,8 +166,8 @@ export function PeBandPane({ width, height, focused }: PaneProps) {
166
166
  selectedTextOverridesCellColor
167
167
  getExportMetadata={() => [["symbol", model.symbol], ["currency", model.currency ?? ""],
168
168
  ["units", conversion
169
- ? `EPS as reported in ${conversion.currency}; FX close of the day it became known; price in ${model.currency ?? ""}; P/E at that close and that week's close`
170
- : "EPS and price in the listing currency; P/E at the close of the week the EPS became known"]]}
169
+ ? `EPS as reported in ${conversion.currency}; FX close of the day it became known; price in ${model.currency ?? ""}; P/E at that day's close`
170
+ : "EPS and price in the listing currency; P/E at the close of the day the EPS became known"]]}
171
171
  renderCell={(row, column) => renderCell(row, column, colors)}
172
172
  rootBefore={<ChartTableHeader width={width} height={height} tableRows={rows.length} tableColumns={columns} query={query} figures={figures}
173
173
  chart={model.weeks.length >= 2 ? { series, formatValue: formatPrice, formatAxisValue: formatAxis, remoteKind: "pe-band", ...link } : null} />} />
@@ -1,6 +1,7 @@
1
1
  import { summaryRowKey, type TickerTableSummaryRow } from "../../../components/ticker/list-table-view";
2
2
  import {
3
3
  CASH_SYMBOL,
4
+ cashLineLabel,
4
5
  formatAllocationDrift,
5
6
  formatAllocationWeight,
6
7
  type PortfolioAllocation,
@@ -31,24 +32,41 @@ function sumKnown(values: readonly (number | null | undefined)[]): number | null
31
32
  * The CASH and TOTAL rows under a book's holdings, as `portfolio show`
32
33
  * prints them. CASH has its value, weight, target, drift and, in TRADE VAL,
33
34
  * the amount that reaches its target: TRADE counts units, which cash has
34
- * none of, so it stays blank there. TOTAL adds up the allocation columns:
35
- * the weight, the targets, the drifts and the trades, so a book whose targets
36
- * cover it sums to zero. Its value, day and P&L are the header's, and stay
37
- * there. Null rows when the book has neither cash nor a target.
35
+ * none of, so it stays blank there. Cash held in several currencies first
36
+ * has a row per currency (CASH HKD, CASH USD) with its value and weight,
37
+ * and the CASH row under them is the whole line, as a ticker's position line
38
+ * is under its lots: the target belongs to all the cash. TOTAL adds up the
39
+ * allocation columns: the weight, the targets, the drifts and the trades, so
40
+ * a book whose targets cover it sums to zero. Its value, day and P&L are the
41
+ * header's, and stay there. Null rows when the book has neither cash nor a
42
+ * target.
38
43
  */
39
44
  export function allocationSummaryRows(
40
45
  allocation: Pick<PortfolioAllocation, "rows" | "cash" | "total" | "weightBasis" | "targetSum">,
41
- { cashCurrency, currency }: { cashCurrency?: string | null; currency: string },
46
+ { currency }: { currency: string },
42
47
  ): TickerTableSummaryRow[] {
43
48
  const rows: TickerTableSummaryRow[] = [];
44
49
  const { cash } = allocation;
50
+ const several = !!cash && cash.balances.length > 1;
51
+ if (cash && several) {
52
+ for (const balance of cash.balances) {
53
+ rows.push({
54
+ id: `cash:${balance.currency}`,
55
+ cells: {
56
+ ticker: { text: cashLineLabel(balance.currency, currency, true) },
57
+ mkt_value: { text: formatCompactAmount(balance.value ?? undefined), value: balance.value },
58
+ weight: { text: formatAllocationWeight(balance.weight), value: balance.weight },
59
+ },
60
+ });
61
+ }
62
+ }
45
63
  if (cash) {
46
64
  rows.push({
47
65
  id: "cash",
48
66
  selectable: true,
49
67
  cells: {
50
- ticker: { text: cashCurrency && cashCurrency !== currency ? `${CASH_SYMBOL} ${cashCurrency}` : CASH_SYMBOL },
51
- mkt_value: { text: formatCompactAmount(cash.value), value: cash.value },
68
+ ticker: { text: several ? CASH_SYMBOL : cashLineLabel(cash.balances[0]?.currency, currency) },
69
+ mkt_value: { text: formatCompactAmount(cash.value ?? undefined), value: cash.value },
52
70
  weight: { text: formatAllocationWeight(cash.weight), value: cash.weight },
53
71
  target_weight: { text: formatAllocationWeight(cash.targetWeight), value: cash.targetWeight },
54
72
  drift: signed(formatAllocationDrift(cash.drift), cash.drift),
@@ -57,6 +75,7 @@ export function allocationSummaryRows(
57
75
  });
58
76
  }
59
77
  const weight = allocation.weightBasis === "total" && allocation.total != null && allocation.total > 0 ? 100 : null;
78
+ // The whole cash line once, never each currency's row too.
60
79
  const lines = [...allocation.rows, ...(cash ? [cash] : [])];
61
80
  const drift = sumKnown(lines.map((line) => line.drift));
62
81
  const tradeValue = sumKnown(lines.map((line) => line.tradeValue));
@@ -15,7 +15,7 @@ import { futuresQuantityText, isFuturesTicker } from "../../../../portfolio/futu
15
15
  import { loadFuturesEntrySize } from "../../../../portfolio/futures-terms";
16
16
  import type { AppConfig } from "../../../../types/config";
17
17
  import type { CliCommandContext, CliCommandDef } from "../../../../types/plugin";
18
- import type { Portfolio, TickerRecord } from "../../../../types/ticker";
18
+ import type { Portfolio, PortfolioCash, TickerRecord } from "../../../../types/ticker";
19
19
  import type { TickerRepository } from "../../../../data/ticker-repository";
20
20
  import type { ConfigContext, MarketContext } from "../../../../cli/types";
21
21
  import { canonicalTickerKey, parsePublicTickerKey } from "../../../../utils/exchanges";
@@ -53,6 +53,7 @@ import { importedFromText } from "../imported-from";
53
53
  import { importPositionsFileCommand, POSITIONS_IMPORT_HELP, POSITIONS_IMPORT_USAGE, type PositionsImportOptions } from "./import-positions";
54
54
  import { savedListingCoinNote } from "../../../../cli/commands/crypto-hints";
55
55
  import { findNamedCollection } from "../../../../portfolio/collection-name";
56
+ import { portfolioCashBalances } from "../../../../portfolio/cash-balances";
56
57
  import { ambiguousQuantityProblem } from "../../../../portfolio/position-quantity";
57
58
  import {
58
59
  CLI_COST_FX_WORDING, loadPurchaseDateCostFx, readCostFxRate, readPurchaseDate, resolvePositionCostFx, type CostFxHistoryClient,
@@ -86,7 +87,7 @@ const ADD_USAGE = "Usage: gloom portfolio add <portfolio> <symbols...> [--file <
86
87
  const CREATE_USAGE = "Usage: gloom portfolio create <name> [--currency <code>]";
87
88
  const POSITION_USAGE = "Usage: gloom portfolio position set <portfolio> <ticker> <shares|contracts> <avg-cost> [currency] [--date <purchase date> | --cost-fx <rate>]";
88
89
  const REMOVE_USAGE = "Usage: gloom portfolio remove <portfolio> <symbols...> [--file <path>]";
89
- const CASH_USAGE = "Usage: gloom portfolio cash set <portfolio> <amount> [currency] | portfolio cash clear <portfolio>";
90
+ const CASH_USAGE = "Usage: gloom portfolio cash set <portfolio> <amount> [currency] | portfolio cash clear <portfolio> [currency]";
90
91
  const TARGET_USAGE = "Usage: gloom portfolio target set <portfolio> <symbol|CASH> <weight%> | target clear <portfolio> [symbol] | target show <portfolio>";
91
92
  const IMPORT_USAGE = "Usage: gloom portfolio import <file> [--name <portfolio>] [--merge | --replace] [--dry-run] | portfolio import --13f <CIK|fund name> [--top N] [--name <portfolio>] [--notional <amount>] [--replace]";
92
93
  const IMPORT_DEFAULT_TOP = 10;
@@ -479,7 +480,7 @@ async function setPositionCommand(
479
480
  function firstPositionCurrencyNote(portfolio: Portfolio, adopted: string): { text: string; warning: boolean } {
480
481
  const note = `"${portfolio.name}" now totals in ${adopted}, its first position's currency`;
481
482
  const held = [
482
- portfolio.cash && portfolio.cash.amount !== 0 ? "cash" : null,
483
+ portfolioCashBalances(portfolio).some((balance) => balance.amount !== 0) ? "cash" : null,
483
484
  Object.keys(portfolio.targetWeights ?? {}).length > 0 ? "targets" : null,
484
485
  ].filter((part): part is string => part !== null);
485
486
  if (held.length === 0) return { text: `${note}.`, warning: false };
@@ -542,17 +543,36 @@ function parseCashArgs(rest: string[], portfolios: readonly Portfolio[]): { name
542
543
  return null;
543
544
  }
544
545
 
546
+ /** Balances as a confirmation lists them: HK$39,000.00 and $1,200.00. */
547
+ function cashBalancesText(balances: readonly PortfolioCash[]): string {
548
+ const amounts = balances.map((balance) => formatAllocationMoney(balance.amount, balance.currency));
549
+ return amounts.length <= 1 ? amounts.join("") : `${amounts.slice(0, -1).join(", ")} and ${amounts.at(-1)!}`;
550
+ }
551
+
552
+ /** The line that says what cash a portfolio holds after a change, once it holds more than one currency's; else null. */
553
+ function cashHeldNote(portfolio: Portfolio, balances: readonly PortfolioCash[], totalsCurrency: string): string | null {
554
+ if (balances.length < 2) return null;
555
+ return `"${portfolio.name}" holds cash in ${balances.length} currencies, ${cashBalancesText(balances)}; reports convert each into ${totalsCurrency}.`;
556
+ }
557
+
545
558
  async function setCashCommand(rest: string[], ctx: CliCommandContext) {
546
559
  await withConfigData(ctx, async ({ config, persistence }) => {
547
560
  const parsed = parseCashArgs(rest, config.portfolios);
548
561
  if (!parsed?.name) ctx.fail(CASH_USAGE);
549
562
  try {
550
563
  const portfolio = requirePortfolio(config, parsed.name);
564
+ const totalsCurrency = resolvePortfolioTotalsCurrency(portfolio, config.baseCurrency);
551
565
  // An amount of a currency reads by its units: 500,000 USD is half a million, 1,234 KWD could be either.
552
- const currency = parsed.currency ?? resolvePortfolioTotalsCurrency(portfolio, config.baseCurrency);
566
+ const currency = parsed.currency ?? totalsCurrency;
553
567
  const amount = parseAmountArg(parsed.amount, "Cash amount", currency);
554
- await saveConfig(setPortfolioCash(config, portfolio.id, { amount, currency }));
555
- console.log(cliStyles.success(`Set cash in "${portfolio.name}" to ${formatAllocationMoney(amount, currency)}.`));
568
+ const { config: next, replaced, balances } = setPortfolioCash(config, portfolio.id, { amount, currency });
569
+ await saveConfig(next);
570
+ // Only this currency's balance changes: a portfolio holds one per currency, and the others stay.
571
+ const replacing = replaced ? `, replacing ${formatAllocationMoney(replaced.amount, replaced.currency)}` : "";
572
+ const which = balances.length > 1 ? `${currency} cash` : "cash";
573
+ console.log(cliStyles.success(`Set ${which} in "${portfolio.name}" to ${formatAllocationMoney(amount, currency)}${replacing}.`));
574
+ const held = cashHeldNote(portfolio, balances, totalsCurrency);
575
+ if (held) console.log(cliStyles.muted(held));
556
576
  const account = findCachedPortfolioAccount(config, portfolio, persistence.resources);
557
577
  if (account && Number.isFinite(account.totalCashValue)) {
558
578
  console.log(cliStyles.warning(
@@ -565,17 +585,47 @@ async function setCashCommand(rest: string[], ctx: CliCommandContext) {
565
585
  });
566
586
  }
567
587
 
568
- async function clearCashCommand(name: string, ctx: CliCommandContext) {
588
+ /**
589
+ * `<portfolio...> [currency]`: a last word that is a currency code, after
590
+ * words that name a portfolio, is the currency to clear; otherwise every word
591
+ * is the name (a portfolio called "Baht THB").
592
+ */
593
+ function parseCashClearArgs(rest: string[], portfolios: readonly Portfolio[]): { name: string; currency?: string } {
594
+ const last = rest.at(-1);
595
+ if (rest.length >= 2 && last && CURRENCY_CODE.test(last)) {
596
+ const name = rest.slice(0, -1).join(" ");
597
+ if (findNamedCollection(portfolios, name)) return { name, currency: last.toUpperCase() };
598
+ }
599
+ return { name: rest.join(" ") };
600
+ }
601
+
602
+ async function clearCashCommand(rest: string[], ctx: CliCommandContext) {
569
603
  await withConfigData(ctx, async ({ config }) => {
604
+ const { name, currency } = parseCashClearArgs(rest, config.portfolios);
570
605
  try {
571
606
  const portfolio = requirePortfolio(config, name);
572
- const result = clearPortfolioCash(config, portfolio.id);
573
- if (!result.changed) {
574
- console.log(cliStyles.warning(`"${portfolio.name}" has no cash recorded.`));
607
+ const totalsCurrency = resolvePortfolioTotalsCurrency(portfolio, config.baseCurrency);
608
+ const result = clearPortfolioCash(config, portfolio.id, currency);
609
+ if (result.removed.length === 0) {
610
+ const held = result.balances.length > 0 ? ` It holds ${result.balances.map((balance) => balance.currency).join(" and ")}.` : "";
611
+ console.log(cliStyles.warning(currency
612
+ ? `"${portfolio.name}" has no ${currency} cash recorded.${held}`
613
+ : `"${portfolio.name}" has no cash recorded.`));
575
614
  return;
576
615
  }
577
616
  await saveConfig(result.config);
578
- console.log(cliStyles.success(`Cleared the cash in "${portfolio.name}".`));
617
+ // One currency of several names it and what stays; all of it names each balance that went once there were several.
618
+ if (currency) {
619
+ const left = result.balances.length > 0 ? `; ${cashBalancesText(result.balances)} ${result.balances.length === 1 ? "stays" : "stay"}` : "";
620
+ const what = result.balances.length > 0 ? `${currency} cash` : "cash";
621
+ console.log(cliStyles.success(`Cleared the ${what} in "${portfolio.name}" (${cashBalancesText(result.removed)})${left}.`));
622
+ } else {
623
+ console.log(cliStyles.success(result.removed.length > 1
624
+ ? `Cleared the cash in "${portfolio.name}": ${cashBalancesText(result.removed)}.`
625
+ : `Cleared the cash in "${portfolio.name}".`));
626
+ }
627
+ const held = cashHeldNote(portfolio, result.balances, totalsCurrency);
628
+ if (held) console.log(cliStyles.muted(held));
579
629
  } catch (error) {
580
630
  failPortfolioCommand(ctx, error, `Failed to clear the cash in "${name}".`);
581
631
  }
@@ -1000,6 +1050,7 @@ const POSITION_HELP = {
1000
1050
  "A future's size is in contracts, at a price per unit of its contract (GC=F: per troy ounce); the contract size is read from its terms, as quote shows them.",
1001
1051
  "The cost is in the currency named after it (GBp or GBX for pence, gbp for pounds), else the listing's. A holding in another currency than the portfolio's (a US stock in a TRY portfolio) can be entered at its cost in the portfolio's currency (position set Lira BRK-B 10 20310 TRY), so P&L is in what was paid.",
1002
1052
  "Entered at its cost in its own currency, its P&L converts the cost at today's rate unless --date gives the purchase date, whose daily FX close is used, or --cost-fx gives the rate paid (portfolio currency per unit of the holding's: 32.15 TRY per USD); then the P&L carries the currency's move since. portfolio show names the holdings whose cost converts at today's rate.",
1053
+ "cash set sets the portfolio's cash in one currency, its own unless named, and keeps its cash in other currencies: HKD and USD can sit side by side, each converted into the portfolio's currency. It names the balance of that currency it replaced. cash clear <portfolio> <currency> clears one currency, cash clear <portfolio> all of it.",
1003
1054
  ],
1004
1055
  };
1005
1056
 
@@ -1039,7 +1090,7 @@ export const portfolioCliCommand: CliCommandDef = {
1039
1090
  "portfolio remove <portfolio> <symbols...> [--file <path>]",
1040
1091
  "portfolio position set <portfolio> <symbol> <shares|contracts> <avg-cost> [currency] [--date <purchase date> | --cost-fx <rate>]",
1041
1092
  "portfolio cash set <portfolio> <amount> [currency]",
1042
- "portfolio cash clear <portfolio>",
1093
+ "portfolio cash clear <portfolio> [currency]",
1043
1094
  "portfolio target set <portfolio> <symbol|CASH> <weight%>",
1044
1095
  "portfolio target clear <portfolio> [symbol|CASH]",
1045
1096
  "portfolio target show <portfolio>",
@@ -1080,6 +1131,8 @@ export const portfolioCliCommand: CliCommandDef = {
1080
1131
  "portfolio position set Lira BRK-B 10 410 USD --date 2024-03-01",
1081
1132
  "portfolio position set Lira KO 40 62.50 USD --cost-fx 32.15",
1082
1133
  "portfolio cash set Research 25000 USD",
1134
+ "portfolio cash set Research 195000 HKD",
1135
+ "portfolio cash clear Research HKD",
1083
1136
  "portfolio target set Research ASML 12.5%",
1084
1137
  "portfolio target set Research CASH 10",
1085
1138
  "portfolio show Research --close",
@@ -1230,7 +1283,7 @@ export const portfolioCliCommand: CliCommandDef = {
1230
1283
  return;
1231
1284
  }
1232
1285
  if (subaction === "clear" && rest.length > 0) {
1233
- await clearCashCommand(rest.join(" "), ctx);
1286
+ await clearCashCommand(rest, ctx);
1234
1287
  return;
1235
1288
  }
1236
1289
  ctx.fail(CASH_USAGE);