gloomberb 0.20.13 → 0.20.14

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 (155) 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/money-markets.ts +7 -0
  10. package/src/api-client/request.ts +12 -2
  11. package/src/architecture/floating-promise-allowlist.json +0 -1
  12. package/src/brokers/signed-in/sign-in-dialog.tsx +38 -38
  13. package/src/cli/commands/market.ts +95 -23
  14. package/src/cli/commands/overview.ts +18 -4
  15. package/src/cli/errors.ts +3 -1
  16. package/src/cli/freshness.ts +7 -2
  17. package/src/cli/glossary.ts +10 -5
  18. package/src/cli/helpers.ts +8 -16
  19. package/src/cli/history-export.ts +4 -0
  20. package/src/cli/known-gaps.ts +2 -2
  21. package/src/cli/listing-arg.ts +79 -11
  22. package/src/cli/not-a-ticker.ts +4 -0
  23. package/src/cli/pane-functions/catalog.ts +29 -8
  24. package/src/cli/pane-functions/headless.ts +5 -2
  25. package/src/cli/pane-functions/options.ts +7 -0
  26. package/src/cli/pane-functions/resolver.ts +61 -15
  27. package/src/cli/result.ts +22 -4
  28. package/src/cli/symbol-args.ts +5 -3
  29. package/src/cli/symbol-list.ts +23 -10
  30. package/src/cli/symbol-rows.ts +135 -3
  31. package/src/cli/treasury-yields.ts +15 -1
  32. package/src/components/chart/composite/format.ts +2 -1
  33. package/src/components/chart/composite/panel-surface/axis-markers.ts +133 -0
  34. package/src/components/chart/composite/panel-surface/level-labels.tsx +78 -0
  35. package/src/components/chart/composite/panel-surface/overlays.ts +108 -0
  36. package/src/components/chart/composite/panel-surface/pan-coast.ts +54 -0
  37. package/src/components/chart/composite/panel-surface/panel-cursor.tsx +138 -0
  38. package/src/components/chart/composite/panel-surface/panel-levels.ts +47 -0
  39. package/src/components/chart/composite/panel-surface/plot-gestures.ts +403 -0
  40. package/src/components/chart/composite/panel-surface/plot-pointer.ts +65 -0
  41. package/src/components/chart/composite/panel-surface/plot-wheel.ts +102 -0
  42. package/src/components/chart/composite/panel-surface/pointer.ts +12 -0
  43. package/src/components/chart/composite/panel-surface/props.ts +79 -0
  44. package/src/components/chart/composite/panel-surface/tool-readout.ts +151 -0
  45. package/src/components/chart/composite/panel-surface/value-axis-gestures.ts +152 -0
  46. package/src/components/chart/composite/panel-surface.tsx +81 -1177
  47. package/src/components/command-bar/commands/collection-list.ts +1 -0
  48. package/src/components/command-bar/routes/root/results.ts +3 -2
  49. package/src/components/command-bar/routes/root/runtime.ts +3 -2
  50. package/src/components/command-bar/routes/root/selection.ts +3 -2
  51. package/src/components/command-bar/routes/root/shortcuts.ts +15 -0
  52. package/src/components/layout/pane/title.ts +10 -4
  53. package/src/components/pane-settings-dialog/tui.tsx +6 -3
  54. package/src/components/pane-settings-dialog.tsx +2 -1
  55. package/src/components/pane-template-wizard.tsx +2 -0
  56. package/src/components/ui/choice-dialog.tsx +1 -1
  57. package/src/components/ui/confirm-dialog.tsx +3 -2
  58. package/src/components/ui/frame.tsx +7 -3
  59. package/src/components/ui/icon.tsx +4 -2
  60. package/src/components/ui/list-view.tsx +8 -0
  61. package/src/components/ui/number-prompt-dialog.tsx +2 -1
  62. package/src/components/use-pane-notice-footer.tsx +3 -1
  63. package/src/docs/snapshot.json +2 -2
  64. package/src/i18n/es.ts +1 -0
  65. package/src/i18n/ja.ts +1 -0
  66. package/src/i18n/ko.ts +1 -0
  67. package/src/i18n/zh-cn.ts +1 -0
  68. package/src/i18n/zh-tw.ts +1 -0
  69. package/src/market-data/market/format.ts +35 -1
  70. package/src/market-data/quotes/contributions.ts +13 -0
  71. package/src/market-data/quotes/export-identity.ts +36 -1
  72. package/src/market-data/quotes/resolution.ts +16 -0
  73. package/src/plugins/builtin/account-management/password-dialog.tsx +2 -2
  74. package/src/plugins/builtin/analytics/risk-client.ts +12 -2
  75. package/src/plugins/builtin/analytics/risk-headless.ts +66 -6
  76. package/src/plugins/builtin/analytics/risk-math.ts +23 -6
  77. package/src/plugins/builtin/analytics/risk-model.ts +20 -9
  78. package/src/plugins/builtin/analytics/risk-pane.tsx +2 -2
  79. package/src/plugins/builtin/chart-composer/catalog-inventory.ts +5 -2
  80. package/src/plugins/builtin/chart-composer/editor.tsx +1 -0
  81. package/src/plugins/builtin/chart-composer/pane.tsx +1 -1
  82. package/src/plugins/builtin/chart-composer/quick-add.tsx +4 -1
  83. package/src/plugins/builtin/chart-composer/series-catalog.ts +17 -1
  84. package/src/plugins/builtin/cloud/plugin.tsx +2 -0
  85. package/src/plugins/builtin/cloud/thesis/module.tsx +2 -0
  86. package/src/plugins/builtin/cloud/upgrade-status-widget.tsx +6 -2
  87. package/src/plugins/builtin/cpi/headless.ts +6 -1
  88. package/src/plugins/builtin/cpi/model.ts +17 -0
  89. package/src/plugins/builtin/cpi/pane.tsx +3 -1
  90. package/src/plugins/builtin/crypto-board/client.ts +6 -1
  91. package/src/plugins/builtin/crypto-board/headless.ts +10 -2
  92. package/src/plugins/builtin/crypto-board/model.ts +89 -11
  93. package/src/plugins/builtin/crypto-board/pane.tsx +20 -5
  94. package/src/plugins/builtin/dividend-yield/client.ts +24 -2
  95. package/src/plugins/builtin/dividend-yield/headless.ts +4 -2
  96. package/src/plugins/builtin/dividend-yield/ranking.ts +2 -1
  97. package/src/plugins/builtin/dividend-yield/view.ts +5 -1
  98. package/src/plugins/builtin/earnings/history-table.ts +8 -0
  99. package/src/plugins/builtin/earnings-ripple/index.tsx +2 -0
  100. package/src/plugins/builtin/econ/calendar-model.ts +17 -1
  101. package/src/plugins/builtin/econ/fred-catalog.ts +33 -4
  102. package/src/plugins/builtin/econ-statistics/headless.ts +21 -0
  103. package/src/plugins/builtin/macro-day/headless.ts +21 -10
  104. package/src/plugins/builtin/macro-day/model.ts +40 -3
  105. package/src/plugins/builtin/macro-day/pane.tsx +26 -8
  106. package/src/plugins/builtin/macro-day/releases.ts +24 -1
  107. package/src/plugins/builtin/money-markets/client.ts +4 -1
  108. package/src/plugins/builtin/money-markets/headless.ts +15 -4
  109. package/src/plugins/builtin/money-markets/index.tsx +1 -1
  110. package/src/plugins/builtin/money-markets/pane.tsx +7 -1
  111. package/src/plugins/builtin/portfolio-list/cli/bulk-symbols.ts +4 -2
  112. package/src/plugins/builtin/portfolio-list/cli/period-report.ts +61 -11
  113. package/src/plugins/builtin/portfolio-list/cli/portfolio-command.ts +11 -3
  114. package/src/plugins/builtin/portfolio-list/cli/watchlist-command.ts +2 -0
  115. package/src/plugins/builtin/portfolio-list/headless.ts +33 -6
  116. package/src/plugins/builtin/portfolio-list/pane/index.tsx +5 -3
  117. package/src/plugins/builtin/portfolio-list/pane/period-pnl.ts +24 -6
  118. package/src/plugins/builtin/portfolio-list/period-pnl.ts +16 -1
  119. package/src/plugins/builtin/portfolio-list/summary/index.tsx +4 -1
  120. package/src/plugins/builtin/portfolio-list/summary/totals.ts +6 -4
  121. package/src/plugins/builtin/portfolio-list/table.tsx +25 -15
  122. package/src/plugins/builtin/shared/cloud-upgrade.ts +4 -2
  123. package/src/plugins/builtin/shared/cpi-year-gap.ts +67 -0
  124. package/src/plugins/builtin/ticker-detail/adr-pair/headless.ts +45 -2
  125. package/src/plugins/builtin/ticker-detail/headless.ts +26 -1
  126. package/src/plugins/builtin/ticker-detail/overview/components.tsx +4 -5
  127. package/src/plugins/builtin/ticker-detail/overview/model.ts +4 -1
  128. package/src/plugins/builtin/ticker-detail/overview-tab.tsx +10 -2
  129. package/src/portfolio/collection-name.ts +2 -1
  130. package/src/portfolio/column-values.ts +14 -4
  131. package/src/portfolio/listed-symbol.ts +4 -2
  132. package/src/portfolio/period-pnl.ts +51 -1
  133. package/src/renderers/dom/dialog-host.tsx +5 -5
  134. package/src/renderers/electrobun/view/remote/capability-invoker.ts +1 -1
  135. package/src/renderers/opentui/dialog-host.tsx +3 -4
  136. package/src/sources/gloomberb-cloud/normalizers.ts +5 -0
  137. package/src/sources/provider-router/history.ts +5 -2
  138. package/src/test-support/plugin-persistence.ts +12 -0
  139. package/src/tickers/company-name-listing.ts +4 -3
  140. package/src/tickers/company-name.ts +19 -1
  141. package/src/tickers/instrument-coverage.ts +27 -0
  142. package/src/tickers/search/home-listing.ts +38 -1
  143. package/src/tickers/search/index.ts +3 -2
  144. package/src/tickers/search/ranking.ts +21 -2
  145. package/src/time-series/base-series.ts +4 -0
  146. package/src/time-series/types.ts +5 -2
  147. package/src/types/financials.ts +13 -0
  148. package/src/types/headless.ts +2 -0
  149. package/src/ui/dialog-stack.ts +17 -0
  150. package/src/ui/dialog.tsx +6 -2
  151. package/src/utils/crypto-pair.ts +9 -0
  152. package/src/utils/exchanges.ts +13 -0
  153. package/src/utils/financial-statements.ts +60 -3
  154. package/src/utils/futures-generic.ts +14 -0
  155. package/src/utils/trailing-dividend.ts +13 -3
