gloomberb 0.20.6 → 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 (67) hide show
  1. package/package.json +1 -1
  2. package/src/api-client/fund-facts.ts +20 -4
  3. package/src/api-client/socket.ts +4 -4
  4. package/src/architecture/shortcut-labels-allowlist.json +1 -0
  5. package/src/cli/commands/market.ts +33 -17
  6. package/src/cli/commands/search.ts +19 -3
  7. package/src/cli/desktop-pane-shot.ts +61 -0
  8. package/src/cli/pane-functions/dom.ts +4 -4
  9. package/src/cli/pane-functions/freshness.ts +38 -5
  10. package/src/cli/pane-functions/screenshot-assessment.ts +16 -4
  11. package/src/cli/quote-answer.ts +57 -1
  12. package/src/cli/result.ts +17 -0
  13. package/src/docs/snapshot.json +55 -16
  14. package/src/i18n/es.ts +2 -0
  15. package/src/i18n/ja.ts +2 -0
  16. package/src/i18n/ko.ts +2 -0
  17. package/src/i18n/zh-cn.ts +2 -0
  18. package/src/i18n/zh-tw.ts +2 -0
  19. package/src/market-data/market/change-basis.ts +49 -8
  20. package/src/market-data/market/dated-previous-close.ts +133 -10
  21. package/src/market-data/market/freshness.ts +18 -6
  22. package/src/market-data/market/status.ts +9 -1
  23. package/src/market-data/published-nse-sessions.ts +16 -1
  24. package/src/market-data/quotes/freshness.ts +15 -0
  25. package/src/plugins/builtin/alerts/alert-engine.ts +15 -0
  26. package/src/plugins/builtin/alerts/cli.ts +22 -9
  27. package/src/plugins/builtin/alerts/headless.ts +1 -1
  28. package/src/plugins/builtin/alerts/index.tsx +5 -1
  29. package/src/plugins/builtin/alerts/metric-command.ts +1 -1
  30. package/src/plugins/builtin/holders/fund-holders.ts +22 -1
  31. package/src/plugins/builtin/holders/headless.ts +5 -4
  32. package/src/plugins/builtin/holders/pane.tsx +7 -3
  33. package/src/plugins/builtin/holders/report-header.ts +23 -0
  34. package/src/plugins/builtin/members/client.ts +1 -1
  35. package/src/plugins/builtin/members/headless.ts +2 -0
  36. package/src/plugins/builtin/members/model.ts +10 -8
  37. package/src/plugins/builtin/members/pane.tsx +4 -1
  38. package/src/plugins/builtin/portfolio-list/cli/portfolio-command.ts +5 -2
  39. package/src/plugins/builtin/portfolio-list/cli/render.ts +66 -23
  40. package/src/plugins/builtin/portfolio-list/headless.ts +2 -1
  41. package/src/plugins/builtin/portfolio-list/income.ts +46 -22
  42. package/src/plugins/builtin/portfolio-list/pane/data.ts +16 -6
  43. package/src/plugins/builtin/portfolio-list/pane/index.tsx +5 -4
  44. package/src/plugins/builtin/portfolio-list/use-throttled-ticker-order.ts +40 -3
  45. package/src/plugins/builtin/sec/fund-facts.ts +25 -5
  46. package/src/plugins/builtin/shared/report-freshness.ts +15 -6
  47. package/src/plugins/builtin/supply-chain/model.ts +18 -6
  48. package/src/portfolio/column-values.ts +3 -0
  49. package/src/portfolio/valuation-basis.ts +23 -1
  50. package/src/state/hooks/quote-streaming.ts +14 -6
  51. package/src/tickers/instrument-kind.ts +22 -1
  52. package/src/tickers/search/index.ts +5 -0
  53. package/src/tickers/terminal-codes.ts +17 -5
  54. package/src/time-series/fundamentals/current-valuation.ts +244 -0
  55. package/src/time-series/fundamentals/historical-valuation.ts +99 -0
  56. package/src/time-series/fundamentals/metric-ids.ts +61 -0
  57. package/src/time-series/fundamentals/period-points.ts +104 -0
  58. package/src/time-series/fundamentals/quarterly-ttm.ts +220 -0
  59. package/src/time-series/fundamentals/series.ts +164 -0
  60. package/src/time-series/fundamentals/source-statements.ts +177 -0
  61. package/src/time-series/fundamentals/statement-fields.ts +154 -0
  62. package/src/time-series/fundamentals/statement-merge.ts +124 -0
  63. package/src/time-series/fundamentals/statement.ts +114 -0
  64. package/src/time-series/fundamentals/valuation-multiples.ts +50 -0
  65. package/src/time-series/fundamentals.ts +18 -1407
  66. package/src/types/financials.ts +9 -0
  67. package/src/utils/debug-log.ts +29 -0
@@ -35,7 +35,7 @@ import {
35
35
  holderValueCurrency,
36
36
  resolveHolderOwnershipPercent,
37
37
  } from "./format";
