gloomberb 0.20.13 → 0.20.16

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 (275) hide show
  1. package/package.json +2 -1
  2. package/patches/@opentui%2Fcore@0.3.2.patch +22 -4
  3. package/src/account/auth-dialog.tsx +22 -4
  4. package/src/account/auth-form.tsx +6 -1
  5. package/src/account/checkout-handoff.tsx +7 -14
  6. package/src/account/device-signin-dialog.tsx +35 -24
  7. package/src/api-client/crypto-markets.ts +10 -0
  8. package/src/api-client/errors.ts +3 -1
  9. package/src/api-client/index.ts +54 -0
  10. package/src/api-client/install-experiments.ts +8 -7
  11. package/src/api-client/money-markets.ts +7 -0
  12. package/src/api-client/paths.ts +2 -1
  13. package/src/api-client/product-waitlist.ts +63 -0
  14. package/src/api-client/request.ts +16 -4
  15. package/src/api-client/types/billing.ts +45 -0
  16. package/src/api-client/yearly-plan.ts +132 -0
  17. package/src/app/global-shortcuts.ts +5 -3
  18. package/src/app/pane-runtime/index.tsx +2 -2
  19. package/src/app/pane-runtime/plugin-bindings.ts +3 -1
  20. package/src/app/pane-runtime/ticker-open-runtime.ts +6 -1
  21. package/src/app/since-last-visit/keys.ts +26 -0
  22. package/src/app/since-last-visit/model.ts +266 -0
  23. package/src/app/since-last-visit/strip.tsx +193 -0
  24. package/src/app/since-last-visit/use-since-last-visit.ts +289 -0
  25. package/src/app/since-last-visit/visit-tracker.ts +191 -0
  26. package/src/app.tsx +15 -0
  27. package/src/architecture/floating-promise-allowlist.json +0 -1
  28. package/src/brokers/signed-in/sign-in-dialog.tsx +38 -38
  29. package/src/cli/commands/market.ts +103 -27
  30. package/src/cli/commands/overview.ts +18 -4
  31. package/src/cli/commands/system.ts +29 -1
  32. package/src/cli/commands/ticker.ts +12 -5
  33. package/src/cli/desktop-pane-shot-api-policy.ts +4 -1
  34. package/src/cli/desktop-pane-shot-browser.ts +2 -1
  35. package/src/cli/desktop-pane-shot-view.ts +3 -7
  36. package/src/cli/desktop-pane-shot.ts +26 -28
  37. package/src/cli/errors.ts +3 -1
  38. package/src/cli/freshness.ts +7 -2
  39. package/src/cli/glossary.ts +10 -5
  40. package/src/cli/help.ts +1 -0
  41. package/src/cli/helpers.ts +8 -16
  42. package/src/cli/history-export.ts +4 -0
  43. package/src/cli/history-rows.ts +24 -0
  44. package/src/cli/index.ts +4 -0
  45. package/src/cli/known-gaps.ts +2 -2
  46. package/src/cli/listing-arg.ts +79 -11
  47. package/src/cli/not-a-ticker.ts +4 -0
  48. package/src/cli/options.ts +29 -1
  49. package/src/cli/pane-functions/catalog.ts +70 -12
  50. package/src/cli/pane-functions/function-help.ts +1 -1
  51. package/src/cli/pane-functions/headless.ts +68 -3
  52. package/src/cli/pane-functions/index.ts +2 -2
  53. package/src/cli/pane-functions/options.ts +7 -0
  54. package/src/cli/pane-functions/resolver.ts +104 -15
  55. package/src/cli/pane-functions/screenshot-payload.ts +3 -0
  56. package/src/cli/report-tables.ts +20 -5
  57. package/src/cli/result.ts +22 -4
  58. package/src/cli/shot-temp-dir.ts +30 -0
  59. package/src/cli/suffixed-listing-rows.ts +11 -0
  60. package/src/cli/symbol-args.ts +5 -3
  61. package/src/cli/symbol-list.ts +23 -10
  62. package/src/cli/symbol-rows.ts +135 -3
  63. package/src/cli/treasury-yields.ts +15 -1
  64. package/src/components/chart/composite/composite-chart.tsx +3 -3
  65. package/src/components/chart/composite/format.ts +2 -1
  66. package/src/components/chart/composite/panel-surface/axis-markers.ts +133 -0
  67. package/src/components/chart/composite/panel-surface/level-labels.tsx +78 -0
  68. package/src/components/chart/composite/panel-surface/overlays.ts +108 -0
  69. package/src/components/chart/composite/panel-surface/pan-coast.ts +54 -0
  70. package/src/components/chart/composite/panel-surface/panel-cursor.tsx +138 -0
  71. package/src/components/chart/composite/panel-surface/panel-levels.ts +47 -0
  72. package/src/components/chart/composite/panel-surface/plot-gestures.ts +403 -0
  73. package/src/components/chart/composite/panel-surface/plot-pointer.ts +65 -0
  74. package/src/components/chart/composite/panel-surface/plot-wheel.ts +102 -0
  75. package/src/components/chart/composite/panel-surface/pointer.ts +12 -0
  76. package/src/components/chart/composite/panel-surface/props.ts +79 -0
  77. package/src/components/chart/composite/panel-surface/tool-readout.ts +151 -0
  78. package/src/components/chart/composite/panel-surface/value-axis-gestures.ts +152 -0
  79. package/src/components/chart/composite/panel-surface.tsx +81 -1177
  80. package/src/components/command-bar/commands/collection-list.ts +1 -0
  81. package/src/components/command-bar/commands/direct/index.ts +31 -8
  82. package/src/components/command-bar/commands/registry.ts +7 -0
  83. package/src/components/command-bar/routes/root/command-items.ts +8 -0
  84. package/src/components/command-bar/routes/root/results.ts +19 -2
  85. package/src/components/command-bar/routes/root/runtime.ts +3 -2
  86. package/src/components/command-bar/routes/root/selection.ts +3 -2
  87. package/src/components/command-bar/routes/root/shortcuts.ts +15 -0
  88. package/src/components/company-logo.tsx +10 -3
  89. package/src/components/data-table/sections.ts +6 -1
  90. package/src/components/layout/pane/title.ts +16 -6
  91. package/src/components/layout/shell/index.tsx +5 -1
  92. package/src/components/layout/shell/ticker-link-menu.ts +12 -9
  93. package/src/components/pane-settings-dialog/tui.tsx +6 -3
  94. package/src/components/pane-settings-dialog.tsx +2 -1
  95. package/src/components/pane-template-wizard.tsx +2 -0
  96. package/src/components/ticker/badge/format.ts +12 -3
  97. package/src/components/ticker/badge/index.tsx +9 -3
  98. package/src/components/ticker/list-table-view.tsx +119 -17
  99. package/src/components/ui/choice-dialog.tsx +1 -1
  100. package/src/components/ui/confirm-dialog.tsx +3 -2
  101. package/src/components/ui/data-table/display-columns.ts +16 -0
  102. package/src/components/ui/data-table/index.tsx +40 -9
  103. package/src/components/ui/data-table/types.ts +14 -0
  104. package/src/components/ui/frame.tsx +7 -3
  105. package/src/components/ui/icon.tsx +4 -2
  106. package/src/components/ui/list-view.tsx +8 -0
  107. package/src/components/ui/number-prompt-dialog.tsx +2 -1
  108. package/src/components/use-pane-notice-footer.tsx +3 -1
  109. package/src/core/state/app/layout-reducer.ts +3 -1
  110. package/src/core/state/app/layout.ts +2 -2
  111. package/src/data/config/layout.ts +14 -0
  112. package/src/data/config/store/normalize.ts +11 -1
  113. package/src/docs/snapshot.json +2 -2
  114. package/src/i18n/es.ts +39 -0
  115. package/src/i18n/ja.ts +39 -0
  116. package/src/i18n/ko.ts +39 -0
  117. package/src/i18n/zh-cn.ts +39 -0
  118. package/src/i18n/zh-tw.ts +39 -0
  119. package/src/layout/pane-follow.ts +141 -4
  120. package/src/layout/pane-layout-move.ts +10 -7
  121. package/src/layout/ticker-navigation.ts +13 -19
  122. package/src/layout/ticker-retarget.ts +3 -2
  123. package/src/market-data/market/format.ts +35 -1
  124. package/src/market-data/market/index-level.ts +19 -0
  125. package/src/market-data/quotes/contributions.ts +13 -0
  126. package/src/market-data/quotes/export-identity.ts +36 -1
  127. package/src/market-data/quotes/resolution.ts +16 -0
  128. package/src/plugins/builtin/account-management/keyboard.ts +14 -0
  129. package/src/plugins/builtin/account-management/model.ts +2 -0
  130. package/src/plugins/builtin/account-management/pane.tsx +79 -7
  131. package/src/plugins/builtin/account-management/password-dialog.tsx +2 -2
  132. package/src/plugins/builtin/account-management/payment-recovery-row.tsx +97 -0
  133. package/src/plugins/builtin/account-management/yearly-plan-row.tsx +359 -0
  134. package/src/plugins/builtin/analytics/risk-client.ts +12 -2
  135. package/src/plugins/builtin/analytics/risk-headless.ts +66 -6
  136. package/src/plugins/builtin/analytics/risk-math.ts +23 -6
  137. package/src/plugins/builtin/analytics/risk-model.ts +20 -9
  138. package/src/plugins/builtin/analytics/risk-pane.tsx +2 -2
  139. package/src/plugins/builtin/awards/pane.tsx +6 -8
  140. package/src/plugins/builtin/changelog/index.tsx +6 -44
  141. package/src/plugins/builtin/changelog/versions.ts +17 -68
  142. package/src/plugins/builtin/chart-composer/catalog-inventory.ts +5 -2
  143. package/src/plugins/builtin/chart-composer/editor.tsx +1 -0
  144. package/src/plugins/builtin/chart-composer/pane.tsx +1 -1
  145. package/src/plugins/builtin/chart-composer/quick-add.tsx +4 -1
  146. package/src/plugins/builtin/chart-composer/series-catalog.ts +17 -1
  147. package/src/plugins/builtin/cloud/askg/executor.ts +2 -1
  148. package/src/plugins/builtin/cloud/askg/sources.ts +2 -1
  149. package/src/plugins/builtin/cloud/plugin.tsx +2 -0
  150. package/src/plugins/builtin/cloud/thesis/module.tsx +2 -0
  151. package/src/plugins/builtin/cloud/upgrade-status-widget.tsx +6 -2
  152. package/src/plugins/builtin/cpi/headless.ts +6 -1
  153. package/src/plugins/builtin/cpi/model.ts +17 -0
  154. package/src/plugins/builtin/cpi/pane.tsx +4 -2
  155. package/src/plugins/builtin/crypto-board/client.ts +6 -1
  156. package/src/plugins/builtin/crypto-board/headless.ts +10 -2
  157. package/src/plugins/builtin/crypto-board/model.ts +89 -11
  158. package/src/plugins/builtin/crypto-board/pane.tsx +20 -5
  159. package/src/plugins/builtin/debt-maturities/model.ts +1 -1
  160. package/src/plugins/builtin/dividend-yield/client.ts +24 -2
  161. package/src/plugins/builtin/dividend-yield/headless.ts +4 -2
  162. package/src/plugins/builtin/dividend-yield/ranking.ts +2 -1
  163. package/src/plugins/builtin/dividend-yield/view.ts +5 -1
  164. package/src/plugins/builtin/earnings/board-table.ts +1 -1
  165. package/src/plugins/builtin/earnings/board.tsx +36 -16
  166. package/src/plugins/builtin/earnings/highlight.ts +47 -0
  167. package/src/plugins/builtin/earnings/history-table.ts +9 -1
  168. package/src/plugins/builtin/earnings/index.tsx +1 -1
  169. package/src/plugins/builtin/earnings-calls/pane.tsx +2 -2
  170. package/src/plugins/builtin/earnings-ripple/index.tsx +2 -0
  171. package/src/plugins/builtin/econ/calendar-model.ts +17 -1
  172. package/src/plugins/builtin/econ/fred-catalog.ts +33 -4
  173. package/src/plugins/builtin/econ-statistics/headless.ts +21 -0
  174. package/src/plugins/builtin/estimate-revisions/model.ts +1 -1
  175. package/src/plugins/builtin/exposure/index.tsx +1 -1
  176. package/src/plugins/builtin/macro-day/headless.ts +21 -10
  177. package/src/plugins/builtin/macro-day/model.ts +42 -3
  178. package/src/plugins/builtin/macro-day/pane.tsx +26 -8
  179. package/src/plugins/builtin/macro-day/releases.ts +24 -1
  180. package/src/plugins/builtin/market-valuation/detail.tsx +3 -3
  181. package/src/plugins/builtin/market-valuation/headless.ts +11 -4
  182. package/src/plugins/builtin/market-valuation/pane.tsx +3 -1
  183. package/src/plugins/builtin/market-valuation/view.ts +14 -0
  184. package/src/plugins/builtin/money-markets/client.ts +4 -1
  185. package/src/plugins/builtin/money-markets/headless.ts +15 -4
  186. package/src/plugins/builtin/money-markets/index.tsx +1 -1
  187. package/src/plugins/builtin/money-markets/pane.tsx +7 -1
  188. package/src/plugins/builtin/news/wire/news/detail-view.tsx +20 -8
  189. package/src/plugins/builtin/pe-band/pane.tsx +1 -1
  190. package/src/plugins/builtin/portfolio-list/cli/bulk-symbols.ts +4 -2
  191. package/src/plugins/builtin/portfolio-list/cli/period-report.ts +61 -11
  192. package/src/plugins/builtin/portfolio-list/cli/portfolio-command.ts +11 -3
  193. package/src/plugins/builtin/portfolio-list/cli/render.ts +8 -1
  194. package/src/plugins/builtin/portfolio-list/cli/watchlist-command.ts +178 -17
  195. package/src/plugins/builtin/portfolio-list/headless.ts +33 -6
  196. package/src/plugins/builtin/portfolio-list/pane/groups.tsx +220 -0
  197. package/src/plugins/builtin/portfolio-list/pane/index.tsx +95 -18
  198. package/src/plugins/builtin/portfolio-list/pane/period-pnl.ts +24 -6
  199. package/src/plugins/builtin/portfolio-list/period-pnl.ts +16 -1
  200. package/src/plugins/builtin/portfolio-list/summary/index.tsx +4 -1
  201. package/src/plugins/builtin/portfolio-list/summary/totals.ts +6 -4
  202. package/src/plugins/builtin/portfolio-list/table.tsx +38 -16
  203. package/src/plugins/builtin/research/corporate-actions-pane.tsx +4 -2
  204. package/src/plugins/builtin/research/relative-valuation-headless.ts +15 -5
  205. package/src/plugins/builtin/research/relative-valuation-model.ts +7 -1
  206. package/src/plugins/builtin/research/relative-valuation-pane.tsx +7 -4
  207. package/src/plugins/builtin/shared/cloud-upgrade.ts +4 -2
  208. package/src/plugins/builtin/shared/cpi-year-gap.ts +67 -0
  209. package/src/plugins/builtin/shared/headless-options.ts +1 -1
  210. package/src/plugins/builtin/social-mentions/model.ts +2 -2
  211. package/src/plugins/builtin/thirteenf/pane.tsx +1 -1
  212. package/src/plugins/builtin/ticker-detail/adr-pair/headless.ts +45 -2
  213. package/src/plugins/builtin/ticker-detail/financials/model.ts +51 -16
  214. package/src/plugins/builtin/ticker-detail/financials/nopat.ts +16 -0
  215. package/src/plugins/builtin/ticker-detail/financials/ratios.ts +44 -13
  216. package/src/plugins/builtin/ticker-detail/financials/schema.ts +33 -2
  217. package/src/plugins/builtin/ticker-detail/financials/tab.tsx +4 -2
  218. package/src/plugins/builtin/ticker-detail/headless-schema.ts +30 -4
  219. package/src/plugins/builtin/ticker-detail/headless.ts +280 -35
  220. package/src/plugins/builtin/ticker-detail/overview/components.tsx +4 -5
  221. package/src/plugins/builtin/ticker-detail/overview/model.ts +9 -2
  222. package/src/plugins/builtin/ticker-detail/overview-tab.tsx +10 -2
  223. package/src/plugins/builtin/ticker-detail/pharma-signals/eligibility.ts +32 -0
  224. package/src/plugins/builtin/ticker-detail/pharma-signals/tab.tsx +162 -0
  225. package/src/plugins/builtin/ticker-detail/pharma-signals/waitlist.ts +126 -0
  226. package/src/plugins/builtin/ticker-detail/research-groups.ts +6 -4
  227. package/src/plugins/builtin/ticker-detail/research-tabs.ts +11 -0
  228. package/src/portfolio/collection-name.ts +2 -1
  229. package/src/portfolio/column-values.ts +34 -12
  230. package/src/portfolio/listed-symbol.ts +4 -2
  231. package/src/portfolio/period-pnl.ts +51 -1
  232. package/src/portfolio/suffixed-listings.ts +3 -1
  233. package/src/portfolio/watchlist-groups.ts +212 -0
  234. package/src/react/ticker-source.ts +3 -1
  235. package/src/renderers/dom/dialog-host.tsx +5 -5
  236. package/src/renderers/dom/styles.css +7 -0
  237. package/src/renderers/electrobun/view/remote/capability-invoker.ts +1 -1
  238. package/src/renderers/opentui/dialog-host.tsx +3 -4
  239. package/src/sources/gloomberb-cloud/normalizers.ts +5 -0
  240. package/src/sources/provider-router/history.ts +5 -2
  241. package/src/state/app/bootstrap.ts +11 -0
  242. package/src/state/app/context/index.tsx +6 -0
  243. package/src/sync/collections-contributor.ts +5 -2
  244. package/src/sync/config-merge.ts +10 -2
  245. package/src/sync/sanitize.ts +28 -0
  246. package/src/telemetry/usage-counts.ts +17 -0
  247. package/src/test-support/plugin-persistence.ts +12 -0
  248. package/src/tickers/company-name-listing.ts +4 -3
  249. package/src/tickers/company-name.ts +19 -1
  250. package/src/tickers/instrument-coverage.ts +27 -0
  251. package/src/tickers/search/home-listing.ts +38 -1
  252. package/src/tickers/search/index.ts +3 -2
  253. package/src/tickers/search/ranking.ts +21 -2
  254. package/src/time-series/base-series.ts +4 -0
  255. package/src/time-series/chart-seed.ts +1 -1
  256. package/src/time-series/financial-period-coverage.ts +4 -12
  257. package/src/time-series/parsed-history-cache.ts +1 -1
  258. package/src/time-series/resolve.ts +1 -1
  259. package/src/time-series/types.ts +5 -2
  260. package/src/time-series/use-chart-resolution.ts +6 -1
  261. package/src/types/config.ts +32 -0
  262. package/src/types/financials.ts +13 -0
  263. package/src/types/headless.ts +7 -0
  264. package/src/types/plugin-context.ts +5 -0
  265. package/src/types/ticker.ts +14 -0
  266. package/src/ui/ascii-font.ts +1 -4
  267. package/src/ui/dialog-stack.ts +17 -0
  268. package/src/ui/dialog.tsx +6 -2
  269. package/src/utils/async-deadline.ts +2 -2
  270. package/src/utils/crypto-pair.ts +9 -0
  271. package/src/utils/csv.ts +44 -5
  272. package/src/utils/exchanges.ts +13 -0
  273. package/src/utils/financial-statements.ts +60 -3
  274. package/src/utils/futures-generic.ts +17 -0
  275. package/src/utils/trailing-dividend.ts +13 -3