@@ -3,8 +3,8 @@ import type { HeadlessPaneDefinition } from "../../../types/plugin";
3
3
  import { resolveHeadlessInstrument } from "../shared/headless-market-data";
4
4
  import { loadMacroDayEarnings, loadMacroDayHistory, loadMacroDaySeriesHistory, loadMacroReleases, macroDayEarningsNotice, type MacroDayEarnings } from "./client";
5
5
  import { fredSeriesArgument } from "../../../series/fred-argument";
6
- import { formatMacroDayMove, macroDayEventLabel, macroDayReleaseName, macroDayStats, macroFigureGapNotices, matchesSurprise, projectMacroDays, type MacroDayEvent,
7
- type MacroDayStats } from "./model";
6
+ import { formatMacroDayMove, macroDayEventLabel, macroDayReleaseName, macroDayStats, macroFigureGapNotices, macroSurpriseBasisLabel,
7
+ macroSurpriseExclusionNote, macroSurpriseOf, matchesSurprise, projectMacroDays, type MacroDayEvent, type MacroDayStats } from "./model";
8
8
  import { MACRO_EVENT_KINDS, MACRO_EVENT_LABELS, MACRO_RELEASE_SOURCES, MACRO_SURPRISE_LABELS, MACRO_SURPRISES, staleMacroReleasesNotice,
9
9
  US_MACRO_EVENT_KINDS, type MacroEventKind, type MacroReleaseFigures, type MacroSurprise } from "./releases";
