gloomberb 0.20.5 → 0.20.6

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 (127) 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/hk-tenders.ts +59 -0
  6. package/src/api-client/index.ts +1 -0
  7. package/src/api-client/types/econ.ts +20 -2
  8. package/src/app.tsx +18 -13
  9. package/src/architecture/floating-promise-allowlist.json +313 -0
  10. package/src/cli/commands/market.ts +164 -40
  11. package/src/cli/commands/news-search.ts +22 -7
  12. package/src/cli/commands/overview.ts +12 -6
  13. package/src/cli/commands/ticker.ts +3 -1
  14. package/src/cli/early-command.ts +2 -0
  15. package/src/cli/errors.ts +10 -1
  16. package/src/cli/fx-forward.ts +76 -12
  17. package/src/cli/fx-pair.ts +1 -1
  18. package/src/cli/fx-quote-rate.ts +23 -0
  19. package/src/cli/help.ts +1 -0
  20. package/src/cli/index-roots.ts +5 -4
  21. package/src/cli/index.ts +40 -3
  22. package/src/cli/known-gaps.ts +11 -8
  23. package/src/cli/listing-arg.ts +6 -4
  24. package/src/cli/options.ts +52 -3
  25. package/src/cli/output-file.ts +5 -3
  26. package/src/cli/pane-functions/catalog.ts +15 -0
  27. package/src/cli/pane-functions/function-help.ts +4 -4
  28. package/src/cli/pane-functions/headless.ts +9 -4
  29. package/src/cli/pane-functions/index.ts +6 -4
  30. package/src/cli/pane-functions/resolver.ts +2 -2
  31. package/src/cli/result.ts +21 -2
  32. package/src/cli/spreadsheet-hint.ts +7 -3
  33. package/src/cli/treasury-yields.ts +5 -3
  34. package/src/components/chart/composite/legend.tsx +40 -2
  35. package/src/components/command-bar/workflow/tickers.ts +2 -2
  36. package/src/components/data-table/view.tsx +9 -2
  37. package/src/components/ui/data-table/opentui/index.tsx +11 -4
  38. package/src/components/ui/data-table/opentui/model.ts +8 -6
  39. package/src/components/ui/data-table/types.ts +6 -1
  40. package/src/components/ui/table-layout.ts +38 -1
  41. package/src/docs/snapshot.json +3 -3
  42. package/src/market-data/market/change-basis.ts +9 -5
  43. package/src/market-data/market/dated-previous-close.ts +57 -6
  44. package/src/market-data/quotes/contributions.ts +2 -0
  45. package/src/market-data/quotes/listing-enterprise-value.ts +50 -0
  46. package/src/plugins/builtin/alerts/metric-data.ts +15 -2
  47. package/src/plugins/builtin/backtest/headless.ts +1 -1
  48. package/src/plugins/builtin/cds/model.ts +0 -6
  49. package/src/plugins/builtin/chart-composer/formula.ts +16 -3
  50. package/src/plugins/builtin/chart-composer/headless-schema.ts +2 -0
  51. package/src/plugins/builtin/chart-composer/headless.ts +2 -1
  52. package/src/plugins/builtin/chart-composer/presets.ts +1 -0
  53. package/src/plugins/builtin/cloud/askg/pane.tsx +55 -13
  54. package/src/plugins/builtin/credit-boards/cdx-pane.tsx +20 -7
  55. package/src/plugins/builtin/credit-boards/client.ts +8 -0
  56. package/src/plugins/builtin/credit-boards/headless.ts +4 -1
  57. package/src/plugins/builtin/credit-boards/model.ts +58 -4
  58. package/src/plugins/builtin/credit-boards/series.ts +63 -6
  59. package/src/plugins/builtin/credit-boards/sovr-pane.tsx +3 -2
  60. package/src/plugins/builtin/credit-conditions/headless.ts +24 -6
  61. package/src/plugins/builtin/credit-conditions/index.tsx +1 -1
  62. package/src/plugins/builtin/credit-conditions/model.ts +12 -6
  63. package/src/plugins/builtin/credit-conditions/series.ts +2 -1
  64. package/src/plugins/builtin/econ/calendar-model.ts +41 -7
  65. package/src/plugins/builtin/econ/calendar-source.ts +7 -1
  66. package/src/plugins/builtin/econ/index.tsx +41 -8
  67. package/src/plugins/builtin/econ/types.ts +3 -0
  68. package/src/plugins/builtin/fixed-income/index.tsx +2 -0
  69. package/src/plugins/builtin/fx-matrix/index.tsx +44 -14
  70. package/src/plugins/builtin/help/keybindings-editor.tsx +6 -2
  71. package/src/plugins/builtin/portfolio-list/cli/render.ts +20 -3
  72. package/src/plugins/builtin/portfolio-list/cli/watchlist-command.ts +5 -1
  73. package/src/plugins/builtin/research/headless-schema.ts +4 -3
  74. package/src/plugins/builtin/research/relative-valuation-columns.ts +145 -47
  75. package/src/plugins/builtin/research/relative-valuation-currency.ts +31 -0
  76. package/src/plugins/builtin/research/relative-valuation-headless.ts +25 -8
  77. package/src/plugins/builtin/research/relative-valuation-model.ts +40 -9
  78. package/src/plugins/builtin/research/relative-valuation-pane.tsx +3 -2
  79. package/src/plugins/builtin/research/relative-valuation-peers.ts +2 -2
  80. package/src/plugins/builtin/thirteenf/api.ts +47 -4
  81. package/src/plugins/builtin/ticker-detail/data-panes/historical-prices.tsx +8 -7
  82. package/src/plugins/builtin/ticker-detail/data-panes/history-bars.ts +8 -5
  83. package/src/plugins/builtin/ticker-detail/financials/model.ts +6 -2
  84. package/src/plugins/builtin/ticker-detail/financials/tab.tsx +1 -1
  85. package/src/plugins/builtin/ticker-detail/headless.ts +6 -4
  86. package/src/plugins/builtin/treasury-auctions/cache.ts +36 -2
  87. package/src/plugins/builtin/treasury-auctions/headless.ts +42 -4
  88. package/src/plugins/builtin/treasury-auctions/hk-headless.ts +126 -0
  89. package/src/plugins/builtin/treasury-auctions/hk-view.tsx +347 -0
  90. package/src/plugins/builtin/treasury-auctions/hk.ts +363 -0
  91. package/src/plugins/builtin/treasury-auctions/index.tsx +14 -1
  92. package/src/plugins/builtin/treasury-auctions/model.ts +16 -8
  93. package/src/plugins/builtin/treasury-auctions/pane.tsx +45 -21
  94. package/src/portfolio/collection-name.ts +22 -0
  95. package/src/renderers/dom/data-table/frozen-column.ts +3 -1
  96. package/src/renderers/dom/data-table/index.tsx +27 -9
  97. package/src/renderers/dom/data-table/row.tsx +2 -0
  98. package/src/renderers/electrobun/bun/desktop/backend.ts +27 -24
  99. package/src/renderers/electrobun/bun/desktop/detached-windows.ts +3 -3
  100. package/src/renderers/electrobun/bun/desktop/snapshot-commit.ts +77 -0
  101. package/src/renderers/electrobun/shared/protocol.ts +4 -0
  102. package/src/renderers/electrobun/view/backend-rpc.ts +3 -0
  103. package/src/renderers/electrobun/view/desktop/window/bridge.ts +3 -0
  104. package/src/sources/gloomberb-cloud/normalizers.ts +9 -5
  105. package/src/sources/provider-router/cache.ts +3 -1
  106. package/src/sync/controller.ts +17 -2
  107. package/src/sync/other-window-tabs.ts +32 -1
  108. package/src/sync/react.ts +4 -4
  109. package/src/time-series/bar-spacing.ts +33 -0
  110. package/src/time-series/base-series.ts +21 -3
  111. package/src/time-series/chart-bounds.ts +31 -0
  112. package/src/time-series/field-catalog.ts +17 -0
  113. package/src/time-series/fundamentals.ts +143 -11
  114. package/src/time-series/ice-credit.ts +32 -6
  115. package/src/time-series/resolve.ts +9 -5
  116. package/src/time-series/session-bar.ts +78 -9
  117. package/src/time-series/studies/formula.ts +53 -10
  118. package/src/time-series/studies/pair.ts +18 -7
  119. package/src/time-series/studies/units.ts +49 -2
  120. package/src/time-series/types.ts +12 -0
  121. package/src/types/desktop-window.ts +2 -0
  122. package/src/types/financials.ts +6 -0
  123. package/src/types/headless.ts +8 -0
  124. package/src/utils/cli-output.ts +6 -3
  125. package/src/utils/ebitda.ts +128 -0
  126. package/src/utils/format.ts +1 -1
  127. package/src/utils/shell-word.ts +13 -0