@@ -152,3 +152,17 @@ export function selectValuationViews(
152
152
  ): IndicatorViewModel[] {
153
153
  return bundle.builds.map((build) => projectView(build, range));
154
154
  }
155
+
156
+ /** Months a period of each periodicity runs. */
157
+ const PERIOD_MONTHS = { monthly: 1, quarterly: 3, annual: 12 } as const;
158
+
159
+ /**
160
+ * A reading's as-of as FA dates a period, by the day it ends: a quarterly series dated 2026-04-01 (the start of Q2,
161
+ * as FRED dates it) is as of 2026-06-30. A reading dated by its own day stays as it is.
162
+ */
163
+ export function readingPeriodEnd(date: string, periodicity: keyof typeof PERIOD_MONTHS | null | undefined): string {
164
+ if (!periodicity || !/^\d{4}-\d{2}-\d{2}/.test(date)) return date;
165
+ const start = new Date(`${date.slice(0, 10)}T00:00:00Z`);
166
+ if (!Number.isFinite(start.getTime())) return date;
167
+ return new Date(Date.UTC(start.getUTCFullYear(), start.getUTCMonth() + PERIOD_MONTHS[periodicity], 0)).toISOString().slice(0, 10);
168
+ }
@@ -29,7 +29,10 @@ function validateRows(rows: readonly MoneyMarketRow[], groups: readonly MoneyMar
29
29
  || !finiteOrNull(row.value) || !finiteOrNull(row.change) || !finiteOrNull(row.previousValue)
30
30
  || !dateOrNull(row.asOf) || !dateOrNull(row.previousAsOf) || row.value != null && row.asOf == null
31
31
  || !Array.isArray(row.history) || row.history.some((point) => point.date == null || !dateOrNull(point.date) || !finiteOrNull(point.value))
32
- || !Array.isArray(row.sourceSeriesIds) || row.sourceSeriesIds.some((id) => typeof id !== "string") || !Array.isArray(row.notes)) return invalid();
32
+ || !Array.isArray(row.sourceSeriesIds) || row.sourceSeriesIds.some((id) => typeof id !== "string") || !Array.isArray(row.notes)
33
+ || row.couponEquivalent !== undefined && !finiteOrNull(row.couponEquivalent)
34
+ || row.couponEquivalentAsOf !== undefined && !dateOrNull(row.couponEquivalentAsOf)
35
+ || row.sourceName !== undefined && typeof row.sourceName !== "string") return invalid();
33
36
  }
