gloomberb 0.20.5 → 0.20.7

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 (185) hide show
  1. package/README.md +1 -1
  2. package/README.zh-CN.md +1 -1
  3. package/package.json +2 -1
  4. package/src/api-client/data.ts +10 -2
  5. package/src/api-client/fund-facts.ts +20 -4
  6. package/src/api-client/hk-tenders.ts +59 -0
  7. package/src/api-client/index.ts +1 -0
  8. package/src/api-client/socket.ts +4 -4
  9. package/src/api-client/types/econ.ts +20 -2
  10. package/src/app.tsx +18 -13
  11. package/src/architecture/floating-promise-allowlist.json +313 -0
  12. package/src/architecture/shortcut-labels-allowlist.json +1 -0
  13. package/src/cli/commands/market.ts +197 -57
  14. package/src/cli/commands/news-search.ts +22 -7
  15. package/src/cli/commands/overview.ts +12 -6
  16. package/src/cli/commands/search.ts +19 -3
  17. package/src/cli/commands/ticker.ts +3 -1
  18. package/src/cli/desktop-pane-shot.ts +61 -0
  19. package/src/cli/early-command.ts +2 -0
  20. package/src/cli/errors.ts +10 -1
  21. package/src/cli/fx-forward.ts +76 -12
  22. package/src/cli/fx-pair.ts +1 -1
  23. package/src/cli/fx-quote-rate.ts +23 -0
  24. package/src/cli/help.ts +1 -0
  25. package/src/cli/index-roots.ts +5 -4
  26. package/src/cli/index.ts +40 -3
  27. package/src/cli/known-gaps.ts +11 -8
  28. package/src/cli/listing-arg.ts +6 -4
  29. package/src/cli/options.ts +52 -3
  30. package/src/cli/output-file.ts +5 -3
  31. package/src/cli/pane-functions/catalog.ts +15 -0
  32. package/src/cli/pane-functions/dom.ts +4 -4
  33. package/src/cli/pane-functions/freshness.ts +38 -5
  34. package/src/cli/pane-functions/function-help.ts +4 -4
  35. package/src/cli/pane-functions/headless.ts +9 -4
  36. package/src/cli/pane-functions/index.ts +6 -4
  37. package/src/cli/pane-functions/resolver.ts +2 -2
  38. package/src/cli/pane-functions/screenshot-assessment.ts +16 -4
  39. package/src/cli/quote-answer.ts +57 -1
  40. package/src/cli/result.ts +38 -2
  41. package/src/cli/spreadsheet-hint.ts +7 -3
  42. package/src/cli/treasury-yields.ts +5 -3
  43. package/src/components/chart/composite/legend.tsx +40 -2
  44. package/src/components/command-bar/workflow/tickers.ts +2 -2
  45. package/src/components/data-table/view.tsx +9 -2
  46. package/src/components/ui/data-table/opentui/index.tsx +11 -4
  47. package/src/components/ui/data-table/opentui/model.ts +8 -6
  48. package/src/components/ui/data-table/types.ts +6 -1
  49. package/src/components/ui/table-layout.ts +38 -1
  50. package/src/docs/snapshot.json +58 -19
  51. package/src/i18n/es.ts +2 -0
  52. package/src/i18n/ja.ts +2 -0
  53. package/src/i18n/ko.ts +2 -0
  54. package/src/i18n/zh-cn.ts +2 -0
  55. package/src/i18n/zh-tw.ts +2 -0
  56. package/src/market-data/market/change-basis.ts +57 -12
  57. package/src/market-data/market/dated-previous-close.ts +184 -10
  58. package/src/market-data/market/freshness.ts +18 -6
  59. package/src/market-data/market/status.ts +9 -1
  60. package/src/market-data/published-nse-sessions.ts +16 -1
  61. package/src/market-data/quotes/contributions.ts +2 -0
  62. package/src/market-data/quotes/freshness.ts +15 -0
  63. package/src/market-data/quotes/listing-enterprise-value.ts +50 -0
  64. package/src/plugins/builtin/alerts/alert-engine.ts +15 -0
  65. package/src/plugins/builtin/alerts/cli.ts +22 -9
  66. package/src/plugins/builtin/alerts/headless.ts +1 -1
  67. package/src/plugins/builtin/alerts/index.tsx +5 -1
  68. package/src/plugins/builtin/alerts/metric-command.ts +1 -1
  69. package/src/plugins/builtin/alerts/metric-data.ts +15 -2
  70. package/src/plugins/builtin/backtest/headless.ts +1 -1
  71. package/src/plugins/builtin/cds/model.ts +0 -6
  72. package/src/plugins/builtin/chart-composer/formula.ts +16 -3
  73. package/src/plugins/builtin/chart-composer/headless-schema.ts +2 -0
  74. package/src/plugins/builtin/chart-composer/headless.ts +2 -1
  75. package/src/plugins/builtin/chart-composer/presets.ts +1 -0
  76. package/src/plugins/builtin/cloud/askg/pane.tsx +55 -13
  77. package/src/plugins/builtin/credit-boards/cdx-pane.tsx +20 -7
  78. package/src/plugins/builtin/credit-boards/client.ts +8 -0
  79. package/src/plugins/builtin/credit-boards/headless.ts +4 -1
  80. package/src/plugins/builtin/credit-boards/model.ts +58 -4
  81. package/src/plugins/builtin/credit-boards/series.ts +63 -6
  82. package/src/plugins/builtin/credit-boards/sovr-pane.tsx +3 -2
  83. package/src/plugins/builtin/credit-conditions/headless.ts +24 -6
  84. package/src/plugins/builtin/credit-conditions/index.tsx +1 -1
  85. package/src/plugins/builtin/credit-conditions/model.ts +12 -6
  86. package/src/plugins/builtin/credit-conditions/series.ts +2 -1
  87. package/src/plugins/builtin/econ/calendar-model.ts +41 -7
  88. package/src/plugins/builtin/econ/calendar-source.ts +7 -1
  89. package/src/plugins/builtin/econ/index.tsx +41 -8
  90. package/src/plugins/builtin/econ/types.ts +3 -0
  91. package/src/plugins/builtin/fixed-income/index.tsx +2 -0
  92. package/src/plugins/builtin/fx-matrix/index.tsx +44 -14
  93. package/src/plugins/builtin/help/keybindings-editor.tsx +6 -2
  94. package/src/plugins/builtin/holders/fund-holders.ts +22 -1
  95. package/src/plugins/builtin/holders/headless.ts +5 -4
  96. package/src/plugins/builtin/holders/pane.tsx +7 -3
  97. package/src/plugins/builtin/holders/report-header.ts +23 -0
  98. package/src/plugins/builtin/members/client.ts +1 -1
  99. package/src/plugins/builtin/members/headless.ts +2 -0
  100. package/src/plugins/builtin/members/model.ts +10 -8
  101. package/src/plugins/builtin/members/pane.tsx +4 -1
  102. package/src/plugins/builtin/portfolio-list/cli/portfolio-command.ts +5 -2
  103. package/src/plugins/builtin/portfolio-list/cli/render.ts +86 -26
  104. package/src/plugins/builtin/portfolio-list/cli/watchlist-command.ts +5 -1
  105. package/src/plugins/builtin/portfolio-list/headless.ts +2 -1
  106. package/src/plugins/builtin/portfolio-list/income.ts +46 -22
  107. package/src/plugins/builtin/portfolio-list/pane/data.ts +16 -6
  108. package/src/plugins/builtin/portfolio-list/pane/index.tsx +5 -4
  109. package/src/plugins/builtin/portfolio-list/use-throttled-ticker-order.ts +40 -3
  110. package/src/plugins/builtin/research/headless-schema.ts +4 -3
  111. package/src/plugins/builtin/research/relative-valuation-columns.ts +145 -47
  112. package/src/plugins/builtin/research/relative-valuation-currency.ts +31 -0
  113. package/src/plugins/builtin/research/relative-valuation-headless.ts +25 -8
  114. package/src/plugins/builtin/research/relative-valuation-model.ts +40 -9
  115. package/src/plugins/builtin/research/relative-valuation-pane.tsx +3 -2
  116. package/src/plugins/builtin/research/relative-valuation-peers.ts +2 -2
  117. package/src/plugins/builtin/sec/fund-facts.ts +25 -5
  118. package/src/plugins/builtin/shared/report-freshness.ts +15 -6
  119. package/src/plugins/builtin/supply-chain/model.ts +18 -6
  120. package/src/plugins/builtin/thirteenf/api.ts +47 -4
  121. package/src/plugins/builtin/ticker-detail/data-panes/historical-prices.tsx +8 -7
  122. package/src/plugins/builtin/ticker-detail/data-panes/history-bars.ts +8 -5
  123. package/src/plugins/builtin/ticker-detail/financials/model.ts +6 -2
  124. package/src/plugins/builtin/ticker-detail/financials/tab.tsx +1 -1
  125. package/src/plugins/builtin/ticker-detail/headless.ts +6 -4
  126. package/src/plugins/builtin/treasury-auctions/cache.ts +36 -2
  127. package/src/plugins/builtin/treasury-auctions/headless.ts +42 -4
  128. package/src/plugins/builtin/treasury-auctions/hk-headless.ts +126 -0
  129. package/src/plugins/builtin/treasury-auctions/hk-view.tsx +347 -0
  130. package/src/plugins/builtin/treasury-auctions/hk.ts +363 -0
  131. package/src/plugins/builtin/treasury-auctions/index.tsx +14 -1
  132. package/src/plugins/builtin/treasury-auctions/model.ts +16 -8
  133. package/src/plugins/builtin/treasury-auctions/pane.tsx +45 -21
  134. package/src/portfolio/collection-name.ts +22 -0
  135. package/src/portfolio/column-values.ts +3 -0
  136. package/src/portfolio/valuation-basis.ts +23 -1
  137. package/src/renderers/dom/data-table/frozen-column.ts +3 -1
  138. package/src/renderers/dom/data-table/index.tsx +27 -9
  139. package/src/renderers/dom/data-table/row.tsx +2 -0
  140. package/src/renderers/electrobun/bun/desktop/backend.ts +27 -24
  141. package/src/renderers/electrobun/bun/desktop/detached-windows.ts +3 -3
  142. package/src/renderers/electrobun/bun/desktop/snapshot-commit.ts +77 -0
  143. package/src/renderers/electrobun/shared/protocol.ts +4 -0
  144. package/src/renderers/electrobun/view/backend-rpc.ts +3 -0
  145. package/src/renderers/electrobun/view/desktop/window/bridge.ts +3 -0
  146. package/src/sources/gloomberb-cloud/normalizers.ts +9 -5
  147. package/src/sources/provider-router/cache.ts +3 -1
  148. package/src/state/hooks/quote-streaming.ts +14 -6
  149. package/src/sync/controller.ts +17 -2
  150. package/src/sync/other-window-tabs.ts +32 -1
  151. package/src/sync/react.ts +4 -4
  152. package/src/tickers/instrument-kind.ts +22 -1
  153. package/src/tickers/search/index.ts +5 -0
  154. package/src/tickers/terminal-codes.ts +17 -5
  155. package/src/time-series/bar-spacing.ts +33 -0
  156. package/src/time-series/base-series.ts +21 -3
  157. package/src/time-series/chart-bounds.ts +31 -0
  158. package/src/time-series/field-catalog.ts +17 -0
  159. package/src/time-series/fundamentals/current-valuation.ts +244 -0
  160. package/src/time-series/fundamentals/historical-valuation.ts +99 -0
  161. package/src/time-series/fundamentals/metric-ids.ts +61 -0
  162. package/src/time-series/fundamentals/period-points.ts +104 -0
  163. package/src/time-series/fundamentals/quarterly-ttm.ts +220 -0
  164. package/src/time-series/fundamentals/series.ts +164 -0
  165. package/src/time-series/fundamentals/source-statements.ts +177 -0
  166. package/src/time-series/fundamentals/statement-fields.ts +154 -0
  167. package/src/time-series/fundamentals/statement-merge.ts +124 -0
  168. package/src/time-series/fundamentals/statement.ts +114 -0
  169. package/src/time-series/fundamentals/valuation-multiples.ts +50 -0
  170. package/src/time-series/fundamentals.ts +18 -1275
  171. package/src/time-series/ice-credit.ts +32 -6
  172. package/src/time-series/resolve.ts +9 -5
  173. package/src/time-series/session-bar.ts +78 -9
  174. package/src/time-series/studies/formula.ts +53 -10
  175. package/src/time-series/studies/pair.ts +18 -7
  176. package/src/time-series/studies/units.ts +49 -2
  177. package/src/time-series/types.ts +12 -0
  178. package/src/types/desktop-window.ts +2 -0
  179. package/src/types/financials.ts +15 -0
  180. package/src/types/headless.ts +8 -0
  181. package/src/utils/cli-output.ts +6 -3
  182. package/src/utils/debug-log.ts +29 -0
  183. package/src/utils/ebitda.ts +128 -0
  184. package/src/utils/format.ts +1 -1
  185. package/src/utils/shell-word.ts +13 -0