@@ -2,7 +2,7 @@ import { logFailure } from "../../utils/log-failure";
2
2
  import { normalizeTickerSymbol } from "../../tickers/search/ranking";
3
3
  import type { CliCommandDef } from "../../types/plugin";
4
4
  import { TIME_RANGES, type TimeRange } from "../../time-series/range";
5
- import { CHART_RESOLUTION_STEP_MS } from "../../time-series/resolution";
5
+ import { CHART_RESOLUTION_STEP_MS, RANGE_HISTORY_RESOLUTION } from "../../time-series/resolution";
6
6
  import { yearToDateStartIndex } from "../../market-data/market/year-to-date";
7
7
  import type { EarningsEvent, MarketDataRequestContext, QuoteBatchResult, QuoteSubscriptionTarget, SecFilingItem } from "../../types/data-provider";
8
8
  import { companyDataNotes, type CompanyFrom } from "../../types/company-from";
@@ -74,6 +74,7 @@ import { loadBankFigures } from "../bank-section";
74
74
  import { latestFinancialPeriod } from "../../utils/latest-financial-period";
75
75
  import type { FuturesContractTermsPayload } from "../../api-client/futures-curve";
76
76
  import { currencyCodeLabel } from "../../utils/currency-units";
77
+ import { fxRateDigits, quotedFxPair } from "../../utils/currency-pair";
77
78
  import {
78
79
  futuresContractLines, futuresPricePer, futuresRollLines, futuresTickOption, isFuturesInstrument, loadFuturesPriceUnit, loadUsdPerMmbtu, usdPerMmbtuText, type UsdPerMmbtu,
79
80
  } from "../../market-data/futures-contract";
@@ -134,7 +135,7 @@ import {
134
135
  fxInterventionLatestNote, fxInterventionPair, fxInterventionWindowNote, loadFxInterventions, type FxInterventionPair,
135
136
  } from "../../market-data/fx-interventions";
136
137
  import { maxDrawdownText, maxRunUp, maxRunUpText } from "../../utils/max-drawdown";