10
10
 
@@ -27,7 +27,8 @@ export const macroDayHeadless: HeadlessPaneDefinition<"bundle"> = {
27
27
  "US listings, or a FRED series (FRED:T10Y2Y, whose moves in a rate or spread read in bp); close-to-close on the release day.",
28
28
  "Published CPI, jobs and FOMC days, and from Gloom Cloud Brazil's IPCA days, the ECB's decision days (every Governing Council monetary policy meeting) and the BoJ's (each monetary policy meeting's Tokyo day, from 2026); sessions after the list's last covered day (releasesThrough) are left out.",
29
29
  "Actual, forecast and prior for the days Gloom Cloud has them (the US headlines from its kept economic calendar, under either feed's title; an FOMC day's are the federal funds target range and whether it held or moved, an ECB day's the deposit facility rate, a BoJ day's its policy rate; IPCA from the central bank's SGS series); --surprise keeps the days that came in hot, cool or in line with the forecast.",
30
- "A CPI day the calendar lists without its year-on-year actual takes one computed from the CPI index against a year earlier, labelled computed.",
30
+ "A CPI day the calendar lists without its year-on-year actual takes one computed from the CPI index against a year earlier, labelled computed; where none can be (October 2026, as the October 2025 index was never published), its surprise is read from core CPI m/m, else CPI m/m, and named so (hot (core m/m)).",
31
+ "With --surprise, the notes say how many days in scope were left out because their surprise cannot be read (no actual, or no forecast).",
31
32
  "A release day without figures says why: before the kept calendar starts, or listed without them.",
32
33
  "A release day that is also the reaction session of the company's own earnings report is marked earnings and left out of the release averages and the normal day.",
33
34
  ] },
