@gloom-sh/terminal 0.20.8 → 0.20.10
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.
- package/package.json +1 -1
- package/src/api-client/auth.ts +6 -0
- package/src/api-client/data.ts +1 -0
- package/src/api-client/earnings.ts +15 -0
- package/src/api-client/futures-curve.ts +5 -1
- package/src/api-client/index.ts +14 -3
- package/src/api-client/types/account.ts +10 -0
- package/src/api-client/types/billing.ts +10 -0
- package/src/api-client/types/econ.ts +19 -7
- package/src/api-client/types/market.ts +7 -0
- package/src/api-client/types/screener.ts +2 -0
- package/src/cli/commands/market.ts +18 -8
- package/src/cli/commands/overview.ts +28 -7
- package/src/cli/commands/ticker.ts +40 -15
- package/src/cli/desktop-pane-shot.ts +39 -0
- package/src/cli/errors.ts +20 -3
- package/src/cli/fx-pair.ts +11 -2
- package/src/cli/history-rows.ts +34 -3
- package/src/cli/index.ts +1 -1
- package/src/cli/listing-arg.ts +51 -13
- package/src/cli/pane-functions/data.ts +3 -2
- package/src/cli/pane-functions/headless.ts +5 -2
- package/src/cli/pane-functions/index.ts +1 -0
- package/src/cli/pane-functions/resolver.ts +2 -1
- package/src/cli/pane-functions/screenshot-assessment.ts +73 -5
- package/src/cli/pane-functions/screenshot-types.ts +4 -0
- package/src/cli/symbol-cells.ts +6 -0
- package/src/cli/symbol-list.ts +14 -6
- package/src/cli/symbol-rows.ts +12 -5
- package/src/components/chart/composite/chart-layout.ts +7 -4
- package/src/components/chart/composite/composite-chart.tsx +6 -16
- package/src/components/chart/composite/toolbar.tsx +258 -82
- package/src/components/chart/composite/use-composite-chart-keyboard.ts +5 -6
- package/src/components/command-bar/list/model.ts +13 -0
- package/src/components/command-bar/routes/ticker-search/actions.ts +2 -0
- package/src/components/command-bar/routes/ticker-search/results.ts +15 -8
- package/src/components/command-bar/surface/index.tsx +10 -5
- package/src/components/command-bar/workflow/alert.ts +21 -7
- package/src/components/data-table/table-pane.ts +3 -1
- package/src/components/layout/pane/footer/model.ts +26 -1
- package/src/components/metric-treemap/heat-surface.tsx +2 -1
- package/src/components/metric-treemap/index.tsx +3 -2
- package/src/components/ui/confirm-dialog.tsx +253 -7
- package/src/components/ui/data-table/index.tsx +1 -1
- package/src/components/ui/data-table/types.ts +7 -0
- package/src/components/ui/list-view.tsx +4 -3
- package/src/components/ui/page-stack-view.tsx +24 -6
- package/src/components/ui/status.tsx +9 -6
- package/src/docs/snapshot.json +36 -0
- package/src/i18n/es.ts +12 -0
- package/src/i18n/ja.ts +12 -0
- package/src/i18n/ko.ts +12 -0
- package/src/i18n/zh-cn.ts +12 -0
- package/src/i18n/zh-tw.ts +12 -0
- package/src/market-data/futures-roll-returns.ts +226 -0
- package/src/market-data/fx-closes.ts +14 -2
- package/src/market-data/market/change-basis.ts +35 -1
- package/src/market-data/market/session-close-note.ts +41 -4
- package/src/market-data/market/status.ts +37 -0
- package/src/market-data/performance.ts +4 -1
- package/src/market-data/quotes/listing-enterprise-value.ts +8 -4
- package/src/market-data/quotes/live-valuation.ts +25 -2
- package/src/market-data/realized-volatility.ts +3 -0
- package/src/market-data/us-bond-market.ts +115 -0
- package/src/plugins/builtin/account-management/invite-row.tsx +54 -0
- package/src/plugins/builtin/account-management/keyboard.ts +3 -0
- package/src/plugins/builtin/account-management/model.ts +1 -0
- package/src/plugins/builtin/account-management/pane.tsx +51 -5
- package/src/plugins/builtin/account-management/trial-cancel.ts +32 -7
- package/src/plugins/builtin/backtest/client.ts +9 -2
- package/src/plugins/builtin/backtest/pane.tsx +1 -1
- package/src/plugins/builtin/backtest/report.ts +22 -6
- package/src/plugins/builtin/backtest/window.ts +17 -9
- package/src/plugins/builtin/cloud/askg/pane-session.ts +94 -0
- package/src/plugins/builtin/cloud/askg/pane.tsx +40 -83
- package/src/plugins/builtin/congress-trades/pane.tsx +8 -2
- package/src/plugins/builtin/correlation/compute.ts +4 -3
- package/src/plugins/builtin/correlation/headless.ts +6 -2
- package/src/plugins/builtin/correlation/index.tsx +7 -3
- package/src/plugins/builtin/correlation/matrix/model.ts +15 -1
- package/src/plugins/builtin/correlation/relationship/model.ts +15 -1
- package/src/plugins/builtin/correlation/relationship/pane.tsx +4 -2
- package/src/plugins/builtin/earnings/board-model.ts +33 -0
- package/src/plugins/builtin/earnings/board-table.ts +50 -11
- package/src/plugins/builtin/earnings/board.tsx +29 -13
- package/src/plugins/builtin/earnings/calendar.tsx +15 -3
- package/src/plugins/builtin/earnings/client.ts +4 -1
- package/src/plugins/builtin/earnings/headless.ts +27 -14
- package/src/plugins/builtin/econ/calendar-source.ts +3 -0
- package/src/plugins/builtin/futures-curve/headless.ts +4 -1
- package/src/plugins/builtin/futures-curve/model.ts +24 -0
- package/src/plugins/builtin/help/index.tsx +1 -1
- package/src/plugins/builtin/ipo-calendar/model.ts +3 -3
- package/src/plugins/builtin/iv-history/headless.ts +12 -10
- package/src/plugins/builtin/kelly-sizer/headless.ts +2 -2
- package/src/plugins/builtin/kelly-sizer/history.ts +10 -3
- package/src/plugins/builtin/kelly-sizer/pane.tsx +2 -2
- package/src/plugins/builtin/kelly-sizer/sections.tsx +1 -1
- package/src/plugins/builtin/macro-day/headless.ts +15 -5
- package/src/plugins/builtin/macro-day/model.ts +17 -4
- package/src/plugins/builtin/macro-day/releases.ts +36 -15
- package/src/plugins/builtin/market-halts/model.ts +3 -2
- package/src/plugins/builtin/market-movers/headless.ts +2 -1
- package/src/plugins/builtin/market-movers/index.tsx +3 -2
- package/src/plugins/builtin/market-movers/model.ts +75 -22
- package/src/plugins/builtin/market-movers/screener.ts +2 -1
- package/src/plugins/builtin/market-movers/table.ts +7 -5
- package/src/plugins/builtin/pe-band/model.ts +4 -0
- package/src/plugins/builtin/portfolio-list/cell-version.ts +4 -4
- package/src/plugins/builtin/portfolio-list/cli/render.ts +9 -4
- package/src/plugins/builtin/portfolio-list/pane/index.tsx +2 -1
- package/src/plugins/builtin/portfolio-list/summary/index.tsx +24 -7
- package/src/plugins/builtin/portfolio-list/summary/totals.ts +40 -11
- package/src/plugins/builtin/portfolio-list/table.tsx +13 -1
- package/src/plugins/builtin/realized-vol/headless.ts +11 -6
- package/src/plugins/builtin/realized-vol/model.ts +14 -6
- package/src/plugins/builtin/realized-vol/pane.tsx +2 -1
- package/src/plugins/builtin/realized-vol/settings.ts +2 -1
- package/src/plugins/builtin/research/analyst-headless.ts +9 -1
- package/src/plugins/builtin/research/analyst-pane.tsx +10 -4
- package/src/plugins/builtin/research/client.ts +25 -1
- package/src/plugins/builtin/research/corporate-actions-pane.tsx +2 -1
- package/src/plugins/builtin/research/event-model.ts +3 -13
- package/src/plugins/builtin/research/event-sources.ts +3 -1
- package/src/plugins/builtin/seasonality/client.ts +66 -17
- package/src/plugins/builtin/seasonality/headless.ts +7 -2
- package/src/plugins/builtin/seasonality/model.ts +12 -3
- package/src/plugins/builtin/seasonality/pane.tsx +4 -2
- package/src/plugins/builtin/shared/use-quote-board.ts +28 -6
- package/src/plugins/builtin/short-interest/headless.ts +2 -0
- package/src/plugins/builtin/short-interest/publications-headless.ts +2 -0
- package/src/plugins/builtin/short-interest/watch-headless.ts +1 -0
- package/src/plugins/builtin/yield-curve/headless.ts +5 -1
- package/src/plugins/builtin/yield-curve/index.tsx +5 -0
- package/src/portfolio/column-values.ts +47 -14
- package/src/portfolio/return-metrics.ts +4 -2
- package/src/renderers/dom/desktop/controls.tsx +1 -1
- package/src/renderers/dom/host/image-surface.tsx +19 -9
- package/src/renderers/dom/host/input.tsx +4 -0
- package/src/renderers/dom/styles.css +7 -4
- package/src/renderers/electrobun/view/cli-pane-shot-entry.tsx +23 -1
- package/src/renderers/opentui/box-width.ts +30 -0
- package/src/sources/gloomberb-cloud/normalizers.ts +2 -0
- package/src/sources/provider-errors.ts +12 -0
- package/src/sources/provider-router/index.ts +12 -4
- package/src/state/pane-session.ts +145 -0
- package/src/tickers/search/home-listing.ts +44 -1
- package/src/tickers/search/index.ts +5 -2
- package/src/tickers/search/ranking.ts +7 -7
- package/src/tickers/us-listing.ts +11 -5
- package/src/time-series/base-series.ts +7 -1
- package/src/time-series/fundamentals/current-valuation.ts +8 -0
- package/src/time-series/fundamentals/series.ts +6 -0
- package/src/time-series/resolve.ts +1 -0
- package/src/types/financials.ts +36 -3
- package/src/types/headless.ts +15 -0
- package/src/ui/host.tsx +2 -0
- package/src/utils/exchanges.ts +13 -8
- package/src/utils/fundamentals.ts +49 -8
- package/src/utils/price-earnings.ts +17 -10
- package/src/utils/price-history-integrity.ts +15 -0
- package/src/utils/reason-codes.ts +79 -0
- package/src/utils/share-multiples.cases.json +889 -0
- package/src/utils/share-multiples.ts +254 -0
- package/src/utils/untrusted-text.ts +11 -0
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
import type { TickerFinancials } from "../../../../types/financials";
|
|
2
2
|
import type { TickerRecord } from "../../../../types/ticker";
|
|
3
|
-
import { convertCurrency, formatCompactAmount } from "../../../../utils/format";
|
|
4
|
-
import { getCurrencySymbol } from "../../../../market-data/market/format";
|
|
5
|
-
import { getActiveQuoteDisplay } from "../../../../market-data/market/status";
|
|
6
|
-
import {
|
|
3
|
+
import { convertCurrency, formatCompactAmount, formatNumber } from "../../../../utils/format";
|
|
4
|
+
import { currencyMinorDigits, getCurrencySymbol } from "../../../../market-data/market/format";
|
|
5
|
+
import { extendedPrintSession, getActiveQuoteDisplay, type ExtendedSession } from "../../../../market-data/market/status";
|
|
6
|
+
import { dayMoveBasisLabel, futuresQuoteFromSettle, quoteChangeBasis, type QuoteChangeBasis } from "../../../../market-data/market/change-basis";
|
|
7
7
|
import { isQuoteStaleForCurrentSession } from "../../../../market-data/quotes/freshness";
|
|
8
8
|
import { headlineQuoteDisplay } from "../../../../portfolio/column-values";
|
|
9
9
|
import type { AllocationHolding } from "../../../../portfolio/allocation";
|
|
@@ -48,10 +48,13 @@ export interface PortfolioSummaryTotals {
|
|
|
48
48
|
/**
|
|
49
49
|
* What Day (or a watchlist's Avg Day) is measured from, as each holding's
|
|
50
50
|
* change line says it: "vs Fri 16 Oct close" when they agree, "vs mixed
|
|
51
|
-
* closes" when they do not (an HKEX listing beside a US one)
|
|
52
|
-
*
|
|
51
|
+
* closes" when they do not (an HKEX listing beside a US one), after the
|
|
52
|
+
* session of the extended-hours prints it is valued at, as the rows mark
|
|
53
|
+
* them ("AH vs Tue 10 Nov close"). Absent without a move.
|
|
53
54
|
*/
|
|
54
55
|
dayChangeBasis?: string;
|
|
56
|
+
/** Some holding's day is valued at an extended-hours print, which dayChangeBasis names. */
|
|
57
|
+
dayAtExtendedPrint?: boolean;
|
|
55
58
|
totalCostBasis: number;
|
|
56
59
|
hasPositions: boolean;
|
|
57
60
|
unrealizedPnl: number;
|
|
@@ -77,17 +80,39 @@ function currencyCode(value: string | undefined): string | null {
|
|
|
77
80
|
|
|
78
81
|
export { resolvePortfolioTotalsCurrency } from "../../../../portfolio/totals-currency";
|
|
79
82
|
|
|
83
|
+
/** From here a book's totals read in whole units (1,588), as `portfolio show` prints market values; below it, to the minor unit (101.10). */
|
|
84
|
+
const WHOLE_AMOUNT_FROM = 1_000;
|
|
85
|
+
/** From here they read compact (1.23B), so a header row keeps its other figures. */
|
|
86
|
+
const COMPACT_AMOUNT_FROM = 1_000_000_000;
|
|
87
|
+
|
|
88
|
+
/**
|
|
89
|
+
* An amount with thousands separators: to the currency's minor unit below a
|
|
90
|
+
* thousand (101.10, ¥950), in whole units from there (1,588, -40,000) and
|
|
91
|
+
* compact from a billion (1.23B). A signed amount carries + or -, except one
|
|
92
|
+
* that rounds to zero.
|
|
93
|
+
*/
|
|
94
|
+
function bookAmountText(value: number | undefined, currency: string, signed: boolean): string {
|
|
95
|
+
if (value == null || !Number.isFinite(value)) return formatCompactAmount(value);
|
|
96
|
+
const abs = Math.abs(value);
|
|
97
|
+
if (abs >= COMPACT_AMOUNT_FROM) return formatCompactAmount(value, { signed });
|
|
98
|
+
const minor = currencyMinorDigits(currency);
|
|
99
|
+
const body = formatNumber(abs, Number(abs.toFixed(minor)) >= WHOLE_AMOUNT_FROM ? 0 : minor);
|
|
100
|
+
if (!/[1-9]/.test(body)) return body;
|
|
101
|
+
return `${value < 0 ? "-" : signed ? "+" : ""}${body}`;
|
|
102
|
+
}
|
|
103
|
+
|
|
80
104
|
/**
|
|
81
|
-
* A
|
|
82
|
-
*
|
|
83
|
-
*
|
|
105
|
+
* A total in the portfolio's currency (bookAmountText): never rounded to a
|
|
106
|
+
* hundred, as a compact 1.6k for $1,587.80 was. Bare when both it and the
|
|
107
|
+
* app's base currency are USD, as the pane has always shown it; otherwise it
|
|
108
|
+
* leads with the currency symbol, as prices do: A$108,612, +$600.12.
|
|
84
109
|
*/
|
|
85
110
|
export function formatPortfolioAmount(
|
|
86
111
|
value: number | undefined,
|
|
87
112
|
currency: string,
|
|
88
113
|
{ signed = false, baseCurrency = "USD" }: { signed?: boolean; baseCurrency?: string } = {},
|
|
89
114
|
): string {
|
|
90
|
-
const text =
|
|
115
|
+
const text = bookAmountText(value, currency, signed);
|
|
91
116
|
const bare = currency === "USD" && (currencyCode(baseCurrency) ?? "USD") === "USD";
|
|
92
117
|
if (bare || value == null || !Number.isFinite(value)) return text;
|
|
93
118
|
const sign = text.startsWith("+") || text.startsWith("-") ? text.charAt(0) : "";
|
|
@@ -135,6 +160,8 @@ export function calculatePortfolioSummaryTotals(
|
|
|
135
160
|
let watchlistChangeSum = 0;
|
|
136
161
|
let watchlistCount = 0;
|
|
137
162
|
const dayBases: Array<QuoteChangeBasis | null> = [];
|
|
163
|
+
// The extended session of each price the day is valued at, null for a regular one.
|
|
164
|
+
const dayPrints: Array<ExtendedSession | null> = [];
|
|
138
165
|
const unavailableConversions = new Set<string>();
|
|
139
166
|
let livePriced = true;
|
|
140
167
|
const pricedLots: PricedPortfolioLot[] = [];
|
|
@@ -249,6 +276,7 @@ export function calculatePortfolioSummaryTotals(
|
|
|
249
276
|
session: valuationBasis === "regular-close" ? "regular" : "active",
|
|
250
277
|
terms,
|
|
251
278
|
}));
|
|
279
|
+
dayPrints.push(valuationBasis === "latest-print" ? extendedPrintSession(quote, activeQuote.price) : null);
|
|
252
280
|
}
|
|
253
281
|
} else {
|
|
254
282
|
// A broker mark is not evidence of an unchanged day.
|
|
@@ -269,7 +297,7 @@ export function calculatePortfolioSummaryTotals(
|
|
|
269
297
|
const unrealizedPnl = signedUnrealizedPnl;
|
|
270
298
|
const unrealizedPnlPct = portfolioPnlPercent(unrealizedPnl, totalCostBasis) ?? Number.NaN;
|
|
271
299
|
const avgWatchlistChange = watchlistCount > 0 ? watchlistChangeSum / watchlistCount : 0;
|
|
272
|
-
const dayChangeBasis =
|
|
300
|
+
const dayChangeBasis = dayMoveBasisLabel(dayBases, dayPrints, { marks: true, now });
|
|
273
301
|
|
|
274
302
|
return {
|
|
275
303
|
totalMktValue,
|
|
@@ -287,6 +315,7 @@ export function calculatePortfolioSummaryTotals(
|
|
|
287
315
|
dailyPnl,
|
|
288
316
|
dailyPnlPct,
|
|
289
317
|
...(dayChangeBasis ? { dayChangeBasis } : {}),
|
|
318
|
+
...(dayChangeBasis && dayPrints.some((print) => print != null) ? { dayAtExtendedPrint: true } : {}),
|
|
290
319
|
totalCostBasis,
|
|
291
320
|
hasPositions,
|
|
292
321
|
unrealizedPnl,
|
|
@@ -52,6 +52,9 @@ const GROSS_WEIGHT_LABEL = "GROSS WT";
|
|
|
52
52
|
/** P&L%'s header over a period: each position's P&L as a share of the book at the start. */
|
|
53
53
|
const CONTRIBUTION_LABEL = "CONTRIB";
|
|
54
54
|
|
|
55
|
+
/** What an extended-hours print's session mark adds to LAST: `AH `, `PM ` or `ON `. */
|
|
56
|
+
const SESSION_MARK_WIDTH = 3;
|
|
57
|
+
|
|
55
58
|
/** The widest a futures quantity grows the QTY column: `-12,000 × 5,000 bushels` fits. */
|
|
56
59
|
const MAX_QUANTITY_COLUMN_WIDTH = 24;
|
|
57
60
|
|
|
@@ -282,6 +285,14 @@ export function PortfolioTickerTable({
|
|
|
282
285
|
(widest, ticker) => Math.max(widest, displayWidth(resolveCell(sharesColumn, ticker, tableFinancialsMap.get(ticker.metadata.ticker)).text)),
|
|
283
286
|
sharesColumn.width,
|
|
284
287
|
)) : 0;
|
|
288
|
+
// A book at the latest print marks an extended-hours print in LAST (AH 158.78), so the column grows to fit the mark.
|
|
289
|
+
const priceColumn = columns.find((column) => column.id === "price");
|
|
290
|
+
const priceWidth = useMemo(() => priceColumn && columnContext.valuationBasis === "latest-print"
|
|
291
|
+
? Math.min(priceColumn.width + SESSION_MARK_WIDTH, sortedTickers.reduce(
|
|
292
|
+
(widest, ticker) => Math.max(widest, displayWidth(resolveCell(priceColumn, ticker, tableFinancialsMap.get(ticker.metadata.ticker)).text)),
|
|
293
|
+
priceColumn.width,
|
|
294
|
+
))
|
|
295
|
+
: 0, [columnContext.valuationBasis, priceColumn, resolveCell, sortedTickers, tableFinancialsMap]);
|
|
285
296
|
// The Ticker column grows to its longest symbol, so ETH-USD and BA:LSE show whole beside their market-state dot.
|
|
286
297
|
const tickerWidth = useMemo(() => Math.min(MAX_TICKER_COLUMN_WIDTH, sortedTickers.reduce(
|
|
287
298
|
(widest, ticker) => Math.max(widest, TICKER_DOT_WIDTH + displayWidth(listedSymbol(ticker, tickerDisplayName(ticker), columnContext.homeMarket))),
|
|
@@ -295,13 +306,14 @@ export function PortfolioTickerTable({
|
|
|
295
306
|
? { ...column, label: "QTY", ...(sharesWidth > column.width ? { width: sharesWidth } : {}) }
|
|
296
307
|
: column.id === "weight" && grossWeights ? { ...column, label: GROSS_WEIGHT_LABEL }
|
|
297
308
|
: column.id === "ticker" && tickerWidth > column.width ? { ...column, width: tickerWidth }
|
|
309
|
+
: column.id === "price" && priceWidth > column.width ? { ...column, width: priceWidth }
|
|
298
310
|
: column.id === "pnl_pct" && period ? { ...column, label: CONTRIBUTION_LABEL }
|
|
299
311
|
: pnlLabel !== "P&L" && (column.id === "pnl" || column.id === "pnl_pct") ? {
|
|
300
312
|
...column,
|
|
301
313
|
label: column.id === "pnl_pct" ? pnlLabel.replace("P&L", "%") : pnlLabel,
|
|
302
314
|
} : column).map((column) => BOOK_CURRENCY_COLUMN_IDS.has(column.id) ? bookCurrencyColumn(column, capCurrency) : column)
|
|
303
315
|
.map((column) => hasFrontReference && column.id === noteColumnId ? { ...column, flexGrow: 1 } : column),
|
|
304
|
-
[capCurrency, columns, grossWeights, hasFrontReference, hasNonShareQuantity, noteColumnId, period, pnlLabel, sharesWidth, tickerWidth]);
|
|
316
|
+
[capCurrency, columns, grossWeights, hasFrontReference, hasNonShareQuantity, noteColumnId, period, pnlLabel, priceWidth, sharesWidth, tickerWidth]);
|
|
305
317
|
// Read again as the rows' data moves, from the cells the rows show; the columns change only when what is hidden does.
|
|
306
318
|
// The company columns hidden last time, per list, stay hidden while a row added since settles.
|
|
307
319
|
const hiddenCompanyRef = useRef<{ list: string | undefined; ids: ReadonlySet<string> }>({ list: undefined, ids: new Set() });
|
|
@@ -44,13 +44,16 @@ export function realizedVolHeadless(initialView: "graph" | "cone"): HeadlessPane
|
|
|
44
44
|
{ key: "tab", type: "enum", values: [{ value: "graph" }, { value: "cone" }], defaultValue: initialView,
|
|
45
45
|
description: "Initial view", pluginState: { pluginId: "ticker-research", key: "activeTabId" } },
|
|
46
46
|
{ key: "estimator", type: "enum", values: ESTIMATOR_OPTIONS.map(({ value }) => ({ value })), defaultValue: "close-to-close", description: "Realized volatility estimator" },
|
|
47
|
-
{ key: "windows", type: "string", defaultValue: "
|
|
47
|
+
{ key: "windows", type: "string", defaultValue: "",
|
|
48
|
+
description: "Comma-separated bar windows from 10,20,30,60,90,180,260: the cone rows and graph lines shown (every row, and the 10,30,90 lines, when left out)" },
|
|
48
49
|
{ key: "lookbackYears", type: "integer", minimum: 1, maximum: 2, defaultValue: 1, description: "Historical lookback in calendar years" },
|
|
49
50
|
{ key: "showIv", type: "boolean", defaultValue: true, description: "Include a dated current ATM IV observation" },
|
|
50
51
|
],
|
|
51
52
|
async load(args, ctx) {
|
|
52
|
-
|
|
53
|
-
|
|
53
|
+
// Windows asked for are the cone's rows and the graph's lines; none asked for, every row and the graph's default lines.
|
|
54
|
+
const asked = String(args.options.windows ?? "").trim();
|
|
55
|
+
const windows = selectedWindows(asked);
|
|
56
|
+
if (asked && (!windows.length || asked.split(",").some((value) => !windows.includes(Number(value))))) {
|
|
54
57
|
throw new Error("Choose bar windows from 10,20,30,60,90,180,260");
|
|
55
58
|
}
|
|
56
59
|
const instrument = await resolveHeadlessInstrument(ctx, args.symbols[0]!);
|
|
@@ -81,7 +84,8 @@ export function realizedVolHeadless(initialView: "graph" | "cone"): HeadlessPane
|
|
|
81
84
|
ctx.signal.throwIfAborted();
|
|
82
85
|
const model = projectRealizedVolatility(history.history, { symbol: instrument.symbol, exchange: instrument.exchange,
|
|
83
86
|
estimator: ESTIMATOR_OPTIONS.find(({ value }) => value === args.options.estimator)?.value,
|
|
84
|
-
windows
|
|
87
|
+
// The windows asked for are the whole report: its rows, whether it is complete, and what it warns of.
|
|
88
|
+
windows, ...(asked ? { coneWindows: windows } : {}), lookbackYears: Number(args.options.lookbackYears) === 2 ? 2 : 1 });
|
|
85
89
|
const errors = [history.error, iv?.error].filter((value): value is string => !!value);
|
|
86
90
|
const proxyReading = proxy ? fxProxyIvLessRv(proxy, history.history, currencyPairInstrument(instrument.symbol, instrument.exchange)) : null;
|
|
87
91
|
// The cone rows are as of the last daily bar, not of when the report ran.
|
|
@@ -98,7 +102,7 @@ export function realizedVolHeadless(initialView: "graph" | "cone"): HeadlessPane
|
|
|
98
102
|
{ key: "percentile", header: "Percentile", format: (value) => typeof value === "number" ? `${value.toFixed(1)}%` : "--" },
|
|
99
103
|
{ key: "sampleSize", header: "Samples" },
|
|
100
104
|
], rows: model.cone.map((row) => ({ ...row })) },
|
|
101
|
-
...proxy && proxyReading ? [fxProxySection(proxy, proxyReading)] : fx ? [] : [{ title: "Current IV", entries: [
|
|
105
|
+
...proxy && proxyReading ? [fxProxySection(proxy, proxyReading)] : fx || !args.options.showIv ? [] : [{ title: "Current IV", entries: [
|
|
102
106
|
{ label: "ATM IV", value: iv?.reference?.value ?? null, formatted: iv?.reference ? `${(iv.reference.value * 100).toFixed(2)}%` : "--" },
|
|
103
107
|
{ label: "Expiry", value: iv?.reference?.expiration ?? null,
|
|
104
108
|
formatted: iv?.reference ? new Date(iv.reference.expiration * 1000).toISOString().slice(0, 10) : "--" },
|
|
@@ -117,7 +121,8 @@ export function realizedVolHeadless(initialView: "graph" | "cone"): HeadlessPane
|
|
|
117
121
|
&& !proxyReading?.stale,
|
|
118
122
|
unavailableSymbols: model.history.length ? [] : [instrument.symbol], errors,
|
|
119
123
|
// A proxy that could not be read leaves the pair's own volatility whole: said, not failed.
|
|
120
|
-
notes: [barsPerYearLabel(model.barsPerYear), ...model.
|
|
124
|
+
notes: [barsPerYearLabel(model.barsPerYear), ...model.rollNote ? [model.rollNote] : [], ...model.historyNote ? [model.historyNote] : [],
|
|
125
|
+
...proxy?.error ? [proxy.error] : [],
|
|
121
126
|
...proxyReading?.note ? [proxyReading.note] : []],
|
|
122
127
|
metadata: { unit: "decimal annualized volatility", annualization: model.barsPerYear, model, currentIv: iv,
|
|
123
128
|
...proxy ? { fxVolProxy: { ...proxy, ...proxyReading } } : {},
|
|
@@ -6,6 +6,7 @@ import {
|
|
|
6
6
|
} from "../shared/volatility";
|
|
7
7
|
import type { SurfaceExpiry, SurfaceSnapshot } from "../vol-surface/model";
|
|
8
8
|
import { formingBarsState, isFormingBar } from "../shared/forming-bars";
|
|
9
|
+
import { rollAdjustedHistory } from "../../../market-data/futures-roll-returns";
|
|
9
10
|
|
|
10
11
|
export interface RealizedVolatilityModel {
|
|
11
12
|
symbol: string;
|
|
@@ -14,7 +15,7 @@ export interface RealizedVolatilityModel {
|
|
|
14
15
|
windows: number[];
|
|
15
16
|
history: PricePoint[];
|
|
16
17
|
series: RollingRealizedVolatilityPoint[];
|
|
17
|
-
/** The cone
|
|
18
|
+
/** The cone's rows: `coneWindows`, every standard window unless asked, independent of chart selection. */
|
|
18
19
|
cone: VolatilityConeStatistics[];
|
|
19
20
|
asOf: Date | null;
|
|
20
21
|
/** What the volatility is annualised at, read from the series' own dates. */
|
|
@@ -37,6 +38,8 @@ export interface RealizedVolatilityModel {
|
|
|
37
38
|
* through 2026-10-29, the last complete session". Null when every bar is final.
|
|
38
39
|
*/
|
|
39
40
|
formingNote: string | null;
|
|
41
|
+
/** A continuous future's estimates read within one contract at each roll: "rolls back-adjusted" (rollAdjustedHistory). Null for anything else. */
|
|
42
|
+
rollNote: string | null;
|
|
40
43
|
}
|
|
41
44
|
|
|
42
45
|
/** "the 180-bar window", "the 180- and 260-bar windows", "the 90-, 180- and 260-bar windows". */
|
|
@@ -53,6 +56,8 @@ export interface RealizedVolatilityProjectionOptions {
|
|
|
53
56
|
estimator?: RealizedVolatilityEstimator;
|
|
54
57
|
lookbackYears?: 1 | 2;
|
|
55
58
|
windows?: readonly number[];
|
|
59
|
+
/** The cone's rows, and the windows a short history or a failed estimate is said for: every standard window when left out. */
|
|
60
|
+
coneWindows?: readonly number[];
|
|
56
61
|
}
|
|
57
62
|
|
|
58
63
|
function lookbackCutoff(date: Date, years: number): number {
|
|
@@ -73,6 +78,7 @@ export function projectRealizedVolatility(
|
|
|
73
78
|
const instrument = currencyPairInstrument(options.symbol, options.exchange);
|
|
74
79
|
const windows = [...new Set(options.windows ?? REALIZED_VOLATILITY_WINDOWS)]
|
|
75
80
|
.filter((window) => REALIZED_VOLATILITY_WINDOWS.some((standard) => standard === window));
|
|
81
|
+
const coneWindows = REALIZED_VOLATILITY_WINDOWS.filter((window) => !options.coneWindows || options.coneWindows.includes(window));
|
|
76
82
|
const warnings: string[] = [];
|
|
77
83
|
// What follows from a history shorter than the windows and lookback asked for: notes, not failures.
|
|
78
84
|
let shortLookback = false;
|
|
@@ -100,15 +106,17 @@ export function projectRealizedVolatility(
|
|
|
100
106
|
const cutoff = asOf ? lookbackCutoff(asOf, lookbackYears) : 0;
|
|
101
107
|
const cadenceIssue = realizedVolatilityCadenceIssue(history);
|
|
102
108
|
if (cadenceIssue) warnings.push(cadenceIssue);
|
|
109
|
+
// A continuous future's returns are each one contract's; the price drawn beside them stays as traded.
|
|
110
|
+
const returns = rollAdjustedHistory(history, options.symbol);
|
|
103
111
|
const series = cadenceIssue
|
|
104
112
|
? history.map((point) => ({ date: point.date, values: Object.fromEntries(windows.map((window) => [window, null])) }))
|
|
105
|
-
: rollingRealizedVolatility(
|
|
106
|
-
const cone = volatilityCone(cadenceIssue ? [] :
|
|
113
|
+
: rollingRealizedVolatility(returns.points, { windows, estimator, instrument });
|
|
114
|
+
const cone = volatilityCone(cadenceIssue ? [] : returns.points, { windows: coneWindows, estimator, lookbackYears, instrument });
|
|
107
115
|
const visible = history.filter((point) => point.date.getTime() > cutoff);
|
|
108
116
|
const visibleSeries = series.filter((point) => point.date.getTime() > cutoff);
|
|
109
117
|
if (history.length > 0 && history[0]!.date.getTime() > cutoff) shortLookback = true;
|
|
110
|
-
for (const window of history.length > 0 && !cadenceIssue ?
|
|
111
|
-
const result = realizedVolatilityResult(
|
|
118
|
+
for (const window of history.length > 0 && !cadenceIssue ? coneWindows : []) {
|
|
119
|
+
const result = realizedVolatilityResult(returns.points, window, estimator, instrument);
|
|
112
120
|
if (result.reason === "insufficient-history") shortWindows.push(window);
|
|
113
121
|
else if (result.reason) warnings.push(`HV${window} unavailable: ${result.reason.replaceAll("-", " ")}`);
|
|
114
122
|
}
|
|
@@ -127,7 +135,7 @@ export function projectRealizedVolatility(
|
|
|
127
135
|
: "the long windows' cone covers part of the lookback"}`;
|
|
128
136
|
return { symbol: options.symbol.trim().toUpperCase(), estimator, lookbackYears, windows,
|
|
129
137
|
history: visible, series: visibleSeries, cone, asOf, barsPerYear: barsPerYear(history.map((point) => point.date), instrument),
|
|
130
|
-
warnings: [...new Set(warnings)], shortWindows, historyNote, formingNote };
|
|
138
|
+
warnings: [...new Set(warnings)], shortWindows, historyNote, formingNote, rollNote: cadenceIssue ? null : returns.note };
|
|
131
139
|
}
|
|
132
140
|
|
|
133
141
|
interface CurrentAtmIvReference {
|
|
@@ -159,7 +159,8 @@ export function RealizedVolPane({ width, height, focused }: PaneProps) {
|
|
|
159
159
|
...(history.loading ? [{ id: "loading", parts: [{ text: "loading history", tone: "muted" as const }] }] : []),
|
|
160
160
|
...(history.data?.stale ? [{ id: "stale", parts: [{ text: "stale history", tone: "warning" as const }] }] : []),
|
|
161
161
|
...(history.data ? [{ id: "cadence", parts: [{
|
|
162
|
-
text: model ? `daily closes · ${barsPerYearLabel(model.barsPerYear)}` : "
|
|
162
|
+
text: model ? `daily closes · ${barsPerYearLabel(model.barsPerYear)}${model.rollNote ? ` · ${model.rollNote}` : ""}` : "daily closes",
|
|
163
|
+
tone: "muted" as const,
|
|
163
164
|
}] }] : []),
|
|
164
165
|
...(model?.asOf ? [{ id: "date", parts: [{ text: model.asOf.toISOString().slice(0, 10), tone: "muted" as const }] }] : []),
|
|
165
166
|
...(showIv && iv.loading ? [{ id: "iv-loading", parts: [{ text: "loading ATM IV", tone: "muted" as const }] }] : []),
|
|
@@ -10,7 +10,8 @@ export const ESTIMATOR_OPTIONS: { value: RealizedVolatilityEstimator; label: str
|
|
|
10
10
|
export const WINDOW_OPTIONS = REALIZED_VOLATILITY_WINDOWS.map((value) => ({ value: String(value), label: `${value} bars` }));
|
|
11
11
|
export const DEFAULT_WINDOWS = ["10", "30", "90"];
|
|
12
12
|
|
|
13
|
+
/** The windows a setting or `--windows` names; the graph's default ones when it names none. */
|
|
13
14
|
export function selectedWindows(value: unknown): number[] {
|
|
14
|
-
const values = Array.isArray(value) ? value : typeof value === "string" ? value.split(",") : DEFAULT_WINDOWS;
|
|
15
|
+
const values = Array.isArray(value) ? value : typeof value === "string" && value.trim() ? value.split(",") : DEFAULT_WINDOWS;
|
|
15
16
|
return [...new Set(values.map(Number).filter((window) => (REALIZED_VOLATILITY_WINDOWS as readonly number[]).includes(window)))].sort((a, b) => a - b);
|
|
16
17
|
}
|
|
@@ -9,7 +9,7 @@ import type {
|
|
|
9
9
|
import type { AnalystResearchData, Quote } from "../../../types/financials";
|
|
10
10
|
import { logFailure } from "../../../utils/log-failure";
|
|
11
11
|
import { formatPercent } from "../../../utils/format";
|
|
12
|
-
import { loadAnalystResearch } from "./client";
|
|
12
|
+
import { hasAnalystCoverage, loadAnalystResearch, noAnalystCoverageText } from "./client";
|
|
13
13
|
import {
|
|
14
14
|
analystReferenceMetadata,
|
|
15
15
|
analystTargetCurrency,
|
|
@@ -185,6 +185,14 @@ export function createAnalystResearchHeadless(
|
|
|
185
185
|
dependencies.loadData(symbol, args, ctx),
|
|
186
186
|
dependencies.loadQuote?.(symbol, ctx) ?? Promise.resolve(null),
|
|
187
187
|
]);
|
|
188
|
+
// A listing no analyst covers has nothing to sum up or list: the report says so once.
|
|
189
|
+
if (!hasAnalystCoverage(data)) {
|
|
190
|
+
return {
|
|
191
|
+
sections: [{ title: "Recent analyst actions", columns: RATING_COLUMNS, rows: [] }],
|
|
192
|
+
empty: noAnalystCoverageText(data.symbol || symbol),
|
|
193
|
+
metadata: { symbol: data.symbol || symbol, name: data.name ?? null },
|
|
194
|
+
};
|
|
195
|
+
}
|
|
188
196
|
const { upside, reference } = analystUpside(data, quote);
|
|
189
197
|
const currency = analystTargetCurrency(data);
|
|
190
198
|
const ratings = sortRatingRows(data.ratings, {
|
|
@@ -27,7 +27,7 @@ import { handleRefreshKey, useClampSelectedIndex } from "../../../components/dat
|
|
|
27
27
|
import { SignInWall } from "../cloud/auth-actions";
|
|
28
28
|
import { isCloudSessionRequired, useResearchCloudSession } from "../shared/research-cloud-session";
|
|
29
29
|
import { useBoundTicker as useSymbolBinding, useTickerRequest } from "../shared/ticker-request";
|
|
30
|
-
import { loadAnalystResearch } from "./client";
|
|
30
|
+
import { hasAnalystCoverage, loadAnalystResearch, noAnalystCoverageText } from "./client";
|
|
31
31
|
import {
|
|
32
32
|
DEFAULT_RATING_SORT,
|
|
33
33
|
analystReferencePrice,
|
|
@@ -109,7 +109,7 @@ function AnalystHeader({ data, history, series, currency, width, height, tableRo
|
|
|
109
109
|
const consensusLabel = !nativePaneChrome && width < 44 ? "Cons." : "Consensus";
|
|
110
110
|
const split = ratingSplit(data);
|
|
111
111
|
// The table body already reports loading, error, and empty states.
|
|
112
|
-
const figures: StatItem[] = data ? [
|
|
112
|
+
const figures: StatItem[] = hasAnalystCoverage(data) ? [
|
|
113
113
|
{ id: "target", label: consensusLabel, value: formatAnalystPrice(target?.average, currency) },
|
|
114
114
|
{
|
|
115
115
|
id: "upside",
|
|
@@ -194,6 +194,10 @@ export function AnalystResearchView({ focused, width, height }: { focused: boole
|
|
|
194
194
|
}, [dataProvider, cloudSession.requestKey]);
|
|
195
195
|
const { data, loading, error, reload } = useTickerRequest<AnalystResearchData>(loader, symbol, exchange);
|
|
196
196
|
const authWall = !data && isCloudSessionRequired(error);
|
|
197
|
+
// A listing no analyst covers loads as research with nothing in it: the body says so, the footer has nothing to add.
|
|
198
|
+
const noCoverage = !!data && !hasAnalystCoverage(data);
|
|
199
|
+
// A failure with nothing loaded is the body's to say; one behind data on screen (a refresh), the footer's.
|
|
200
|
+
const failedEmpty = !!symbol && !data && !loading && !!error && !authWall;
|
|
197
201
|
const rows = useMemo(() => sortRatingRows(data?.ratings ?? [], sortPreference), [data?.ratings, sortPreference]);
|
|
198
202
|
const ratingCurrency = analystTargetCurrency(data);
|
|
199
203
|
const columns = useMemo(
|
|
@@ -278,9 +282,9 @@ export function AnalystResearchView({ focused, width, height }: { focused: boole
|
|
|
278
282
|
const selectedRow = rows.length > 0 ? rows[selectedIdx] : undefined;
|
|
279
283
|
const footer = (
|
|
280
284
|
<AnalystFooter
|
|
281
|
-
data={authWall ? null : data}
|
|
285
|
+
data={authWall || noCoverage ? null : data}
|
|
282
286
|
loading={loading}
|
|
283
|
-
error={authWall ? null : error}
|
|
287
|
+
error={authWall || failedEmpty ? null : error}
|
|
284
288
|
width={width}
|
|
285
289
|
binding={binding}
|
|
286
290
|
focused={focused}
|
|
@@ -332,6 +336,8 @@ export function AnalystResearchView({ focused, width, height }: { focused: boole
|
|
|
332
336
|
getItemKey={(row, index) => `${row.date}:${row.firm}:${index}`}
|
|
333
337
|
renderCell={renderCell}
|
|
334
338
|
selectedTextOverridesCellColor
|
|
339
|
+
status={noCoverage ? { empty: true, emptyTitle: noAnalystCoverageText(symbol ?? data?.symbol ?? "") }
|
|
340
|
+
: failedEmpty && error ? { error, subject: "Analyst research" } : undefined}
|
|
335
341
|
emptyStateTitle={loading ? "Loading analyst data..." : error ?? "No analyst data"}
|
|
336
342
|
/>
|
|
337
343
|
</>
|
|
@@ -1,6 +1,15 @@
|
|
|
1
|
+
import { isNoDataAnswer } from "../../../sources/provider-errors";
|
|
2
|
+
import { hasAnalystResearchValue } from "../../../sources/provider-router/financials";
|
|
1
3
|
import type { DataProvider, MarketDataRequestContext } from "../../../types/data-provider";
|
|
2
4
|
import type { AnalystResearchData } from "../../../types/financials";
|
|
3
5
|
|
|
6
|
+
/**
|
|
7
|
+
* The listing's analyst research. A listing no analyst covers (CENN) is
|
|
8
|
+
* answered with research that holds nothing, which `hasAnalystCoverage`
|
|
9
|
+
* reads, not with a failure: the service answered it has nothing for a
|
|
10
|
+
* symbol it knows. A symbol it does not know, and a source that did not
|
|
11
|
+
* answer, still fail.
|
|
12
|
+
*/
|
|
4
13
|
export async function loadAnalystResearch(
|
|
5
14
|
provider: DataProvider,
|
|
6
15
|
symbol: string,
|
|
@@ -8,5 +17,20 @@ export async function loadAnalystResearch(
|
|
|
8
17
|
context?: MarketDataRequestContext,
|
|
9
18
|
): Promise<AnalystResearchData> {
|
|
10
19
|
if (!provider.getAnalystResearch) throw new Error("Analyst data unavailable");
|
|
11
|
-
|
|
20
|
+
try {
|
|
21
|
+
return await provider.getAnalystResearch(symbol, exchange, context);
|
|
22
|
+
} catch (error) {
|
|
23
|
+
if (!isNoDataAnswer(error)) throw error;
|
|
24
|
+
return { symbol, recommendations: [], ratings: [], earningsEstimates: [], revenueEstimates: [] };
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
/** Whether any analyst covers the listing: a target, a rating mix, an action or an estimate. */
|
|
29
|
+
export function hasAnalystCoverage(data: AnalystResearchData | null | undefined): boolean {
|
|
30
|
+
return !!data && hasAnalystResearchValue(data);
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/** What a pane or a report says for a listing no analyst covers. */
|
|
34
|
+
export function noAnalystCoverageText(symbol: string): string {
|
|
35
|
+
return `No analyst coverage for ${symbol}.`;
|
|
12
36
|
}
|
|
@@ -27,6 +27,7 @@ import { useResolvedEntryValue, useSecFilingDocuments, useSecFilingsQuery } from
|
|
|
27
27
|
import { instrumentFromTicker } from "../../../market-data/request-types";
|
|
28
28
|
import { usePaneTicker } from "../../../state/app/context";
|
|
29
29
|
import { mayBeUsEquityTicker } from "../../../utils/sec";
|
|
30
|
+
import { loadAnalystResearch } from "./client";
|
|
30
31
|
import { useAssetData, usePluginPaneState } from "../../runtime";
|
|
31
32
|
import { handleRefreshKey } from "../../../components/data-table/table-pane";
|
|
32
33
|
import { SignInWall } from "../cloud/auth-actions";
|
|
@@ -469,7 +470,7 @@ export function CorporateActionsView({
|
|
|
469
470
|
}, [dataProvider, cloudSession.requestKey]);
|
|
470
471
|
const analystLoader = useCallback(async (nextSymbol: string, nextExchange: string, forceRefresh: boolean) => {
|
|
471
472
|
if (!dataProvider?.getAnalystResearch) return null;
|
|
472
|
-
return dataProvider
|
|
473
|
+
return loadAnalystResearch(dataProvider, nextSymbol, nextExchange, forceRefresh ? { cacheMode: "refresh" } : undefined);
|
|
473
474
|
}, [dataProvider, cloudSession.requestKey]);
|
|
474
475
|
// The earnings calendar's next report, which the rows are resolved against as `earnings` and ERN read it.
|
|
475
476
|
const calendarLoader = useCallback((nextSymbol: string, _exchange: string, forceRefresh: boolean) => (
|
|
@@ -16,6 +16,7 @@ import {
|
|
|
16
16
|
import { computeTTM } from "../ticker-detail/financials/aggregation";
|
|
17
17
|
import { classifyInstrumentType } from "../../../tickers/instrument-kind";
|
|
18
18
|
import { declaredDividends } from "../../../utils/declared-dividends";
|
|
19
|
+
import { isReasonCode, readableStatus } from "../../../utils/reason-codes";
|
|
19
20
|
import { fundamentalsEpsCurrency, SERVED_TRAILING_EPS } from "../../../utils/fundamentals";
|
|
20
21
|
import {
|
|
21
22
|
earningsDateStatus,
|
|
@@ -497,7 +498,7 @@ export function eventSourceNotice(state: EventSourceState): EventSourceNotice |
|
|
|
497
498
|
.filter(([section, status]) => status === "unavailable" && (state.variant !== "earnings-estimates" || section === "earnings"))
|
|
498
499
|
.map(([section]) => section);
|
|
499
500
|
// Sections and estimates that a source failed to give share one line: "Unavailable: earnings, analyst estimates (the source did not answer)".
|
|
500
|
-
const estimatesCode =
|
|
501
|
+
const estimatesCode = isReasonCode(state.estimatesError);
|
|
501
502
|
const sharedLine = !state.actionsError && unavailableSections.length > 0 && estimatesCode;
|
|
502
503
|
|
|
503
504
|
if (state.actionsError) {
|
|
@@ -530,23 +531,12 @@ export function eventSourceNotice(state: EventSourceState): EventSourceNotice |
|
|
|
530
531
|
};
|
|
531
532
|
}
|
|
532
533
|
|
|
533
|
-
/** A data service's reason code (UPSTREAM_ERROR) rather than words. */
|
|
534
|
-
const REASON_CODE = /^[A-Z][A-Z0-9_]+$/;
|
|
535
|
-
|
|
536
534
|
/**
|
|
537
535
|
* A source's failure in words: a reason code reads as what happened
|
|
538
536
|
* ("UPSTREAM_ERROR" is "the source did not answer"); a sentence stands.
|
|
539
537
|
*/
|
|
540
538
|
export function sourceErrorText(error: string): string {
|
|
541
|
-
|
|
542
|
-
if (!REASON_CODE.test(text)) return text;
|
|
543
|
-
switch (text) {
|
|
544
|
-
case "TIMEOUT": return "the source timed out";
|
|
545
|
-
case "NOT_FOUND":
|
|
546
|
-
case "NO_DATA": return "the source has none for this symbol";
|
|
547
|
-
case "RATE_LIMITED": return "the source is busy, try again shortly";
|
|
548
|
-
default: return "the source did not answer";
|
|
549
|
-
}
|
|
539
|
+
return readableStatus(error.trim());
|
|
550
540
|
}
|
|
551
541
|
|
|
552
542
|
function hasCorporateActionRows(data: CorporateActionsData): boolean {
|
|
@@ -5,6 +5,7 @@ import type {
|
|
|
5
5
|
TickerFinancials,
|
|
6
6
|
} from "../../../types/financials";
|
|
7
7
|
import { formatEventMetric } from "./event-model";
|
|
8
|
+
import { loadAnalystResearch } from "./client";
|
|
8
9
|
import { formatPercent, formatPercentRaw } from "../../../utils/format";
|
|
9
10
|
import { loadEarningsCalendar } from "../earnings/data/cache";
|
|
10
11
|
import { calendarEventOf, newYorkDay, withResolvedEarnings } from "../shared/earnings-calendar";
|
|
@@ -74,7 +75,8 @@ function settledError(result: PromiseSettledResult<unknown>): string | null {
|
|
|
74
75
|
export async function loadEventSources(provider: DataProvider, symbol: string, today = newYorkDay()): Promise<EventSources> {
|
|
75
76
|
const [actions, estimates, financials, calendar] = await Promise.allSettled([
|
|
76
77
|
provider.getCorporateActions?.(symbol, "") ?? null,
|
|
77
|
-
|
|
78
|
+
// A listing no analyst covers answers with no estimates, not a failure.
|
|
79
|
+
provider.getAnalystResearch ? loadAnalystResearch(provider, symbol, "") : null,
|
|
78
80
|
provider.getTickerFinancials(symbol, ""),
|
|
79
81
|
loadEarningsCalendar(provider, [symbol]),
|
|
80
82
|
]);
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { unavailableText } from "../../../components/ui/status";
|
|
2
2
|
import { getSharedMarketDataCoordinator, MarketDataCoordinator, resolveEntryValue } from "../../../market-data/coordinator";
|
|
3
|
-
import
|
|
3
|
+
import { isContinuousFuture, rollAdjustedHistory } from "../../../market-data/futures-roll-returns";
|
|
4
|
+
import type { ChartRequest, InstrumentRef } from "../../../market-data/request-types";
|
|
4
5
|
import type { ManualChartResolution } from "../../../time-series/resolution";
|
|
5
6
|
import type { DataProvider } from "../../../types/data-provider";
|
|
6
7
|
import type { PricePoint } from "../../../types/financials";
|
|
@@ -12,6 +13,14 @@ export interface SeasonalityHistory {
|
|
|
12
13
|
stale: boolean;
|
|
13
14
|
error: string | null;
|
|
14
15
|
fetchedAt: number;
|
|
16
|
+
/** A continuous future's returns, read within one contract at each roll: "rolls back-adjusted" (rollAdjustedHistory). */
|
|
17
|
+
rollNote?: string;
|
|
18
|
+
/**
|
|
19
|
+
* The bars as served and their size, what a capture hands the pane to read
|
|
20
|
+
* again: a continuous future's daily bars before their rolls were closed,
|
|
21
|
+
* anything else's `history` itself.
|
|
22
|
+
*/
|
|
23
|
+
served: { points: PricePoint[]; resolution: ManualChartResolution };
|
|
15
24
|
}
|
|
16
25
|
|
|
17
26
|
/** Monthly closes for the Returns and Overlay tabs, daily closes for Weekdays. */
|
|
@@ -19,27 +28,63 @@ export type SeasonalityCadence = "monthly" | "daily";
|
|
|
19
28
|
|
|
20
29
|
const CANCELLED = "Seasonality history load was cancelled";
|
|
21
30
|
/** The cadence each tab reads, and so the cadence a screenshot of it captures. */
|
|
22
|
-
|
|
31
|
+
const SEASONALITY_HISTORY_RESOLUTION: Record<SeasonalityCadence, ManualChartResolution> = { monthly: "1mo", daily: "1d" };
|
|
23
32
|
/** Daily history is served to five years; a longer request can come back as weekly bars. */
|
|
24
33
|
const BUFFER_RANGE = { monthly: "ALL", daily: "5Y" } as const;
|
|
25
34
|
|
|
35
|
+
/**
|
|
36
|
+
* The bars a tab reads: monthly or daily ones, and for a continuous future
|
|
37
|
+
* (NG=F) daily ones either way, the newest a read returns (all of NG=F's,
|
|
38
|
+
* from August 2000), whose rolls are back-adjusted before the months are
|
|
39
|
+
* taken. A lookback reaching before them says where they start
|
|
40
|
+
* (SeasonalityModel.historyStart).
|
|
41
|
+
*/
|
|
42
|
+
function seasonalityRequest(instrument: InstrumentRef, cadence: SeasonalityCadence): ChartRequest {
|
|
43
|
+
if (isContinuousFuture(instrument.symbol)) {
|
|
44
|
+
return { instrument, bufferRange: "ALL", granularity: "resolution", resolution: "1d", newestBars: true };
|
|
45
|
+
}
|
|
46
|
+
return { instrument, bufferRange: BUFFER_RANGE[cadence], granularity: "resolution", resolution: SEASONALITY_HISTORY_RESOLUTION[cadence] };
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/**
|
|
50
|
+
* A continuous future's daily bars with every roll back-adjusted, as the tab
|
|
51
|
+
* reads them: the Weekdays tab the last five years of sessions, the others
|
|
52
|
+
* each month's last close dated by the month's first day, as monthly bars
|
|
53
|
+
* are. Anything else as served.
|
|
54
|
+
*/
|
|
55
|
+
function seasonalitySeries(
|
|
56
|
+
bars: readonly PricePoint[], symbol: string, cadence: SeasonalityCadence,
|
|
57
|
+
): Pick<SeasonalityHistory, "history" | "rollNote" | "served"> {
|
|
58
|
+
if (!isContinuousFuture(symbol)) {
|
|
59
|
+
return { history: [...bars], served: { points: [...bars], resolution: SEASONALITY_HISTORY_RESOLUTION[cadence] } };
|
|
60
|
+
}
|
|
61
|
+
const adjusted = rollAdjustedHistory(bars, symbol);
|
|
62
|
+
const note = { served: { points: [...bars], resolution: "1d" as const }, ...adjusted.note ? { rollNote: adjusted.note } : {} };
|
|
63
|
+
if (cadence === "daily") {
|
|
64
|
+
const from = new Date(adjusted.points.at(-1)?.date ?? 0);
|
|
65
|
+
from.setUTCFullYear(from.getUTCFullYear() - 5);
|
|
66
|
+
return { history: adjusted.points.filter((point) => new Date(point.date).getTime() > from.getTime()), ...note };
|
|
67
|
+
}
|
|
68
|
+
const months = new Map<string, PricePoint>();
|
|
69
|
+
for (const point of adjusted.points) {
|
|
70
|
+
const day = new Date(point.date).toISOString();
|
|
71
|
+
months.set(day.slice(0, 7), { date: new Date(`${day.slice(0, 7)}-01T00:00:00Z`), close: point.close });
|
|
72
|
+
}
|
|
73
|
+
return { history: [...months.values()], ...note };
|
|
74
|
+
}
|
|
75
|
+
|
|
26
76
|
export function cachedSeasonalityHistory(
|
|
27
77
|
request: { instrument: InstrumentRef; cadence?: SeasonalityCadence },
|
|
28
78
|
): SeasonalityHistory | null {
|
|
29
79
|
const coordinator = getSharedMarketDataCoordinator();
|
|
30
80
|
if (!coordinator) return null;
|
|
31
81
|
const cadence = request.cadence ?? "monthly";
|
|
32
|
-
const entry = coordinator.getChartEntry(
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
granularity: "resolution",
|
|
36
|
-
resolution: SEASONALITY_HISTORY_RESOLUTION[cadence],
|
|
37
|
-
});
|
|
38
|
-
const history = resolveEntryValue(entry);
|
|
39
|
-
if (!history?.length) return null;
|
|
82
|
+
const entry = coordinator.getChartEntry(seasonalityRequest(request.instrument, cadence));
|
|
83
|
+
const served = resolveEntryValue(entry);
|
|
84
|
+
if (!served?.length) return null;
|
|
40
85
|
const now = Date.now();
|
|
41
86
|
return {
|
|
42
|
-
|
|
87
|
+
...seasonalitySeries(served, request.instrument.symbol, cadence),
|
|
43
88
|
stale: !!entry.error || (entry.staleAt != null && entry.staleAt <= now),
|
|
44
89
|
error: entry.error?.message ?? null,
|
|
45
90
|
fetchedAt: entry.fetchedAt ?? now,
|
|
@@ -51,7 +96,9 @@ export function cachedSeasonalityHistory(
|
|
|
51
96
|
* refetches. Monthly bars, because daily history is only served to 5Y where
|
|
52
97
|
* provider support is not known yet, and a longer daily request comes back as
|
|
53
98
|
* Monday-stamped weeks that file a week's close under the wrong month. The
|
|
54
|
-
* Weekdays tab needs sessions, so it reads those five years of daily bars.
|
|
99
|
+
* Weekdays tab needs sessions, so it reads those five years of daily bars. A
|
|
100
|
+
* continuous future reads the newest daily bars a request returns for every
|
|
101
|
+
* tab, so its rolls can be back-adjusted (seasonalitySeries).
|
|
55
102
|
*/
|
|
56
103
|
export async function loadSeasonalityHistory(
|
|
57
104
|
request: { instrument: InstrumentRef; cadence?: SeasonalityCadence; signal?: AbortSignal; forceRefresh?: boolean },
|
|
@@ -63,14 +110,16 @@ export async function loadSeasonalityHistory(
|
|
|
63
110
|
const coordinator = marketData ? new MarketDataCoordinator(marketData) : getSharedMarketDataCoordinator();
|
|
64
111
|
try {
|
|
65
112
|
if (!coordinator) throw new Error("Market data coordinator unavailable");
|
|
66
|
-
const entry = await abortable(coordinator.loadChart(
|
|
67
|
-
|
|
68
|
-
const
|
|
69
|
-
|
|
113
|
+
const entry = await abortable(coordinator.loadChart(seasonalityRequest(request.instrument, cadence),
|
|
114
|
+
{ forceRefresh: request.forceRefresh }), request.signal, CANCELLED);
|
|
115
|
+
const series = seasonalitySeries(resolveEntryValue(entry) ?? [], request.instrument.symbol, cadence);
|
|
116
|
+
const history = series.history;
|
|
117
|
+
return { ...series, stale: !!entry.error || (entry.staleAt != null && entry.staleAt <= now),
|
|
70
118
|
error: entry.error?.message ?? (history.length ? null : unavailableText(cadence === "daily" ? "Daily price history" : "Monthly price history")),
|
|
71
119
|
fetchedAt: entry.fetchedAt ?? now };
|
|
72
120
|
} catch (error) {
|
|
73
121
|
if (request.signal?.aborted || (error instanceof Error && error.name === "AbortError")) throw abortError(CANCELLED);
|
|
74
|
-
return { history: [], stale: false, error: errorMessage(error), fetchedAt: now
|
|
122
|
+
return { history: [], stale: false, error: errorMessage(error), fetchedAt: now,
|
|
123
|
+
served: { points: [], resolution: SEASONALITY_HISTORY_RESOLUTION[cadence] } };
|
|
75
124
|
}
|
|
76
125
|
}
|