34
37
  for (const stats of rows.map((row) => row.percentile)) validatePercentile(stats);
35
38
  }
@@ -1,5 +1,6 @@
1
1
  import { MISSING_VALUE } from "../../../utils/format";
2
2
  import type { HeadlessPaneDefinition } from "../../../types/plugin";
3
+ import type { HeadlessPaneFreshness } from "../../../types/headless";
3
4
  import type { MoneyMarketRow } from "../../../api-client/money-markets";
4
5
  import { fetchHongKongMoneyMarkets, fetchMoneyMarkets } from "./client";
5
6
  import { isHongKongTab, MONEY_MARKET_TABS, moneyMarketChange, moneyMarketNotices, moneyMarketRowNotices, moneyMarketRows, moneyMarketValue } from "./model";
@@ -7,17 +8,25 @@ import { isHongKongTab, MONEY_MARKET_TABS, moneyMarketChange, moneyMarketNotices
7
8
  const FRED_FRESHNESS = { source: "FRED", status: "not-a-feed", basis: "published daily and weekly data" } as const;
8
9
  const HONG_KONG_FRESHNESS = { ...FRED_FRESHNESS, source: "HKMA", basis: "published Exchange Fund Bill closing yields" } as const;
9
10
 
11
+ /** Bills read from Treasury's own daily file, which posts the day that afternoon, where FRED lags a session or two. */
12
+ const TREASURY_BILL_FRESHNESS = { ...FRED_FRESHNESS, source: "U.S. Treasury", basis: "published daily bill rates" } as const;
13
+
10
14
  /** The rows a view reports, without their histories, and what the view declares about them beyond the definition. */
11
15
  export function moneyMarketReport(rows: readonly MoneyMarketRow[], hongKong: boolean) {
16
+ const treasury = rows.length > 0 && rows.every((row) => row.sourceName === "U.S. Treasury");
17
+ const freshness: HeadlessPaneFreshness | undefined = hongKong ? HONG_KONG_FRESHNESS : treasury ? TREASURY_BILL_FRESHNESS : undefined;
12
18
  return {
13
- ...hongKong ? { freshness: HONG_KONG_FRESHNESS } : {},
19
+ ...freshness ? { freshness } : {},
14
20
  rows: rows.map(({ history: _history, ...row }) => ({ ...row, percentileValue: row.percentile.value })),
15
- };
21
+ } as { freshness?: HeadlessPaneFreshness; rows: Array<Omit<MoneyMarketRow, "history"> & { percentileValue: number | null }> };
16
22
  }