137
- import { isPastPriceWindow, loadPriceWindowHistory, PRICE_WINDOW_FROM_HELP, PRICE_WINDOW_TO_HELP, priceWindowText, readPriceWindow, type PriceWindow } from "../../utils/price-window";
138
+ import { isPastPriceWindow, loadPriceWindowHistory, PRICE_WINDOW_FROM_HELP, PRICE_WINDOW_TO_HELP, priceWindowInterval, priceWindowText, readPriceWindow, type PriceWindow } from "../../utils/price-window";
138
139
  import {
139
140
  BAR_INTERVAL_LABELS,
140
141
  closedPeriodBarDay,
@@ -214,12 +215,13 @@ import {
214
215
  } from "./news-search";
215
216
  import { displayTimeZone, formatUtcDayTime, formatUtcTime } from "../../utils/utc-time";
216
217
  import { localReportTiming } from "../../utils/report-timing";
217
- import { DAY_SO_FAR_TEXT, withSessionBar } from "../../time-series/session-bar";
218
+ import { DAY_SO_FAR_TEXT, dailyOrLongerBarSize, withSessionBar } from "../../time-series/session-bar";
219
+ import { requestedBarSize } from "../../time-series/bar-spacing";
218
220
  import { isFiniteNumber } from "../../utils/guards";
219
221
  import { exportedFundamentals } from "../../utils/price-earnings";
220
222
  import { withBankEnterpriseValue } from "../../utils/fundamentals";
221
223
  import { fundamentalsFreshness, quotesFreshness, rowsFreshness, valuationFreshness } from "../freshness";
222
- import { fxPairListing, fxQuoteRateObservation, METAL_NAMES, readFxQuoteRate } from "../fx-quote-rate";
224
+ import { fxPairListing, fxQuoteRateMove, fxQuoteRateObservation, METAL_NAMES, readFxQuoteRate } from "../fx-quote-rate";
223
225
  import { quoteBarNotes } from "../../market-data/quotes/intraday-bar";
224
226
  import { cedearRatioText, depositaryPairText, isReceiptSide, listingCedearRatio, listingDepositaryPair } from "../../market-data/depositary-pair";
225
227
  import { isPesoDollarPair, loadPesoDollarRates, pesoDollarRateLines, pesoDollarRatesJson } from "../peso-dollar-rates";
@@ -302,7 +304,8 @@ import { knownGapMessage, subMinuteDataMessage } from "../known-gaps";
302
304
  import { phraseSearchReport } from "./search";
303
305
  import { secRegistrantMismatchMessage, SecRegistrantMismatchError, areDifferentCompanies } from "../../sources/sec-registrant";
304
306
  import { isCryptoPairSymbol, isRoundTheClockCoin } from "../../utils/crypto-pair";
305
- import { isUsListingExchange } from "../../utils/exchanges";
307
+ import { canonicalExchange, isUsListingExchange } from "../../utils/exchanges";
308
+ import { listingSuffixVenue } from "../../sources/listing-symbols";
306
309
  import { resolveTickerInstrumentKind } from "../../tickers/instrument-kind";
307
310
  import {
308
311
  describeFormerIssuer, describeTickerChange, movedAwayChange, startTickerChangeLookup, tickerChangeLine, type FormerIssuer, type TickerChange,
@@ -311,9 +314,11 @@ import { noSecReportsNotice, nonUsSecListingVenue, secFilingItemCodes } from "..
311
314
  import type { MarketContext } from "../types";
312
315
  import { windowRows } from "../row-window";
313
316
  import { answerQuote, errorMessage, notUsTickerSentence } from "../quote-answer";
314
- import { crossRate, describeFxConversion, describeFxLegs, describeFxRate, formatFxRate, FX_USAGE, parseFxArgs, type FxQuotedFigure } from "../fx-pair";
317
+ import { crossRate, describeFxConversion, describeFxLegs, describeFxRate, formatFxAmount, formatFxRate, FX_USAGE, parseFxArgs, type FxQuotedFigure } from "../fx-pair";
315
318
  import {
319
+ describeCarrySides,
316
320
  describeShortRate,
321
+ forwardCarry,
317
322
  shortRateGrowthText,
318
323
  formatForwardPoints,
319
324
  formatSignedPercent,
@@ -328,7 +333,7 @@ import { unavailableOnServer } from "../../plugins/builtin/shared/cloud-resource
328
333
  const utcClock = (time: number) => new Date(time).toISOString().slice(11, 16);
329
334
 
330
335
  /** `fx`'s forward form, for its usage line. */
331
- const FX_FORWARD_USAGE = "fx <base>/<quote> --forward <tenor>";
336
+ const FX_FORWARD_USAGE = "fx [amount] <base>/<quote> --forward <tenor>";
332
337
  import {
333
338
  holderListFacts,
334
339
  holderListPeriod,
@@ -725,15 +730,15 @@ function compareColumns() {
725
730
  value: (row: QuoteRow) => exportFigure(row.rawPreviousClose),
726
731
  format: (_value: unknown, row: QuoteRow) => yieldLevelCell(row.previousClose, row),
727
732
  },
728
- // A narrow terminal drops these before it cuts the names short.
733
+ // A narrow terminal moves these under their row, as the quote table does, before it cuts the names short.
729
734
  // An export writes the range as plain numbers (12.5-13.1), and each end as a number in Day Low and Day High.
730
735
  {
731
- key: "dayRange", header: "Day Range", align: "right" as const, optional: true, dropPriority: 1,
736
+ key: "dayRange", header: "Day Range", align: "right" as const, stackPriority: 1,
732
737
  value: (row: QuoteRow) => row.rawDayLow != null && row.rawDayHigh != null ? `${exportFigure(row.rawDayLow)}-${exportFigure(row.rawDayHigh)}` : "",
733
738
  format: (_value: unknown, row: QuoteRow) => row.dayRange,
734
739
  },
735
- { key: "volume", header: "Volume", align: "right" as const, format: formatCountCell, optional: true, dropPriority: 2 },
736
- { key: "currency", header: "Cur", shrink: false, optional: true, dropPriority: 3, format: currencyCell },
740
+ { key: "volume", header: "Volume", align: "right" as const, format: formatCountCell, stackPriority: 2 },
741
+ { key: "currency", header: "Cur", shrink: false, stackPriority: 3, format: currencyCell },
737
742
  ...CHANGE_BASIS_EXPORT_COLUMNS,
738
743
  ...EXTENDED_CHANGE_EXPORT_COLUMNS,
739
744
  ...DAY_RANGE_EXPORT_COLUMNS,
@@ -781,6 +786,16 @@ function quoteSessionFields(quote: Quote | null | undefined) {
781
786
  return quote?.changeBasis === "none" ? { ...fields, change: null, changePercent: null } : fields;
782
787
  }
783
788
 
789
+ /**
790
+ * The listing a row names: a vendor's suffixed symbol as the listing its
791
+ * quote confirms (2330.TW as 2330:TWSE), as RV, the portfolios and the panes
792
+ * name it; any other as asked.
793
+ */
794
+ function quoteRowSymbol(result: Pick<QuoteCliRecord, "target" | "quote">): string {
795
+ const venue = listingSuffixVenue(result.target.symbol, canonicalExchange(result.quote?.listingExchangeName || result.quote?.exchangeName) || undefined);
796
+ return venue ? `${venue.symbol}:${venue.exchange}` : result.target.symbol;
797
+ }
798
+
784
799
  function quoteRows(results: QuoteCliRecord[], now = Date.now()) {
785
800
  return results.map((result) => {
786
801
  const quote = result.quote;
@@ -816,7 +831,7 @@ function quoteRows(results: QuoteCliRecord[], now = Date.now()) {
816
831
  const previousClose = display.price != null && display.change != null ? display.price - display.change : quote?.previousClose;
817
832
  const last = price(display.price);
818
833
  return {
819
- symbol: result.target.symbol,
834
+ symbol: quoteRowSymbol(result),
820
835
  name: quote?.name || result.listing?.name || "",
821
836
  price: `${last}${per}`,
822
837
  pence: penceFigure(display.price, quote, /\.(\d+)/.exec(last)?.[1]?.length ?? 0),
@@ -1624,11 +1639,16 @@ async function loadListingHistory(
1624
1639
  const loaded = quote || window ? answered : await stoppedUsListingHistory(listing, market, loadRange, context, answered);
1625
1640
  // With no quote and no bar in over a month, when the listing last traded is said first.
1626
1641
  const lastTraded = quote || window ? null : noQuoteLastTraded(loaded);
1627
- const { resolution } = loaded;
1642
+ // The size the bars were served in, else the one asked for, never their spacing alone: B95 on SGX trades a few
1643
+ // times a month, and its daily bars a week or two apart are still daily (requestedBarSize).
1644
+ const asked = window ? priceWindowInterval(window) : RANGE_HISTORY_RESOLUTION[loadRange];
1645
+ const resolution = loaded.resolution ?? (dailyOrLongerBarSize(asked).barSize
1646
+ ? requestedBarSize(loaded.points.map((point) => new Date(point.date).getTime()), asked as "1d" | "1wk" | "1mo") : null);
1628
1647
  // While the session trades the day's bar is the quote's, whatever range the history was cut for (withSessionBar).
1629
1648
  // A window that ended before today has no session in progress.
1630
1649
  const points = window && isPastPriceWindow(window) ? loaded.points
1631
- : withSessionBar(loaded.points, quote, { now: Date.now(), venue: quote?.listingExchangeName || exchange || undefined });
1650
+ : withSessionBar(loaded.points, quote, { now: Date.now(), venue: quote?.listingExchangeName || exchange || undefined,
1651
+ ...dailyOrLongerBarSize(resolution) });
1632
1652
  const fromQuote = points !== loaded.points;
1633
1653
  const identity = listingIdentity(listing, quote);
1634
1654
  // Without a quote currency, the listing metadata research reads (as `ticker` does) may still state it.
@@ -1682,7 +1702,8 @@ async function loadListingHistory(
1682
1702
  ...(volumeNote ? { note: volumeNote } : {}),
1683
1703
  }) : rowsFreshness(data, {
1684
1704
  ...source,
1685
- ...barHistoryFreshness(intraday ? null : barResolutionFromDates(data.map((row) => row.date))),
1705
+ // The size the heading names (served, else asked for), not the spacing a thin listing's few trades leave.
1706
+ ...barHistoryFreshness(intraday ? null : interval ?? barResolutionFromDates(data.map((row) => row.date))),
1686
1707
  observedKey: "date",
1687
1708
  oldest: null,
1688
1709
  cadenceExchange: venue,
@@ -2716,11 +2737,13 @@ async function runNews(rawArgs: string[], ctx: Parameters<CliCommandDef["execute
2716
2737
  const empty = emptyMessage(false);
2717
2738
  // A bare coin ticker read as another listing (ETH, the Grayscale fund) says where the coin is, as `quote` does.
2718
2739
  const read = listing ? [...listingReadNotes(listing), ...coinListingNotes(listing, quote)] : [];
2719
- // A word that is also the company's name ("gold" for Gold.com Inc.) says once which ticker it found and how
2720
- // to search the stories that mention it instead, when those stories are mostly about something else.
2740
+ // A word that is also the company's name ("gold" for Gold.com Inc., "peso" for PesoRama on the TSX Venture)
2741
+ // says once which ticker it found and how to search the stories that mention it instead, when those stories
2742
+ // are mostly about something else. The word is bare, so a listing abroad is one the lookup found, not one typed.
2721
2743
  const typed = args[0]?.trim() ?? "";
2722
- const wordHint = listing && resolved && !listing.exchange && !feed && !exchangeOption && commonWordCandidate(typed, identity?.name)
2723
- && wordMeansMore(await searchNewsStories(typed, 20).catch(logFailure("cli.commands-market", "Search news stories for a ticker word failed", [])), listing.symbol)
2744
+ const wordHint = listing && resolved && !feed && !exchangeOption && commonWordCandidate(typed, identity?.name)
2745
+ && wordMeansMore(await searchNewsStories(typed, 20).catch(logFailure("cli.commands-market", "Search news stories for a ticker word failed", [])), listing.symbol,
2746
+ listing.exchange ? `${listing.symbol}:${listing.exchange}` : listing.symbol)
2724
2747
  ? `${typed} ${cliArrow("→")} ${identity?.name ?? listing.symbol} (ticker ${listing.symbol}). For stories that mention ${typed.toLowerCase()}, try: ${quotedSearchCommand(typed.toLowerCase())}`
2725
2748
  : null;
2726
2749
  ctx.printResult({
@@ -3577,7 +3600,17 @@ async function runOptions(rawArgs: string[], ctx: Parameters<CliCommandDef["exec
3577
3600
  /** What an options chain export's `interval` says: one quote snapshot, not bars. */
3578
3601
  const OPTIONS_EXPORT_INTERVAL = "snapshot";
3579
3602
 
3580
- /** `fx --date`: a past day as YYYY-MM-DD; today's close is not in yet, so it is refused, as is a day ahead. */
3603
+ /** Saturday or Sunday, for a YYYY-MM-DD day. */
3604
+ function isWeekendDay(date: string): boolean {
3605
+ const day = new Date(`${date}T00:00:00Z`).getUTCDay();
3606
+ return day === 0 || day === 6;
3607
+ }
3608
+
3609
+ /**
3610
+ * `fx --date`: a past day as YYYY-MM-DD, or today on a weekend, which reads the
3611
+ * Friday close; a weekday's close is not in yet, so today is refused then, as
3612
+ * is a day ahead.
3613
+ */
3581
3614
  function readFxDate(value: string, ctx: Parameters<CliCommandDef["execute"]>[1]): string {
3582
3615
  let date: string;
3583
3616
  try {
@@ -3587,8 +3620,9 @@ function readFxDate(value: string, ctx: Parameters<CliCommandDef["execute"]>[1])
3587
3620
  }
3588
3621
  if (!date) return ctx.fail("--date takes a day, such as --date 2026-09-02.");
3589
3622
  const today = isoDateToday();
3590
- if (date >= today) {
3591
- return ctx.fail(`${date} has no daily close yet: --date takes a day before today (${today}).`, "Without --date, fx gives the latest rate.");
3623
+ // A weekend has no close of its own, so today's, on a Saturday or a Sunday, is the Friday close, which is final.
3624
+ if (date > today || (date === today && !isWeekendDay(date))) {
3625
+ return ctx.fail(`${date} has no daily close yet: --date takes a day before today (${today} UTC), or today on a weekend.`, "Without --date, fx gives the latest rate.");
3592
3626
  }
3593
3627
  return date;
3594
3628
  }
@@ -3679,6 +3713,46 @@ async function runFxOnDate(
3679
3713
  });
3680
3714
  }
3681
3715
 
3716
+ /**
3717
+ * What one unit of `quote` (a forward's quote currency) is worth in the
3718
+ * reader's currency at spot, to show a carry in it: 1 when they are the same,
3719
+ * the forward's own spot inverted when the reader's is the pair's base,
3720
+ * otherwise the pair's own quote. Null when no conversion is needed; the
3721
+ * sentence saying why it is missing when no quote came back.
3722
+ */
3723
+ async function carryInCurrency(
3724
+ quote: string,
3725
+ reader: string,
3726
+ base: string,
3727
+ spot: number,
3728
+ market: MarketContext,
3729
+ forceRefresh: boolean | undefined,
3730
+ ): Promise<{ rate: number; text: string } | { missing: string } | null> {
3731
+ if (reader === quote) return null;
3732
+ const marketText = (rate: number) => {
3733
+ const quoted = quotedFxPair(quote, reader, rate);
3734
+ return `${quoted.pair} ${quoted.rate.toFixed(fxRateDigits(quoted.pair.slice(4), quoted.rate))}`;
3735
+ };
3736
+ if (reader === base) return { rate: 1 / spot, text: marketText(1 / spot) };
3737
+ // A failed read is said in the carry's warning, with the reason it gave; the forward itself stands.
3738
+ const read = await readFxQuoteRate(quote, reader, (targets, options) => market.dataProvider.getQuotesBatch(targets, options),
3739
+ { forceRefresh: forceRefresh === true }).catch((error: unknown) => ({ failed: errorMessage(error) }));
3740
+ if (read && "rate" in read) return { rate: read.rate, text: marketText(read.rate) };
3741
+ const reason = read && "failed" in read && read.failed ? ` (${read.failed})` : "";
3742
+ return { missing: `The carry is not shown in ${reader}, your base currency: no ${quote}/${reader} rate came back${reason}.` };
3743
+ }
3744
+
3745
+ /**
3746
+ * `USD/MXN -0.68% on the day (previous close 18.75924)`: the move of the pair
3747
+ * as markets quote it, as `quote` gives it, whichever way round it was asked.
3748
+ */
3749
+ function describeFxMove(currency: string, baseCurrency: string, rate: number, move: { percent: number; previousRate: number }): string {
3750
+ const now = quotedFxPair(currency, baseCurrency, rate);
3751
+ const before = quotedFxPair(currency, baseCurrency, move.previousRate);
3752
+ const percent = (now.rate / before.rate - 1) * 100;
3753
+ return `${now.pair} ${formatSignedPercent(percent, 2)} on the day (previous close ${before.rate.toFixed(fxRateDigits(before.pair.slice(4), before.rate))})`;
3754
+ }
3755
+
3682
3756
  async function runFx(rawArgs: string[], ctx: Parameters<CliCommandDef["execute"]>[1]) {
3683
3757
  const args = [...rawArgs];
3684
3758
  const dateOption = takeOption(args, "--date");
@@ -3708,9 +3782,11 @@ async function runFx(rawArgs: string[], ctx: Parameters<CliCommandDef["execute"]
3708
3782
  const { request, amount, toUsdByDefault } = parsed;
3709
3783
  const { currency, baseCurrency } = request;
3710
3784
  const pair = `${currency}/${baseCurrency}`;
3711
- if (tenor) {
3712
- if (amount != null) ctx.fail("--forward prices a pair, not an amount.", `Usage: gloom ${FX_FORWARD_USAGE}`);
3713
- if (currency === baseCurrency) ctx.fail(`${pair} has no forward: both sides are ${currency}.`, `Usage: gloom ${FX_FORWARD_USAGE}`);
3785
+ if (tenor && currency === baseCurrency) ctx.fail(`${pair} has no forward: both sides are ${currency}.`, `Usage: gloom ${FX_FORWARD_USAGE}`);
3786
+ // A carry is on an amount held: zero or less holds nothing, and a sign would turn who earns it around.
3787
+ if (tenor && amount != null && !(amount > 0)) {
3788
+ ctx.fail(`The carry is on an amount above zero; ${args[0]!.trim()} is not.`,
3789
+ `For the forward alone, drop the amount: gloom fx ${pair} --forward ${forwardOption}.`);
3714
3790
  }
3715
3791
  // The short rates are read alongside spot. A failed read is held as a value, not left to reject
3716
3792
  // unobserved while spot loads, and is raised where the forward needs the rates.
@@ -3746,8 +3822,11 @@ async function runFx(rawArgs: string[], ctx: Parameters<CliCommandDef["execute"]
3746
3822
  // A rate older than its feed's delay is stale, as `quote` says of the same quote.
3747
3823
  const stale = observation?.stale === true;
3748
3824
  const converted = amount == null ? null : amount * rate;
3825
+ // The day's move, as `quote` gives the pair's: against the previous daily close.
3826
+ const move = quoted ? fxQuoteRateMove(quoted) : null;
3749
3827
  const row = {
3750
3828
  currency, baseCurrency, rate, asOf, stale, pair, inverse: 1 / rate,
3829
+ ...(move ? { changePercent: move.percent, previousClose: move.previousRate } : {}),
3751
3830
  ...(quoted ? { quotes: quoted.quotes.map(({ symbol }) => symbol), ...(quoted.viaUsd ? { via: "USD" } : {}) } : {}),
3752
3831
  ...(quoted?.derivedFrom ? { derived: true, derivedFrom: quoted.derivedFrom } : {}),
3753
3832
  ...(amount == null ? {} : { amount, converted }),
@@ -3784,24 +3863,54 @@ async function runFx(rawArgs: string[], ctx: Parameters<CliCommandDef["execute"]
3784
3863
  ? [`${short.name}: ${short.attribution.text.replace(/\.$/, "")} (${short.attribution.licenceUrl}).`] : []))];
3785
3864
  const staleRates = [base.rate, quote.rate].filter((short) => short.stale)
3786
3865
  .map((short) => `${short.name} (${short.currency}) is the last copy read, dated ${short.asOf ?? "undated"}; its source could not be read since.`);
3866
+ // With an amount, the carry: the forward points on it over the tenor, in the quote currency and in the
3867
+ // reader's base currency at spot, and the side that earns it.
3868
+ const carry = amount == null ? null : forwardCarry(amount, implied);
3869
+ const readerCurrency = market.config.baseCurrency;
3870
+ const carryConversion = carry ? await carryInCurrency(baseCurrency, readerCurrency, currency, rate, market, ctx.cliOptions.refresh) : null;
3787
3871
  const forwardRow = {
3788
3872
  pair, tenor: tenor.label, days: tenor.days, forwardDate, spot: rate, spotAsOf: asOf, forward: implied.forward,
3789
3873
  points: implied.points, pointSize: implied.pointSize, premiumPercent: implied.premiumPercent, annualizedPercent: implied.annualizedPercent,
3790
3874
  baseRate: rateFields(base.rate), quoteRate: rateFields(quote.rate), method: "covered interest parity", label: IMPLIED_FORWARD_LABEL,
3875
+ ...(carry ? {
3876
+ amount, carry: carry.value, carryCurrency: baseCurrency, carryEarnedBy: carry.earnedBy,
3877
+ ...(carryConversion && "rate" in carryConversion
3878
+ ? { carryConverted: carry.value * carryConversion.rate, carryConvertedCurrency: readerCurrency, carryConversionRate: carryConversion.rate }
3879
+ : {}),
3880
+ } : {}),
3791
3881
  };
3792
3882
  const growth = (short: typeof base.rate) => shortRateGrowthText(short, tenor.days);
3793
- const compounded = [base.rate, quote.rate].filter((short) => short.compounding === "business-252").map((short) => short.name);
3883
+ const compoundedOverBusinessDays = [base.rate, quote.rate].filter((short) => short.compounding === "business-252").map((short) => short.name);
3884
+ const compoundedDaily = [base.rate, quote.rate].filter((short) => short.compounding === "daily-365").map((short) => short.name);
3885
+ const simple = [base.rate, quote.rate].filter((short) => !short.compounding).map((short) => short.name);
3886
+ // How each leg grows, named: a compounded rate by how it compounds, the rest as simple interest.
3887
+ const growthNote = [
3888
+ ...compoundedOverBusinessDays.length > 0
3889
+ ? [`${compoundedOverBusinessDays.join(" and ")} compounds over business days (252 a year, taken as 252/365 of the ${tenor.days} days)`] : [],
3890
+ ...compoundedDaily.length > 0 ? [`${compoundedDaily.join(" and ")} compounds daily on ACT/365`] : [],
3891
+ ...simple.length === 2 ? [`each rate earns simple interest over the ${tenor.days} days`]
3892
+ : simple.length === 1 ? [`${simple[0]} earns simple interest`] : [],
3893
+ ].join(", ");
3794
3894
  // A currency typed as its name (yen) says which code it was read as, as the spot answer does.
3795
- const forwardWarnings = [...request.readAs ?? [], ...rateNotes, ...staleRates];
3895
+ const forwardWarnings = [
3896
+ ...request.readAs ?? [], ...rateNotes, ...staleRates,
3897
+ ...toUsdByDefault && amount != null
3898
+ ? [`No second currency given, so ${currency} is priced against USD; for another, write fx ${args[0]!.trim()} ${currency}/<to> --forward ${tenor.label}.`]
3899
+ : [],
3900
+ ...carryConversion && "missing" in carryConversion ? [carryConversion.missing] : [],
3901
+ ];
3796
3902
  return ctx.printResult({ data: [forwardRow], freshness, ...(forwardWarnings.length > 0 ? { warnings: forwardWarnings } : {}) }, {
3797
3903
  text: () => [
3798
3904
  `${pair} ${tenor.label} forward ${formatFxRate(implied.forward)}, ${IMPLIED_FORWARD_LABEL}`,
3799
3905
  `Spot ${formatFxRate(rate)} · forward points ${formatForwardPoints(implied.points)} (pips of ${implied.pointSize}) · ${implied.premiumPercent >= 0 ? "premium" : "discount"} ${formatSignedPercent(implied.premiumPercent)} over ${tenor.days} days to ${forwardDate}, ${formatSignedPercent(implied.annualizedPercent, 2)} a year (×360/${tenor.days})`,
3800
3906
  `${currency} rate: ${describeShortRate(base.rate)}`,
3801
3907
  `${baseCurrency} rate: ${describeShortRate(quote.rate)}`,
3802
- `Covered interest parity: ${formatFxRate(rate)} × ${growth(quote.rate)} / ${growth(base.rate)}; ${compounded.length > 0
3803
- ? `${compounded.join(" and ")} compounds over business days (252 a year, taken as 252/365 of the ${tenor.days} days), the other rate earns simple interest`
3804
- : `each rate earns simple interest over the ${tenor.days} days`}, standing in for a ${tenor.label} term rate.`,
3908
+ `Covered interest parity: ${formatFxRate(rate)} × ${growth(quote.rate)} / ${growth(base.rate)}; ${growthNote}, standing in for a ${tenor.label} term rate.`,
3909
+ ...carry ? [
3910
+ `Carry on ${formatFxAmount(carry.amount, currency)} over ${tenor.days} days: ${formatFxAmount(carry.value, baseCurrency)}${carryConversion && "rate" in carryConversion
3911
+ ? `, ${formatFxAmount(carry.value * carryConversion.rate, readerCurrency)} at spot ${carryConversion.text}` : ""}`,
3912
+ describeCarrySides(carry, currency, baseCurrency, tenor.days),
3913
+ ] : [],
3805
3914
  ...attributions,
3806
3915
  ].join("\n"),
3807
3916
  exportIdentity: { symbolOrSeries: pair, currencyOrUnit: `${baseCurrency} per ${currency}`, interval: `forward ${tenor.label}` },
@@ -3815,6 +3924,15 @@ async function runFx(rawArgs: string[], ctx: Parameters<CliCommandDef["execute"]
3815
3924
  { key: "points", header: "Points", align: "right" },
3816
3925
  { key: "premiumPercent", header: "Premium %", align: "right" },
3817
3926
  { key: "annualizedPercent", header: "Annualized %", align: "right" },
3927
+ ...(carry ? [
3928
+ { key: "amount", header: "Amount", align: "right" as const },
3929
+ { key: "carry", header: "Carry", align: "right" as const },
3930
+ { key: "carryCurrency", header: "Carry currency" },
3931
+ { key: "carryEarnedBy", header: "Earned by" },
3932
+ ...(carryConversion && "rate" in carryConversion ? [
3933
+ { key: "carryConverted", header: `Carry (${readerCurrency})`, align: "right" as const },
3934
+ ] : []),
3935
+ ] : []),
3818
3936
  ],
3819
3937
  });
3820
3938
  }
@@ -3840,6 +3958,7 @@ async function runFx(rawArgs: string[], ctx: Parameters<CliCommandDef["execute"]
3840
3958
  const metal = quoted?.derivedFrom ? (METAL_NAMES[currency] ? currency : baseCurrency) : null;
3841
3959
  const rateText = [
3842
3960
  describeFxRate(request, rate, quoted && !quoted.viaUsd ? quoted.quotes[0] : undefined),
3961
+ ...move ? [describeFxMove(currency, baseCurrency, rate, move)] : [],
3843
3962
  ...quoted?.viaUsd ? [describeFxLegs(quoted.quotes)] : [],
3844
3963
  ...metal ? [`derived: ${METAL_NAMES[metal]!.toLowerCase()} from ${quoted!.derivedFrom}, the front-month future (spot ${METAL_NAMES[metal]!.toLowerCase()} is not quoted)`] : [],
3845
3964
  ...peso ? [`${peso.spotKind} rate`] : [],
@@ -3861,6 +3980,10 @@ async function runFx(rawArgs: string[], ctx: Parameters<CliCommandDef["execute"]
3861
3980
  { key: "stale", header: "Stale" },
3862
3981
  { key: "pair", header: "Pair" },
3863
3982
  { key: "inverse", header: "Inverse", align: "right" },
3983
+ ...(move ? [
3984
+ { key: "changePercent", header: "Chg %", align: "right" as const },
3985
+ { key: "previousClose", header: "Previous close", align: "right" as const },
3986
+ ] : []),
3864
3987
  ...(amount == null ? [] : [
3865
3988
  { key: "amount", header: "Amount", align: "right" as const },
3866
3989
  { key: "converted", header: "Converted", align: "right" as const },
@@ -3955,7 +4078,7 @@ export const marketDataCliCommands: BuiltinCliCommandDef[] = [
3955
4078
  options: [EXCHANGE_OPTION, LIST_FILE_OPTION],
3956
4079
  sections: [QUOTE_CSV_SECTION],
3957
4080
  examples: ["quote AAPL MSFT NVDA", "quote SAN:EPA BHP:ASX", "quote BTC-USD EURUSD=X", "quote binance:BZUSDT", "quote AAPL --json", "quote --file holdings.csv",
3958
- "quote --file holdings.csv --csv > quotes.csv"],
4081
+ "quote --file holdings.csv --csv --output quotes.csv"],
3959
4082
  },
3960
4083
  execute: (args, ctx) => runQuote(args, ctx, "quote"),
3961
4084
  },
@@ -4016,8 +4139,8 @@ export const marketDataCliCommands: BuiltinCliCommandDef[] = [
4016
4139
  }],
4017
4140
  examples: [
4018
4141
  "history AAPL", "history BHP:ASX --range 5Y", "history JPM --from 2007 --to 2009", "history ZAR=X --range ALL", "history ZAR=X --tail 5",
4019
- "history AAPL --range 5Y --csv > aapl.csv", "history AAPL MSFT 000660.KS --range 1M --csv",
4020
- "history --file holdings.txt --start 2024-01-01 --end 2024-12-31 --csv > bars.csv",
4142
+ "history AAPL --range 5Y --csv --output aapl.csv", "history AAPL MSFT 000660.KS --range 1M --csv",
4143
+ "history --file holdings.txt --start 2024-01-01 --end 2024-12-31 --csv --output bars.csv",
4021
4144
  ],
4022
4145
  },
4023
4146
  unknownOptionHint: historyOptionHint,
@@ -4119,7 +4242,7 @@ export const marketDataCliCommands: BuiltinCliCommandDef[] = [
4119
4242
  group: CLI_COMMAND_GROUPS.companyData,
4120
4243
  usage: ["financials <symbol>"],
4121
4244
  options: [EXCHANGE_OPTION, TABLE_SECTION_OPTION],
4122
- examples: ["financials MSFT", "financials SAN:EPA", "financials MSFT --json", "financials MSFT --csv > msft.csv"],
4245
+ examples: ["financials MSFT", "financials SAN:EPA", "financials MSFT --json", "financials MSFT --csv --output msft.csv"],
4123
4246
  },
4124
4247
  unknownOptionHint: financialsOptionHint,
4125
4248
  execute: (args, ctx) => runFinancials(args, ctx, "statements"),
@@ -4273,14 +4396,14 @@ export const marketDataCliCommands: BuiltinCliCommandDef[] = [
4273
4396
  usage: ["fx <currency>", "fx <base>/<quote>", "fx <amount> <from>/<to>", "fx <amount> <from> <to>", "fx <pair> --date <day>", FX_FORWARD_USAGE],
4274
4397
  options: [
4275
4398
  { flags: "--date <day>", description: `The rate at that day's daily FX close, such as a transaction date (${DATE_OPTION_EXAMPLES}); a weekend or holiday reads the trading day before it` },
4276
- { flags: "--forward <tenor>", description: "The forward implied by both currencies' short rates (covered interest parity), not a dealer quote: 30d, 2w, 3m, up to 1y; today's only, so not with --date" },
4399
+ { flags: "--forward <tenor>", description: "The forward implied by both currencies' short rates (covered interest parity), not a dealer quote: 30d, 2w, 3m, up to 1y; with an amount, the carry on it and who earns it; today's only, so not with --date" },
4277
4400
  ],
4278
4401
  sections: [{
4279
4402
  title: "Direction",
4280
4403
  lines: [
4281
4404
  "A bare code is one unit of it in your base currency. A pair reads as markets quote it: USD/NGN is how many NGN one USD buys. Two codes neither of which is USD, such as ZAR/NGN, cross through their USD rates.",
4282
4405
  "A currency's name stands for its code: fx yen is JPY, fx rand ZAR, fx Swiss franc CHF, and the answer says which it read. A name several currencies share (peso, dollar, franc, krona, rupee) lists them: write one as its code.",
4283
- "The answer states both directions: 1 NGN = 0.000752791 USD (USD/NGN 1328.39). --json, --csv and --ndjson carry rate (base currency per currency), pair, inverse, asOf and stale.",
4406
+ "The answer states both directions: 1 NGN = 0.000752791 USD (USD/NGN 1328.39), then the day's move of the pair as markets quote it, against its previous daily close, as quote gives it. --json, --csv and --ndjson carry rate (base currency per currency), pair, inverse, asOf, stale, and changePercent and previousClose of the rate as asked.",
4284
4407
  ],
4285
4408
  }, {
4286
4409
  title: "Amounts",
@@ -4290,16 +4413,17 @@ export const marketDataCliCommands: BuiltinCliCommandDef[] = [
4290
4413
  }, {
4291
4414
  title: "A past day",
4292
4415
  lines: [
4293
- "--date gives the rate at that day's daily FX close instead of the latest: fx USD/CAD --date 2026-09-02, or with an amount, fx 1250 USD/CAD --date 2026-09-02. Each currency's USD pair is read at its close of that day and crossed through USD, as the latest rate is. A weekend or market holiday has no close: the answer then gives the trading day before it and says so. The source line dates the close; --json adds date (the day asked for) and asOf (the close used).",
4416
+ "--date gives the rate at that day's daily FX close instead of the latest: fx USD/CAD --date 2026-09-02, or with an amount, fx 1250 USD/CAD --date 2026-09-02. Each currency's USD pair is read at its close of that day and crossed through USD, as the latest rate is. A weekend or market holiday has no close: the answer then gives the trading day before it and says so, today included on a Saturday or Sunday. The source line dates the close; --json adds date (the day asked for) and asOf (the close used).",
4294
4417
  ],
4295
4418
  }, {
4296
4419
  title: "Forwards",
4297
4420
  lines: [
4298
- "--forward <tenor> gives the forward implied by covered interest parity: spot × (1 + quote rate × days/basis) / (1 + base rate × days/basis), with the forward points (pips of 0.0001, 0.01 against JPY) and the premium over spot for the period and a year. It is implied by rates, not a dealer quote.",
4299
- "The rates are SOFR (USD), €STR (EUR), SONIA (GBP) and TIIE 28d (MXN), each with its day and publisher. A pair whose rate is missing says which one. Tenors count calendar days from today: 30d, 2w, 3m, 1y. The forward is today's: it does not take --date, as only the latest short rates are served.",
4421
+ "--forward <tenor> gives the forward implied by covered interest parity: spot × (1 + quote rate × days/basis) / (1 + base rate × days/basis), a compounded rate (CDI, ZARONIA) grown as it compounds, with the forward points (pips of 0.0001, 0.01 against JPY) and the premium over spot for the period and a year. It is implied by rates, not a dealer quote.",
4422
+ "The rates are SOFR (USD), €STR (EUR), SONIA (GBP), TIIE 28d (MXN), CDI (BRL), SORA (SGD) and ZARONIA (ZAR), and for TRY the CBRT's policy rate (one-week repo), each with its day and publisher. A pair whose rate is missing says which one. Tenors count calendar days from today: 30d, 2w, 3m, 1y. The forward is today's: it does not take --date, as only the latest short rates are served.",
4423
+ "An amount in front gives the carry on it: fx 5000000 USD/MXN --forward 30d is the forward points on 5,000,000 USD over the 30 days, in MXN and in your base currency at spot, and which side earns it. The side holding the currency whose rate earns more over the tenor earns it: short USD/MXN (selling USD forward) when the forward is above spot. The amount is above zero, and a forward at spot has no carry.",
4300
4424
  ],
4301
4425
  }],
4302
- examples: ["fx EUR", "fx NGN", "fx yen", "fx USD/NGN", "fx ZAR/NGN", "fx 1234.5 EUR/USD", "fx 1234,5 EUR USD", "fx USD/CAD --date 2026-09-02", "fx JPY --json", "fx USD/MXN --forward 30d", "fx EUR/USD --forward 3m"],
4426
+ examples: ["fx EUR", "fx NGN", "fx yen", "fx USD/NGN", "fx ZAR/NGN", "fx 1234.5 EUR/USD", "fx 1234,5 EUR USD", "fx USD/CAD --date 2026-09-02", "fx JPY --json", "fx USD/MXN --forward 30d", "fx EUR/USD --forward 3m", "fx 5000000 USD/MXN --forward 30d"],
4303
4427
  },
4304
4428
  execute: runFx,
4305
4429
  },
@@ -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.
@@ -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")],
@@ -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.