gloomberb 0.20.2 → 0.20.3

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 (362) hide show
  1. package/README.md +1 -1
  2. package/README.zh-CN.md +1 -1
  3. package/package.json +2 -1
  4. package/src/account/auth-form.tsx +13 -8
  5. package/src/account/upgrade-dialog.tsx +1 -1
  6. package/src/api-client/central-bank-rates.ts +5 -0
  7. package/src/api-client/data.ts +17 -4
  8. package/src/api-client/debt-maturities.ts +45 -2
  9. package/src/api-client/earnings.ts +4 -2
  10. package/src/api-client/errors.ts +21 -11
  11. package/src/api-client/index.ts +1 -0
  12. package/src/api-client/paths.ts +9 -1
  13. package/src/api-client/social-mentions.ts +47 -0
  14. package/src/api-client/types/econ.ts +4 -0
  15. package/src/app.tsx +11 -1
  16. package/src/cli/command-options.ts +2 -1
  17. package/src/cli/commands/market.ts +111 -29
  18. package/src/cli/commands/options-chain.ts +23 -6
  19. package/src/cli/commands/overview.ts +13 -5
  20. package/src/cli/commands/plugins.ts +49 -18
  21. package/src/cli/commands/search.ts +25 -6
  22. package/src/cli/commands/ticker.ts +4 -2
  23. package/src/cli/fx-quote-rate.ts +49 -1
  24. package/src/cli/glossary.ts +95 -15
  25. package/src/cli/history-rows.ts +9 -25
  26. package/src/cli/index.ts +6 -38
  27. package/src/cli/known-gaps.ts +3 -3
  28. package/src/cli/listing-arg.ts +78 -18
  29. package/src/cli/name-entries.ts +3 -2
  30. package/src/cli/not-a-ticker.ts +6 -2
  31. package/src/cli/pane-functions/capabilities.ts +12 -1
  32. package/src/cli/pane-functions/function-help.ts +23 -11
  33. package/src/cli/pane-functions/headless.ts +3 -1
  34. package/src/cli/pane-functions/index.ts +32 -4
  35. package/src/cli/pane-functions/market-session.ts +8 -3
  36. package/src/cli/pane-functions/resolver.ts +18 -11
  37. package/src/cli/pane-functions/screenshot-payload.ts +36 -6
  38. package/src/cli/pane-functions/screenshot-render.ts +4 -0
  39. package/src/cli/quote-answer.ts +10 -0
  40. package/src/cli/report-tables.ts +22 -2
  41. package/src/cli/result.ts +7 -3
  42. package/src/cli/spreadsheet-hint.ts +43 -0
  43. package/src/cli/symbol-list.ts +58 -4
  44. package/src/cli/symbol-rows.ts +49 -2
  45. package/src/cli/ticker-resolution.ts +98 -5
  46. package/src/cli/unknown-command.ts +88 -0
  47. package/src/components/command-bar/assist/model.ts +6 -1
  48. package/src/components/command-bar/commands/direct/index.ts +9 -1
  49. package/src/components/command-bar/commands/registry.ts +18 -0
  50. package/src/components/command-bar/pane-actions.ts +30 -13
  51. package/src/components/command-bar/panel/index.tsx +6 -3
  52. package/src/components/command-bar/panel/prompt-binding.ts +4 -0
  53. package/src/components/command-bar/panel/types.ts +3 -0
  54. package/src/components/command-bar/routes/header-market.ts +108 -0
  55. package/src/components/command-bar/routes/root/command-items.ts +5 -0
  56. package/src/components/command-bar/routes/root/provider-search.ts +190 -32
  57. package/src/components/command-bar/routes/root/results.ts +3 -0
  58. package/src/components/command-bar/routes/root/runtime.ts +28 -5
  59. package/src/components/command-bar/routes/ticker-search/results.ts +53 -6
  60. package/src/components/command-bar/routing/list-state.ts +38 -0
  61. package/src/components/command-bar/selection-hint.ts +28 -0
  62. package/src/components/command-bar/surface/index.tsx +41 -3
  63. package/src/components/command-bar/view-model.ts +15 -0
  64. package/src/components/command-bar/workflow/tickers.ts +3 -2
  65. package/src/components/company-logo.tsx +20 -2
  66. package/src/components/data-table/export.ts +13 -8
  67. package/src/components/feedback-dialog.tsx +2 -1
  68. package/src/components/form-modal/field-row.tsx +2 -1
  69. package/src/components/input-search-bar.tsx +2 -2
  70. package/src/components/layout/double-escape-close.ts +8 -5
  71. package/src/components/layout/header.tsx +75 -44
  72. package/src/components/layout/market-summary.ts +322 -116
  73. package/src/components/layout/pane/footer/index.tsx +26 -8
  74. package/src/components/layout/pane/footer/model.ts +46 -20
  75. package/src/components/layout/pane/header.tsx +3 -2
  76. package/src/components/layout/shell/chrome.ts +15 -15
  77. package/src/components/layout/status-bar.tsx +8 -7
  78. package/src/components/layout/status-widget-space.ts +8 -0
  79. package/src/components/markdown-editor.tsx +2 -2
  80. package/src/components/onboarding/account-step/form-panel.tsx +0 -3
  81. package/src/components/onboarding/onboarding-keyboard.ts +15 -6
  82. package/src/components/onboarding/onboarding-wizard.tsx +61 -11
  83. package/src/components/onboarding/portfolio-step/broker-fields-panel.tsx +0 -1
  84. package/src/components/onboarding/portfolio-step/positions-panel.tsx +0 -2
  85. package/src/components/price-sparkline/model.ts +26 -10
  86. package/src/components/ticker/list-table-view.tsx +29 -4
  87. package/src/components/ui/button.tsx +13 -2
  88. package/src/components/ui/column-grid.tsx +18 -9
  89. package/src/components/ui/data-table/index.tsx +1 -1
  90. package/src/components/ui/data-table/opentui/index.tsx +2 -1
  91. package/src/components/ui/data-table/types.ts +18 -0
  92. package/src/components/ui/delayed-mark.tsx +3 -2
  93. package/src/components/ui/field-grid.tsx +0 -2
  94. package/src/components/ui/fields.tsx +7 -4
  95. package/src/components/ui/inline-quick-add.tsx +2 -2
  96. package/src/components/ui/key-hint-words.ts +153 -0
  97. package/src/components/ui/key-hints.tsx +73 -0
  98. package/src/components/ui/menu.tsx +3 -1
  99. package/src/components/ui/message-composer.tsx +2 -2
  100. package/src/components/ui/shortcut-hint.tsx +28 -3
  101. package/src/components/ui/tabs.tsx +7 -0
  102. package/src/components/ui/text-prompt-dialog.tsx +2 -1
  103. package/src/core/state/app/command-bar-launch.ts +3 -0
  104. package/src/data/config/store/normalize.ts +6 -0
  105. package/src/docs/snapshot.json +120 -69
  106. package/src/i18n/es.ts +24 -1
  107. package/src/i18n/ja.ts +24 -1
  108. package/src/i18n/ko.ts +24 -1
  109. package/src/i18n/zh-cn.ts +24 -1
  110. package/src/i18n/zh-tw.ts +24 -1
  111. package/src/layout/pane-manager/gridlock.ts +11 -0
  112. package/src/market-data/bars-per-year.ts +27 -9
  113. package/src/market-data/coordinator/quotes.ts +22 -3
  114. package/src/market-data/futures-board.ts +80 -0
  115. package/src/market-data/futures-contract.ts +9 -3
  116. package/src/market-data/market/change-basis.ts +2 -2
  117. package/src/market-data/market/dated-previous-close.ts +163 -47
  118. package/src/market-data/market/format.ts +14 -3
  119. package/src/market-data/market/freshness.ts +24 -7
  120. package/src/market-data/market/header-market.ts +154 -0
  121. package/src/market-data/market/index-level.ts +29 -0
  122. package/src/market-data/market/index-session-venues.ts +44 -0
  123. package/src/market-data/market/status.ts +7 -2
  124. package/src/market-data/market/venue-session.ts +72 -0
  125. package/src/market-data/model-dividend-yield.ts +23 -8
  126. package/src/market-data/options-alternatives.ts +39 -4
  127. package/src/market-data/published-apac-sessions.ts +40 -2
  128. package/src/market-data/quotes/export-identity.ts +76 -0
  129. package/src/market-data/quotes/freshness.ts +22 -0
  130. package/src/market-data/quotes/time.ts +42 -1
  131. package/src/market-data/realized-volatility.ts +11 -7
  132. package/src/market-data/tax-equivalent.ts +145 -27
  133. package/src/plugins/builtin/account-management/pane.tsx +2 -2
  134. package/src/plugins/builtin/alerts/alert-engine.ts +12 -6
  135. package/src/plugins/builtin/alerts/alert-log.ts +6 -2
  136. package/src/plugins/builtin/alerts/calendar-events.ts +74 -12
  137. package/src/plugins/builtin/alerts/cli-forms.ts +11 -1
  138. package/src/plugins/builtin/alerts/cli-move.ts +234 -0
  139. package/src/plugins/builtin/alerts/cli.ts +224 -33
  140. package/src/plugins/builtin/alerts/command.ts +33 -6
  141. package/src/plugins/builtin/alerts/event-rows.ts +18 -4
  142. package/src/plugins/builtin/alerts/events-pane.tsx +6 -2
  143. package/src/plugins/builtin/alerts/events.ts +9 -0
  144. package/src/plugins/builtin/alerts/format.ts +40 -15
  145. package/src/plugins/builtin/alerts/headless.ts +31 -18
  146. package/src/plugins/builtin/alerts/history.ts +1 -0
  147. package/src/plugins/builtin/alerts/index.tsx +86 -12
  148. package/src/plugins/builtin/alerts/live.ts +2 -1
  149. package/src/plugins/builtin/alerts/move-checks.ts +155 -0
  150. package/src/plugins/builtin/alerts/move.ts +160 -0
  151. package/src/plugins/builtin/alerts/pane.tsx +52 -22
  152. package/src/plugins/builtin/alerts/price-text.ts +62 -0
  153. package/src/plugins/builtin/alerts/price.ts +17 -0
  154. package/src/plugins/builtin/alerts/quotes.ts +84 -3
  155. package/src/plugins/builtin/alerts/scheduled-check.ts +7 -1
  156. package/src/plugins/builtin/alerts/storage.ts +20 -7
  157. package/src/plugins/builtin/alerts/types.ts +13 -0
  158. package/src/plugins/builtin/analytics/risk-client.ts +60 -39
  159. package/src/plugins/builtin/analytics/risk-episodes.ts +18 -0
  160. package/src/plugins/builtin/analytics/risk-headless.ts +20 -4
  161. package/src/plugins/builtin/analytics/risk-model.ts +68 -1
  162. package/src/plugins/builtin/analytics/risk-pane.tsx +15 -3
  163. package/src/plugins/builtin/backtest/engine.ts +4 -2
  164. package/src/plugins/builtin/backtest/window.ts +3 -1
  165. package/src/plugins/builtin/broker-manager/sign-in-end.ts +1 -1
  166. package/src/plugins/builtin/central-bank-rates/client.ts +4 -0
  167. package/src/plugins/builtin/central-bank-rates/headless.ts +1 -1
  168. package/src/plugins/builtin/central-bank-rates/model.ts +18 -8
  169. package/src/plugins/builtin/central-bank-rates/pane.tsx +6 -3
  170. package/src/plugins/builtin/chart-composer/cli-options.ts +5 -0
  171. package/src/plugins/builtin/chart-composer/headless-schema.ts +17 -1
  172. package/src/plugins/builtin/chart-composer/headless.ts +2 -0
  173. package/src/plugins/builtin/cloud/upgrade-status-widget.tsx +9 -2
  174. package/src/plugins/builtin/crypto-board/headless.ts +82 -17
  175. package/src/plugins/builtin/crypto-board/index.tsx +24 -2
  176. package/src/plugins/builtin/crypto-board/model.ts +5 -2
  177. package/src/plugins/builtin/crypto-board/pane.tsx +4 -1
  178. package/src/plugins/builtin/debt-maturities/client.ts +111 -6
  179. package/src/plugins/builtin/debt-maturities/headless.ts +84 -1
  180. package/src/plugins/builtin/debt-maturities/model.ts +97 -14
  181. package/src/plugins/builtin/debt-maturities/pane.tsx +165 -15
  182. package/src/plugins/builtin/debt-maturities/series.ts +3 -1
  183. package/src/plugins/builtin/dividend-yield/client.ts +22 -6
  184. package/src/plugins/builtin/dividend-yield/headless.ts +113 -46
  185. package/src/plugins/builtin/dividend-yield/model.ts +5 -2
  186. package/src/plugins/builtin/dividend-yield/pane.tsx +6 -3
  187. package/src/plugins/builtin/dividend-yield/ranking-reads.ts +11 -4
  188. package/src/plugins/builtin/dividend-yield/ranking.ts +113 -18
  189. package/src/plugins/builtin/dividend-yield/types.ts +2 -0
  190. package/src/plugins/builtin/dividend-yield/view.ts +3 -0
  191. package/src/plugins/builtin/econ/calendar-model.ts +21 -3
  192. package/src/plugins/builtin/econ/detail-view.tsx +5 -3
  193. package/src/plugins/builtin/econ/figures.ts +13 -0
  194. package/src/plugins/builtin/econ/fred-catalog.ts +6 -3
  195. package/src/plugins/builtin/econ/index.tsx +5 -3
  196. package/src/plugins/builtin/econ/types.ts +5 -0
  197. package/src/plugins/builtin/equity-screener/footer.ts +45 -0
  198. package/src/plugins/builtin/equity-screener/pane.tsx +4 -18
  199. package/src/plugins/builtin/equity-screener/ticker-check.tsx +2 -1
  200. package/src/plugins/builtin/fixed-income/model.ts +1 -0
  201. package/src/plugins/builtin/futures/table.tsx +1 -1
  202. package/src/plugins/builtin/futures-curve/model.ts +3 -10
  203. package/src/plugins/builtin/help/function-card.tsx +2 -1
  204. package/src/plugins/builtin/help/function-index.ts +1 -0
  205. package/src/plugins/builtin/insider/client.ts +31 -14
  206. package/src/plugins/builtin/insider/signals-model.ts +2 -7
  207. package/src/plugins/builtin/iv-history/headless.ts +1 -2
  208. package/src/plugins/builtin/iv-history/model.ts +33 -23
  209. package/src/plugins/builtin/iv-history/screen-pane.tsx +0 -3
  210. package/src/plugins/builtin/kelly-sizer/headless.ts +64 -16
  211. package/src/plugins/builtin/kelly-sizer/history.ts +37 -28
  212. package/src/plugins/builtin/kelly-sizer/pane.tsx +43 -10
  213. package/src/plugins/builtin/kelly-sizer/sections.tsx +7 -2
  214. package/src/plugins/builtin/kelly-sizer/units.ts +29 -0
  215. package/src/plugins/builtin/news/index.tsx +7 -13
  216. package/src/plugins/builtin/news/overview-headlines.tsx +117 -0
  217. package/src/plugins/builtin/news/ticker-news.ts +35 -0
  218. package/src/plugins/builtin/news/wire/news/detail-view.tsx +8 -6
  219. package/src/plugins/builtin/news/wire/news/row.ts +49 -0
  220. package/src/plugins/builtin/news/wire/news/table.tsx +9 -20
  221. package/src/plugins/builtin/options/analytics.ts +7 -2
  222. package/src/plugins/builtin/options/live-quotes.ts +6 -1
  223. package/src/plugins/builtin/options/table.ts +3 -2
  224. package/src/plugins/builtin/options/view.tsx +11 -9
  225. package/src/plugins/builtin/options-scenario/client.ts +3 -0
  226. package/src/plugins/builtin/options-scenario/headless.ts +1 -1
  227. package/src/plugins/builtin/perps/client.ts +5 -4
  228. package/src/plugins/builtin/perps/headless.ts +134 -124
  229. package/src/plugins/builtin/perps/markets-section.tsx +2 -2
  230. package/src/plugins/builtin/perps/model.ts +8 -4
  231. package/src/plugins/builtin/perps/open-market.ts +4 -4
  232. package/src/plugins/builtin/perps/venue-markets.ts +3 -6
  233. package/src/plugins/builtin/portfolio-list/cell-version.ts +1 -0
  234. package/src/plugins/builtin/portfolio-list/cli/bulk-symbols.ts +34 -10
  235. package/src/plugins/builtin/portfolio-list/cli/period-report.ts +28 -2
  236. package/src/plugins/builtin/portfolio-list/cli/portfolio-command.ts +7 -3
  237. package/src/plugins/builtin/portfolio-list/cli/render.ts +66 -22
  238. package/src/plugins/builtin/portfolio-list/grid.tsx +5 -3
  239. package/src/plugins/builtin/portfolio-list/pane/data.ts +34 -1
  240. package/src/plugins/builtin/portfolio-list/pane/index.tsx +6 -0
  241. package/src/plugins/builtin/portfolio-list/pane/streaming.ts +15 -6
  242. package/src/plugins/builtin/portfolio-list/quick-add/resolution.ts +19 -7
  243. package/src/plugins/builtin/portfolio-list/table.tsx +30 -4
  244. package/src/plugins/builtin/realized-vol/evidence.ts +33 -6
  245. package/src/plugins/builtin/realized-vol/fx-proxy.ts +135 -0
  246. package/src/plugins/builtin/realized-vol/headless.ts +44 -8
  247. package/src/plugins/builtin/realized-vol/model.ts +9 -5
  248. package/src/plugins/builtin/realized-vol/pane.tsx +49 -15
  249. package/src/plugins/builtin/sec/headless.ts +48 -6
  250. package/src/plugins/builtin/sec/index.tsx +6 -4
  251. package/src/plugins/builtin/sec/model.ts +4 -1
  252. package/src/plugins/builtin/shared/earnings-calendar.ts +2 -0
  253. package/src/plugins/builtin/shared/market-cap-bands.ts +12 -0
  254. package/src/plugins/builtin/shared/report-freshness.ts +3 -1
  255. package/src/plugins/builtin/shared/use-quote-board.ts +5 -3
  256. package/src/plugins/builtin/shared/volatility/options.ts +63 -2
  257. package/src/plugins/builtin/social-mentions/headless.ts +72 -3
  258. package/src/plugins/builtin/social-mentions/index.tsx +8 -4
  259. package/src/plugins/builtin/social-mentions/lock-note.ts +6 -2
  260. package/src/plugins/builtin/social-mentions/outliers-client.ts +101 -0
  261. package/src/plugins/builtin/social-mentions/outliers-model.ts +162 -0
  262. package/src/plugins/builtin/social-mentions/outliers-names.ts +51 -0
  263. package/src/plugins/builtin/social-mentions/outliers.tsx +276 -0
  264. package/src/plugins/builtin/social-mentions/pane.tsx +32 -3
  265. package/src/plugins/builtin/supply-chain/graph-pane.tsx +2 -2
  266. package/src/plugins/builtin/thirteenf/api.ts +36 -2
  267. package/src/plugins/builtin/thirteenf/data.ts +4 -1
  268. package/src/plugins/builtin/thirteenf/headless.ts +14 -6
  269. package/src/plugins/builtin/thirteenf/model.ts +56 -1
  270. package/src/plugins/builtin/thirteenf/pane.tsx +8 -8
  271. package/src/plugins/builtin/thirteenf/report-notes.ts +11 -0
  272. package/src/plugins/builtin/thirteenf/table.ts +2 -1
  273. package/src/plugins/builtin/thirteenf/types.ts +6 -0
  274. package/src/plugins/builtin/ticker-detail/data-panes/historical-prices.tsx +23 -3
  275. package/src/plugins/builtin/ticker-detail/financials/model.ts +5 -0
  276. package/src/plugins/builtin/ticker-detail/headless-schema.ts +2 -1
  277. package/src/plugins/builtin/ticker-detail/headless.ts +21 -66
  278. package/src/plugins/builtin/ticker-detail/index.tsx +5 -0
  279. package/src/plugins/builtin/ticker-detail/overview/components.tsx +13 -1
  280. package/src/plugins/builtin/ticker-detail/overview/model.ts +6 -4
  281. package/src/plugins/builtin/ticker-detail/overview/pane.tsx +15 -0
  282. package/src/plugins/builtin/ticker-detail/overview/tax-equivalent.ts +69 -0
  283. package/src/plugins/builtin/ticker-detail/overview-tab.tsx +41 -6
  284. package/src/plugins/builtin/ticker-detail/quote-monitor/card.tsx +47 -24
  285. package/src/plugins/builtin/ticker-detail/quote-monitor/export.ts +46 -0
  286. package/src/plugins/builtin/ticker-detail/quote-monitor/index.tsx +20 -1
  287. package/src/plugins/builtin/ticker-detail/quote-monitor/rows.ts +120 -0
  288. package/src/plugins/builtin/ticker-detail/research-tabs.ts +1 -5
  289. package/src/plugins/builtin/ticker-detail/settings.ts +6 -6
  290. package/src/plugins/builtin/treasury-auctions/cache.ts +85 -19
  291. package/src/plugins/builtin/treasury-auctions/index.tsx +22 -11
  292. package/src/plugins/builtin/treasury-auctions/model.ts +23 -0
  293. package/src/plugins/builtin/treasury-auctions/treasury-direct.ts +128 -0
  294. package/src/plugins/builtin/world-indices/client.ts +2 -0
  295. package/src/plugins/compat.ts +15 -0
  296. package/src/plugins/host-link.ts +6 -1
  297. package/src/plugins/installer.ts +8 -3
  298. package/src/portfolio/column-values.ts +14 -4
  299. package/src/portfolio/listed-symbol.ts +78 -0
  300. package/src/portfolio/real-return.ts +172 -0
  301. package/src/public/__snapshots__/public-api.test.ts.snap +1 -0
  302. package/src/renderers/browser/config-host.ts +56 -15
  303. package/src/renderers/browser/main.tsx +3 -1
  304. package/src/renderers/browser/ui-host.tsx +1 -0
  305. package/src/renderers/cloudflare/http-proxy.ts +1 -0
  306. package/src/renderers/dom/boot-frame.ts +2 -2
  307. package/src/renderers/dom/data-table/row.tsx +4 -1
  308. package/src/renderers/dom/desktop/controls.tsx +4 -4
  309. package/src/renderers/dom/desktop/dialog-actions.tsx +60 -41
  310. package/src/renderers/dom/dom-ui-host.tsx +3 -1
  311. package/src/renderers/dom/host/input.tsx +4 -1
  312. package/src/renderers/dom/host/tabs.tsx +10 -1
  313. package/src/renderers/dom/styles.css +33 -13
  314. package/src/renderers/electrobun/bun/desktop/app-name.ts +1 -1
  315. package/src/renderers/opentui/host.tsx +2 -1
  316. package/src/sources/gloomberb-cloud/fred-series.ts +12 -0
  317. package/src/sources/gloomberb-cloud/index.ts +31 -2
  318. package/src/sources/gloomberb-cloud/normalizers.ts +29 -3
  319. package/src/sources/provider-router/cached-routes.ts +19 -7
  320. package/src/state/pane-table-export-registry.ts +19 -6
  321. package/src/test-support/preload.ts +5 -1
  322. package/src/theme/colors.ts +9 -1
  323. package/src/theme/themes.ts +62 -15
  324. package/src/theme/tone-contrast.ts +40 -0
  325. package/src/theme/ui-tokens.ts +23 -3
  326. package/src/tickers/batched-lookups.ts +57 -8
  327. package/src/tickers/company-name-listing.ts +156 -14
  328. package/src/tickers/company-name.ts +30 -6
  329. package/src/tickers/list.ts +7 -0
  330. package/src/tickers/search/home-listing.ts +31 -9
  331. package/src/tickers/search/index.ts +13 -3
  332. package/src/tickers/search/listing-index.ts +558 -0
  333. package/src/tickers/search/major-listings.chunk.ts +10 -0
  334. package/src/tickers/search/major-listings.json +3346 -0
  335. package/src/tickers/search/ranking.ts +68 -1
  336. package/src/tickers/search/types.ts +4 -0
  337. package/src/tickers/terminal-codes.ts +26 -1
  338. package/src/time-series/calendar-month-returns.ts +47 -0
  339. package/src/time-series/currency-conversion.ts +130 -0
  340. package/src/time-series/hooks.ts +2 -0
  341. package/src/time-series/price-comparison.ts +34 -11
  342. package/src/time-series/resolve-context.ts +3 -0
  343. package/src/time-series/resolve.ts +14 -2
  344. package/src/time-series/spec.ts +1 -0
  345. package/src/time-series/studies/indicators.ts +4 -1
  346. package/src/time-series/types.ts +8 -0
  347. package/src/types/config.ts +8 -0
  348. package/src/types/data-provider.ts +28 -0
  349. package/src/types/financials.ts +20 -2
  350. package/src/types/headless.ts +12 -0
  351. package/src/ui/host.tsx +8 -0
  352. package/src/utils/datetime-format.ts +17 -3
  353. package/src/utils/display-number.ts +15 -0
  354. package/src/utils/double-escape-close.ts +61 -16
  355. package/src/utils/float32-price.ts +24 -0
  356. package/src/utils/forward-dividend.ts +81 -16
  357. package/src/utils/fx-market-hours.ts +11 -0
  358. package/src/utils/plugin-proxy-hosts.json +2 -1
  359. package/src/utils/price-history.ts +7 -6
  360. package/src/utils/report-timing.ts +62 -0
  361. package/src/utils/sec-filings.ts +32 -0
  362. package/src/utils/utc-time.ts +5 -0