17
23
 
24
+ /** A bill's coupon equivalent, the rate a money fund's yield compares with, beside its discount rate; never on other rows. */
25
+ const hasCouponEquivalent = (rows: readonly MoneyMarketRow[]) => rows.some((row) => row.couponEquivalent !== undefined);
26
+
18
27
  export const moneyMarketsHeadless: HeadlessPaneDefinition<"bundle"> = {
19
28
  discovery: { aliases: ["BTMM"], dataRequirements: ["Gloom Cloud money-markets endpoint"],
20
- limitations: ["Published daily and weekly observations.", "Treasury bill discount yields.", "Net liquidity is a same-date proxy.",
29
+ limitations: ["Published daily and weekly observations.", "Treasury bills: Treasury's daily closing bid as a discount rate with its coupon equivalent, not the yield curve's constant-maturity yield.", "Net liquidity is a same-date proxy.",
21
30
  "Hong Kong: HKMA's Exchange Fund Bill closing yields, a week or two after the day; each row is dated by its own day. HIBOR is not licensed for redistribution."] },
22
31
  shape: "bundle", argument: { kind: "none" },
23
32
  freshness: FRED_FRESHNESS,
@@ -34,7 +43,9 @@ export const moneyMarketsHeadless: HeadlessPaneDefinition<"bundle"> = {
34
43
  return { complete, ...report.freshness ? { freshness: report.freshness } : {},
35
44
  sections: [{ title: hongKong ? "Exchange Fund Bill yields" : "Observations", columns: [
36
45
  { key: "label", header: "Instrument" },
37
- { key: "value", header: "Level", align: "right", format: (value, row) => moneyMarketValue(value as number | null, row.unit as "percent" | "usd-billions") },
46
+ { key: "value", header: hasCouponEquivalent(rows) ? "Discount" : "Level", align: "right", format: (value, row) => moneyMarketValue(value as number | null, row.unit as "percent" | "usd-billions") },
47
+ ...hasCouponEquivalent(rows) ? [{ key: "couponEquivalent", header: "Coupon eq", align: "right" as const,
48
+ format: (value: unknown) => moneyMarketValue((value as number | null | undefined) ?? null, "percent") }] : [],
38
49
  { key: "change", header: "Change", align: "right", format: (value, row) => moneyMarketChange(value as number | null, row.changeUnit as "basis-points" | "usd-billions") },
39
50
  // A narrow terminal moves the status, percentile and earlier date under each row first.
40
51
  { key: "previousAsOf", header: "Versus", shrink: false, stackPriority: 1 },
@@ -13,7 +13,7 @@ export const moneyMarketsModule: PluginModule = {
13
13
  options: MONEY_MARKET_TABS.map(({ value, label }) => ({ value, label })) }] } }],
14
14
  paneTemplates: [{ id: "money-markets-pane", paneId: "money-markets", label: "Money Markets",
15
15
  description: "Funding rates, Treasury bills and Federal Reserve liquidity, and Hong Kong's Exchange Fund Bill yields, with historical context.",
16
- keywords: ["btmm", "money", "rates", "bills", "sofr", "liquidity", "hibor", "hong kong", "hkd", "exchange fund bills", "efb", "hkma"], shortcut: { prefix: "BTMM" },
16
+ keywords: ["btmm", "money", "rates", "bills", "t-bill", "t-bills", "tbill", "tbills", "treasury bill", "treasury bills", "money market", "sofr", "liquidity", "hibor", "hong kong", "hkd", "exchange fund bills", "efb", "hkma"], shortcut: { prefix: "BTMM" },
17
17
  headless: moneyMarketsHeadless }],
18
18
  setup(ctx) { moneyMarketsCache.attach(ctx.persistence); hongKongMoneyMarketsCache.attach(ctx.persistence); },
19
19
  dispose() { moneyMarketsCache.reset(); hongKongMoneyMarketsCache.reset(); },
@@ -54,10 +54,16 @@ function ObservationDetail({ row, width, height, focused = false }: { row: Money
54
54
  detail: `${formatPercentileRank(p.value, "1Y")} · ${row.asOf ?? MISSING_VALUE}` },
55
55
  { id: "change", label: "Change", value: moneyMarketChange(row.change, row.changeUnit), detail: `since ${row.previousAsOf ?? MISSING_VALUE}` },
56
56
  { id: "range", label: "1Y range", value: `${moneyMarketValue(p.min, row.unit)} to ${moneyMarketValue(p.max, row.unit)}` },
57
- // A bill yield is HKMA's; the US rows name their FRED series.
57
+ // A bill yield is HKMA's; a US bill read from Treasury's daily file says so; the other US rows name their FRED series.
58
58
  row.group === "efb" ? { id: "series", label: "Source", value: "HKMA", detail: "closing yield, 16:00 HKT" }
59
+ : row.sourceName === "U.S. Treasury" ? { id: "series", label: "Source", value: "U.S. Treasury", detail: "daily bill rates" }
59
60
  : { id: "series", label: "FRED", value: row.sourceSeriesIds.join(", "), detail: row.frequency },
60
61
  ];
62
+ // A bill's discount rate understates what it pays: its coupon equivalent is the rate to set beside a fund's yield.
63
+ if (row.couponEquivalent != null) {
64
+ items.splice(1, 0, { id: "coupon", label: "Coupon eq", value: moneyMarketValue(row.couponEquivalent, "percent"),
65
+ detail: row.couponEquivalentAsOf ?? MISSING_VALUE });
66
+ }
61
67
  return <StatChartDetail items={items} width={width} height={height} empty={row.history.every((point) => point.value == null)}
62
68
  emptySubject="history" emptyTitle="No history available."
63
69
  renderChart={(chartHeight) => <ObservationChart row={row} width={width} height={chartHeight} focused={focused} />} />;
@@ -15,7 +15,7 @@ import { truncateToDisplayWidth } from "../../../../../utils/format";
15
15
  import { wrapTextLines } from "../../../../../utils/text-wrap";
16
16
  import { formatDetailDate, formatDetailTime } from "../../../../../utils/datetime-format";
17
17
  import { logFailure } from "../../../../../utils/log-failure";
18
- import { mergeNewsArticle } from "../../../../../news/news-model";
18
+ import { mergeNewsArticle, newsArticleRevision } from "../../../../../news/news-model";
19
19
  import { usePluginPaneState } from "../../../../runtime";
20
20
  import { formatNewsCategory } from "../categories";
21
21
  import { shareItemExcerpt } from "../../../../../shares/item";
@@ -25,6 +25,11 @@ function hasStoryItems(article: MarketNewsItem | null): boolean {
25
25
  return (article?.items?.length ?? 0) > 0;
26
26
  }
27
27
 
28
+ /** A story as one answer covers it: the same id and revision ask nothing new, whatever the object. */
29
+ function storyRevisionKey(article: MarketNewsItem): string {
30
+ return `${article.id}\n${newsArticleRevision(article)}`;
31
+ }
32
+
28
33
  /**
29
34
  * The open story is pane state, not component state: it is part of what the
30
35
  * pane shows, so it survives a relaunch and travels with a shared pane. A
@@ -49,7 +54,10 @@ export function useNewsArticleDetail(
49
54
  loading: boolean;
50
55
  error: string | null;
51
56
  } | null>(null);
52
- const requestedArticle = useRef<MarketNewsItem | null>(null);
57
+ // The revisions of the open story asked for. The feed takes an answer in as a new object, and
58
+ // one with no coverage (no items, or an empty list) still has none: keyed by object, that copy
59
+ // would be asked for again, and its answer would make another, without end.
60
+ const requestedRevisions = useRef(new Set<string>());
53
61
  const standaloneRequestId = useRef<string | null>(null);
54
62
  const listedDetailArticle = useMemo(
55
63
  () => articles.find((article) => article.id === detailArticleId) ?? null,
@@ -96,15 +104,19 @@ export function useNewsArticleDetail(
96
104
  if (!baseDetailArticle || hasStoryItems(baseDetailArticle) || !loadArticleDetail) return;
97
105
  // A story fetched by id is already the detail; asking again adds nothing.
98
106
  if (baseDetailArticle === currentStandalone?.article) return;
99
- if (requestedArticle.current === baseDetailArticle) return;
100
- requestedArticle.current = baseDetailArticle;
107
+ const revision = storyRevisionKey(baseDetailArticle);
108
+ if (requestedRevisions.current.has(revision)) return;
109
+ requestedRevisions.current.add(revision);
101
110
  let active = true;
102
111
  setRequest({ base: baseDetailArticle, loading: true, error: null });
103
112
  void loadArticleDetail(baseDetailArticle.id)
104
113
  .then((article) => {
105
- if (!active) return;
106
114
  if (article && article.id !== baseDetailArticle.id) throw new Error("Story detail identity mismatch.");
107
- setRequest({ base: baseDetailArticle, article: article ? mergeNewsArticle(baseDetailArticle, article) : undefined, loading: false, error: null });
115
+ const merged = article ? mergeNewsArticle(baseDetailArticle, article) : undefined;
116
+ // The feed shows the story as merged here next: that revision is answered too.
117
+ if (merged) requestedRevisions.current.add(storyRevisionKey(merged));
118
+ if (!active) return;
119
+ setRequest({ base: baseDetailArticle, article: merged, loading: false, error: null });
108
120
  })
109
121
  .catch((error: unknown) => {
110
122
  if (!active) return;
@@ -114,12 +126,12 @@ export function useNewsArticleDetail(
114
126
  }, [baseDetailArticle, currentStandalone?.article, loadArticleDetail]);
115
127
 
116
128
  const openArticle = useCallback((article: MarketNewsItem) => {
117
- requestedArticle.current = null;
129
+ requestedRevisions.current.clear();
118
130
  standaloneRequestId.current = null;
119
131
  setDetailArticleId(article.id);
120
132
  }, [setDetailArticleId]);
121
133
  const closeDetail = useCallback(() => {
122
- requestedArticle.current = null;
134
+ requestedRevisions.current.clear();
123
135
  standaloneRequestId.current = null;
124
136
  setDetailArticleId(null);
125
137
  setRequest(null);
@@ -35,7 +35,7 @@ function tableColumns(conversion: PeBandModel["conversion"]): DataTableColumn[]
35
35
  { id: "known", label: "Known", width: 11, align: "left" },
36
36
  { id: "eps", label: conversion ? `EPS ${conversion.currency}` : "EPS", width: 9, align: "right" },
37
37
  ...(conversion ? [{ id: "fx", label: fxPairQuote(conversion.currency, conversion.latest.rate).pair, width: 9, align: "right" as const }] : []),
38
- { id: "yoy", label: "YoY", width: 8, align: "right" },
38
+ { id: "yoy", label: "YoY", width: 8, align: "right", omitWhenEmpty: true },
39
39
  { id: "price", label: "Price", width: 10, align: "right" },
40
40
  { id: "pe", label: "P/E", width: 7, align: "right" },
41
41
  ];
@@ -199,11 +199,13 @@ export function printSymbolRows(
199
199
  export async function addOneSymbol(
200
200
  ctx: CliCommandContext,
201
201
  market: MarketContext,
202
- { symbol, exchange, collection, notes: inputNotes = [], retry, reject, add }: {
202
+ { symbol, exchange, collection, notes: inputNotes = [], retry, reject, add, member }: {
203
203
  symbol: string;
204
204
  exchange: string | undefined;
205
205
  notes?: readonly string[];
206
206
  collection: CollectionRef;
207
+ /** Whether a saved row is in the list added to (`addSymbol`). */
208
+ member?: (ticker: TickerRecord) => boolean;
207
209
  /** The add of one listing, for the choices a failure names. */
208
210
  retry: (key: string) => string;
209
211
  reject?: (input: string) => Error | null;
@@ -212,7 +214,7 @@ export async function addOneSymbol(
212
214
  ): Promise<void> {
213
215
  const { dataProvider, store } = market;
214
216
  const dryRun = ctx.cliOptions.dryRun;
215
- const { row, error, lookup } = await addSymbol(symbol, { exchange, store, dataProvider, reject, retry, dryRun, add });
217
+ const { row, error, lookup } = await addSymbol(symbol, { exchange, store, dataProvider, reject, retry, dryRun, add, member });
216
218
  if (row.status === "needs_choice") {
217
219
  const message = row.message ?? symbol;
218
220
  const { successors, matches } = choiceOffers([row], retry);
@@ -17,13 +17,19 @@ import { cliStyles, colorBySign, renderTable } from "../../../../utils/cli-outpu
17
17
  import type { PriceWindow } from "../../../../utils/price-window";
18
18
  import { apiClient } from "../../../../api-client";
19
19
  import { inflationMethodText, loadPeriodInflation, monthText, realReturn } from "../../../../portfolio/real-return";
20
- import { loadPeriodPnl, periodBasisText, periodBoughtText, periodSharedDay, periodUnpricedText, type LoadedPeriodPnl } from "../period-pnl";
20
+ import { loadPeriodPnl, periodBasisText, periodBoughtText, periodCurrencyParts, periodFxLabel, periodSharedDay, periodUnpricedText, type LoadedPeriodPnl } from "../period-pnl";
21
21
 
22
22
  const signedPercent = (value: number | null) => value == null || !Number.isFinite(value) ? "—"
23
23
  : `${value > 0 ? "+" : value < 0 ? "-" : ""}${Math.abs(value).toFixed(2)}%`;
24
24
 
25
25
  /** `Fri 23 Oct`, with the year when it is not this one. */
26
26
  const dayText = (day: string, year: number) => periodDayText(day, year);
27
+ /**
28
+ * The columns `--csv` gained after its own were set, written after
29
+ * `retrieved_at` so none it had moves: what a row is (holding, fx, subtotal,
30
+ * total), its P&L with FX, and whether it counts every holding and why not.
31
+ */
32
+ const PERIOD_APPENDED_KEYS = ["rowType", "total", "status", "reason"] as const;
27
33
 
28
34
  /**
29
35
  * `portfolio show <name> --from <date> [--to <date>]`: P&L and contribution
@@ -84,11 +90,20 @@ export async function showPeriodPnl({ ctx, portfolio, name, tickers, currency, w
84
90
  const contributionNote = result.contributionBase == null ? null
85
91
  : `Contribution is P&L over the book's ${result.contributionBasis === "gross" ? "gross exposure" : "value"} at the start, ${formatAllocationMoney(result.contributionBase, currency, { whole: true })}${result.contributionBasis === "gross" ? ", longs plus shorts at their absolute value, as the book holds a short" : ""}; cash excluded.`;
86
92
  const fxRows = result.rows.filter((row) => row.rates);
87
- const fxCurrencies = [...new Set(fxRows.map((row) => row.rates!.currency))].join(", ");
93
+ // The book by currency, once it holds more than its own: an FX line each, and each one's local, FX and total.
94
+ const parts = periodCurrencyParts(result);
95
+ const unpricedText = periodUnpricedText(result, label);
96
+ const boughtText = periodBoughtText(result, label);
97
+ const reasons = new Map(result.unpricedReasons.map(({ symbol, reason }) => [symbol, reason]));
98
+ /** A total over holdings some of which have no P&L says which it leaves out. */
99
+ const leftOut = (symbols: readonly string[]) => symbols.length
100
+ ? { status: "partial", reason: `leaves out ${symbols.map((symbol) => `${label(symbol)} (${reasons.get(symbol) ?? "no P&L"})`).join(", ")}` }
101
+ : { status: "complete", reason: null };
88
102
 
89
103
  if (structured) {
90
104
  const data = result.rows.map((row) => {
91
105
  const ticker = bySymbol.get(row.symbol);
106
+ const counted = row.pnl != null && Number.isFinite(row.pnl) && row.fx != null && Number.isFinite(row.fx);
92
107
  return {
93
108
  symbol: row.symbol, listing: label(row.symbol), shares: shares(row.symbol), priceUnits: Number.isFinite(row.priceUnits) ? row.priceUnits : null,
94
109
  ...(ticker && isFuturesTicker(ticker) ? { contractSize: futures.get(row.symbol)?.size?.size ?? null } : {}),
@@ -98,17 +113,32 @@ export async function showPeriodPnl({ ctx, portfolio, name, tickers, currency, w
98
113
  fxCurrency: row.rates?.currency ?? null, fxStart: row.rates?.start ?? null, fxEnd: row.rates?.end ?? null,
99
114
  ...(row.rates && row.end && result.latestFx.includes(`${row.rates.currency}|${row.end.day}`) ? { fxEndLatest: true } : {}),
100
115
  contribution: row.contribution, baseCurrency: currency,
116
+ // The columns added since, after the export's own (`PERIOD_APPENDED_KEYS`): what the row is, its P&L with FX, and
117
+ // for a holding with no P&L why, which the totals leave it out for.
118
+ rowType: "holding", total: counted ? row.pnl! + row.fx! : null,
119
+ status: counted ? "counted" : "left out", reason: counted ? null : reasons.get(row.symbol) ?? "no P&L",
101
120
  };
102
121
  });
122
+ // Each currency's FX line (its pnl the move, as the one FX line's was, and in fx), then each currency's part of the
123
+ // book when the text prints the table of them, then the book's total, each saying when it leaves a holding out.
124
+ // A part's pnl is its price P&L, as a holding's is; total adds its FX. Summing the holding rows gives the price P&L.
103
125
  const extraRows: Record<string, unknown>[] = [
104
- ...(fxRows.length ? [{ symbol: "FX", pnl: result.fx, contribution: result.fxContribution, baseCurrency: currency }] : []),
105
- { symbol: "TOTAL", pnl: result.total, contribution: result.totalContribution, baseCurrency: currency },
126
+ ...parts.filter((part) => !part.own).map((part) => ({ symbol: "FX", currency: part.currency, pnl: part.fx, fx: part.fx, fxCurrency: part.currency,
127
+ contribution: part.fxContribution, baseCurrency: currency, rowType: "fx", total: part.fx, ...leftOut(part.unpriced) })),
128
+ ...(parts.length > 1 ? parts : []).map((part) => ({ symbol: "SUBTOTAL", currency: part.currency, pnl: part.local, fx: part.fx,
129
+ contribution: part.contribution, baseCurrency: currency, rowType: "subtotal", total: part.total, ...leftOut(part.unpriced) })),
130
+ { symbol: "TOTAL", pnl: result.total, fx: result.fx, contribution: result.totalContribution, baseCurrency: currency,
131
+ rowType: "total", total: result.total, ...leftOut(result.unpriced) },
106
132
  ];
133
+ const notes = [unpricedText, boughtText].filter((note): note is string => !!note);
107
134
  ctx.printResult({ data, metadata: {
108
135
  portfolioId: portfolio.id, portfolioName: name, baseCurrency: currency, from: window.from, to: window.to,
109
136
  startDay, endDay, basis: basisText, fx: result.fx, fxContribution: result.fxContribution, total: result.total, totalContribution: result.totalContribution,
137
+ totalStatus: leftOut(result.unpriced).status,
138
+ currencies: (result.currencies ?? []).map((part) => ({ ...part, ...leftOut(part.unpriced) })),
110
139
  contributionBase: result.contributionBase, contributionBasis: result.contributionBasis,
111
140
  complete: result.unpriced.length === 0, unpricedSymbols: result.unpriced, unpriced: result.unpricedReasons, failures: result.failures,
141
+ ...(notes.length ? { notes } : {}),
112
142
  boughtInWindowSymbols: result.boughtInWindow, latestPriceAt: result.latestPriceAt == null ? null : new Date(result.latestPriceAt).toISOString(),
113
143
  ...(explain ? { glossary: explained.map(({ term, definition }) => ({ term, definition })) } : {}),
114
144
  ...(inflation ? { real: "error" in inflation ? { error: inflation.error } : {
@@ -119,7 +149,7 @@ export async function showPeriodPnl({ ctx, portfolio, name, tickers, currency, w
119
149
  readings: inflation.readings,
120
150
  } } : {}),
121
151
  method: "Each holding's price move times the units held now (contracts times their size for a future), converted at the end's FX rate; the FX line is each holding's start value times its currency's move. Contribution divides by the book's value at the start, gross when it holds a short.",
122
- }, freshness }, { rows: (rows) => [...(rows as Record<string, unknown>[]), ...extraRows] });
152
+ }, freshness }, { rows: (rows) => [...(rows as Record<string, unknown>[]), ...extraRows], exportNotes: notes, exportAppendedKeys: PERIOD_APPENDED_KEYS });
123
153
  return;
124
154
  }
125
155
 
@@ -143,9 +173,10 @@ export async function showPeriodPnl({ ctx, portfolio, name, tickers, currency, w
143
173
  ]);
144
174
  const blank = (count: number) => Array.from({ length: count }, () => "");
145
175
  const lead = 3 + (dated ? 2 : 0) + 2;
146
- if (fxRows.length) rows.push([`FX (${fxCurrencies})`, ...blank(lead - 1), money(result.fx), colorBySign(signedPercent(result.fxContribution), result.fxContribution ?? 0)]);
147
- rows.push([cliStyles.bold("TOTAL"), ...blank(lead - 1), cliStyles.bold(money(result.total)),
148
- result.totalContribution == null ? "—" : colorBySign(signedPercent(result.totalContribution), result.totalContribution)]);
176
+ const percent = (value: number | null) => value == null || !Number.isFinite(value) ? "—" : colorBySign(signedPercent(value), value);
177
+ // An FX line per currency, so the rows add up to the total and each currency's move reads on its own.
178
+ for (const part of parts) if (!part.own) rows.push([periodFxLabel(part.currency), ...blank(lead - 1), money(part.fx), percent(part.fxContribution)]);
179
+ rows.push([cliStyles.bold("TOTAL"), ...blank(lead - 1), cliStyles.bold(money(result.total)), percent(result.totalContribution)]);
149
180
 
150
181
  console.log(cliStyles.bold(`${name} (${currency})`));
151
182
  console.log(cliStyles.muted(basisText));
@@ -161,6 +192,27 @@ export async function showPeriodPnl({ ctx, portfolio, name, tickers, currency, w
161
192
  { header: `P&L (${currency})`, align: "right" },
162
193
  { header: "Contribution", align: "right" },
163
194
  ], rows));
195
+ if (parts.length > 1) {
196
+ // What each currency's holdings made from their prices, from the currency, and together, and the book's; one
197
+ // currency's would repeat the total.
198
+ // A figure that leaves a holding out names it, as fn PF's Left out does; a currency with none counted reads —.
199
+ const leftOutCell = (symbols: readonly string[]) => symbols.length ? symbols.map(label).join(", ") : "—";
200
+ const anyLeftOut = result.unpriced.length > 0;
201
+ console.log("");
202
+ console.log(renderTable([
203
+ { header: "Currency" },
204
+ { header: `Local (${currency})`, align: "right" },
205
+ { header: `FX (${currency})`, align: "right" },
206
+ { header: `Total (${currency})`, align: "right" },
207
+ { header: "Contribution", align: "right" },
208
+ ...anyLeftOut ? [{ header: "Left out" }] : [],
209
+ ], [
210
+ ...parts.map((part) => [part.currency, money(part.local), part.own ? "—" : money(part.fx), money(part.total), percent(part.contribution),
211
+ ...anyLeftOut ? [leftOutCell(part.unpriced)] : []]),
212
+ [cliStyles.bold("TOTAL"), money(result.total - result.fx), money(result.fx), cliStyles.bold(money(result.total)), percent(result.totalContribution),
213
+ ...anyLeftOut ? [leftOutCell(result.unpriced)] : []],
214
+ ]));
215
+ }
164
216
  console.log("");
165
217
  const notes: string[] = [];
166
218
  // As markets quote the pair, as `portfolio show` writes its FX line: USD/HKD 7.7531 on Fri 23 Oct, 7.7502 on Fri 30 Oct.
@@ -171,12 +223,10 @@ export async function showPeriodPnl({ ctx, portfolio, name, tickers, currency, w
171
223
  const latest = result.latestFx.includes(`${row.rates!.currency}|${row.end!.day}`);
172
224
  return `${start.pair} ${formatFxRate(start.rate)} on ${dayText(row.start!.day, year)}, ${formatFxRate(end.rate)} ${latest ? "latest" : `on ${dayText(row.end!.day, year)}`}`;
173
225
  };
174
- if (fxRows.length) notes.push(`FX: ${[...new Set(fxRows.map(rateText))].join("; ")}. P&L converts at the end's rate; the FX line is the currency's move on the start value.`);
226
+ if (fxRows.length) notes.push(`FX: ${[...new Set(fxRows.map(rateText))].join("; ")}. P&L converts at the end's rate; ${parts.filter((part) => !part.own).length > 1 ? "each FX line is its currency's move" : "the FX line is the currency's move"} on the start value.`);
175
227
  if (contributionNote) notes.push(contributionNote);
176
228
  if (realNote) notes.push(realNote);
177
- const unpricedText = periodUnpricedText(result, label);
178
229
  if (unpricedText) notes.push(cliStyles.warning(unpricedText));
179
- const boughtText = periodBoughtText(result, label);
180
230
  if (boughtText) notes.push(boughtText);
181
231
  for (const note of [...new Set(notes)]) console.log(note.startsWith("\u001b") ? note : cliStyles.muted(note));
182
232
  console.log(`\n${cliFreshnessFooter(freshness)}`);
@@ -3,7 +3,8 @@ import { withConfigData } from "../../../../cli/scoped-context";
3
3
  import { withCollectionConfigData, withCollectionMarketData } from "../../../../cli/suffixed-listing-rows";
4
4
  import { countCollectionTickers } from "../../../../cli/helpers";
5
5
  import { exitLeavingReadsBehind } from "../../../../cli/result";
6
- import { resolveCliTicker, resolveTickerForCli } from "../../../../cli/ticker-resolution";
6
+ import { resolveTickerForCli } from "../../../../cli/ticker-resolution";
7
+ import { resolveListTicker } from "../../../../cli/symbol-rows";
7
8
  import { takeFlag, takeOption } from "../../../../cli/commands/command-utils";
8
9
  import { EXCHANGE_OPTION, listingKeys, loadSavedListing, parseListingArg, requireSavedListing, savedListingCandidates, savedListingName, type ListingArg } from "../../../../cli/listing-arg";
9
10
  import { cliStyles, renderStats, renderTable } from "../../../../utils/cli-output";
@@ -244,6 +245,7 @@ async function addTickerToPortfolioCommand(
244
245
  retry: (key) => `gloom portfolio add ${shellWord(portfolio.name)} ${key}`,
245
246
  reject: cashRefusal(portfolio, exchange),
246
247
  add: (ticker) => addTickerToPortfolio(ticker, portfolio.id),
248
+ member: (ticker) => ticker.metadata.portfolios.includes(portfolio.id),
247
249
  });
248
250
  }
249
251
 
@@ -271,6 +273,7 @@ async function addToPortfolioCommand(args: string[], file: string | undefined, e
271
273
  onProgress: progressNotice(ctx),
272
274
  retry,
273
275
  add: (ticker) => addTickerToPortfolio(ticker, portfolio.id),
276
+ member: (ticker) => ticker.metadata.portfolios.includes(portfolio.id),
274
277
  });
275
278
  printSymbolRows(ctx, rows, { verb: "add", collection: { kind: "portfolio", name: portfolio.name }, repeated: list.repeated, notes: list.notes, retry, dryRun });
276
279
  });
@@ -368,7 +371,10 @@ async function setPositionCommand(
368
371
  const shares = parseAmountArg(sharesValue, positionQuantityLabel({ metadata: { ticker: symbol, assetCategory: undefined } }));
369
372
  const avgCost = parseAmountArg(avgCostValue, "Average cost");
370
373
  // The notes say which listing a bare symbol went to, and that a bare coin ticker is not the coin, as `portfolio add` does.
371
- const { ticker, notes } = await resolveCliTicker(symbol, store, dataProvider, exchange);
374
+ // A bare symbol that reads as a future in a book of listings on another venue keeps the book's venue, or asks.
375
+ const { ticker, notes } = await resolveListTicker(symbol, {
376
+ store, dataProvider, exchange, member: (row) => row.metadata.portfolios.includes(portfolio.id),
377
+ });
372
378
  // `1.250` and `1.000` ask which was meant, as `1,250` did above: a dot before three digits is as often thousands.
373
379
  const lots = ambiguousQuantityProblem(sharesValue, ticker, { listing: savedListingName(ticker).key });
374
380
  if (lots) throw new PortfolioCliError(lots);
@@ -651,7 +657,9 @@ async function setTargetCommand(rest: string[], exchange: string | undefined, ct
651
657
  const coinNote = listing.exchange ? null : savedListingCoinNote(listing.symbol, ticker);
652
658
  if (coinNote) notes = [coinNote];
653
659
  } else {
654
- const { ticker: resolved, notes: resolvedNotes } = await resolveCliTicker(symbol, store, dataProvider, exchange);
660
+ const { ticker: resolved, notes: resolvedNotes } = await resolveListTicker(symbol, {
661
+ store, dataProvider, exchange, member: (row) => row.metadata.portfolios.includes(portfolio.id),
662
+ });
655
663
  notes = resolvedNotes;
656
664
  if (!resolved.metadata.portfolios.includes(portfolio.id)) {
657
665
  if (!isManualPortfolio(portfolio)) {
@@ -97,6 +97,7 @@ import { isoDateToday } from "../../../../utils/calendar-date";
97
97
  import { lastTradeDate } from "../../../../tickers/listing-fate";
98
98
  import type { PriceWindow } from "../../../../utils/price-window";
99
99
  import { showPeriodPnl } from "./period-report";
100
+ import { sectionWatchlistItems, UNGROUPED_LABEL, watchlistGroups } from "../../../../portfolio/watchlist-groups";
100
101
  import { DIVIDEND_READ_DEADLINE_MS, incomeGapNote, loadHoldingDividends, portfolioIncome, projectDrip, showsIncomeColumns, type DripYear, type HoldingDividend } from "../income";
101
102
 
102
103
  /** Money prices pad to the currency's minor unit ($337.90, not $337.9), as the ticker view does. */
@@ -1455,7 +1456,11 @@ async function showCollectionWithMarketData(
1455
1456
  if (unprojected.length > 0) console.log(cliStyles.muted(`Not projected: ${unprojected.join("; ")}.`));
1456
1457
  }
1457
1458
  } else {
1458
- const watched = await valueWatchlistRows({ tickers: filtered, quotes, dataProvider, currency, toBase });
1459
+ // A list with groups runs group by group, as PF shows it, and each row names its group.
1460
+ const sections = sectionWatchlistItems(watchlistGroups(config.watchlists.find((entry) => entry.id === id)), filtered, (ticker) => ticker.metadata.ticker);
1461
+ const groupOf = new Map(sections?.flatMap((section) => section.items.map((ticker) => [ticker.metadata.ticker, section.name] as const)));
1462
+ const valued = await valueWatchlistRows({ tickers: sections ? sections.flatMap((section) => section.items) : filtered, quotes, dataProvider, currency, toBase });
1463
+ const watched = sections ? valued.map((entry) => ({ ...entry, row: { ...entry.row, group: groupOf.get(entry.ticker.metadata.ticker) ?? null } })) : valued;
1459
1464
  if (structured) {
1460
1465
  ctx.printResult({
1461
1466
  data: watched.map((entry) => entry.row),
@@ -1477,6 +1482,7 @@ async function showCollectionWithMarketData(
1477
1482
  const changeText = quote?.delisting ? "—" : headline ? colorBySign(formatPercentRaw(headline.changePercent), headline.change) : "—";
1478
1483
  const staleText = quote?.delisting ? delistingLabel(quote.delisting) : lastTrade ? `STALE ${lastTrade}` : "STALE";
1479
1484
  return [
1485
+ ...sections ? [groupOf.get(ticker.metadata.ticker) ?? UNGROUPED_LABEL] : [],
1480
1486
  listingLabel(ticker),
1481
1487
  venue ?? "—",
1482
1488
  priceText,
@@ -1490,6 +1496,7 @@ async function showCollectionWithMarketData(
1490
1496
 
1491
1497
  console.log(renderTable(
1492
1498
  [
1499
+ ...sections ? [{ header: "Group" }] : [],
1493
1500
  { header: "Ticker" },
1494
1501
  { header: "Exchange" },
1495
1502
  { header: "Last", align: "right" },