@@ -63,7 +64,11 @@ export const macroDayHeadless: HeadlessPaneDefinition<"bundle"> = {
63
64
  const header = (label: string) => yieldMoves ? `${label} bp` : label;
64
65
  const release = String(args.options.release ?? "all");
65
66
  const surprise = String(args.options.surprise ?? "all") as MacroSurprise | "all";
66
- const events = model.events.filter((event) => (release === "all" || event.kind === release) && matchesSurprise(event, surprise));
67
+ const scoped = model.events.filter((event) => release === "all" || event.kind === release);
68
+ const events = scoped.filter((event) => matchesSurprise(event, surprise));
69
+ // A surprise filter says how many days it could not read, and the notes below say why for them too.
70
+ const unread = surprise === "all" ? [] : scoped.filter((event) => macroSurpriseOf(event.figures) == null);
71
+ const excluded = macroSurpriseExclusionNote(scoped, surprise);
67
72
  // The days the filter keeps get a row of their own: how the name moved on hot CPI days.
68
73
  const selected = surprise === "all" ? [] : [row(`${MACRO_SURPRISE_LABELS[surprise]} ${release === "all" ? "release"
69
74
  : MACRO_EVENT_LABELS[release as MacroEventKind]}`, macroDayStats(events, model.normal.meanAbs))];
@@ -74,8 +79,9 @@ export const macroDayHeadless: HeadlessPaneDefinition<"bundle"> = {
74
79
  const beforeCalendar = (event: MacroDayEvent) => predates(event) && !event.figures;
75
80
  const noForecast = (event: MacroDayEvent) => predates(event) && !!event.figures && event.figures.forecast == null;
76
81
  /** "CPI and Jobs days": the kinds of the listed days `pick` takes, in the order the summary lists them. */
82
+ const noted = [...events, ...unread];
77
83
  const daysOf = (pick: (event: MacroDayEvent) => boolean) => {
78
- const labels = model.kinds.filter((kind) => events.some((event) => event.kind === kind && pick(event))).map((kind) => MACRO_EVENT_LABELS[kind]);
84
+ const labels = model.kinds.filter((kind) => noted.some((event) => event.kind === kind && pick(event))).map((kind) => MACRO_EVENT_LABELS[kind]);
79
85
  return `${labels.length > 1 ? `${labels.slice(0, -1).join(", ")} and ${labels.at(-1)}` : labels[0]} days`;
80
86
  };
81
87
  // A release Gloom Cloud alone lists (IPCA, the ECB, the BoJ) is summed up on its own: "Any release" is then the US ones'.
@@ -83,9 +89,10 @@ export const macroDayHeadless: HeadlessPaneDefinition<"bundle"> = {
83
89
  const missing = (event: MacroDayEvent) => event.figures ? null : event.figuresMissing
84
90
  ?? (beforeCalendar(event) ? `before ${figuresFrom}, when Gloom Cloud's economic calendar starts` : null);
85
91
  const figureNotes = [
86
- ...(events.some(beforeCalendar) ? [`${daysOf(beforeCalendar)} before ${figuresFrom} have no actual, forecast or prior: Gloom Cloud's economic calendar starts then.`] : []),
87
- ...(events.some(noForecast) ? [`Forecasts start ${figuresFrom}, with Gloom Cloud's economic calendar: ${daysOf(noForecast)} before it have an actual and prior, no forecast or surprise.`] : []),
88
- ...macroFigureGapNotices(events),
92
+ ...(excluded ? [excluded] : []),
93
+ ...(noted.some(beforeCalendar) ? [`${daysOf(beforeCalendar)} before ${figuresFrom} have no actual, forecast or prior: Gloom Cloud's economic calendar starts then.`] : []),
94
+ ...(noted.some(noForecast) ? [`Forecasts start ${figuresFrom}, with Gloom Cloud's economic calendar: ${daysOf(noForecast)} before it have an actual and prior, no forecast or surprise.`] : []),
95
+ ...macroFigureGapNotices(noted.toSorted((left, right) => right.date.localeCompare(left.date) || left.kind.localeCompare(right.kind))),
89
96
  ];
90
97
  return {
91
98
  sections: [
@@ -102,13 +109,17 @@ export const macroDayHeadless: HeadlessPaneDefinition<"bundle"> = {
102
109
  { key: "actual", header: "Actual", textFormat: (value, row) => typeof value !== "string" ? MISSING_VALUE
103
110
  : row.actualComputed === true ? `${value} (computed)` : value },
104
111
  { key: "forecast", header: "Forecast" }, { key: "prior", header: "Prior" },
105
- { key: "surprise", header: "Surprise" },
112
+ // A surprise read from another print than the headline's names it: hot (core m/m).
113
+ { key: "surprise", header: "Surprise", textFormat: (value, row) => typeof value !== "string" ? MISSING_VALUE
114
+ : typeof row.surpriseBasis === "string" ? `${value} (${row.surpriseBasis})` : value },
106
115
  { key: "session", header: "Session" }, { key: "move", header: header("Move"), format: move }, { key: "multiple", header: "vs normal", format: multiple }],
107
116
  rows: events.map((day) => {
108
117
  const { figures, figuresMissing: _gap, ...event } = day;
109
118
  const why = missing(day);
110
119
  return { ...event, event: macroDayReleaseName(day), actual: figures?.actual ?? null,
111
- forecast: figures?.forecast ?? null, prior: figures?.prior ?? null, surprise: figures?.surprise ?? null,
120
+ forecast: figures?.forecast ?? null, prior: figures?.prior ?? null, surprise: macroSurpriseOf(figures),
121
+ ...(macroSurpriseBasisLabel(figures) ? { surpriseBasis: macroSurpriseBasisLabel(figures),
122
+ surpriseBasisActual: figures!.surpriseBasis!.actual, surpriseBasisForecast: figures!.surpriseBasis!.forecast } : {}),
112
123
  ...(figures ? { headline: figures.event } : {}), ...(figures?.decision ? { decision: figures.decision } : {}),
113
124
  ...(figures?.computed ? { actualComputed: true, actualBasis: figures.computed } : {}),
114
125
  ...(figures?.actualMissing ? { actualMissing: figures.actualMissing } : {}),
@@ -119,9 +119,43 @@ export const macroFigureGapNotices = (events: readonly Pick<MacroDayEvent, "kind
119
119
  const label = `${event.date} ${MACRO_EVENT_LABELS[event.kind]}`;
120
120
  if (!event.figures) return event.figuresMissing ? [`${label} has no figures: ${event.figuresMissing}.`] : [];
121
121
  if (event.figures.computed) return [`${label} actual is ${event.figures.computed}.`];
122
- return event.figures.actualMissing ? [`${label} has no actual: ${event.figures.actualMissing}.`] : [];
122
+ // The print its surprise is read from instead, with its own figures.
123
+ const basis = event.figures.surpriseBasis;
124
+ const read = basis ? ` Surprise read from ${basis.basis}: ${basis.actual} vs ${basis.forecast} forecast.` : "";
125
+ return event.figures.actualMissing ? [`${label} has no actual: ${event.figures.actualMissing}.${read}`]
126
+ : basis ? [`${label} has no actual.${read}`] : [];
123
127
  });
124
128
 
129
+ /**
130
+ * Whether a day's print came in hot, cool or in line: its headline against
131
+ * the consensus, or where the headline has no actual (a CPI day with no y/y)
132
+ * the print the surprise is read from instead (core m/m, else m/m). Null
133
+ * when neither can say.
134
+ */
135
+ export const macroSurpriseOf = (figures: Pick<MacroReleaseFigures, "surprise" | "surpriseBasis"> | null | undefined): MacroSurprise | null =>
136
+ figures?.surprise ?? figures?.surpriseBasis?.surprise ?? null;
137
+
138
+ /** The print a surprise was read from when it is not the headline's, as a cell names it: `core m/m`; null for the headline's own. */
139
+ export const macroSurpriseBasisLabel = (figures: Pick<MacroReleaseFigures, "surprise" | "surpriseBasis"> | null | undefined): string | null =>
140
+ figures?.surprise == null && figures?.surpriseBasis ? figures.surpriseBasis.basis : null;
141
+
142
+ /**
143
+ * What a surprise filter leaves out, for the days in scope: those whose
144
+ * surprise cannot be read, "3 prints excluded: no actual." (or no forecast,
145
+ * for a print with no consensus). Null when the filter keeps every day it can
146
+ * read, and with no filter.
147
+ */
148
+ export function macroSurpriseExclusionNote(events: readonly Pick<MacroDayEvent, "figures">[], surprise: MacroSurprise | "all"): string | null {
149
+ if (surprise === "all") return null;
150
+ const unread = events.filter((event) => macroSurpriseOf(event.figures) == null);
151
+ if (!unread.length) return null;
152
+ const noActual = unread.filter((event) => !event.figures?.actual).length;
153
+ const noForecast = unread.length - noActual;
154
+ const prints = `${unread.length} print${unread.length === 1 ? "" : "s"} excluded`;
155
+ return noActual && noForecast ? `${prints}: ${noActual} no actual, ${noForecast} no forecast.`
156
+ : `${prints}: no ${noActual ? "actual" : "forecast"}.`;
157
+ }
158
+
125
159
  /** What a row adds to its release's name: a policy decision's move, and the earnings marker. */
126
160
  export const macroDayEventNote = (event: Pick<MacroDayEvent, "earnings" | "figures">) =>
127
161
  [event.figures?.decision, event.earnings ? "(earnings)" : null].filter(Boolean).join(" ");
@@ -141,9 +175,12 @@ export function macroDayStats(events: readonly MacroDayEvent[], normalAbs: numbe
141
175
  return stats(events.filter((event) => !event.earnings).map((event) => event.move), normalAbs);
142
176
  }
143
177
 
144
- /** Whether a release day's print matches a surprise filter; `all` matches every day, figures or not. */
178
+ /**
179
+ * Whether a release day's print matches a surprise filter (`macroSurpriseOf`, the m/m print's where the headline has
180
+ * no actual); `all` matches every day, figures or not.
181
+ */
145
182
  export const matchesSurprise = (event: Pick<MacroDayEvent, "figures">, surprise: MacroSurprise | "all") =>
146
- surprise === "all" || event.figures?.surprise === surprise;
183
+ surprise === "all" || macroSurpriseOf(event.figures) === surprise;
147
184
 
148
185
  function stats(moves: number[], normalAbs: number | null): MacroDayStats {
149
186
  if (!moves.length) return { count: 0, meanAbs: null, mean: null, hitRate: null, multiple: null };
@@ -15,7 +15,7 @@ import { Box } from "../../../ui";
15
15
  import { loadMacroDayEarnings, loadMacroDayHistory, loadMacroReleases, macroDayEarningsNotice } from "./client";
16
16
  import {
17
17
  formatMacroDayMove, macroDayEventLabel, macroDayEventNote, macroDayMoveDecimals, macroDayStats, matchesSurprise, macroFigureGapNotices,
18
- projectMacroDays, type MacroDayEvent,
18
+ macroSurpriseBasisLabel, macroSurpriseExclusionNote, macroSurpriseOf, projectMacroDays, type MacroDayEvent,
19
19
  type MacroDayModel, type MacroDayMoveBasis,
20
20
  } from "./model";
21
21
  import { MACRO_EVENT_KINDS, MACRO_EVENT_LABELS, MACRO_SURPRISE_LABELS, MACRO_SURPRISES, staleMacroReleasesNotice, type MacroEventKind,
@@ -36,11 +36,24 @@ const moveColumns = (basis: MacroDayMoveBasis): DataTableColumn[] => [
36
36
  /** What each release came out with, under the labels the economic calendar gives them. */
37
37
  const FIGURES = [["actual", "Actual"], ["forecast", "Forecast"], ["prior", "Prior"]] as const;
38
38
 
39
- /** The figure columns, shown once any listed day has figures, each as wide as its header and its widest value. */
39
+ /**
40
+ * Whether the print came in hot, cool or in line, in words, so it never rests on the Actual's colour alone; a
41
+ * surprise read from another print than the headline's names it: "Hot (core m/m)".
42
+ */
43
+ export function macroSurpriseText(event: Pick<MacroDayEvent, "figures">): string {
44
+ const surprise = macroSurpriseOf(event.figures);
45
+ if (!surprise) return "";
46
+ const basis = macroSurpriseBasisLabel(event.figures);
47
+ return basis ? `${MACRO_SURPRISE_LABELS[surprise]} (${basis})` : MACRO_SURPRISE_LABELS[surprise];
48
+ }
49
+
50
+ /** The figure columns, shown once any listed day has figures, each as wide as its header and its widest value; Surprise after them. */
40
51
  function figureColumns(rows: readonly MacroDayEvent[]): DataTableColumn[] {
41
52
  if (!rows.some((event) => event.figures)) return [];
42
- return FIGURES.map(([id, label]) => ({ id, label, align: "right", width: tableColumnWidth({ label,
43
- width: Math.max(6, ...rows.map((event) => displayWidth(event.figures?.[id] ?? ""))) }) }));
53
+ return [...FIGURES.map(([id, label]): DataTableColumn => ({ id, label, align: "right", width: tableColumnWidth({ label,
54
+ width: Math.max(6, ...rows.map((event) => displayWidth(event.figures?.[id] ?? ""))) }) })),
55
+ { id: "surprise", label: "Surprise", align: "left", width: tableColumnWidth({ label: "Surprise",
56
+ width: Math.max(...rows.map((event) => displayWidth(macroSurpriseText(event)))) }) }];
44
57
  }
45
58
 
46
59
  /**
@@ -123,16 +136,20 @@ export function MacroDayPane({ width, height, focused }: PaneProps) {
123
136
  [history.data, lookback, symbol]);
124
137
  const releasesNotice = history.data ? staleMacroReleasesNotice(history.data.releases) : null;
125
138
  const earningsNotice = history.data ? macroDayEarningsNotice(history.data.earnings) : null;
126
- const rows = useMemo(() => model ? model.events.filter((event) => (release === "all" || event.kind === release)
127
- && matchesSurprise(event, surprise)) : [], [model, release, surprise]);
139
+ const scoped = useMemo(() => model ? model.events.filter((event) => release === "all" || event.kind === release) : [], [model, release]);
140
+ const rows = useMemo(() => scoped.filter((event) => matchesSurprise(event, surprise)), [scoped, surprise]);
141
+ // A surprise filter says how many days in scope it could not read: "3 prints excluded: no actual."
142
+ const excluded = useMemo(() => macroSurpriseExclusionNote(scoped, surprise), [scoped, surprise]);
128
143
  const stats = useMemo(() => !model?.events.length ? [] : surprise === "all" ? figures(model, release) : surpriseFigures(model, rows),
129
144
  [model, release, surprise, rows]);
130
145
  const columns = useMemo(() => columnsFor(release, rows, model?.basis), [model?.basis, release, rows]);
131
146
 
132
147
  // A covered release day the calendar left without figures says why; days before the calendar are the docs' to explain.
133
- const figureGaps = useMemo(() => macroFigureGapNotices(rows), [rows]);
148
+ // Why a listed day, or one the filter left out, has no actual.
149
+ const figureGaps = useMemo(() => macroFigureGapNotices(surprise === "all" ? rows : scoped.filter((event) => matchesSurprise(event, surprise)
150
+ || macroSurpriseOf(event.figures) == null)), [rows, scoped, surprise]);
134
151
  usePaneNoticeFooter({ registrationId: "macro-day-notices", focused,
135
- notices: [...new Set([identityError, history.error, history.data?.error, releasesNotice, earningsNotice, ...figureGaps]
152
+ notices: [...new Set([identityError, history.error, history.data?.error, releasesNotice, earningsNotice, excluded, ...figureGaps]
136
153
  .filter((value): value is string => !!value))] });
137
154
  usePaneFooter("macro-day", () => ({ info: [
138
155
  ...(history.loading ? [{ id: "loading", parts: [{ text: "loading history", tone: "muted" as const }] }] : []),
@@ -147,6 +164,7 @@ export function MacroDayPane({ width, height, focused }: PaneProps) {
147
164
  if (column.id === "actual") return { text: event.figures?.actual ?? "", color: event.figures?.surprise === "hot" ? colors.positive
148
165
  : event.figures?.surprise === "cool" ? colors.negative : undefined };
149
166
  if (column.id === "forecast") return { text: event.figures?.forecast ?? "" };
167
+ if (column.id === "surprise") return { text: macroSurpriseText(event) };
150
168
  if (column.id === "prior") return { text: event.figures?.prior ?? "" };
151
169
  if (column.id === "move") {
152
170
  const basis = model?.basis ?? "return";
@@ -62,6 +62,19 @@ export interface MacroReleaseFigures {
62
62
  computed?: string;
63
63
  /** Why a day with a consensus or a prior has no actual, where it cannot be computed either. */
64
64
  actualMissing?: string;
65
+ /**
66
+ * Where the headline has no actual (a CPI day without its y/y), the print its surprise is read from instead:
67
+ * core m/m, else m/m, against its own consensus. `surprise` stays the headline's own, null.
68
+ */
69
+ surpriseBasis?: MacroSurpriseBasis;
70
+ }
71
+
72
+ /** The print a day's surprise is read from when its headline has none: `core m/m`, 0.3% against 0.2%, hot. */
73
+ interface MacroSurpriseBasis {
74
+ basis: string;
75
+ actual: string;
76
+ forecast: string;
77
+ surprise: MacroSurprise;
65
78
  }
66
79
 
67
80
  export interface MacroRelease {
@@ -106,8 +119,18 @@ function servedFigures(value: unknown): MacroReleaseFigures | undefined {
106
119
  const decision = text(figures?.decision);
107
120
  const computed = text(figures?.computed);
108
121
  const actualMissing = text(figures?.actualMissing);
122
+ const surpriseBasis = servedSurpriseBasis(figures?.surpriseBasis);
109
123
  return { event, actual: text(figures?.actual), forecast: text(figures?.forecast), prior: text(figures?.prior), surprise,
110
- ...(decision ? { decision } : {}), ...(computed ? { computed } : {}), ...(actualMissing ? { actualMissing } : {}) };
124
+ ...(decision ? { decision } : {}), ...(computed ? { computed } : {}), ...(actualMissing ? { actualMissing } : {}),
125
+ ...(surpriseBasis ? { surpriseBasis } : {}) };
126
+ }
127
+
128
+ /** The print a surprise is read from as served, or undefined when it breaks the contract. */
129
+ function servedSurpriseBasis(value: unknown): MacroSurpriseBasis | undefined {
130
+ const served = value as Partial<Record<keyof MacroSurpriseBasis, unknown>> | null;
131
+ const basis = text(served?.basis), actual = text(served?.actual), forecast = text(served?.forecast);
132
+ const surprise = MACRO_SURPRISES.find((candidate) => candidate === served?.surprise);
133
+ return basis && actual && forecast && surprise ? { basis, actual, forecast, surprise } : undefined;
111
134
  }
112
135
 
113
136
  /**
@@ -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} />} />;
@@ -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)) {
@@ -104,6 +104,7 @@ async function addTickerToWatchlistCommand(
104
104
  notes,
105
105
  retry: (key) => `gloom watchlist add ${shellWord(watchlist.name)} ${key}`,
106
106
  add: (ticker) => addTickerToWatchlist(ticker, watchlist.id),
107
+ member: (ticker) => ticker.metadata.watchlists.includes(watchlist.id),
107
108
  });
108
109
  }
109
110
 
@@ -130,6 +131,7 @@ async function addToWatchlistCommand(args: string[], file: string | undefined, e
130
131
  suggest: true,
131
132
  dryRun,
132
133
  add: (ticker) => addTickerToWatchlist(ticker, watchlist.id),
134
+ member: (ticker) => ticker.metadata.watchlists.includes(watchlist.id),
133
135
  });
134
136
  printSymbolRows(ctx, rows, { verb: "add", collection: { kind: "watchlist", name: watchlist.name }, repeated: list.repeated, notes: list.notes, retry, dryRun });
135
137
  });