@@ -4,6 +4,7 @@ import { fixedIncomeShortcut } from "../fixed-income/shortcut";
4
4
  import {
5
5
  attachTreasuryAuctionsPersistence,
6
6
  resetTreasuryAuctionsPersistence,
7
+ TREASURY_DIRECT_CONNECTION_ID,
7
8
  TREASURY_FISCAL_DATA_CONNECTION_ID,
8
9
  } from "./cache";
9
10
  import { AUCTION_HISTORY_WINDOWS, auctionHistoryLabel } from "./model";
@@ -11,7 +12,7 @@ import { createPublicPaneShare } from "../shared/public-pane";
11
12
  import { treasuryAuctionsHeadless } from "./headless";
12
13
 
13
14
 
14
- let disposeConnection: (() => void) | null = null;
15
+ let disposeConnections: Array<() => void> = [];
15
16
 
16
17
  export function treasuryAuctionsSettings(): PaneSettingsDef {
17
18
  return {
@@ -31,19 +32,29 @@ export function treasuryAuctionsSettings(): PaneSettingsDef {
31
32
  export const treasuryAuctionsModule: PluginModule = {
32
33
  setup(ctx) {
33
34
  attachTreasuryAuctionsPersistence(ctx.persistence, ctx.connectionHealth);
34
- disposeConnection = ctx.connectionHealth.registerSource({
35
- id: TREASURY_FISCAL_DATA_CONNECTION_ID,
36
- name: "Treasury Fiscal Data",
37
- kind: "api",
38
- ownerId: "credit",
39
- priority: 300,
40
- detail: "fiscaldata.treasury.gov",
41
- });
35
+ disposeConnections = [
36
+ ctx.connectionHealth.registerSource({
37
+ id: TREASURY_FISCAL_DATA_CONNECTION_ID,
38
+ name: "Treasury Fiscal Data",
39
+ kind: "api",
40
+ ownerId: "credit",
41
+ priority: 300,
42
+ detail: "fiscaldata.treasury.gov",
43
+ }),
44
+ ctx.connectionHealth.registerSource({
45
+ id: TREASURY_DIRECT_CONNECTION_ID,
46
+ name: "TreasuryDirect",
47
+ kind: "api",
48
+ ownerId: "credit",
49
+ priority: 301,
50
+ detail: "treasurydirect.gov",
51
+ }),
52
+ ];
42
53
  },
43
54
 
44
55
  dispose() {
45
- disposeConnection?.();
46
- disposeConnection = null;
56
+ for (const dispose of disposeConnections) dispose();
57
+ disposeConnections = [];
47
58
  resetTreasuryAuctionsPersistence();
48
59
  },
49
60
 
@@ -298,6 +298,29 @@ export function isPendingAuction(auction: TreasuryAuction): boolean {
298
298
  return rateValue(auction) == null && auction.bidToCoverRatio == null;
299
299
  }
300
300
 
301
+ /**
302
+ * One board from Fiscal Data's auctions and TreasuryDirect's. An auction in
303
+ * both (same CUSIP and day) is one row, the one with its results: Fiscal Data
304
+ * posts a day's auctions as announced and fills the results in later, or not
305
+ * at all while it lags, and TreasuryDirect has them within minutes. When both
306
+ * have them, or neither does, the Fiscal Data row stays, as it was before
307
+ * TreasuryDirect was read. An auction only TreasuryDirect lists is added, from
308
+ * `from` (an ISO date) on: it reads further back than a short window shows.
309
+ */
310
+ export function mergeAuctionSources(
311
+ fiscal: readonly TreasuryAuction[],
312
+ direct: readonly TreasuryAuction[],
313
+ from: string,
314
+ ): TreasuryAuction[] {
315
+ const supplement = new Map(direct.filter((auction) => auction.auctionDate >= from).map((auction) => [auction.id, auction]));
316
+ const merged = fiscal.map((auction) => {
317
+ const other = supplement.get(auction.id);
318
+ supplement.delete(auction.id);
319
+ return other && isPendingAuction(auction) && !isPendingAuction(other) ? other : auction;
320
+ });
321
+ return [...merged, ...supplement.values()];
322
+ }
323
+
301
324
  /**
302
325
  * The announced offering, for pending and completed auctions alike. Total
303
326
  * accepted also counts SOMA add-ons, which would overstate completed sizes.
@@ -0,0 +1,128 @@
1
+ import { ApiRequestError } from "../../../api-client/errors";
2
+ import { createThrottledFetch } from "../../../utils/throttled-fetch";
3
+ import type { TreasuryAuction } from "./types";
4
+
5
+ /**
6
+ * TreasuryDirect's securities search lists every security announced or
7
+ * auctioned, results included, as soon as Treasury posts them. Fiscal Data's
8
+ * auction dataset is the fuller record but updates in batches and has stopped
9
+ * updating for weeks at a time, so the board reads this beside it for the
10
+ * auctions of the last weeks and the ones announced.
11
+ */
12
+ const SEARCH_URL = "https://www.treasurydirect.gov/TA_WS/securities/search";
13
+
14
+ /**
15
+ * How far back the search is read: wider than the longest stretch Fiscal Data
16
+ * has been seen to lag, small enough to stay one request of about 90 KB
17
+ * compressed (the search sends every field of a security; a year is ten times that).
18
+ */
19
+ export const DIRECT_LOOKBACK_DAYS = 60;
20
+ /** Announced auctions are listed days to two weeks ahead; a month leaves none out. */
21
+ const DIRECT_LOOKAHEAD_DAYS = 30;
22
+
23
+ const DIRECT_FETCH = createThrottledFetch({
24
+ requestsPerMinute: 20,
25
+ maxRetries: 2,
26
+ timeoutMs: 20_000,
27
+ backoffBaseMs: 800,
28
+ defaultHeaders: { Accept: "application/json" },
29
+ });
30
+
31
+ const isoDate = (time: number): string => new Date(time).toISOString().slice(0, 10);
32
+
33
+ /**
34
+ * The days a board for `days` days of history reads from TreasuryDirect:
35
+ * that many days back, no further than `DIRECT_LOOKBACK_DAYS`, up to a month
36
+ * ahead. Both ends are inclusive.
37
+ */
38
+ export function directSearchRange(days: number, now = Date.now()): { startDate: string; endDate: string } {
39
+ return {
40
+ startDate: isoDate(now - Math.min(days, DIRECT_LOOKBACK_DAYS) * 86_400_000),
41
+ endDate: isoDate(now + DIRECT_LOOKAHEAD_DAYS * 86_400_000),
42
+ };
43
+ }
44
+
45
+ export function buildDirectSearchUrl(days: number, now = Date.now()): string {
46
+ const params = new URLSearchParams({
47
+ ...directSearchRange(days, now),
48
+ dateFieldName: "competitiveAuctionCloseDate",
49
+ format: "json",
50
+ });
51
+ return `${SEARCH_URL}?${params}`;
52
+ }
53
+
54
+ const text = (value: unknown): string => (typeof value === "string" ? value.trim() : "");
55
+
56
+ /** TreasuryDirect sends a figure an auction has not published as "" and every number as a string. */
57
+ function toNumber(value: unknown): number | null {
58
+ const stated = text(value);
59
+ if (!stated) return null;
60
+ const parsed = Number(stated);
61
+ return Number.isFinite(parsed) ? parsed : null;
62
+ }
63
+
64
+ /**
65
+ * One security of the search as the board's auction, with the figures Fiscal
66
+ * Data carries under the same names: a bill's discount and investment rates,
67
+ * a note's, bond's or TIPS's high and median yield, an FRN's high discount
68
+ * margin, the prices, bid-to-cover and the competitive awards. The id is
69
+ * Fiscal Data's (CUSIP and auction date), so one auction in both feeds is one
70
+ * row. Null for a record without a CUSIP, a type or the day bidding closes.
71
+ */
72
+ export function normalizeDirectAuction(raw: unknown): TreasuryAuction | null {
73
+ if (!raw || typeof raw !== "object" || Array.isArray(raw)) return null;
74
+ const record = raw as Record<string, unknown>;
75
+ const cusip = text(record.cusip);
76
+ const auctionDate = /^\d{4}-\d{2}-\d{2}/.exec(text(record.competitiveAuctionCloseDate))?.[0];
77
+ // Bill, Note or Bond: Treasury's own `type` splits out CMBs (a bill here, as Fiscal Data has them), FRNs and TIPS.
78
+ const securityType = text(record.securityType);
79
+ if (!cusip || !auctionDate || !securityType) return null;
80
+ const bill = securityType === "Bill";
81
+ return {
82
+ id: `${cusip}|${auctionDate}`,
83
+ cusip,
84
+ secType: text(record.inflationProtected) === "Yes" ? "TIPS" : text(record.floatingRate) === "Yes" ? "FRN" : securityType,
85
+ securityTerm: text(record.securityTerm) || "—",
86
+ auctionDate,
87
+ highInvestmentRate: toNumber(record.investmentRate),
88
+ // A bill's `highRate` is its discount rate; a note or bond states its coupon elsewhere.
89
+ highDiscountRate: bill ? toNumber(record.highRate) : null,
90
+ avgMedDiscountRate: bill ? toNumber(record.medianRate) : null,
91
+ highDiscountMargin: toNumber(record.highDiscountMargin),
92
+ highYield: toNumber(record.highYield),
93
+ avgMedYield: toNumber(record.medianYield),
94
+ highPrice: toNumber(record.highPrice),
95
+ lowPrice: toNumber(record.lowPrice),
96
+ avgMedPrice: toNumber(record.averagePrice),
97
+ bidToCoverRatio: toNumber(record.bidToCoverRatio),
98
+ competitiveAccepted: toNumber(record.subtotalCompetitiveParAwardedInsideOfOfferingAmount),
99
+ indirectAccepted: toNumber(record.indirectBiddersCompetitiveParAwarded),
100
+ directAccepted: toNumber(record.directBiddersCompetitiveParAwarded),
101
+ primaryDealerAccepted: toNumber(record.primaryDealersCompetitiveParAwarded),
102
+ totalAccepted: toNumber(record.grandTotalParAwarded),
103
+ offeringAmount: toNumber(record.offeringAmount),
104
+ };
105
+ }
106
+
107
+ /**
108
+ * The auctions of a search response, each once. A body that is not a list of
109
+ * securities is a failure (an error page, a changed endpoint), never a quiet
110
+ * period; a record it cannot identify is skipped.
111
+ */
112
+ export function parseDirectAuctions(body: unknown): TreasuryAuction[] {
113
+ if (!Array.isArray(body)) throw new Error("TreasuryDirect securities search did not return a list of securities");
114
+ const auctions = new Map<string, TreasuryAuction>();
115
+ for (const raw of body) {
116
+ const auction = normalizeDirectAuction(raw);
117
+ if (auction && !auctions.has(auction.id)) auctions.set(auction.id, auction);
118
+ }
119
+ return [...auctions.values()];
120
+ }
121
+
122
+ /** The auctions of the last `days` days (at most `DIRECT_LOOKBACK_DAYS`) and the ones announced. */
123
+ export async function fetchDirectAuctions(days: number): Promise<TreasuryAuction[]> {
124
+ const response = await DIRECT_FETCH.fetch(buildDirectSearchUrl(days));
125
+ // The status stays: an overloaded server is a failure a saved board may answer for, a refusal is not.
126
+ if (!response.ok) throw new ApiRequestError(`TreasuryDirect request failed (${response.status})`, response.status);
127
+ return parseDirectAuctions(await response.json());
128
+ }
@@ -33,8 +33,10 @@ export async function loadWorldIndexQuotes(
33
33
  else errors.push(`${symbol}: ${message}`);
34
34
  };
35
35
  if (provider.getQuotesBatch) {
36
+ // Each row's change is a move from a dated close: an index's is checked against its daily closes first.
36
37
  const results = await provider.getQuotesBatch(
37
38
  entries.map((entry) => ({ symbol: entry.symbol, exchange: "" })),
39
+ { datesChangeBasis: true },
38
40
  );
39
41
  const bySymbol = new Map(results.map((result) => [result.target.symbol, result]));
40
42
  for (const entry of entries) {
@@ -70,6 +70,14 @@ export interface PluginManifest {
70
70
  minGloomberb: string | null;
71
71
  /** gloom.json `icon`: the plugin's logo, a path inside the checkout such as `icon.webp`. */
72
72
  icon: string | null;
73
+ /**
74
+ * gloom.json `hosts`, which the plugin directory shows as the plugin's
75
+ * network access. Null without a gloom.json. The web proxies the `hosts`
76
+ * the plugin exports instead, so `plugin doctor` checks the two agree.
77
+ */
78
+ hosts: string[] | null;
79
+ /** gloom.json `linkHosts`: pages the plugin only opens as links, never fetches. */
80
+ linkHosts: string[];
73
81
  }
74
82
 
75
83
  function readJson(path: string): Record<string, unknown> | null {
@@ -83,6 +91,11 @@ function readJson(path: string): Record<string, unknown> | null {
83
91
  }
84
92
  }
85
93
 
94
+ function hostList(value: unknown): string[] {
95
+ if (!Array.isArray(value)) return [];
96
+ return value.filter((host): host is string => typeof host === "string" && host.trim() !== "").map((host) => host.trim().toLowerCase());
97
+ }
98
+
86
99
  function versionField(value: unknown): string | null {
87
100
  return typeof value === "string" && parseSemver(value) ? value.trim() : null;
88
101
  }
@@ -109,6 +122,8 @@ export function readPluginManifest(pluginDir: string): PluginManifest {
109
122
  ?? versionField(gloom?.minGloomberb)
110
123
  ?? peerRangeMinimum(peers?.gloomberb),
111
124
  icon: typeof gloom?.icon === "string" && gloom.icon.trim() ? gloom.icon.trim() : null,
125
+ hosts: gloom ? hostList(gloom.hosts) : null,
126
+ linkHosts: hostList(gloom?.linkHosts),
112
127
  };
113
128
  }
114
129
 
@@ -114,13 +114,18 @@ function linkTarget(hostRoot: string, pkg: string): string | null {
114
114
  * that by the folder's identity: one folder can still come back under two
115
115
  * spellings (a short 8.3 name, another case). A link that is right must be
116
116
  * left alone; rewriting it leaves a moment in which it is missing.
117
+ *
118
+ * So is the target itself: a Gloom run from a plugin's own `node_modules`
119
+ * (a plugin can install `gloomberb` as a devDependency for its tests) is
120
+ * the host there, and replacing that folder with a link would delete it.
117
121
  */
118
122
  function alreadyLinked(path: string, target: string): boolean {
119
123
  try {
120
- if (!isLink(path, lstatSync(path))) return false;
124
+ const stats = lstatSync(path);
121
125
  const linked = realpathSync(path);
122
126
  const wanted = realpathSync(target);
123
127
  if (process.platform === "win32" ? linked.toLowerCase() === wanted.toLowerCase() : linked === wanted) return true;
128
+ if (!isLink(path, stats)) return false;
124
129
  const a = statSync(path, { bigint: true });
125
130
  const b = statSync(target, { bigint: true });
126
131
  return a.ino !== 0n && a.ino === b.ino && a.dev === b.dev;
@@ -385,13 +385,18 @@ async function installDependencies(targetDir: string, quiet: boolean, timeoutMs?
385
385
  // their own CI can typecheck against the real API. At runtime the host is
386
386
  // symlinked in instead, and pulling a second full copy here would both
387
387
  // waste a lot of disk and risk a duplicate React.
388
- const output = quiet ? "pipe" : "inherit";
388
+ // Bun's own lines (its version, "[5.00ms] done") are kept off the
389
+ // terminal like git's, and shown only when they say why it failed.
389
390
  const bun = bunCommand();
390
391
  const result = bun
391
- ? await recordDependencyInstall(recordAs, () => run(bun.command, ["install", "--production"], targetDir, { stdout: output, stderr: output }, bun.env, timeoutMs)
392
+ ? await recordDependencyInstall(recordAs, () => run(bun.command, ["install", "--production"], targetDir, { stdout: "pipe", stderr: "pipe" }, bun.env, timeoutMs)
392
393
  .catch(logFailure("plugin-installer", "Plugin dependency installation failed", null)))
393
394
  : null;
394
- if (result?.code !== 0 && !quiet) console.error(cliStyles.warning("Warning: failed to install plugin dependencies."));
395
+ if (result?.code !== 0 && !quiet) {
396
+ console.error(cliStyles.warning("Warning: failed to install plugin dependencies."));
397
+ const output = result ? result.stderr.trim() || result.stdout.trim() : "";
398
+ if (output) console.error(output);
399
+ }
395
400
 
396
401
  // After `bun install`, which prunes links it does not know about.
397
402
  const link = linkHostPackages(targetDir);
@@ -1,5 +1,6 @@
1
1
  // Public API: gloomberb/components re-exports getColumnValue, getSortValue and
2
2
  // ColumnContext from here, so external plugins depend on their names and shapes.
3
+ import { exportedListingKey, listedSymbol } from "./listed-symbol";
3
4
  import { comparablePriceEarnings, formatPriceEarnings } from "../utils/price-earnings";
4
5
  import { convertMarketCapitalization, listedMarketCapitalization } from "../utils/market-capitalization";
5
6
  import type { ColumnConfig } from "../types/config";
@@ -85,6 +86,8 @@ import {
85
86
 
86
87
  export interface ColumnContext {
87
88
  activeTab?: string;
89
+ /** The market most of the list's listings trade in (listHomeMarket): a row outside it shows its venue (BA:LSE). */
90
+ homeMarket?: string;
88
91
  /** Money columns convert into this: a portfolio's totals currency, else the base currency. */
89
92
  baseCurrency: string;
90
93
  exchangeRates: Map<string, number>;
@@ -503,7 +506,7 @@ export function getColumnValue(
503
506
  ticker: TickerRecord,
504
507
  financials: TickerFinancials | undefined,
505
508
  ctx: ColumnContext,
506
- ): { text: string; color?: string; value?: number | null; pnlBasis?: PortfolioPositionPnl["basis"] } {
509
+ ): { text: string; color?: string; value?: number | string | null; valueUnit?: string; pnlBasis?: PortfolioPositionPnl["basis"] } {
507
510
  const sent = financials?.quote;
508
511
 
509
512
  const fundamentals = financials?.fundamentals;
@@ -542,7 +545,8 @@ export function getColumnValue(
542
545
  case "ticker": {
543
546
  // A print older than its venue's latest session pictures no session, not the market's current one.
544
547
  const statusDot = marketStateDot(quoteDotMarketState(quote));
545
- return { text: `${statusDot} ${tickerDisplayName(ticker)}` };
548
+ // An export names the listing with its venue, without the dot: BA:LSE, never a bare BA read as Boeing.
549
+ return { text: `${statusDot} ${listedSymbol(ticker, tickerDisplayName(ticker), ctx.homeMarket)}`, value: exportedListingKey(ticker) };
546
550
  }
547
551
  case "name":
548
552
  // The name the listing's quote gives now, as `quote` and `portfolio show` name it, else the saved one.
@@ -621,7 +625,8 @@ export function getColumnValue(
621
625
  case "market_cap": {
622
626
  const cap = liveMarketCapitalization(quote, fundamentals);
623
627
  const value = cap ? listedMarketCapitalization(convertMarketCapitalization(cap.value, cap.currency, ctx.baseCurrency, ctx.exchangeRates)) : null;
624
- return { text: value == null ? "—" : formatCompact(value, { fixedDecimals: true }) };
628
+ // An export writes the whole figure, not the three digits the cell shows (72.27B), in the base currency it names.
629
+ return { text: value == null ? "—" : formatCompact(value, { fixedDecimals: true }), value, valueUnit: ctx.baseCurrency };
625
630
  }
626
631
  case "pe":
627
632
  return { text: formatPriceEarnings(liveTrailingPE(quote, fundamentals)) };
@@ -766,7 +771,12 @@ export function getColumnValue(
766
771
  const time = getPortfolioValuationTime(quote, ctx.valuationBasis, positionMetrics, futures?.settlement);
767
772
  if (!time) return { text: "—" };
768
773
  // In UTC, as the header says; a close the venue's calendar gives no hour for is dated by its day.
769
- return { text: time.dateOnly ? formatShortDate(time.time, MONTH_DAY) : formatFeedTime(time.time, ctx.now, "—", { utc: true }) };
774
+ // An export writes the date with it, as ISO: 16:49 alone says nothing of which day.
775
+ const iso = new Date(time.time).toISOString();
776
+ return {
777
+ text: time.dateOnly ? formatShortDate(time.time, MONTH_DAY) : formatFeedTime(time.time, ctx.now, "—", { utc: true }),
778
+ value: time.dateOnly ? iso.slice(0, 10) : iso,
779
+ };
770
780
  }
771
781
  case PRICE_SPARKLINE_COLUMN_ID:
772
782
  return { text: "" };
@@ -0,0 +1,78 @@
1
+ import type { TickerRecord } from "../types/ticker";
2
+ import { canonicalExchange, canonicalTickerKey, isUsEquityExchange, parsePublicTickerKey } from "../utils/exchanges";
3
+ import { classifyInstrumentType, kindFromListingSyntax } from "../tickers/instrument-kind";
4
+ import { listingSuffixVenue } from "../sources/listing-symbols";
5
+
6
+ /**
7
+ * A saved symbol as the listing it is: its venue from its key (BA:LSE) or its
8
+ * row, and a vendor's suffix the venue settles taken off (BA.L on LSE is BA).
9
+ */
10
+ function venueListing(symbol: string, exchange: string | undefined): { symbol: string; exchange: string | undefined } {
11
+ const parsed = parsePublicTickerKey(symbol);
12
+ const venue = parsed.exchange ?? (exchange || undefined);
13
+ return listingSuffixVenue(parsed.symbol, venue) ?? { symbol: parsed.symbol, exchange: venue };
14
+ }
15
+
16
+ /**
17
+ * The market a row's listing trades in: every US venue is one market (US), as
18
+ * is a broker's SMART routing, which names no venue; any other its venue (LSE, HKEX).
19
+ */
20
+ function listingMarket(ticker: TickerRecord): string | null {
21
+ const { metadata } = ticker;
22
+ // An index, a pair, a future, a coin or a perpetual is no company's listing on a venue.
23
+ if (kindFromListingSyntax(metadata.ticker, metadata.exchange)) return null;
24
+ const kind = classifyInstrumentType(metadata.assetCategory);
25
+ if (kind && kind !== "equity" && kind !== "fund") return null;
26
+ const exchange = canonicalExchange(venueListing(metadata.ticker, metadata.exchange).exchange);
27
+ if (!exchange) return null;
28
+ return isUsEquityExchange(exchange) || exchange === "SMART" ? "US" : exchange;
29
+ }
30
+
31
+ /**
32
+ * The market most of a list's listings trade in, its home: a list of US names
33
+ * with BAE Systems among them is a US list. US on a tie, or when no row is a
34
+ * listing on a venue.
35
+ */
36
+ export function listHomeMarket(tickers: Iterable<TickerRecord>): string {
37
+ const counts = new Map<string, number>();
38
+ for (const ticker of tickers) {
39
+ const market = listingMarket(ticker);
40
+ if (market) counts.set(market, (counts.get(market) ?? 0) + 1);
41
+ }
42
+ let home = "US";
43
+ let most = counts.get("US") ?? 0;
44
+ for (const [market, count] of counts) {
45
+ if (count > most) {
46
+ home = market;
47
+ most = count;
48
+ }
49
+ }
50
+ return home;
51
+ }
52
+
53
+ /**
54
+ * A row's symbol as a list shows it: with its venue (BA:LSE, RHM:XETRA,
55
+ * 0005:HKEX) when it trades outside the list's home market, so BA on LSE never
56
+ * reads as Boeing in a US list; else as `display` writes it.
57
+ */
58
+ export function listedSymbol(ticker: TickerRecord, display: string, homeMarket: string | undefined): string {
59
+ const market = listingMarket(ticker);
60
+ if (!market || !homeMarket || market === homeMarket || display.includes(":")) return display;
61
+ const listing = venueListing(ticker.metadata.ticker, ticker.metadata.exchange);
62
+ return canonicalTickerKey(listing.symbol, listing.exchange);
63
+ }
64
+
65
+ /**
66
+ * A listing as an export names it, always with its venue (BA:LSE, AAPL:NASDAQ), so a script never reads BA as
67
+ * Boeing; an index, a pair, a future or a coin is its symbol (^HSI, CL=F), which no venue qualifies.
68
+ */
69
+ export function exportedListingSymbol(symbol: string, exchange: string | undefined, instrumentType?: string | null): string {
70
+ if (kindFromListingSyntax(symbol, exchange) || classifyInstrumentType(instrumentType) === "index") return parsePublicTickerKey(symbol).symbol;
71
+ const listing = venueListing(symbol, exchange);
72
+ return canonicalTickerKey(listing.symbol, listing.exchange);
73
+ }
74
+
75
+ /** A row's listing as an export names it (`exportedListingSymbol`). */
76
+ export function exportedListingKey(ticker: TickerRecord): string {
77
+ return exportedListingSymbol(ticker.metadata.ticker, ticker.metadata.exchange, ticker.metadata.assetCategory);
78
+ }
@@ -0,0 +1,172 @@
1
+ import type { CloudFredObservationPayload, CloudFredSeriesPayload } from "../api-client/types/econ";
2
+ import type { PriceWindow } from "../utils/price-window";
3
+
4
+ /**
5
+ * A book's return after its currency's consumer prices (`portfolio show
6
+ * --from <date> --real`): the nominal return deflated by the change in the
7
+ * CPI over the period, (1 + nominal) / (1 + inflation) - 1.
8
+ */
9
+
10
+ /** Where a currency's consumer prices are read: an index level, or the published changes chained into one. */
11
+ export interface CpiSource {
12
+ currency: string;
13
+ /** The series Gloom Cloud serves at `/cloud/econ/series/:id`: the level, or the change from the month before. */
14
+ series: string;
15
+ /** The change from a year before, read for whole years so a twelve-month period is the published figure. */
16
+ yearSeries?: string;
17
+ kind: "level" | "changes";
18
+ /** "US CPI": what the report names. */
19
+ label: string;
20
+ publisher: string;
21
+ }
22
+
23
+ export const CPI_SOURCES: Readonly<Record<string, CpiSource>> = {
24
+ // Not seasonally adjusted, as the BLS publishes it and as a period's change is quoted: an adjusted index
25
+ // is revised every year, so the same period would read differently later.
26
+ USD: { currency: "USD", series: "CPIAUCNS", kind: "level", label: "US CPI", publisher: "BLS" },
27
+ // The central bank's table gives TurkStat's changes on the index, not its level: whole years are the
28
+ // year-on-year change TurkStat computes from the level, the months left over its monthly changes.
29
+ TRY: { currency: "TRY", series: "TURCPIMOM", yearSeries: "TURCPIYOY", kind: "changes", label: "Türkiye CPI", publisher: "TurkStat" },
30
+ };
31
+
32
+ /** One published CPI value the figure was read from, as the source gives it. */
33
+ interface CpiReading {
34
+ series: string;
35
+ /** YYYY-MM. */
36
+ month: string;
37
+ value: number;
38
+ }
39
+
40
+ export interface PeriodInflation {
41
+ source: CpiSource;
42
+ /** YYYY-MM: the month whose CPI starts the period, the last one out at its start. */
43
+ fromMonth: string;
44
+ /** YYYY-MM: the month whose CPI ends it, the last one out at its end or the latest published. */
45
+ toMonth: string;
46
+ /** The CPI's change between them, as a fraction: 0.2977 for 29.77%. */
47
+ inflation: number;
48
+ /** The end's own month is not published yet, so the latest is used. */
49
+ latestPublished: boolean;
50
+ /** The published values it was computed from: the two levels, or the changes chained. */
51
+ readings: CpiReading[];
52
+ }
53
+
54
+ /** YYYY-MM of the month before the one `day` (YYYY-MM-DD) falls in. */
55
+ function monthBefore(day: string): string {
56
+ const [year, month] = day.slice(0, 7).split("-").map(Number) as [number, number];
57
+ return month === 1 ? `${year - 1}-12` : `${year}-${String(month - 1).padStart(2, "0")}`;
58
+ }
59
+
60
+ const monthIndex = (month: string) => Number(month.slice(0, 4)) * 12 + Number(month.slice(5, 7)) - 1;
61
+ const indexMonth = (index: number) => `${Math.floor(index / 12)}-${String((index % 12) + 1).padStart(2, "0")}`;
62
+
63
+ function publishedMonths(observations: readonly CloudFredObservationPayload[]) {
64
+ return observations
65
+ .filter((row) => row.value != null && Number.isFinite(row.value))
66
+ .map((row) => ({ month: row.date.slice(0, 7), value: row.value! }))
67
+ .sort((left, right) => left.month.localeCompare(right.month));
68
+ }
69
+
70
+ /**
71
+ * The CPI's change over a period, from the month before its start's month (the
72
+ * last CPI out when it starts) to the month before its end's, or the latest
73
+ * month published when that is not out yet. A month with no level (the US
74
+ * skipped October 2025) reads the month before it. Published changes chain
75
+ * from the end back: a year-on-year change for each whole year, then the
76
+ * monthly changes of the months left; a missing change leaves it unpriced.
77
+ * Null when the series does not reach either month.
78
+ */
79
+ export function periodInflation(
80
+ source: CpiSource,
81
+ observations: readonly CloudFredObservationPayload[],
82
+ window: PriceWindow,
83
+ yearOnYear: readonly CloudFredObservationPayload[] = [],
84
+ ): PeriodInflation | null {
85
+ const months = publishedMonths(observations);
86
+ if (!months.length) return null;
87
+ const wantedFrom = monthBefore(window.from);
88
+ const wantedTo = monthBefore(window.to);
89
+ const latest = months.at(-1)!.month;
90
+ const toMonth = wantedTo <= latest ? wantedTo : latest;
91
+ const latestPublished = wantedTo > latest;
92
+ // A series that starts after the period's first month says nothing of the months before it.
93
+ if (wantedFrom < months[0]!.month || toMonth < wantedFrom) return null;
94
+ if (source.kind === "level") {
95
+ const at = (month: string) => months.findLast((row) => row.month <= month);
96
+ const start = at(wantedFrom), end = at(toMonth);
97
+ if (!start || !end || end.month < start.month) return null;
98
+ return {
99
+ source, fromMonth: start.month, toMonth: end.month, inflation: end.value / start.value - 1, latestPublished,
100
+ readings: [start, end].map((row) => ({ series: source.series, ...row })),
101
+ };
102
+ }
103
+ const monthly = new Map(months.map((row) => [row.month, row.value]));
104
+ const yearly = new Map(publishedMonths(yearOnYear).map((row) => [row.month, row.value]));
105
+ const readings: CpiReading[] = [];
106
+ let index = 1;
107
+ let at = monthIndex(toMonth);
108
+ const first = monthIndex(wantedFrom);
109
+ while (at - first >= 12 && source.yearSeries && yearly.has(indexMonth(at))) {
110
+ const value = yearly.get(indexMonth(at))!;
111
+ readings.unshift({ series: source.yearSeries, month: indexMonth(at), value });
112
+ index *= 1 + value / 100;
113
+ at -= 12;
114
+ }
115
+ for (; at > first; at--) {
116
+ const value = monthly.get(indexMonth(at));
117
+ if (value == null) return null;
118
+ readings.unshift({ series: source.series, month: indexMonth(at), value });
119
+ index *= 1 + value / 100;
120
+ }
121
+ return { source, fromMonth: wantedFrom, toMonth, inflation: index - 1, latestPublished, readings };
122
+ }
123
+
124
+ /** How the figure was read, for the report: `the BLS index`, `TurkStat's year-on-year change`. */
125
+ export function inflationMethodText(read: Pick<PeriodInflation, "source" | "readings" | "fromMonth" | "toMonth">): string {
126
+ const { source, readings } = read;
127
+ if (read.fromMonth === read.toMonth) return `no ${source.publisher} month published inside the period`;
128
+ if (source.kind === "level") return `the ${source.publisher} index`;
129
+ const years = readings.filter((row) => row.series === source.yearSeries).length;
130
+ const months = readings.length - years;
131
+ const parts = [
132
+ ...(years ? [years === 1 ? "year-on-year change" : `${years} year-on-year changes`] : []),
133
+ ...(months ? [months === 1 ? "monthly change" : `${months} monthly changes`] : []),
134
+ ];
135
+ return `${source.publisher}'s ${parts.join(" and ")}${readings.length > 1 ? " chained" : ""}`;
136
+ }
137
+
138
+ /** The real return, as a fraction, of a nominal one after `inflation`. */
139
+ export function realReturn(nominal: number, inflation: number): number {
140
+ return (1 + nominal) / (1 + inflation) - 1;
141
+ }
142
+
143
+ /** `Oct 2025`. */
144
+ export function monthText(month: string): string {
145
+ const [year, number] = month.split("-");
146
+ return `${["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"][Number(number) - 1]} ${year}`;
147
+ }
148
+
149
+ /** Reads a currency's CPI over a window, with a year before it for the starting month. */
150
+ export async function loadPeriodInflation(
151
+ currency: string,
152
+ window: PriceWindow,
153
+ client: { getCloudFredSeries(id: string, params: { startDate: string; endDate: string; limit: number; sortOrder: "asc" }): Promise<CloudFredSeriesPayload> },
154
+ ): Promise<PeriodInflation | { error: string }> {
155
+ const source = CPI_SOURCES[currency];
156
+ if (!source) {
157
+ const known = Object.keys(CPI_SOURCES).join(" and ");
158
+ return { error: `--real deflates by the consumer prices of a ${known} portfolio; there is no ${currency} CPI series here.` };
159
+ }
160
+ const startYear = Number(window.from.slice(0, 4)) - 1;
161
+ const params = { startDate: `${startYear}${window.from.slice(4, 7)}-01`, endDate: window.to, limit: 1000, sortOrder: "asc" as const };
162
+ try {
163
+ const [payload, yearly] = await Promise.all([
164
+ client.getCloudFredSeries(source.series, params),
165
+ source.yearSeries ? client.getCloudFredSeries(source.yearSeries, params) : null,
166
+ ]);
167
+ return periodInflation(source, payload.observations, window, yearly?.observations)
168
+ ?? { error: `${source.label} does not cover ${window.from} to ${window.to}.` };
169
+ } catch (error) {
170
+ return { error: `${source.label} could not be read: ${error instanceof Error ? error.message : String(error)}` };
171
+ }
172
+ }
@@ -372,6 +372,7 @@ exports[`the runtime exports of every public subpath are the reviewed ones 1`] =
372
372
  "paneBg",
373
373
  "paneTitleBg",
374
374
  "paneTitleText",
375
+ "placeholderText",
375
376
  "previewTheme",
376
377
  "priceColor",
377
378
  "shownPriceColor",