@@ -29,17 +29,31 @@ export function newsSearchText(args: readonly string[]): string | null {
29
29
  /** How to type a word as text to search from a shell: `'"gold"'` keeps the quotes a shell would drop. */
30
30
  export const quotedSearchCommand = (word: string) => `gloom news '"${word}"'`;
31
31
 
32
+ /**
33
+ * The words of a company's name, lower-cased, each run of letters split where
34
+ * its case changes from lower to upper: "PesoRama Inc." is peso, rama and inc.
35
+ */
36
+ function companyNameWords(companyName: string): string[] {
37
+ return companyName
38
+ .replace(/(\p{Ll})(\p{Lu})/gu, "$1 $2")
39
+ .toLowerCase()
40
+ .split(/[^a-z]+/)
41
+ .filter(Boolean);
42
+ }
43
+
32
44
  /**
33
45
  * Whether a word typed for `news` may mean more than the listing it found:
34
46
  * a plain word (letters only, three or more, typed with a lower-case letter,
35
- * as a word is and a ticker rarely is) that is one of the words of the
36
- * company's name ("gold" for Gold.com Inc., "gap" for The Gap). The stories
37
- * then decide (`wordMeansMore`).
47
+ * as a word is and a ticker rarely is) that is a whole word of the company's
48
+ * name, the name split at its case changes too ("gold" for Gold.com Inc.,
49
+ * "gap" for The Gap, "peso" for PesoRama Inc.); a word a name only starts
50
+ * with ("cost" in Costco, "app" in AppLovin) is not. The stories then decide
51
+ * (`wordMeansMore`).
38
52
  */
39
53
  export function commonWordCandidate(typed: string, companyName: string | null | undefined): boolean {
40
54
  const word = typed.trim();
41
55
  if (!/^[A-Za-z]{3,}$/.test(word) || !/[a-z]/.test(word) || !companyName) return false;
42
- return companyName.toLowerCase().split(/[^a-z]+/).includes(word.toLowerCase());
56
+ return companyNameWords(companyName).includes(word.toLowerCase());
43
57
  }
44
58
 
45
59
  /**
@@ -48,10 +62,11 @@ export function commonWordCandidate(typed: string, companyName: string | null |
48
62
  * them filed under the ticker. "gold" is mostly the metal's market; "meta"
49
63
  * is mostly Meta Platforms.
50
64
  */
51
- export function wordMeansMore(stories: readonly NewsArticle[], symbol: string): boolean {
65
+ export function wordMeansMore(stories: readonly NewsArticle[], symbol: string, key = symbol): boolean {
52
66
  if (stories.length < 3) return false;
53
- const ticker = symbol.toUpperCase();
54
- const filed = stories.filter((story) => (story.tickers ?? []).some((entry) => entry.toUpperCase() === ticker)).length;
67
+ // A listing outside the US is tagged with its venue (PESO:TSXV), a US one bare.
68
+ const tickers = new Set([symbol.toUpperCase(), key.toUpperCase()]);
69
+ const filed = stories.filter((story) => (story.tickers ?? []).some((entry) => tickers.has(entry.toUpperCase()))).length;
55
70
  return filed * 2 < stories.length;
56
71
  }
57
72
 
@@ -49,6 +49,8 @@ import {
49
49
  NO_CONSENSUS_NOTE,
50
50
  noScheduledReleasesMessage,
51
51
  parseCountryFilter,
52
+ listingEnd,
53
+ pastReleaseListing,
52
54
  shortCalendarEnd,
53
55
  type CountryFilter,
54
56
  type ImpactFilter,
@@ -524,10 +526,10 @@ async function runEcon(args: string[], ctx: Parameters<CliCommandDef["execute"]>
524
526
  // alone keeps the newest events of the whole calendar, the past week's too.
525
527
  const from = fromOption ?? (ctx.cliOptions.tail != null ? null : new Date(todayStart).toISOString().slice(0, 10));
526
528
  const fromTime = from == null ? Number.NEGATIVE_INFINITY : Date.parse(`${from}T00:00:00Z`);
527
- const lastEvent = events.reduce<Date | null>((last, event) => (!last || event.date > last ? event.date : last), null);
528
- const listedThrough = lastEvent ? lastEvent.toISOString().slice(0, 10) : null;
529
+ // The last day the listing reaches, as Gloom Cloud says it: past it, it lists each central bank's next decision.
530
+ const listedThrough = listingEnd(events, past?.listedThrough);
529
531
  // A calendar that stops short of a week ahead says so under the table.
530
- const listedAfter = shortCalendarEnd(events, Math.max(todayStart, fromTime)) ? `No events listed after ${listedThrough}` : null;
532
+ const listedAfter = shortCalendarEnd(events, Math.max(todayStart, fromTime), past?.listedThrough) ? `No events listed after ${listedThrough}` : null;
531
533
  // A day before anything the calendar holds says where its listing starts.
532
534
  const firstEvent = events.reduce<Date | null>((first, event) => (!first || event.date < first ? event.date : first), null);
533
535
  const listedFrom = firstEvent ? firstEvent.toISOString().slice(0, 10) : null;
@@ -586,9 +588,13 @@ async function runEcon(args: string[], ctx: Parameters<CliCommandDef["execute"]>
586
588
  consensusReadAt: event.consensus?.readAt ?? null,
587
589
  };
588
590
  });
589
- // A filter of countries only, none of which has anything in the window, says so as its empty list.
591
+ // A filter of countries only, none of which has anything in the window, says so as its empty list, with where
592
+ // the listing ends.
590
593
  const allUnscheduled = unscheduled.length > 0 && unscheduled.length === country.split(",").length;
591
- const notes = [listedBefore, listedAfter, ...(rows.length > 0 ? blankTimeNotes(rows) : []),
594
+ // Rows after the listing's end are each bank's next decision, and say so where the end is said.
595
+ const listedPast = listed.some(pastReleaseListing)
596
+ ? `No releases listed after ${listedThrough}; the rows after it are each central bank's next decision` : null;
597
+ const notes = [listedBefore, listedPast ?? listedAfter, ...(rows.length > 0 ? blankTimeNotes(rows) : []),
592
598
  rows.length > 0 && unscheduled.length > 0 ? noScheduledReleasesMessage(unscheduled) : null,
593
599
  // A dash under Forecast on a release still to come is a consensus not in yet, not a missing figure.
594
600
  listed.some(awaitsConsensus) ? NO_CONSENSUS_NOTE : null]
@@ -606,7 +612,7 @@ async function runEcon(args: string[], ctx: Parameters<CliCommandDef["execute"]>
606
612
  }, {
607
613
  dateKey: "date",
608
614
  defaultLimit: 50,
609
- empty: allUnscheduled ? noScheduledReleasesMessage(unscheduled)
615
+ empty: allUnscheduled ? noScheduledReleasesMessage(unscheduled, listedThrough)
610
616
  : [econEmptyMessage(from, listedThrough, listedAfter != null), search == null ? null : policyDecisionHint(search, country)].filter(Boolean).join(" "),
611
617
  ...(footnote ? { footnote } : {}),
612
618
  // What the text says under the table, a script reads in the CSV's closing lines.
@@ -424,7 +424,7 @@ function resolveSearchName(candidate: TickerSearchCandidate): string {
424
424
  function searchType(candidate: TickerSearchCandidate): string | undefined {
425
425
  return instrumentTypeLabel(candidate.result?.type
426
426
  || candidate.result?.brokerContract?.secType
427
- || candidate.ticker?.metadata.assetCategory, resolveSearchName(candidate));
427
+ || candidate.ticker?.metadata.assetCategory, resolveSearchName(candidate), { symbol: candidate.symbol });
428
428
  }
429
429
 
430
430
  /** What `--json` lists for a symbol search no longer lists: its category says so, and it keeps its last date and price. */
@@ -502,9 +502,25 @@ function catalogHint(query: string): string {
502
502
  /** What a search for a name in another script (任天堂) that found nothing says: listings are named in Latin letters. */
503
503
  const OTHER_SCRIPT_NO_MATCH = "No matches. Try the ticker or the English name.";
504
504
 
505
+ /** Words that say a query names a fund, which a fund's own name can hold anywhere ("Nippon India ETF Nifty IT"). */
506
+ const FUND_WORDS = new Set(["ETF", "ETFS", "ETN", "ETNS", "FUND", "FUNDS", "UCITS", "TRUST", "INDEX"]);
507
+
508
+ /**
509
+ * For a fund's name of three words or more that found nothing: try fewer, the
510
+ * first half of the others with the fund's word, as a fund can word its name
511
+ * in another order. Null for any other query.
512
+ */
513
+ function fundSearchHint(query: string): string | null {
514
+ const words = query.replace(/"/g, "").trim().split(/\s+/).filter(Boolean);
515
+ const fund = words.filter((word) => FUND_WORDS.has(word.toUpperCase()));
516
+ const rest = words.filter((word) => !FUND_WORDS.has(word.toUpperCase()));
517
+ if (words.length < 3 || fund.length === 0 || rest.length < 2) return null;
518
+ return `A fund's name can put its words in another order. Try fewer words: gloom search "${[...rest.slice(0, Math.ceil(rest.length / 2)), ...fund].join(" ")}"`;
519
+ }
520
+
505
521
  /** The line an empty search ends with: where else to look, or for a name in another script, what to type instead. */
506
522
  function emptySearchHint(query: string): string {
507
- return hasNonLatinLetters(query) ? OTHER_SCRIPT_NO_MATCH : catalogHint(query);
523
+ return hasNonLatinLetters(query) ? OTHER_SCRIPT_NO_MATCH : fundSearchHint(query) ?? catalogHint(query);
508
524
  }
509
525
 
510
526
  /**
@@ -589,7 +605,7 @@ export function buildSearchReport({
589
605
  if (functions.length > 0) lines.push("", renderFunctionMatches(functions));
590
606
  else if (!gap && !bank && !setting && !charted) {
591
607
  return [...lines, ...hasNonLatinLetters(query) ? [cliStyles.muted(OTHER_SCRIPT_NO_MATCH)]
592
- : [cliStyles.muted("No matches found."), cliStyles.muted(wrapToTerminal(catalogHint(query)))]].join("\n");
608
+ : [cliStyles.muted("No matches found."), cliStyles.muted(wrapToTerminal(emptySearchHint(query)))]].join("\n");
593
609
  }
594
610
  if (pointToCatalog) lines.push("", cliStyles.muted(wrapToTerminal(catalogHint(query))));
595
611
  return lines.join("\n");
@@ -1,4 +1,5 @@
1
1
  import { logFailure } from "../../utils/log-failure";
2
+ import { ebitdaLacksDepreciation } from "../../utils/ebitda";
2
3
  import { formatShortDate, parseDisplayDate } from "../../utils/datetime-format";
3
4
  import { formatReportedMoney, REPORTING_CURRENCY_NOT_SOURCED } from "../../utils/reported-money";
4
5
  import {
@@ -226,7 +227,8 @@ function buildStatementMetrics(
226
227
  ["Net Income", netIncome],
227
228
  ["Income incl. NCI", income(statement.netIncomeIncludingNoncontrollingInterests)],
228
229
  ["Income Common", income(statement.netIncomeCommonStockholders)],
229
- ["EBITDA", money(statement.ebitda)],
230
+ // Operating income plus D&A; without D&A there is none, and the line says why.
231
+ ["EBITDA", ebitdaLacksDepreciation(statement) ? "no D&A" : money(statement.ebitda)],
230
232
  ["Operating Cash Flow", money(statement.operatingCashFlow)],
231
233
  ["Free Cash Flow", money(statement.freeCashFlow)],
232
234
  ["Cash", balance("cashAndCashEquivalents")],
@@ -165,6 +165,12 @@ export interface DesktopPaneShotRenderResult {
165
165
  * capture shows. Absent when every table is read from the viewport.
166
166
  */
167
167
  reportRows?: DesktopPaneShotRenderedRow[];
168
+ /**
169
+ * The rows each visible table holds, by `tableIndex`, drawn or not (the
170
+ * table's `rowCount`); null for a table that does not say. With `rows`, what
171
+ * a capture that cuts a list says it shows: "36 of 76 rows".
172
+ */
173
+ tableRowTotals?: Array<number | null>;
168
174
  /** `truncationReasons` without the cuts of tables whose every row is in `reportRows`. */
169
175
  reportTruncationReasons?: string[];
170
176
  /** Text of the pane footers, where a pane says whether its data is live, delayed or stale. */
@@ -596,6 +602,7 @@ async function capturePageScreenshot({
596
602
  await browser.open(url);
597
603
  await waitForShotReady(session);
598
604
  if (fitRows) await growToFitRows(session, { widthPx, heightPx, deviceScaleFactor, ...fitRows });
605
+ if (captureImage) await hideCutRows(session);
599
606
  const rendered = await readRenderedPaneState(session);
600
607
  if (captureImage && statusLine) {
601
608
  const line = await statusLine(rendered);
@@ -658,6 +665,52 @@ async function growToFitRows(session: CdpPage, size: {
658
665
  await waitForShotReady(session);
659
666
  }
660
667
 
668
+ /**
669
+ * An image ends on a whole row: a row its list's scroll box cuts at the
670
+ * bottom edge is hidden, and so is one wholly outside the box, which the
671
+ * box already clips but the row count would read. A row with no whole row
672
+ * above it stays, cut, rather than leave the list blank. The live pane keeps
673
+ * its partly visible last row, as every scrolling list reads.
674
+ */
675
+ async function hideCutRows(session: CdpPage): Promise<void> {
676
+ await session.send("Runtime.evaluate", {
677
+ expression: `(() => {
678
+ const root = document.getElementById("root") || document.body;
679
+ const rows = [...root.querySelectorAll(
680
+ '[data-gloom-role="data-table-row"], [data-gloom-role="data-table-section-header"], [data-gloom-role="desktop-list-row"], [data-gloom-row="true"]',
681
+ )];
682
+ const clips = (element) => {
683
+ const style = getComputedStyle(element);
684
+ return /(auto|scroll|hidden|clip)/.test(style.overflowY) && element.clientHeight > 0;
685
+ };
686
+ const wholeAbove = new Map();
687
+ const cut = [];
688
+ for (const row of rows) {
689
+ let box = row.parentElement;
690
+ while (box && box !== root && !clips(box)) box = box.parentElement;
691
+ if (!box || box === root) continue;
692
+ const area = box.getBoundingClientRect();
693
+ // The box's visible height: a horizontal scrollbar takes its own rows.
694
+ const bottom = area.top + box.clientTop + box.clientHeight;
695
+ const rect = row.getBoundingClientRect();
696
+ if (rect.height <= 0) continue;
697
+ if (rect.bottom <= area.top + 1 || rect.top >= bottom - 1) {
698
+ cut.push(row);
699
+ } else if (rect.top >= area.top - 1 && rect.bottom <= bottom + 1) {
700
+ wholeAbove.set(box, true);
701
+ } else if (rect.bottom > bottom + 1) {
702
+ cut.push({ row, box });
703
+ }
704
+ }
705
+ for (const entry of cut) {
706
+ if (entry instanceof Element) entry.style.visibility = "hidden";
707
+ else if (wholeAbove.get(entry.box)) entry.row.style.visibility = "hidden";
708
+ }
709
+ })()`,
710
+ returnByValue: true,
711
+ });
712
+ }
713
+
661
714
  const LOADING_STATE_PATTERNS = [
662
715
  /\bLoading(?: [^.]{0,80})?\.{3}/gi,
663
716
  /\bRendering pane\.{3}/gi,
@@ -865,6 +918,10 @@ async function readRenderedPaneState(session: CdpPage): Promise<DesktopPaneShotR
865
918
  truncated: truncationReasons.size > 0,
866
919
  truncationReasons: [...truncationReasons],
867
920
  ...(reportedTables.size > 0 ? { reportRows, reportTruncationReasons: [...reportTruncationReasons] } : {}),
921
+ tableRowTotals: visibleTables.map((_table, tableIndex) => {
922
+ const metadata = semanticTables[tableIndex] && semanticTables[tableIndex].metadata;
923
+ return metadata && typeof metadata.rowCount === "number" ? metadata.rowCount : null;
924
+ }),
868
925
  semanticUi,
869
926
  };
870
927
  })()`,
@@ -886,6 +943,7 @@ async function readRenderedPaneState(session: CdpPage): Promise<DesktopPaneShotR
886
943
  truncationReasons?: string[];
887
944
  reportRows?: DesktopPaneShotRenderedRow[];
888
945
  reportTruncationReasons?: string[];
946
+ tableRowTotals?: Array<number | null>;
889
947
  semanticUi?: RemoteUiNodeSnapshot[];
890
948
  };
891
949
  };
@@ -922,6 +980,9 @@ async function readRenderedPaneState(session: CdpPage): Promise<DesktopPaneShotR
922
980
  reportRows: value.reportRows,
923
981
  reportTruncationReasons: (value.reportTruncationReasons ?? []).filter((reason): reason is string => typeof reason === "string"),
924
982
  } : {}),
983
+ ...(Array.isArray(value?.tableRowTotals) && value.tableRowTotals.length > 0 ? {
984
+ tableRowTotals: value.tableRowTotals.map((total) => typeof total === "number" && Number.isFinite(total) ? total : null),
985
+ } : {}),
925
986
  loadingStateDetected: value?.loadingStateDetected === true || loadingStateMarkers.length > 0,
926
987
  errorStateDetected: value?.errorStateDetected === true || errorStateMarkers.length > 0,
927
988
  errorStateMarkers,
@@ -18,6 +18,8 @@ export async function dispatchEarlyCommand(args: string[]): Promise<boolean> {
18
18
  }
19
19
  const token = foldTypedText(parsed.args[0] ?? "").trim().toLowerCase();
20
20
  if (token !== versionCommand.name && !versionCommand.aliases?.includes(token)) return false;
21
+ // A file to write is the regular dispatcher's to save.
22
+ if (parsed.options.output !== undefined) return false;
21
23
  const options = parsed.options;
22
24
  setCliColorEnabledOverride(options.color);
23
25
  setCliWidthOverride(options.width ?? null);
package/src/cli/errors.ts CHANGED
@@ -26,6 +26,15 @@ function unreachableHint(): string {
26
26
  : "Check the internet connection, then try again.";
27
27
  }
28
28
 
29
+ /**
30
+ * An answer of the data service that a source it reads failed and nothing it
31
+ * kept could stand in (the 13F source down): the service was reached, and
32
+ * asked again later it may answer.
33
+ */
34
+ export function isSourceUnavailableAnswer(error: unknown): error is ApiRequestError {
35
+ return error instanceof ApiRequestError && error.code === SOURCE_UNAVAILABLE_CODE;
36
+ }
37
+
29
38
  export interface CliErrorContext {
30
39
  /** The command that failed, used to point at its help. */
31
40
  command?: string;
@@ -124,7 +133,7 @@ function cliErrorObject(error: unknown): CliErrorObject {
124
133
  return unreachableError();
125
134
  }
126
135
  // A source failed (a timeout, a rate limit) where none had the data to answer: asked again it may.
127
- if (isSourceFailure(error)) {
136
+ if (isSourceFailure(error) || isSourceUnavailableAnswer(error)) {
128
137
  return { code: SOURCE_UNAVAILABLE_CODE, message: error instanceof Error ? error.message : String(error), retryable: true };
129
138
  }
130
139
  // A listing read the data service failed to answer twice: said in Gloom's words. Any other 5xx keeps the server's.
@@ -61,6 +61,9 @@ export interface ImpliedForward {
61
61
  premiumPercent: number;
62
62
  /** The same premium a year: `premiumPercent` × 360 / days. */
63
63
  annualizedPercent: number;
64
+ /** What one unit of the base and of the quote currency grows to over the tenor at its own rate. */
65
+ baseGrowth: number;
66
+ quoteGrowth: number;
64
67
  }
65
68
 
66
69
  /**
@@ -75,7 +78,9 @@ export function impliedForward(
75
78
  base: Pick<CloudShortRate, "dayCountBasis" | "compounding"> & { value: number },
76
79
  quote: Pick<CloudShortRate, "dayCountBasis" | "compounding"> & { value: number; currency: string },
77
80
  ): ImpliedForward {
78
- const forward = spot * shortRateGrowth(quote, days) / shortRateGrowth(base, days);
81
+ const baseGrowth = shortRateGrowth(base, days);
82
+ const quoteGrowth = shortRateGrowth(quote, days);
83
+ const forward = spot * quoteGrowth / baseGrowth;
79
84
  const pointSize = forwardPointSize(quote.currency);
80
85
  const premiumPercent = (forward / spot - 1) * 100;
81
86
  return {
@@ -85,25 +90,32 @@ export function impliedForward(
85
90
  pointSize,
86
91
  premiumPercent,
87
92
  annualizedPercent: premiumPercent * 360 / days,
93
+ baseGrowth,
94
+ quoteGrowth,
88
95
  };
89
96
  }
90
97
 
91
98
  /**
92
99
  * What one unit grows to over `days` at a short rate: simple interest on its
93
- * day count, or, for a rate compounded over 252 business days (CDI),
94
- * (1 + r)^(days / 365), business days taken as 252/365 of the calendar days.
100
+ * day count; for a rate compounded over 252 business days (CDI),
101
+ * (1 + r)^(days / 365), business days taken as 252/365 of the calendar days;
102
+ * for one compounded daily on ACT/365 (ZARONIA), (1 + r / 365)^days.
95
103
  */
96
104
  function shortRateGrowth(rate: Pick<CloudShortRate, "dayCountBasis" | "compounding"> & { value: number }, days: number): number {
97
- return rate.compounding === "business-252"
98
- ? (1 + rate.value / 100) ** (days / 365)
99
- : 1 + (rate.value / 100) * days / rate.dayCountBasis;
105
+ if (rate.compounding === "business-252") return (1 + rate.value / 100) ** (days / 365);
106
+ if (rate.compounding === "daily-365") return (1 + rate.value / 100 / 365) ** days;
107
+ return 1 + (rate.value / 100) * days / rate.dayCountBasis;
100
108
  }
101
109
 
102
- /** `(1 + 3.92% × 92/360)`, or `(1 + 13.65%)^(92/365)` for a compounded rate: one leg of the parity, as `fx --forward` prints it. */
110
+ /**
111
+ * `(1 + 3.92% × 92/360)`, `(1 + 13.65%)^(92/365)` for a rate compounded over
112
+ * business days, `(1 + 7.099%/365)^92` for one compounded daily: one leg of
113
+ * the parity, as `fx --forward` prints it.
114
+ */
103
115
  export function shortRateGrowthText(rate: Pick<CloudShortRate, "dayCountBasis" | "compounding"> & { value: number }, days: number): string {
104
- return rate.compounding === "business-252"
105
- ? `(1 + ${formatRatePercent(rate.value)})^(${days}/365)`
106
- : `(1 + ${formatRatePercent(rate.value)} × ${days}/${rate.dayCountBasis})`;
116
+ if (rate.compounding === "business-252") return `(1 + ${formatRatePercent(rate.value)})^(${days}/365)`;
117
+ if (rate.compounding === "daily-365") return `(1 + ${formatRatePercent(rate.value)}/365)^${days}`;
118
+ return `(1 + ${formatRatePercent(rate.value)} × ${days}/${rate.dayCountBasis})`;
107
119
  }
108
120
 
109
121
  /** A rate the forward can use: listed for the currency, with a value. */
@@ -141,8 +153,60 @@ export function formatForwardPoints(points: number): string {
141
153
  return `${points >= 0 ? "+" : ""}${points.toFixed(1)}`;
142
154
  }
143
155
 
144
- /** `TIIE 28d 6.776% (Banco de México, 2026-10-20; ACT/360)`, `CDI 13.65% (Banco Central do Brasil, 2026-11-05; BUS/252 compounded)`. */
156
+ /**
157
+ * `TIIE 28d 6.776% (Banco de México, 2026-10-20; ACT/360)`, `CDI 13.65% (Banco Central do Brasil, 2026-11-05; BUS/252 compounded)`,
158
+ * `ZARONIA 7.099% (South African Reserve Bank, 2026-11-05; ACT/365 compounded daily)`.
159
+ */
145
160
  export function describeShortRate(rate: CloudShortRate & { value: number }): string {
146
- const basis = rate.compounding === "business-252" ? "BUS/252 compounded" : `ACT/${rate.dayCountBasis}`;
161
+ const basis = rate.compounding === "business-252" ? "BUS/252 compounded"
162
+ : rate.compounding === "daily-365" ? "ACT/365 compounded daily" : `ACT/${rate.dayCountBasis}`;
147
163
  return `${rate.name} ${formatRatePercent(rate.value)} (${rate.publisher}, ${rate.asOf ?? "undated"}; ${basis})`;
148
164
  }
165
+
166
+ /**
167
+ * The carry of a forward on an amount of the pair's base currency, above
168
+ * zero: the forward points on it over the tenor, in the quote currency. The
169
+ * side that holds the currency whose rate earns more over the tenor (the
170
+ * larger growth factor) earns it: with the forward above spot, the seller of
171
+ * the base currency forward (short the pair); below spot, the buyer (long).
172
+ * A forward at spot has no carry.
173
+ */
174
+ export interface ForwardCarry {
175
+ /** The amount, in the pair's base currency. */
176
+ amount: number;
177
+ /** Amount × |forward - spot|, in the quote currency: what one side pays the other. */
178
+ value: number;
179
+ /** The side that earns it; null when the forward is at spot. */
180
+ earnedBy: "long" | "short" | null;
181
+ /** The currency whose rate earns more over the tenor, from the two growth factors; null when they are equal. */
182
+ higher: "base" | "quote" | null;
183
+ }
184
+
185
+ export function forwardCarry(
186
+ amount: number,
187
+ implied: Pick<ImpliedForward, "spot" | "forward" | "baseGrowth" | "quoteGrowth">,
188
+ ): ForwardCarry {
189
+ const difference = implied.forward - implied.spot;
190
+ return {
191
+ amount,
192
+ value: Math.abs(amount * difference),
193
+ earnedBy: difference > 0 ? "short" : difference < 0 ? "long" : null,
194
+ higher: implied.quoteGrowth > implied.baseGrowth ? "quote" : implied.quoteGrowth < implied.baseGrowth ? "base" : null,
195
+ };
196
+ }
197
+
198
+ /**
199
+ * Who earns the carry and who pays it, by side of the pair: `Short USD/MXN
200
+ * (selling USD forward) earns it and long USD/MXN (buying USD forward) pays
201
+ * it: MXN's rate earns more over the 30 days.` A forward at spot has none.
202
+ */
203
+ export function describeCarrySides(carry: ForwardCarry, base: string, quote: string, days: number): string {
204
+ if (carry.earnedBy == null || carry.higher == null) {
205
+ return `No carry: at these rates ${base} and ${quote} earn the same over the ${days} days, so the forward is at spot.`;
206
+ }
207
+ const short = `short ${base}/${quote} (selling ${base} forward)`;
208
+ const long = `long ${base}/${quote} (buying ${base} forward)`;
209
+ const [earns, pays] = carry.earnedBy === "short" ? [short, long] : [long, short];
210
+ const higher = carry.higher === "quote" ? quote : base;
211
+ return `${earns.charAt(0).toUpperCase()}${earns.slice(1)} earns it and ${pays} pays it: ${higher}'s rate earns more over the ${days} days.`;
212
+ }
@@ -161,7 +161,7 @@ export function parseFxArgs(words: readonly string[], baseCurrency: string): FxA
161
161
  * An amount in its currency's minor units, grouped (1,234.50 EUR; 1,235 JPY).
162
162
  * One too small for them keeps six significant figures instead of reading 0.
163
163
  */
164
- function formatFxAmount(amount: number, currency: string): string {
164
+ export function formatFxAmount(amount: number, currency: string): string {
165
165
  const digits = currencyMinorDigits(currency);
166
166
  const rounded = Number(amount.toFixed(digits));
167
167
  if (rounded === 0 && amount !== 0) return `${formatFxRate(amount)} ${currency}`;
@@ -160,6 +160,29 @@ async function metalFromFuture(
160
160
  };
161
161
  }
162
162
 
163
+ /**
164
+ * The rate's move on the day, as `quote` gives its pair's: the rate against
165
+ * the same reading at the previous daily closes (the pair's own close, or
166
+ * each dollar pair's for a cross), in percent. Null for a rate priced from a
167
+ * future, or when a close is missing.
168
+ */
169
+ export function fxQuoteRateMove(rate: FxQuoteRate): { percent: number; previousRate: number } | null {
170
+ if (rate.derivedFrom) return null;
171
+ const closes = rate.quotes.map(({ quote }) => quote.previousClose);
172
+ if (!closes.every(isUsableRate)) return null;
173
+ let previousRate: number;
174
+ if (rate.viaUsd) {
175
+ // Each dollar pair as USD per unit, as the cross is read: EURUSD=X as sent, USDJPY=X inverted.
176
+ const [from, into] = rate.quotes.map(({ symbol }, index) => symbol.startsWith("USD") ? 1 / closes[index]! : closes[index]!) as [number, number];
177
+ previousRate = from / into;
178
+ } else {
179
+ // The pair's own quote, inverted when the rate is (JPY/EUR read from EURJPY=X).
180
+ previousRate = rate.rate === rate.quotes[0]!.figure ? closes[0]! : 1 / closes[0]!;
181
+ }
182
+ const percent = (rate.rate / previousRate - 1) * 100;
183
+ return Number.isFinite(percent) ? { percent, previousRate } : null;
184
+ }
185
+
163
186
  /** How long past its feed's delay a weekday FX rate stays current, counted while the FX market trades. */
164
187
  const FX_STALE_AFTER_DELAY_MS = 15 * 60_000;
165
188
 
package/src/cli/help.ts CHANGED
@@ -47,6 +47,7 @@ const GLOBAL_OPTIONS: Array<[string, string]> = [
47
47
  ["--json", "Print the full result as JSON"],
48
48
  ["--csv", "Print rows as CSV under the columns the text shows; fn reports and fundamentals put each table under # section: and end with # source lines"],
49
49
  ["--ndjson", "Print one JSON object per table row"],
50
+ ["--output <path>, --out <path>", "Write a --csv, --json or --ndjson export to this file in UTF-8, and print where it went (a redirect is UTF-16 in Windows PowerShell 5.1)"],
50
51
  ["--limit <n>", "Show at most n rows, the first n as printed"],
51
52
  ["--tail <n>", "Show the newest n rows of a dated series (history, fred, econ) in their printed order, or the last n of another list"],
52
53
  ["--refresh", "Fetch fresh data instead of reading the cache"],
@@ -1,4 +1,5 @@
1
1
  import { indexRootFor, type IndexRoot } from "../tickers/index-roots";
2
+ import { commandWord } from "../utils/shell-word";
2
3
 
3
4
  /** A broker's code for an index: VIX.X and $VIX.X as thinkorswim writes it, $VIX as Schwab does. */
4
5
  export interface BrokerIndexCode extends IndexRoot {
@@ -26,12 +27,12 @@ export function brokerIndexReadAs(code: BrokerIndexCode): string {
26
27
  return `Read ${code.typed} as ${code.symbol} (${code.name}).`;
27
28
  }
28
29
 
29
- /** "^VIX Cboe Volatility Index (try: gloom quote ^VIX)", under a bare root that found nothing. */
30
+ /** `^VIX Cboe Volatility Index (try: gloom quote "^VIX")`, under a bare root that found nothing. */
30
31
  export function indexRootTryLine(root: IndexRoot, command = "quote"): string {
31
- return `${root.symbol} ${root.name} (try: gloom ${command} ${root.symbol})`;
32
+ return `${root.symbol} ${root.name} (try: gloom ${command} ${commandWord(root.symbol)})`;
32
33
  }
33
34
 
34
- /** "also ^MOVE ICE BofA MOVE Index (gloom quote ^MOVE)", under a bare root that quoted another instrument. */
35
+ /** `also ^MOVE ICE BofA MOVE Index (gloom quote "^MOVE")`, under a bare root that quoted another instrument. */
35
36
  export function indexRootAlsoLine(root: IndexRoot, command = "quote"): string {
36
- return `also ${root.symbol} ${root.name} (gloom ${command} ${root.symbol})`;
37
+ return `also ${root.symbol} ${root.name} (gloom ${command} ${commandWord(root.symbol)})`;
37
38
  }
package/src/cli/index.ts CHANGED
@@ -2,7 +2,9 @@ import { VERSION } from "../version";
2
2
  import type { CliCommandContext, CliCommandDef, CliDispatchResult, CliLaunchRequest } from "../types/plugin";
3
3
  import type { LoadedExternalPlugin } from "../plugins/loader";
4
4
  import { loadCliConfigIfAvailable } from "./context";
5
- import { parseCliGlobalArgs } from "./options";
5
+ import { checkCliOutputFormat, commandOwnsOutput, parseCliGlobalArgs, type CliGlobalOptions } from "./options";
6
+ import { checkOutputPath, resolveOutputPath, writeOutputFile } from "./output-file";
7
+ import { printCliResult, takeCliFileExport } from "./result";
6
8
  import {
7
9
  buildCliCommandRegistry,
8
10
  createCliCommandContext,
@@ -189,7 +191,7 @@ export function createCoreCliCommands(
189
191
  "fn HP AAPL",
190
192
  "fn ANR SAN:EPA",
191
193
  "fn CBR --json",
192
- "fn WEI --csv --section europe > europe.csv",
194
+ "fn WEI --csv --section europe --output europe.csv",
193
195
  "fn RV NEE,FSLR --csv --output rv.csv",
194
196
  "fn 13F AAPL --view=ticker-holdings",
195
197
  "fn OVME --spot 100 --strike 100 --days 30 --volatility 25",
@@ -413,7 +415,8 @@ export { buildSearchReport, searchCandidatesForCli };
413
415
  export async function dispatchCli(args: string[], options: DispatchCliOptions = {}): Promise<CliDispatchResult> {
414
416
  let parsed;
415
417
  try {
416
- parsed = parseCliGlobalArgs(args);
418
+ // --output without a format is refused once the command is known: a plugin's own --output is not the export's.
419
+ parsed = parseCliGlobalArgs(args, { deferOutputCheck: true });
417
420
  } catch (error) {
418
421
  printCliError(asUsageError(error), inferCliErrorOptions(args));
419
422
  process.exitCode = 1;
@@ -438,6 +441,15 @@ export async function dispatchCli(args: string[], options: DispatchCliOptions =
438
441
  if (!resolved) {
439
442
  return { kind: "unhandled" };
440
443
  }
444
+ try {
445
+ // A plugin command with its own --output keeps it: the global flag yields, as it does to `fn` and `shot`.
446
+ if (parsed.options.output !== undefined && commandOwnsOutput(resolved.command)) parsed = parseCliGlobalArgs(args, { ownsOutput: true });
447
+ checkCliOutputFormat(parsed);
448
+ } catch (error) {
449
+ printCliError(asUsageError(error), parsed.options);
450
+ process.exitCode = 1;
451
+ return { kind: "handled" };
452
+ }
441
453
 
442
454
  // The overview includes installed commands; one built-in command's help only
443
455
  // needs that command. An unknown help topic may belong to an installed plugin.
@@ -459,13 +471,19 @@ export async function dispatchCli(args: string[], options: DispatchCliOptions =
459
471
  : foldCommandArgs(resolved.command, parsed.args.slice(1), parsed.literalStart - 1);
460
472
  try {
461
473
  if (!helpOnly && resolved.builtin) checkCliCommandOptions(resolved.command, commandArgs, parsed.literalStart - 1);
474
+ // The file --output names, checked before the command runs so a path that cannot be written fails at once.
475
+ const outputPath = parsed.options.output !== undefined && !helpOnly ? resolveOutputPath(parsed.options.output) : null;
476
+ const replacing = outputPath ? await checkOutputPath(outputPath) : false;
477
+ takeCliFileExport();
462
478
  // What it answers from a saved copy, its refresh having failed, its closing line says.
463
479
  const result = await collectSavedCopies(() => Promise.resolve(target.command.execute(
464
480
  commandArgs,
465
481
  createCliCommandContext(target.ownerId, registry, parsed.options, commandArgs),
466
482
  )));
483
+ if (outputPath) await saveFileExport(outputPath, parsed.options, resolved.command.name, replacing);
467
484
  return normalizeCliDispatchResult(result);
468
485
  } catch (error) {
486
+ takeCliFileExport();
469
487
  // A coin typed without its quote currency (USDT) is named by its one symbol (USDT-USD) in the hint.
470
488
  if (parsed.options.format !== "json") await primeBoardCoins([error instanceof Error ? error.message : String(error)]);
471
489
  printCliError(error, parsed.options, { command: resolved.command.name, args: commandArgs,
@@ -475,6 +493,25 @@ export async function dispatchCli(args: string[], options: DispatchCliOptions =
475
493
  }
476
494
  }
477
495
 
496
+ /**
497
+ * Writes the export a command printed to the file `--output` named, in
498
+ * UTF-8 without a byte order mark, and says where it went: `Saved <path>`,
499
+ * `Replaced <path>` over a file that was there, or in JSON its envelope. A
500
+ * command that printed no export (its result failed, or it has no table to
501
+ * export) writes no file and says so.
502
+ */
503
+ async function saveFileExport(path: string, options: CliGlobalOptions, command: string, replacing: boolean): Promise<void> {
504
+ const written = takeCliFileExport();
505
+ if (written === null) {
506
+ if (process.exitCode) return;
507
+ throw new Error(`${command} printed no ${options.format.toUpperCase()} export; nothing was written to ${path}.`);
508
+ }
509
+ await writeOutputFile(path, `${written}\n`);
510
+ printCliResult({ data: { output: path, format: options.format, replaced: replacing } },
511
+ { ...options, output: undefined, format: options.format === "json" ? "json" : "text" },
512
+ { text: () => `${replacing ? "Replaced" : "Saved"} ${path}` });
513
+ }
514
+
478
515
  /** Explains why dispatch found no command in `args`, suggesting the closest one. */
479
516
  export async function failUnknownCliCommand(args: string[], options: DispatchCliOptions = {}): Promise<never> {
480
517
  let token = args[0] ?? "";
@@ -2,6 +2,7 @@ import { listingSuffixExchange } from "../sources/listing-symbols";
2
2
  import { kindFromListingSyntax } from "../tickers/instrument-kind";
3
3
  import { macroReleaseTopic } from "../plugins/builtin/shared/macro-releases";
4
4
  import { parsePublicTickerKey } from "../utils/exchanges";
5
+ import { commandWord } from "../utils/shell-word";
5
6
  import { listingAbroadVenue } from "../utils/sec";
6
7
  import { nimCommand } from "./bank-section";
7
8
  import { treasuryYieldLine, treasuryYieldTenor } from "./treasury-yields";
@@ -174,8 +175,8 @@ const BANK_FIGURES_TOPIC = {
174
175
  * command or a function. One example, writing a file.
175
176
  */
176
177
  function exportLine(symbol = "LMT"): string {
177
- return `Export: add --csv or --json to any command to print its result as CSV or JSON, e.g. gloom history ${symbol} --csv > ${
178
- symbol.toLowerCase().replace(/[^a-z0-9]+/g, "-")}.csv`;
178
+ return `Export: add --csv or --json to any command to print its result as CSV or JSON, and --output <file> to write it to a file in UTF-8, e.g. gloom history ${
179
+ commandWord(symbol)} --csv --output ${symbol.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, "")}.csv`;
179
180
  }
180
181
 
181
182
  const EXPORT_POINTER = {
@@ -352,13 +353,15 @@ const COMMAND_POINTERS: ReadonlyArray<{
352
353
  },
353
354
  {
354
355
  // A currency forward, not a forward rate on a yield curve, forward guidance, a forward P/E or the forward
355
- // inflation series: a query that says more than "forward" has to name FX.
356
- names: ["forward", "forwards", "fwd", "fwds"],
357
- words: ["rate", "rates", "implied", "hedge", "hedging", "cost", "costs", "premium", "interest", "1w", "2w", "30d", "1m", "3m",
356
+ // inflation series: a query that says more than "forward" has to name FX. A hedge or a carry alone is the
357
+ // forward's too (a hedge fund or a carry cost is not).
358
+ names: ["forward", "forwards", "fwd", "fwds", "hedge", "hedging", "carry"],
359
+ words: ["rate", "rates", "implied", "cost", "costs", "premium", "interest", "1w", "2w", "30d", "1m", "3m",
358
360
  "6m", "1y"],
359
- qualifiers: ["fx", "currency", "currencies", "point", "points", "pips", "cip", "covered", "parity", "outright",
360
- "usd", "mxn", "eur", "gbp", "usdmxn", "eurusd", "gbpusd", "eurmxn", "peso", "dollar", "euro", "sterling"],
361
- line: "FX forwards implied by both currencies' short rates (covered interest parity), with forward points and the hedge cost: gloom fx USD/MXN --forward 30d",
361
+ qualifiers: ["fx", "currency", "currencies", "point", "points", "pips", "cip", "covered", "parity", "outright", "trade",
362
+ "usd", "mxn", "eur", "gbp", "zar", "try", "usdmxn", "eurusd", "gbpusd", "eurmxn", "usdzar", "usdtry", "peso", "dollar", "euro",
363
+ "sterling", "rand", "lira"],
364
+ line: "FX forwards implied by both currencies' short rates (covered interest parity), with forward points, the hedge cost and, for an amount, the carry and who earns it: gloom fx 5000000 USD/MXN --forward 30d",
362
365
  },
363
366
  {
364
367
  names: ["defi", "tvl", "tvls", "total value locked", "on-chain", "onchain", "aave", "lido", "eigenlayer", "morpho"],