38
- import { holderPeriodsDiffer, holderShareBasisMarker, nonUsHolderCaveat } from "./report-header";
38
+ import { holderPeriodsDiffer, holderShareBasisMarker, isNoHoldersAnswer, nonUsHolderCaveat, noHoldersText } from "./report-header";
39
39
  import {
40
40
  buildColumns,
41
41
  hasHolderChanges,
@@ -80,11 +80,15 @@ export function HoldersView({ focused, width, height }: { focused: boolean; widt
80
80
  const tableScrollRef = useRef<ScrollBoxRenderable | null>(null);
81
81
 
82
82
  const exchange = ticker?.metadata.exchange ?? "";
83
+ const savedCurrency = ticker?.metadata.currency ?? "";
83
84
  const issuerListing = useIssuerListing(ticker);
84
85
  const loadHolders = useMemo(() => symbol ? async (forceRefresh: boolean) => {
85
86
  if (!dataProvider) throw new Error("Holder data unavailable");
86
- return loadHolderData(dataProvider, symbol, exchange, forceRefresh ? { cacheMode: "refresh" } : undefined);
87
- } : null, [dataProvider, exchange, symbol]);
87
+ return loadHolderData(dataProvider, symbol, exchange, forceRefresh ? { cacheMode: "refresh" } : undefined).catch((error: unknown) => {
88
+ // The source has none: the pane says so, and abroad which filings were read, not the source's NO_DATA.
89
+ throw isNoHoldersAnswer(error) ? new Error(noHoldersText(symbol, exchange, savedCurrency)) : error;
90
+ });
91
+ } : null, [dataProvider, exchange, savedCurrency, symbol]);
88
92
  // Another ticker's holders stay up until its own answer, and a failed
89
93
  // refresh keeps the last holders; the failure goes to the footer.
90
94
  const { data, loading, error, reload } = useAsyncResource<HolderData>(loadHolders, {
@@ -2,6 +2,7 @@ import type { HolderData } from "../../../types/financials";
2
2
  import { currencyUnitLabel, resolveCurrencyUnit } from "../../../utils/currency-units";
3
3
  import { adrRatioText } from "../../../utils/depositary-receipt";
4
4
  import { canonicalExchange, isUsListingExchange, resolveExchangeTimeZone } from "../../../utils/exchanges";
5
+ import { isNoSourceAnswer } from "../../../sources/provider-errors";
5
6
 
6
7
  /**
7
8
  * The lines above a holder table in text reports (`holders`, `insider`,
@@ -170,3 +171,25 @@ export function nonUsHolderCaveat(exchange?: string | null, currency?: string |
170
171
  // Few filers report a line abroad, so a small position can lead the list.
171
172
  return `SEC 13F filings only, not the ${venue} share register: the line's largest holders may be missing.`;
172
173
  }
174
+
175
+ /**
176
+ * What a listing no holder source has rows for reads, in place of the
177
+ * source's bare NO_DATA. Abroad it says which filings were read, in the
178
+ * caveat's words: a Shanghai or Shenzhen line no 13F filer reports holding
179
+ * is not one with no shareholders.
180
+ */
181
+ export function noHoldersText(symbol: string, exchange?: string | null, currency?: string | null): string {
182
+ if (!isNonUsHolderListing(exchange, currency)) return `No holders on record for ${symbol}.`;
183
+ const canonical = canonicalExchange(exchange ?? "");
184
+ const venue = resolveExchangeTimeZone(canonical) ? canonical : "local";
185
+ return `No holders on record for ${symbol}: no SEC 13F filing reports it, and the ${venue} share register is not read.`;
186
+ }
187
+
188
+ /**
189
+ * A holder read the source answered with nothing: a miss, or one that
190
+ * crossed the desktop or screenshot bridge, which carries only its message,
191
+ * the source's bare NO_DATA.
192
+ */
193
+ export function isNoHoldersAnswer(error: unknown): boolean {
194
+ return isNoSourceAnswer(error) || (error instanceof Error && error.message.trim() === "NO_DATA");
195
+ }
@@ -40,7 +40,7 @@ async function fetchFundPayload<T>(fund: string, fetcher: () => Promise<T>, vali
40
40
  try { return validate(await fetcher()); } catch (error) {
41
41
  if (error instanceof ApiRequestError && error.status === 404) {
42
42
  const funds = await fetchFunds(client).then((payload) => payload.funds, () => { /* Intentional ignore: an unreadable covered list leaves the server's own message. */ return []; });
43
- if (funds.length && !coveredFund(funds, fund)) throw new Error(notCoveredMessage(fund, funds));
43
+ if (funds.length && !coveredFund(funds, fund)) { const text = notCoveredMessage(fund); throw new Error(`${text.title} ${text.message}`); }
44
44
  }
45
45
  throw unavailableOnServer(error, unavailable);
46
46
  }
@@ -27,7 +27,9 @@ export const membersHeadless: HeadlessPaneDefinition<"rows"> = {
27
27
  }
28
28
  if (args.options.tab === "changes") {
29
29
  const data = await fetchChanges(fund, context.apiClient);
30
+ // An empty table says why: the fund's index changes are not followed, or none is stored, as the pane says.
30
31
  return { freshness: { status: "not-a-feed", basis: "index changes" }, rows: data.changes.map((row) => ({ ...row, reason: changeReason(row) })), columns: [{ key: "effectiveDate", header: "Effective" }, { key: "added", header: "Added" }, { key: "removed", header: "Removed" }, { key: "daysToGo", header: "In days", align: "right" }, { key: "reason", header: "Reason" }],
32
+ empty: data.available ? "No stored index changes." : `Index changes are not covered for ${data.fund.ticker}.`,
31
33
  complete: data.available && !data.stale, metadata: { ...data, changes: undefined } };
32
34
  }
33
35
  const data = await fetchMembers(fund, context.apiClient);
@@ -18,14 +18,16 @@ export function coveredFund(funds: MemberFundsPayload["funds"], input: string) {
18
18
  const symbol = canonicalFund(input);
19
19
  return funds.find((fund) => fund.ticker === symbol || fund.aliases.some((alias) => alias.toUpperCase() === symbol));
20
20
  }
21
- /** Every symbol that opens this fund: the server's aliases and the app's own. */
22
- function fundAliases(fund: MemberFundsPayload["funds"][number]) {
23
- const local = Object.entries(LOCAL_ALIASES).flatMap(([alias, ticker]) => ticker === fund.ticker ? [alias] : []);
24
- return [...new Set([...fund.aliases.map((alias) => alias.toUpperCase()), ...local])].filter((alias) => alias !== fund.ticker);
25
- }
26
- export function notCoveredMessage(input: string, funds: MemberFundsPayload["funds"]) {
27
- const covered = funds.map((fund) => { const aliases = fundAliases(fund); return aliases.length ? `${fund.ticker} (${aliases.join(", ")})` : fund.ticker; });
28
- return `${requestedSymbol(input)} is not a covered fund. Covered: ${covered.join(", ")}.`;
21
+ /**
22
+ * What a fund MEMB does not cover reads: that it is not covered, and where its fund facts and the covered list are,
23
+ * as a command (`gloom fn ETF SMH`) for the report and as a function for the pane. Never the whole covered list.
24
+ */
25
+ export function notCoveredMessage(input: string, surface: "report" | "pane" = "report") {
26
+ const symbol = requestedSymbol(input);
27
+ const title = `${symbol} is not a covered fund.`;
28
+ const message = surface === "pane" ? `Its fund facts are in ETF ${symbol}. MEMB with no fund lists the funds it covers.`
29
+ : `Its fund facts: gloom fn ETF ${symbol}. The covered funds: gloom fn MEMB.`;
30
+ return { title, message };
29
31
  }
30
32
  /** "Partial 1D 334/504 · 91.5% wt": how many holdings have a fresh 1D return, and their share of the fund. */
31
33
  export function coverageText(aggregate: FundMembersPayload["aggregate"], short = false) {
@@ -191,7 +191,10 @@ type FundPaneProps = Pick<PaneProps, "width" | "height" | "focused"> & { fund: s
191
191
  function CoveredFund({ fund, requested, ...props }: FundPaneProps) {
192
192
  const resource = useAsyncResource(loadFunds, { initialData: cachedFunds });
193
193
  const funds = resource.data?.payload.funds;
194
- if (funds?.length && !coveredFund(funds, fund)) return <PaneStatusBody empty emptyTitle={notCoveredMessage(requested, funds)} />;
194
+ if (funds?.length && !coveredFund(funds, fund)) {
195
+ const text = notCoveredMessage(requested, "pane");
196
+ return <PaneStatusBody empty emptyTitle={text.title} emptyMessage={text.message} />;
197
+ }
195
198
  return <FundView key={fund} fund={fund} {...props} />;
196
199
  }
197
200
  export function MembersPane(props: PaneProps) {
@@ -2,6 +2,7 @@ import { saveConfig } from "../../../../data/config/store";
2
2
  import { withConfigData } from "../../../../cli/scoped-context";
3
3
  import { withCollectionConfigData, withCollectionMarketData } from "../../../../cli/suffixed-listing-rows";
4
4
  import { countCollectionTickers } from "../../../../cli/helpers";
5
+ import { exitLeavingReadsBehind } from "../../../../cli/result";
5
6
  import { resolveCliTicker, resolveTickerForCli } from "../../../../cli/ticker-resolution";
6
7
  import { takeFlag, takeOption } from "../../../../cli/commands/command-utils";
7
8
  import { EXCHANGE_OPTION, listingKeys, loadSavedListing, parseListingArg, requireSavedListing, savedListingCandidates, savedListingName, type ListingArg } from "../../../../cli/listing-arg";
@@ -1150,7 +1151,8 @@ export const portfolioCliCommand: CliCommandDef = {
1150
1151
  if (action === "show") {
1151
1152
  const name = args.slice(1).join(" ");
1152
1153
  if (!name) ctx.fail("Usage: gloom portfolio show <name> [--close] [--explain] [--drip] [--from <date> [--to <date>]]");
1153
- await showCollection(name, ctx, { explain, basis, drip, ...(period ? { period } : {}), ...(real ? { real } : {}) });
1154
+ const shown = await showCollection(name, ctx, { explain, basis, drip, ...(period ? { period } : {}), ...(real ? { real } : {}) });
1155
+ if (shown.readsLeftBehind) exitLeavingReadsBehind();
1154
1156
  return;
1155
1157
  }
1156
1158
 
@@ -1218,6 +1220,7 @@ export const portfolioCliCommand: CliCommandDef = {
1218
1220
  ctx.fail(TARGET_USAGE);
1219
1221
  }
1220
1222
 
1221
- await showCollection(args.join(" "), ctx, { explain, basis, drip, ...(period ? { period } : {}) });
1223
+ const shown = await showCollection(args.join(" "), ctx, { explain, basis, drip, ...(period ? { period } : {}) });
1224
+ if (shown.readsLeftBehind) exitLeavingReadsBehind();
1222
1225
  },
1223
1226
  };
@@ -23,6 +23,7 @@ import {
23
23
  getPortfolioValuationTime,
24
24
  valuationBasisLabel,
25
25
  valuationTimeIso,
26
+ valuesAtNominalPrice,
26
27
  valuesAtSettlement,
27
28
  type PortfolioValuationBasis,
28
29
  } from "../../../../portfolio/valuation-basis";
@@ -55,7 +56,7 @@ import type { DataProvider } from "../../../../types/data-provider";
55
56
  import type { CliCommandContext } from "../../../../types/plugin";
56
57
  import type { MarketContext } from "../../../../cli/types";
57
58
  import type { Portfolio, TickerPosition, TickerRecord } from "../../../../types/ticker";
58
- import type { TickerFinancials } from "../../../../types/financials";
59
+ import type { Quote, TickerFinancials } from "../../../../types/financials";
59
60
  import type { TickerInstrumentKind } from "../../../../types/instrument";
60
61
  import { resolveTickerInstrumentKind } from "../../../../tickers/instrument-kind";
61
62
  import { perpetualListing } from "../../../../tickers/perpetual-listing";
@@ -235,8 +236,15 @@ export interface ShowCollectionOptions {
235
236
  cpi?: Parameters<typeof showPeriodPnl>[0]["cpi"];
236
237
  }
237
238
 
238
- export async function showCollection(name: string, ctx: CliCommandContext, options: ShowCollectionOptions = {}) {
239
- await withMarketData(ctx, (context) => showCollectionWithMarketData(name, ctx, context, options));
239
+ /**
240
+ * Prints a portfolio or watchlist. `readsLeftBehind` says reads it stopped
241
+ * waiting for (dividends past their deadline) are still out, which a CLI
242
+ * process need not wait for once the report is out.
243
+ */
244
+ export async function showCollection(name: string, ctx: CliCommandContext, options: ShowCollectionOptions = {}): Promise<{ readsLeftBehind: boolean }> {
245
+ const outcome = { readsLeftBehind: false };
246
+ await withMarketData(ctx, (context) => showCollectionWithMarketData(name, ctx, context, options, outcome));
247
+ return outcome;
240
248
  }
241
249
 
242
250
  /** What `--explain` names a report by when it shows no terms. */
@@ -364,8 +372,12 @@ interface PortfolioValuationFields {
364
372
  valuationPrice: number | null;
365
373
  /** An ISO instant in UTC, or an ISO date for a close whose hour the venue's calendar does not give. */
366
374
  valuationAsOf: string | null;
367
- /** Only on a future valued at its exchange settlement, which `valuationAsOf` dates by its session. */
368
- valuationPriceKind?: "settle";
375
+ /**
376
+ * Only on a future valued at its exchange settlement, which `valuationAsOf`
377
+ * dates by its session, and on a holding at its venue's nominal price,
378
+ * nothing having traded, dated by the session it is that price for.
379
+ */
380
+ valuationPriceKind?: PortfolioValuationPriceKind;
369
381
  }
370
382
 
371
383
  export interface PortfolioValuation {
@@ -499,7 +511,7 @@ export async function valuePortfolioPositions({
499
511
  values.push({ ticker, quote, activeQuote, headline, extended, position: null, metrics: null, pnl: null, dayMove: null, futures: futuresTerms,
500
512
  valuation: { valuationBasis: basis, valuationPrice: known(priced?.price),
501
513
  valuationAsOf: settledHeadline ? futuresTerms!.settlement!.date : valuationTimeIso(getPortfolioValuationTime(quote, basis)),
502
- ...(settledHeadline ? { valuationPriceKind: "settle" as const } : {}) },
514
+ ...(settledHeadline ? { valuationPriceKind: "settle" as const } : valuesAtNominalPrice(quote, null, basis) ? { valuationPriceKind: "nominal" as const } : {}) },
503
515
  row: { symbol: ticker.metadata.ticker, ...listingColumns(ticker, quote), exchange: ticker.metadata.exchange, shares: null, avgCost: null,
504
516
  positionCurrency: null, quotePrice: known(headline?.price), ...quoteMoveColumns(headline), ...extendedQuoteFields(extended), quoteCurrency: quote?.currency ?? null,
505
517
  volume: known(quote?.volume), costBasis: null, marketValue: null, unrealizedPnl: null, baseCurrency: currency } });
@@ -546,7 +558,8 @@ export async function valuePortfolioPositions({
546
558
  holding.marketValue = holding.marketValue == null || marketValue == null ? null : holding.marketValue + marketValue;
547
559
  holding.units += metrics.totalShares;
548
560
  holding.unitPrice ??= valuationQuote ? known(await toBase(valuationQuote.price, quoteCurrency)) : null;
549
- const change = valuationQuote?.change;
561
+ // A listing that no longer trades does not move, as the pane's Day counts it: its last session's change is not today's.
562
+ const change = quote?.delisting ? 0 : valuationQuote?.change;
550
563
  const dayMove = valuationQuote && change != null && Number.isFinite(change)
551
564
  ? { change: await toBase(metrics.totalPriceUnits * change, quoteCurrency),
552
565
  previousValue: await toBase(metrics.grossPriceUnits * (valuationQuote.price - change), quoteCurrency) }
@@ -555,7 +568,8 @@ export async function valuePortfolioPositions({
555
568
  dayMove: dayMove && Number.isFinite(dayMove.change) && Number.isFinite(dayMove.previousValue) ? dayMove : null,
556
569
  valuation: { valuationBasis: basis, valuationPrice: known(valuationQuote?.price),
557
570
  valuationAsOf: valuationTimeIso(getPortfolioValuationTime(quote, basis, metrics, settlement)),
558
- ...(atSettlement && settlement ? { valuationPriceKind: "settle" as const } : {}) },
571
+ ...(atSettlement && settlement ? { valuationPriceKind: "settle" as const }
572
+ : valuesAtNominalPrice(quote, metrics, basis) ? { valuationPriceKind: "nominal" as const } : {}) },
559
573
  row: { symbol: ticker.metadata.ticker, ...listingColumns(ticker, quote), exchange: ticker.metadata.exchange,
560
574
  shares: metrics.totalShares, avgCost: known(position.avgCost), positionCurrency,
561
575
  priceBasis: position.priceBasis ?? null, quantityUnit: metrics.priceBasis === "percent-of-par" ? "face" : null, quotePriceBasis: quote?.priceBasis ?? null,
@@ -564,7 +578,9 @@ export async function valuePortfolioPositions({
564
578
  volume: known(quote?.volume), quoteAsOf: quote ? quoteHeadlineTime(quote) : null,
565
579
  costBasis: known(direction * costBasisBase), marketValue,
566
580
  unrealizedPnl: known(pnl), baseCurrency: currency, dateAcquired: position.dateAcquired ?? null,
567
- pnlBasis: selectedPnl.basis, brokerUnrealizedPnl: known(position.unrealizedPnl), brokerPnlCurrency: positionCurrency, brokerPnlAsOf: null } });
581
+ pnlBasis: selectedPnl.basis, brokerUnrealizedPnl: known(position.unrealizedPnl), brokerPnlCurrency: positionCurrency, brokerPnlAsOf: null,
582
+ // Only at a nominal price: `quoteAsOf` is the last print, older than the session that price is for.
583
+ ...quotePriceKindField(quote) } });
568
584
  }
569
585
  }
570
586
 
@@ -577,22 +593,25 @@ export async function valuePortfolioPositions({
577
593
  * The holdings' move over the day of the prices they are valued at, in the
578
594
  * portfolio's currency, and that move against their value at the close
579
595
  * before, with what it is measured from as the pane's Day says it ("vs Fri 16
580
- * Oct close", "vs mixed closes"). Null when any priced holding's move is
581
- * unknown, as the pane's Day is.
596
+ * Oct close", "vs mixed closes"): at the latest print, the move of that print,
597
+ * a pre-market or after-hours one included; at the close, the regular
598
+ * session's. A listing that no longer trades counts as no move and names no
599
+ * basis. Null when any priced holding's move is unknown, as the pane's Day is.
582
600
  */
583
601
  export function portfolioDayMove(
584
- valuation: Pick<PortfolioValuation, "positions">,
602
+ valuation: Pick<PortfolioValuation, "positions" | "basis">,
585
603
  now = Date.now(),
586
604
  ): { change: number; changePercent: number | null; basis: string | null } | null {
587
605
  let change = 0;
588
606
  let previousValue = 0;
589
607
  const bases: Array<QuoteChangeBasis | null> = [];
608
+ const session = valuation.basis === "regular-close" ? "regular" : "active";
590
609
  for (const entry of valuation.positions) {
591
610
  if (!entry.position) continue;
592
611
  if (!entry.dayMove) return null;
593
612
  change += entry.dayMove.change;
594
613
  previousValue += entry.dayMove.previousValue;
595
- bases.push(quoteChangeBasis(entry.quote, { terms: entry.futures }));
614
+ if (!entry.quote?.delisting) bases.push(quoteChangeBasis(entry.quote, { session, terms: entry.futures }));
596
615
  }
597
616
  return {
598
617
  change,
@@ -765,6 +784,8 @@ function portfolioValuationFreshness(
765
784
  source,
766
785
  observedKey: "valuationAsOf",
767
786
  citeOldest: true,
787
+ // A book across markets names each one's session and open: an HKEX book holding one US fund is not dated by the US day alone.
788
+ datesEachVenue: true,
768
789
  ...(note ? { note: `priced at ${valuationBasisLabel(valuation.basis, { futures: holdsFutures(valuation) })}` } : {}),
769
790
  }, undefined, now);
770
791
  }
@@ -779,12 +800,21 @@ function valuationBasisLine(basis: PortfolioValuationBasis, futures: boolean): s
779
800
  return `Priced at ${valuationBasisLabel(basis, { futures })}`;
780
801
  }
781
802
 
803
+ /** What a row's price is when it is not a print or a close: a future's settlement, or a venue's nominal price. */
804
+ export type PortfolioValuationPriceKind = "settle" | "nominal";
805
+
806
+ /** `quotePriceKind: "nominal"` for a quote at its venue's nominal price (Quote.nominalPrice); nothing for any other. */
807
+ function quotePriceKindField(quote: Quote | null | undefined): { quotePriceKind?: "nominal" } {
808
+ return quote?.nominalPrice ? { quotePriceKind: "nominal" } : {};
809
+ }
810
+
782
811
  /**
783
812
  * An As of cell: when the price a row's value uses is from (`valuationAsOf`),
784
- * in UTC as its header says; a close dated only by its day says so, and a
785
- * future's settlement names its session.
813
+ * in UTC as its header says; a close dated only by its day says so, a
814
+ * future's settlement names its session, and a nominal price the session it
815
+ * is the venue's price for (`Fri 6 Nov nominal`).
786
816
  */
787
- export function valuationTimeText(value: unknown, now = Date.now(), kind?: "settle"): string {
817
+ export function valuationTimeText(value: unknown, now = Date.now(), kind?: PortfolioValuationPriceKind): string {
788
818
  const time = parseReportTime(value);
789
819
  if (!time) return "—";
790
820
  return time.dateOnly ? `${formatUtcDayTime(time, now)} ${kind ?? "close"}` : formatUtcDayTime(time, now);
@@ -808,6 +838,7 @@ async function showCollectionWithMarketData(
808
838
  ctx: CliCommandContext,
809
839
  { config, store, dataProvider, persistence }: MarketContext,
810
840
  { explain = false, basis = "latest-print", drip, dividendDeadlineMs = DIVIDEND_READ_DEADLINE_MS, futuresSources, costFxHistory = apiClient, period, real = false, cpi }: ShowCollectionOptions,
841
+ outcome: { readsLeftBehind: boolean } = { readsLeftBehind: false },
811
842
  ) {
812
843
  const tickers = (await store.loadAllTickers()).sort((left, right) =>
813
844
  left.metadata.ticker.localeCompare(right.metadata.ticker)
@@ -855,8 +886,15 @@ async function showCollectionWithMarketData(
855
886
 
856
887
  const futuresHeld = filtered.filter((ticker) => isFuturesTicker(ticker)
857
888
  && ticker.metadata.positions.some((position) => position.portfolio === id && position.shares !== 0));
889
+ // A book says what its day's move is from on either basis, so its quotes' previous closes are dated.
890
+ const quotesRead = loadCollectionQuotes(filtered, collection, dataProvider, { datesChangeBasis: isPortfolio });
891
+ // What each holding pays a year is read beside its quote, under one deadline from here.
892
+ const dividendsRead = matchedPortfolio && !period
893
+ ? loadHoldingDividends(filtered.filter((ticker) => ticker.metadata.positions.some((position) => position.portfolio === id && position.shares !== 0)),
894
+ quotesRead, dataProvider, { deadlineMs: dividendDeadlineMs })
895
+ : null;
858
896
  const [quotes, futures, purchaseDateFx] = await Promise.all([
859
- loadCollectionQuotes(filtered, collection, dataProvider, { datesChangeBasis: basis === "regular-close" }),
897
+ quotesRead,
860
898
  isPortfolio ? loadPortfolioFuturesTerms(futuresHeld, {
861
899
  settlement: basis === "regular-close",
862
900
  sources: { history: dailyFuturesHistory(dataProvider), ...futuresSources },
@@ -906,7 +944,8 @@ async function showCollectionWithMarketData(
906
944
  // What each holding pays a year: trailing dividends per share times its shares, in the portfolio's currency.
907
945
  // By symbol: a lot whose cost converts at its purchase date's FX close is valued on a copy of its record.
908
946
  const held = filtered.filter((ticker) => valued.some((entry) => entry.ticker.metadata.ticker === ticker.metadata.ticker && entry.position));
909
- const { dividends } = await loadHoldingDividends(held, quotes, dataProvider, { deadlineMs: dividendDeadlineMs });
947
+ const { dividends, timedOut } = await dividendsRead!;
948
+ outcome.readsLeftBehind = timedOut;
910
949
  // Lots without a position or shares are no lot of income; a row of their own keeps its place with none.
911
950
  const income = await portfolioIncome(valued.map((entry) => ({
912
951
  symbol: entry.position && entry.metrics ? entry.ticker.metadata.ticker : "",
@@ -967,8 +1006,9 @@ async function showCollectionWithMarketData(
967
1006
  };
968
1007
  });
969
1008
  const totalPnlValue = unavailablePnl.size > 0 ? null : totalPnl;
970
- // At the close, the value is Last times the shares, so the day's move from the close before is said beside it.
971
- const dayMove = basis === "regular-close" ? portfolioDayMove(valuation) : null;
1009
+ // The value's move from the closes before, totalled under Chg and said with its base under the table: at the close
1010
+ // that is Last times the shares; at the latest print, an after-hours print included, as Value is.
1011
+ const dayMove = portfolioDayMove(valuation);
972
1012
  const cashExport = cash && allocation.cash ? {
973
1013
  ...cash,
974
1014
  weight: allocation.cash.weight,
@@ -1053,7 +1093,7 @@ async function showCollectionWithMarketData(
1053
1093
  total: allocation.total, cash: cashExport, targetSum: allocation.targetSum,
1054
1094
  // Only on a book that holds a short: its weights are shares of `weightBase`, its gross exposure, not of the total.
1055
1095
  ...(allocation.weightBasis === "gross" ? { weightBasis: allocation.weightBasis, weightBase: allocation.weightBase } : {}),
1056
- ...(basis === "regular-close" ? { dayChange: dayMove?.change ?? null, dayChangePercent: dayMove?.changePercent ?? null, dayChangeBasis: dayMove?.basis ?? null } : {}),
1096
+ dayChange: dayMove?.change ?? null, dayChangePercent: dayMove?.changePercent ?? null, dayChangeBasis: dayMove?.basis ?? null,
1057
1097
  unpricedCount: allocation.unpriced.length, unpricedSymbols: allocation.unpriced,
1058
1098
  totalUnrealizedPnl: totalPnlValue,
1059
1099
  annualIncome: totalIncome, knownAnnualIncome: income.knownIncome, portfolioYield,
@@ -1163,8 +1203,9 @@ async function showCollectionWithMarketData(
1163
1203
  ...allocationCells(cashExport, { unpriced: cashExport.value == null }), ...(showIncome ? ["", ""] : []), "", ""]);
1164
1204
  }
1165
1205
  const total = allocation.total;
1206
+ const totalChange = dayMove?.changePercent != null ? colorBySign(formatPercentRaw(dayMove.changePercent), dayMove.change) : "—";
1166
1207
  rows.push([
1167
- cliStyles.bold("TOTAL"), "", "", ...extendedSessions.map(() => ""), "", "",
1208
+ cliStyles.bold("TOTAL"), "", totalChange, ...extendedSessions.map(() => ""), "", "",
1168
1209
  cliStyles.bold(wholeMoney(total)),
1169
1210
  formatAllocationWeight(totalWeight(allocation)),
1170
1211
  ...(showTargets ? [formatAllocationWeight(allocation.targetSum), "", "", ""] : []),
@@ -1200,7 +1241,7 @@ async function showCollectionWithMarketData(
1200
1241
  rows,
1201
1242
  ));
1202
1243
  console.log("");
1203
- if (basis === "regular-close") console.log(dayMoveLine(dayMove, currency, colorBySign, cliStyles.muted));
1244
+ if (valued.some((entry) => entry.position)) console.log(dayMoveLine(dayMove, currency, colorBySign, cliStyles.muted));
1204
1245
  if (valued.some((entry) => entry.position)) console.log(exposureLine(exposure, currency));
1205
1246
  // The rates the holdings in another currency are valued at, dated, so a stale one is seen beside the value it moves.
1206
1247
  const fxLine = fxRatesLine(toBase.conversions(), { warning: cliStyles.warning });
@@ -1482,6 +1523,8 @@ async function valueWatchlistRows({
1482
1523
  // A stale quote (as the source line counts it) and the exchange-local date it last traded.
1483
1524
  stale,
1484
1525
  lastTradeDate: lastTrade,
1526
+ // Only at a nominal price: `quoteAsOf` is the last print, older than the session that price is for.
1527
+ ...quotePriceKindField(quote),
1485
1528
  // A listing that no longer trades: its status and last session.
1486
1529
  ...quote?.delisting ? { delisting: quote.delisting } : {},
1487
1530
  },
@@ -115,7 +115,8 @@ const VALUATION_TIME_COLUMN: HeadlessPaneColumn = {
115
115
  key: "valuationAsOf",
116
116
  header: "As of (UTC)",
117
117
  // Exports keep the ISO time.
118
- textFormat: (value, row) => valuationTimeText(value, undefined, row.valuationPriceKind === "settle" ? "settle" : undefined),
118
+ textFormat: (value, row) => valuationTimeText(value, undefined,
119
+ row.valuationPriceKind === "settle" || row.valuationPriceKind === "nominal" ? row.valuationPriceKind : undefined),
119
120
  shrink: false,
120
121
  description: "When the price the row is valued at is from: its print, or the regular close with --close (a future's settlement).",
121
122
  };
@@ -80,21 +80,24 @@ export interface HoldingDividends {
80
80
  /**
81
81
  * The dividends of a portfolio's shares and funds, keyed by ticker: each
82
82
  * holding's cash history through the data provider, so a history read in the
83
- * last hours comes from the cache, measured as DVD measures it. Every read
84
- * shares one deadline; a holding not read by then, or whose read failed, has
85
- * an unknown rate, never a zero.
83
+ * last hours comes from the cache, measured as DVD measures it. The histories
84
+ * need no quote, so they are read beside the quotes (`quotes` may still be
85
+ * coming), and every read shares one deadline from the call; a holding not
86
+ * read by then, or whose read failed, has an unknown rate, never a zero. A
87
+ * listing its quote shows pays nothing (a coin) is left out once it is in.
86
88
  */
87
89
  export async function loadHoldingDividends(
88
90
  tickers: readonly TickerRecord[],
89
- quotes: ReadonlyMap<string, Quote>,
91
+ quotes: ReadonlyMap<string, Quote> | PromiseLike<ReadonlyMap<string, Quote>>,
90
92
  provider: Pick<DataProvider, "getCorporateActions">,
91
93
  { deadlineMs = DIVIDEND_READ_DEADLINE_MS }: { deadlineMs?: number } = {},
92
94
  ): Promise<HoldingDividends> {
93
- const payers = tickers.filter((ticker) => paysDividends(ticker, quotes.get(ticker.metadata.ticker)));
94
95
  const dividends = new Map<string, HoldingDividend>();
95
96
  const getCorporateActions = provider.getCorporateActions?.bind(provider);
96
97
  // A source with no distribution histories at all (a custom provider) has no income to report, as a coin book has none.
97
- if (payers.length === 0 || !getCorporateActions) return { dividends, timedOut: false };
98
+ if (tickers.length === 0 || !getCorporateActions) return { dividends, timedOut: false };
99
+ // Quotes that fail fail the report that asked for them, not this.
100
+ const quoted = Promise.resolve(quotes).then((known) => known, () => new Map<string, Quote>());
98
101
  let timedOut = false;
99
102
  let timer: ReturnType<typeof setTimeout> | undefined;
100
103
  const deadline = new Promise<"deadline">((resolve) => {
@@ -102,26 +105,47 @@ export async function loadHoldingDividends(
102
105
  });
103
106
  const unread = (why: "timed-out" | "sign-in" | "offline" | "failed"): HoldingDividend =>
104
107
  ({ perShare: null, currency: null, price: null, gap: { cause: "unread", why } });
108
+ const started = new Set<TickerRecord>();
109
+ const read = async (ticker: TickerRecord) => {
110
+ if (timedOut) return;
111
+ started.add(ticker);
112
+ const symbol = ticker.metadata.ticker;
113
+ const exchange = ticker.metadata.exchange ?? "";
114
+ const history = Promise.resolve().then(() => getCorporateActions(symbol, exchange));
115
+ history.catch(() => {
116
+ // Intentional ignore: a read left behind at the deadline has no reader; one awaited below reports its own failure.
117
+ });
118
+ const known = await Promise.race([quoted, deadline]);
119
+ if (known === "deadline") return;
120
+ const quote = known.get(symbol);
121
+ if (!paysDividends(ticker, quote)) return;
122
+ // The quote already read prices the cash; nothing asks for it again.
123
+ const source = {
124
+ getCorporateActions: () => history,
125
+ getQuote: async () => { if (!quote) throw new Error("No quote"); return quote; },
126
+ };
127
+ const result = await Promise.race([
128
+ fetchProviderDividendData(source, symbol, regularSessionValuationPrice(quote), exchange, quote?.currency)
129
+ .then(holdingDividend, (error: unknown) => unread(unreadWhy(error))),
130
+ deadline,
131
+ ]);
132
+ if (result !== "deadline") dividends.set(symbol, result);
133
+ };
105
134
  try {
106
- await Promise.race([deadline, mapWithConcurrency(payers, DIVIDEND_CONCURRENCY, async (ticker) => {
107
- const symbol = ticker.metadata.ticker;
108
- if (timedOut) return;
109
- const quote = quotes.get(symbol);
110
- // The quote already read prices the cash; nothing asks for it again.
111
- const source = {
112
- getCorporateActions,
113
- getQuote: async () => { if (!quote) throw new Error("No quote"); return quote; },
114
- };
115
- const read = fetchProviderDividendData(source, symbol, regularSessionValuationPrice(quote), ticker.metadata.exchange ?? "", quote?.currency)
116
- .then(holdingDividend, (error: unknown) => unread(unreadWhy(error)));
117
- const result = await Promise.race([read, deadline]);
118
- if (result !== "deadline") dividends.set(symbol, result);
119
- })]);
135
+ await Promise.race([deadline, (async () => {
136
+ // A listing its record types as a share or fund starts at once; one only its quote types starts once the quotes are in.
137
+ await mapWithConcurrency(tickers.filter((ticker) => paysDividends(ticker, undefined)), DIVIDEND_CONCURRENCY, read);
138
+ const known = await quoted;
139
+ await mapWithConcurrency(tickers.filter((ticker) => !started.has(ticker) && paysDividends(ticker, known.get(ticker.metadata.ticker))),
140
+ DIVIDEND_CONCURRENCY, read);
141
+ })()]);
120
142
  } finally {
121
143
  clearTimeout(timer);
122
144
  }
123
- for (const ticker of payers) {
124
- if (!dividends.has(ticker.metadata.ticker)) dividends.set(ticker.metadata.ticker, unread("timed-out"));
145
+ const known = await quoted;
146
+ for (const ticker of tickers) {
147
+ const symbol = ticker.metadata.ticker;
148
+ if (!dividends.has(symbol) && paysDividends(ticker, known.get(symbol))) dividends.set(symbol, unread("timed-out"));
125
149
  }
126
150
  return { dividends, timedOut };
127
151
  }
@@ -276,17 +276,24 @@ export function getCollectionTickersFromConfig(
276
276
  .sort((left, right) => left.metadata.ticker.localeCompare(right.metadata.ticker));
277
277
  }
278
278
 
279
+ export interface SortedTickers {
280
+ tickers: TickerRecord[];
281
+ /** The rows that have a figure in the sort column; the rest sit last, in their listed order. */
282
+ valued: Set<string>;
283
+ }
284
+
279
285
  export function sortTickers(
280
286
  tickers: TickerRecord[],
281
287
  financialsMap: Map<string, TickerFinancials>,
282
288
  sortPreference: CollectionSortPreference,
283
289
  columnContext: ColumnContext,
284
290
  columns: ColumnConfig[],
285
- ) {
286
- if (!sortPreference.columnId) return tickers;
291
+ ): SortedTickers {
292
+ const valued = new Set<string>();
293
+ if (!sortPreference.columnId) return { tickers, valued };
287
294
 
288
295
  const sortColumn = columns.find((column) => column.id === sortPreference.columnId);
289
- if (!sortColumn) return tickers;
296
+ if (!sortColumn) return { tickers, valued };
290
297
  const sortContextVersion = `${sortColumn.id}|${columnContextVersion(sortColumn.id, columnContext)}`;
291
298
  const sortValues = new Map<string, ReturnType<typeof getSortValue>>();
292
299
  for (const ticker of tickers) {
@@ -294,17 +301,20 @@ export function sortTickers(
294
301
  // Ticker records and financials are replaced, never mutated, so their
295
302
  // identities version a row without walking its positions on every tick.
296
303
  const version = `${sortContextVersion}|${objectVersion(ticker)}|${objectVersion(financials)}`;
297
- sortValues.set(ticker.metadata.ticker, sortValueCache.get(
304
+ const value = sortValueCache.get(
298
305
  `${ticker.metadata.ticker}:${sortColumn.id}`,
299
306
  version,
300
307
  () => getSortValue(sortColumn, ticker, financials, columnContext),
301
- ));
308
+ );
309
+ sortValues.set(ticker.metadata.ticker, value);
310
+ if (value != null && !(typeof value === "number" && !Number.isFinite(value))) valued.add(ticker.metadata.ticker);
302
311
  }
303
312
 
304
- return [...tickers].sort((leftTicker, rightTicker) => {
313
+ const sorted = [...tickers].sort((leftTicker, rightTicker) => {
305
314
  const leftValue = sortValues.get(leftTicker.metadata.ticker) ?? null;
306
315
  const rightValue = sortValues.get(rightTicker.metadata.ticker) ?? null;
307
316
 
308
317
  return compareSortValues(leftValue, rightValue, sortPreference.direction);
309
318
  });
319
+ return { tickers: sorted, valued };
310
320
  }
@@ -358,16 +358,17 @@ export function PortfolioListPane({ focused, width, height }: PaneProps) {
358
358
  const sortNow = activeSort.columnId === "latency" ? now : Math.floor(now / DAY_MS) * DAY_MS;
359
359
  const sortContext: ColumnContext = useMemo(() => sharePositionMetrics({ ...baseColumnContext, now: sortNow }, baseColumnContext), [baseColumnContext, sortNow]);
360
360
 
361
- const candidateSortedTickers = useMemo(
361
+ const candidateSort = useMemo(
362
362
  () => sortTickers(tickers, financialsMap, activeSort, sortContext, columns),
363
363
  [tickers, financialsMap, activeSort, sortContext, columns],
364
364
  );
365
365
  const candidateSymbols = useMemo(
366
- () => candidateSortedTickers.map((ticker) => ticker.metadata.ticker),
367
- [candidateSortedTickers],
366
+ () => candidateSort.tickers.map((ticker) => ticker.metadata.ticker),
367
+ [candidateSort],
368
368
  );
369
369
  const orderResetKey = `${activeCollectionId}|${activeSort.columnId ?? ""}|${activeSort.direction}`;
370
- const orderedSymbols = useThrottledTickerOrder(candidateSymbols, orderResetKey);
370
+ // Rows getting their first figure (the quotes landing after the rows) take their place at once.
371
+ const orderedSymbols = useThrottledTickerOrder(candidateSymbols, orderResetKey, { valuedSymbols: candidateSort.valued });
371
372
  // Keyed on the records, not the re-sorted candidates, so the rows keep their
372
373
  // identity across ticks until the throttled order actually moves.
373
374
  const tickerBySymbol = useMemo(