gloomberb 0.20.8 → 0.20.9

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 (42) hide show
  1. package/package.json +1 -1
  2. package/src/api-client/futures-curve.ts +5 -1
  3. package/src/cli/commands/overview.ts +2 -0
  4. package/src/cli/pane-functions/data.ts +3 -2
  5. package/src/cli/pane-functions/headless.ts +1 -0
  6. package/src/cli/symbol-cells.ts +6 -0
  7. package/src/cli/symbol-list.ts +14 -6
  8. package/src/cli/symbol-rows.ts +12 -5
  9. package/src/components/ui/page-stack-view.tsx +24 -6
  10. package/src/market-data/futures-roll-returns.ts +226 -0
  11. package/src/market-data/market/session-close-note.ts +41 -4
  12. package/src/market-data/quotes/listing-enterprise-value.ts +8 -4
  13. package/src/plugins/builtin/backtest/client.ts +9 -2
  14. package/src/plugins/builtin/backtest/pane.tsx +1 -1
  15. package/src/plugins/builtin/backtest/report.ts +22 -6
  16. package/src/plugins/builtin/backtest/window.ts +17 -9
  17. package/src/plugins/builtin/correlation/headless.ts +6 -2
  18. package/src/plugins/builtin/correlation/index.tsx +7 -3
  19. package/src/plugins/builtin/correlation/matrix/model.ts +15 -1
  20. package/src/plugins/builtin/correlation/relationship/model.ts +15 -1
  21. package/src/plugins/builtin/correlation/relationship/pane.tsx +4 -2
  22. package/src/plugins/builtin/futures-curve/headless.ts +4 -1
  23. package/src/plugins/builtin/futures-curve/model.ts +24 -0
  24. package/src/plugins/builtin/kelly-sizer/headless.ts +2 -2
  25. package/src/plugins/builtin/kelly-sizer/history.ts +10 -3
  26. package/src/plugins/builtin/kelly-sizer/pane.tsx +2 -2
  27. package/src/plugins/builtin/kelly-sizer/sections.tsx +1 -1
  28. package/src/plugins/builtin/realized-vol/headless.ts +11 -6
  29. package/src/plugins/builtin/realized-vol/model.ts +14 -6
  30. package/src/plugins/builtin/realized-vol/pane.tsx +2 -1
  31. package/src/plugins/builtin/realized-vol/settings.ts +2 -1
  32. package/src/plugins/builtin/seasonality/client.ts +66 -17
  33. package/src/plugins/builtin/seasonality/headless.ts +7 -2
  34. package/src/plugins/builtin/seasonality/model.ts +12 -3
  35. package/src/plugins/builtin/seasonality/pane.tsx +4 -2
  36. package/src/plugins/builtin/shared/use-quote-board.ts +28 -6
  37. package/src/renderers/dom/desktop/controls.tsx +1 -1
  38. package/src/renderers/dom/styles.css +7 -4
  39. package/src/renderers/opentui/box-width.ts +30 -0
  40. package/src/types/financials.ts +16 -3
  41. package/src/types/headless.ts +6 -0
  42. package/src/utils/fundamentals.ts +49 -8
@@ -6,6 +6,7 @@ import { runBacktest, type BacktestOptions, type BacktestResult } from "./engine
6
6
  import { delistingLabel } from "../../../market-data/quotes/delisting";
7
7
  import type { BacktestBar, Rule } from "./rules";
8
8
  import { formingBarsState, isFormingBar } from "../shared/forming-bars";
9
+ import { ROLLS_BACK_ADJUSTED } from "../../../market-data/futures-roll-returns";
9
10
 
10
11
  /** Which served sessions a run tests. */
11
12
  export interface BacktestWindowOptions {
@@ -34,6 +35,8 @@ export interface HistoryBacktestResult extends BacktestResult {
34
35
  * later sessions change it.
35
36
  */
36
37
  repeatable: boolean;
38
+ /** A continuous future's bars were back-adjusted at its rolls (BacktestHistory.rollNote). */
39
+ rollNote?: string;
37
40
  }
38
41
 
39
42
  /**
@@ -47,7 +50,7 @@ export interface HistoryBacktestResult extends BacktestResult {
47
50
  * says so, and is repeatable.
48
51
  */
49
52
  export function backtestWindow(
50
- history: Pick<BacktestHistory, "bars" | "skippedDates" | "undatedSkipped" | "delisting"> & { symbol?: string },
53
+ history: Pick<BacktestHistory, "bars" | "skippedDates" | "undatedSkipped" | "delisting" | "rollNote"> & { symbol?: string },
51
54
  options: BacktestWindowOptions = {},
52
55
  ): { bars: BacktestBar[]; warnings: string[]; repeatable: boolean } {
53
56
  const end = options.end?.trim() || null;
@@ -95,7 +98,7 @@ export function backtestWindow(
95
98
 
96
99
  /** The run over a loaded history: its window's bars, then the engine, every left-out session warned first. */
97
100
  export function runHistoryBacktest(
98
- history: Pick<BacktestHistory, "bars" | "skippedDates" | "undatedSkipped" | "delisting"> & { symbol?: string },
101
+ history: Pick<BacktestHistory, "bars" | "skippedDates" | "undatedSkipped" | "delisting" | "rollNote"> & { symbol?: string },
99
102
  entry: Rule,
100
103
  exit: Rule,
101
104
  options: BacktestOptions & BacktestWindowOptions,
@@ -103,20 +106,25 @@ export function runHistoryBacktest(
103
106
  const window = backtestWindow(history, options);
104
107
  // A currency pair's year is every weekday, however short the run.
105
108
  const result = runBacktest(window.bars, entry, exit, { ...options, instrument: options.instrument ?? currencyPairInstrument(history.symbol) });
106
- return { ...result, warnings: [...window.warnings, ...result.warnings], repeatable: window.repeatable };
109
+ return { ...result, warnings: [...window.warnings, ...result.warnings], repeatable: window.repeatable,
110
+ ...(history.rollNote ? { rollNote: history.rollNote } : {}) };
107
111
  }
108
112
 
109
113
  /**
110
114
  * What a futures continuation is, said wherever its backtest is read: a
111
- * continuous symbol (CL=F) rolls front months by volume, a generic (CL2F5R)
112
- * by its rule, and unless adjusted each roll is a jump between two contracts'
113
- * prices that the returns include. Null for anything else, a dated contract included.
115
+ * continuous symbol (CL=F) rolls front months, its bars back-adjusted at
116
+ * each roll as `rollNote` says (rollAdjustedHistory), a generic (CL2F5R) by
117
+ * its rule; unless adjusted each roll is a jump between two contracts' prices
118
+ * that the returns include. Null for anything else, a dated contract included.
114
119
  */
115
- export function continuationNote(symbol: string, exchange?: string | null): string | null {
120
+ export function continuationNote(symbol: string, exchange?: string | null, rollNote?: string | null): string | null {
116
121
  const key = parsePublicTickerKey(symbol);
117
122
  if (/^[A-Z0-9]{1,6}=F$/.test(key.symbol)) {
118
- return `${key.symbol} is a rolled front-month continuation, not one contract: it moves to the next contract as that one`
119
- + " becomes the most active, and each roll shows in the returns as a jump between the two contracts' prices.";
123
+ const jump = "each roll shows in the returns as a jump between the two contracts' prices";
124
+ const head = `${key.symbol} is a rolled front-month continuation, not one contract`;
125
+ if (rollNote === ROLLS_BACK_ADJUSTED) return `${head}: ${rollNote}, so prices before each roll are not prices that traded.`;
126
+ if (rollNote?.startsWith(ROLLS_BACK_ADJUSTED)) return `${head}: ${rollNote}; before then ${jump}.`;
127
+ return `${head}: it moves to the next contract as that one becomes the most active, and ${jump}.`;
120
128
  }
121
129
  const generic = futuresGenericListing(symbol, exchange ?? key.exchange);
122
130
  if (!generic) return null;
@@ -4,7 +4,7 @@ import { formatNumber, formatSignificant, significantDecimals } from "../../../u
4
4
  import { logFailure } from "../../../utils/log-failure";
5
5
  import { mixedSessionCloseNote } from "../../../market-data/market/session-close-note";
6
6
  import { resolveHeadlessInstrument, loadHeadlessSymbols } from "../shared/headless-market-data";
7
- import { buildCorrelationMatrix, buildCorrelationSeries, buildGeoCorrelationSeries, pairKey, type CorrelationSeries } from "./matrix/model";
7
+ import { buildCorrelationMatrix, buildCorrelationSeries, buildGeoCorrelationSeries, correlationRollNotes, pairKey, type CorrelationSeries } from "./matrix/model";
8
8
  import { geoSeriesToken, loadGeoCorrelationHistory } from "./geo";
9
9
  import { buildRelationshipAnalysis, DEFAULT_RELATIONSHIP_SECOND_SYMBOL } from "./relationship/model";
10
10
  import { paneSchemas } from "./headless-schema";
@@ -73,9 +73,11 @@ export const correlationHeadless: HeadlessPaneDefinition<"rows"> = {
73
73
  reason: row.sampleSize < 5 ? "Insufficient shared return observations" : "Zero return variance",
74
74
  }));
75
75
  const asOf = newestReportTime(symbols.map((symbol) => bySymbol.get(symbol)?.prices.at(-1)?.dateKey));
76
+ const rollNotes = correlationRollNotes(symbols, bySymbol);
76
77
  return {
77
78
  freshness: { asOf, ...unfinishedBarFreshness([...bars.values()], asOf?.slice(0, 10)) },
78
79
  rows, unavailableSymbols,
80
+ ...(rollNotes.length ? { notes: rollNotes } : {}),
79
81
  errors: [
80
82
  ...loaded.errors,
81
83
  // A thin pair says which side is short of daily bars; a pair with enough returns and no value has no variance.
@@ -114,7 +116,8 @@ export const relationshipHeadless: HeadlessPaneDefinition<"series"> = {
114
116
  const loaded = await loadHeadlessSymbols(symbols, ctx, (symbol) => loadListedHistory(ctx, symbol, range));
115
117
  const listings = new Map(loaded.entries.map(({ symbol, data }) => [symbol, data]));
116
118
  const histories = new Map(loaded.entries.map(({ symbol, data }) => [symbol, data.points]));
117
- const analysis = buildRelationshipAnalysis(histories.get(symbols[0]!) ?? [], histories.get(symbols[1]!) ?? [], correlationWindow);
119
+ const analysis = buildRelationshipAnalysis(histories.get(symbols[0]!) ?? [], histories.get(symbols[1]!) ?? [], correlationWindow,
120
+ [symbols[0]!, symbols[1]!]);
118
121
  const [left, right] = symbols.map((symbol) => ({ symbol, ...listings.get(symbol) }));
119
122
  const sessionNote = listings.size === 2 ? mixedSessionCloseNote(left!, right!, analysis.aligned.at(-1)?.dateKey) : null;
120
123
  const unavailableSymbols = symbols.filter((symbol) => (histories.get(symbol) ?? []).filter((point) => (
@@ -147,6 +150,7 @@ export const relationshipHeadless: HeadlessPaneDefinition<"series"> = {
147
150
  freshness: unfinishedBarFreshness([...histories.values()], analysis.aligned.at(-1)?.dateKey, [...listings.values()].map(({ quotedAt }) => quotedAt)) ?? {},
148
151
  unavailableSymbols: [...new Set(unavailableSymbols)],
149
152
  errors: [...loaded.errors, ...(analysis.correlationUnavailableReason ? [analysis.correlationUnavailableReason] : [])],
153
+ ...(analysis.rollNotes.length ? { notes: analysis.rollNotes } : {}),
150
154
  metadata: {
151
155
  left: symbols[0], right: symbols[1], range, correlationWindow,
152
156
  returnAlignment: CORRELATION_RETURN_BASIS,
@@ -36,6 +36,7 @@ import {
36
36
  buildCorrelationPaneTitle,
37
37
  buildGeoCorrelationSeries,
38
38
  buildStatusSummary,
39
+ correlationRollNotes,
39
40
  type CorrelationSeries,
40
41
  getSeriesForEntry,
41
42
  pairKey,
@@ -219,12 +220,15 @@ function CorrelationMatrixPane({ focused, width, height }: PaneProps) {
219
220
  });
220
221
 
221
222
  // The ticker set and range are visible in-pane and an invalid list shows in
222
- // the body, so the footer only carries load state. `r` is global: no hint.
223
+ // the body, so the footer carries load state, and a future's rolls as GR
224
+ // says them. `r` is global: no hint.
225
+ const rollNotes = correlationRollNotes(symbols, seriesBySymbol).join(" · ");
223
226
  usePaneFooter("correlation", () => ({
224
227
  info: !settings.symbolsError && symbols.length >= 2 && statusSummary
225
- ? [{ id: "status", parts: [{ text: statusSummary, tone: "muted" as const }] }]
228
+ ? [{ id: "status", parts: [{ text: statusSummary, tone: "muted" as const }] },
229
+ ...(rollNotes ? [{ id: "rolls", parts: [{ text: rollNotes, tone: "muted" as const }] }] : [])]
226
230
  : [],
227
- }), [settings.symbolsError, statusSummary, symbols.length]);
231
+ }), [rollNotes, settings.symbolsError, statusSummary, symbols.length]);
228
232
 
229
233
  // Rows are exactly as wide as the matrix (after the one-cell inset), so the
230
234
  // zebra and hover bands stop at the last column instead of running on.
@@ -1,3 +1,4 @@
1
+ import { rollAdjustedHistory } from "../../../../market-data/futures-roll-returns";
1
2
  import { pricePointIntegrity, type PriceHistoryIntegrity } from "../../../../utils/price-history-integrity";
2
3
  import type { QueryEntry } from "../../../../market-data/result-types";
3
4
  import { colors } from "../../../../theme/colors";
@@ -24,6 +25,8 @@ export interface CorrelationSeries {
24
25
  observationCount: number;
25
26
  /** Bars left out because their prices contradict each other, kept as the source reported them. */
26
27
  integrity?: PriceHistoryIntegrity[];
28
+ /** A continuous future's returns, read within one contract at each roll: "rolls back-adjusted" (rollAdjustedHistory). */
29
+ rollNote?: string;
27
30
  loading?: boolean;
28
31
  refreshError?: string;
29
32
  fetchedAt?: number | null;
@@ -90,12 +93,15 @@ export function getSeriesForEntry(
90
93
  */
91
94
  export function buildCorrelationSeries(symbol: string, history: readonly PricePoint[]): CorrelationSeries {
92
95
  const integrity = history.flatMap((point) => { const issue = pricePointIntegrity(point); return issue ? [issue] : []; });
93
- const prices = dailyCloses(history);
96
+ // The closes are read for returns alone: a continuous future's are each one contract's.
97
+ const returns = rollAdjustedHistory(history, symbol);
98
+ const prices = dailyCloses(returns.points);
94
99
  const observationCount = Math.max(0, prices.length - 1);
95
100
  return {
96
101
  symbol, prices, observationCount,
97
102
  status: observationCount < MIN_CORRELATION_OBSERVATIONS ? "insufficient" : "ready",
98
103
  ...(integrity.length ? { integrity } : {}),
104
+ ...(returns.note ? { rollNote: returns.note } : {}),
99
105
  };
100
106
  }
101
107
 
@@ -190,6 +196,14 @@ export function buildStatusSummary(
190
196
  return parts.join(" · ");
191
197
  }
192
198
 
199
+ /** "NG=F: rolls back-adjusted" for each listed continuous future, as GR says it: the pane's footer and `fn CORR`'s notes. */
200
+ export function correlationRollNotes(symbols: readonly string[], seriesBySymbol: ReadonlyMap<string, CorrelationSeries>): string[] {
201
+ return symbols.flatMap((symbol) => {
202
+ const note = seriesBySymbol.get(symbol)?.rollNote;
203
+ return note ? [`${symbol}: ${note}`] : [];
204
+ });
205
+ }
206
+
193
207
  /**
194
208
  * The matrix already labels every symbol on both axes and the pane now carries
195
209
  * its own range control, so the title stays generic instead of repeating them.
@@ -6,6 +6,7 @@ import type { PaneSettingsDef, PaneTemplateCreateOptions } from "../../../../typ
6
6
  import type { PricePoint } from "../../../../types/financials";
7
7
  import { formatTickerListInput, parseTickerListInput } from "../../../../tickers/list";
8
8
  import { alignDailyCloses, dailyCloses, pearsonCorrelation } from "../compute";
9
+ import { rollAdjustedHistory } from "../../../../market-data/futures-roll-returns";
9
10
 
10
11
  export type RelationshipRange = Extract<TimeRange, "1M" | "3M" | "6M" | "1Y" | "5Y" | "ALL">;
11
12
 
@@ -51,6 +52,8 @@ export interface RelationshipAnalysis {
51
52
  stats: RelationshipRegressionStats | null;
52
53
  latestRatio: number | null;
53
54
  latestCorrelation: number | null;
55
+ /** A continuous future's returns read within one contract at each roll: "NG=F: rolls back-adjusted". */
56
+ rollNotes: string[];
54
57
  }
55
58
 
56
59
  function syntheticChartPoint(date: Date, value: number): ProjectedChartPoint {
@@ -148,10 +151,16 @@ function computeRelationshipRegression(returns: RelationshipReturnPoint[]): Rela
148
151
  };
149
152
  }
150
153
 
154
+ /**
155
+ * The pair's ratio from the prices as traded, and its returns, rolling
156
+ * correlation and regression from each side's returns, a continuous future's
157
+ * within one contract at each roll (rollAdjustedHistory) when `symbols` names it.
158
+ */
151
159
  export function buildRelationshipAnalysis(
152
160
  leftPoints: PricePoint[],
153
161
  rightPoints: PricePoint[],
154
162
  correlationWindow = DEFAULT_RELATIONSHIP_CORRELATION_WINDOW,
163
+ symbols?: readonly [string, string],
155
164
  ): RelationshipAnalysis {
156
165
  const issues = (points: PricePoint[]) => points.flatMap((point) => {
157
166
  const issue = pricePointIntegrity(point); return issue ? [issue] : [];
@@ -159,7 +168,11 @@ export function buildRelationshipAnalysis(
159
168
  // Bars whose prices contradict each other are gaps, as history leaves them blank (dailyCloses); kept for the export.
160
169
  const integrity = { left: issues(leftPoints), right: issues(rightPoints) };
161
170
  const aligned = alignRelationshipPrices(leftPoints, rightPoints);
162
- const returns = buildRelationshipReturns(aligned);
171
+ const [left, right] = symbols
172
+ ? [rollAdjustedHistory(leftPoints, symbols[0]), rollAdjustedHistory(rightPoints, symbols[1])]
173
+ : [{ points: leftPoints, note: null }, { points: rightPoints, note: null }];
174
+ const returns = buildRelationshipReturns(left.note || right.note ? alignRelationshipPrices(left.points, right.points) : aligned);
175
+ const rollNotes = symbols ? [[symbols[0], left.note], [symbols[1], right.note]].flatMap(([symbol, note]) => note ? [`${symbol}: ${note}`] : []) : [];
163
176
  const correlationPoints = buildRollingCorrelationPoints(returns, correlationWindow);
164
177
  const scatterPoints = returns.map((entry, index) => ({
165
178
  x: entry.rightReturn * 100,
@@ -181,6 +194,7 @@ export function buildRelationshipAnalysis(
181
194
  stats,
182
195
  latestRatio: aligned.at(-1)?.ratio ?? null,
183
196
  latestCorrelation,
197
+ rollNotes,
184
198
  ...(correlationUnavailableReason ? { correlationUnavailableReason } : {}),
185
199
  ...(integrity.left.length || integrity.right.length ? { integrity } : {}),
186
200
  };
@@ -144,7 +144,7 @@ export function RelationshipGraphPane({ focused, width, height }: PaneProps) {
144
144
  const left = data?.[0] ?? null;
145
145
  const right = data?.[1] ?? null;
146
146
  const analysis = useMemo(() => (
147
- left && right ? buildRelationshipAnalysis(left.points, right.points, correlationWindow) : null
147
+ left && right ? buildRelationshipAnalysis(left.points, right.points, correlationWindow, [left.symbol, right.symbol]) : null
148
148
  ), [correlationWindow, left, right]);
149
149
  const cycleRange = useCallback(() => setRange((current) => nextRelationshipRange(current)), [setRange]);
150
150
  const cycleWindow = useCallback(() => setCorrelationWindow((current) => nextRelationshipWindow(current)), [setCorrelationWindow]);
@@ -243,7 +243,9 @@ export function RelationshipGraphPane({ focused, width, height }: PaneProps) {
243
243
 
244
244
  // The legend reads the values at the cursor and the axis carries its date,
245
245
  // so the footer only reports loading.
246
- usePaneStatusFooter({ registrationId: "relationship-graph", loading });
246
+ const rollInfo = useMemo(() => analysis?.rollNotes.length
247
+ ? [{ id: "rolls", parts: [{ text: analysis.rollNotes.join(" · "), tone: "muted" as const }] }] : undefined, [analysis]);
248
+ usePaneStatusFooter({ registrationId: "relationship-graph", loading, ...(rollInfo ? { info: rollInfo } : {}) });
247
249
 
248
250
  if (!pair) {
249
251
  return (
@@ -4,7 +4,7 @@ import type { HeadlessPaneColumn, HeadlessPaneDefinition, HeadlessPaneEntry, Hea
4
4
  import { formatPercentRaw } from "../../../utils/format";
5
5
  import { DATE_OPTION_EXAMPLES } from "../../../utils/calendar-date";
6
6
  import { fetchFuturesCurve, loadCurveSpot, loadCurveSpotBars, loadCurveSpotCloses, loadFuturesCurveAsOf } from "./client";
7
- import { curveReportFreshness, basisSpotSymbol, BASIS_CONVENTION, blankBasisNote, catalogueCurveUnit, curveAsOfDate, curveCache, curveSpotBars, curveBasisPercent, curveBasisRows, curveChangeText, curveContractCode, curvePrice, curveReadsThirtySeconds, curveRoundedPrice, curveSpotSource, curveSpotPremium, curveSpreadLabel, curveTimestamp, curveNoTradeSince, curveSessionNote, curveSettleShown, curveStandIn, curveUnitLabel, curveRootNamed, noTradeChangeNote, normalizeCurveRoot, shortDatedBasisNote, skippedSpreadNotice, spotIndexSymbol, thinSpreadNotice, unpairedContractCount, unsupportedCurveRootMessage, type ContractBasis, type CurveSpotPremium } from "./model";
7
+ import { curveReportFreshness, basisSpotSymbol, BASIS_CONVENTION, blankBasisNote, catalogueCurveUnit, curveAsOfDate, curveCache, curveSpotBars, curveBasisPercent, curveBasisRows, curveChangeText, curveContractCode, curveIncompleteDetail, curvePrice, curveReadsThirtySeconds, curveRoundedPrice, curveSpotSource, curveSpotPremium, curveSpreadLabel, curveTimestamp, curveNoTradeSince, curveSessionNote, curveSettleShown, curveStandIn, curveUnitLabel, curveRootNamed, noTradeChangeNote, normalizeCurveRoot, shortDatedBasisNote, skippedSpreadNotice, spotIndexSymbol, thinSpreadNotice, unpairedContractCount, unsupportedCurveRootMessage, type ContractBasis, type CurveSpotPremium } from "./model";
8
8
  import { COMMODITIES_VIEW_STATE } from "../commodities-energy/view-state";
9
9
  import { knownGapMessage } from "../../../cli/known-gaps";
10
10
 
@@ -235,6 +235,8 @@ export const futuresCurveHeadless: HeadlessPaneDefinition<"bundle"> = {
235
235
  annualizedRollYield: data.slope.annualizedRollYield == null ? null : Number(data.slope.annualizedRollYield.toFixed(2)),
236
236
  percentile: rank(data.slope.percentile), rollPercentile: rank(data.slope.rollPercentile), [SKIPPED_FIELD]: data.slope.skippedSymbols ?? [] };
237
237
  const spreadFormats = { ...ROLL_YIELD_FORMAT, ...thirtySecondsFormat(root, "value") };
238
+ // The status line names the contracts a partial curve lacks, not just that it is partial.
239
+ const incompleteDetail = data.status === "available" ? null : curveIncompleteDetail(data);
238
240
  return {
239
241
  freshness,
240
242
  sections: [
@@ -252,6 +254,7 @@ export const futuresCurveHeadless: HeadlessPaneDefinition<"bundle"> = {
252
254
  ],
253
255
  errors: data.gaps,
254
256
  ...(notes.length ? { notes } : {}),
257
+ ...(incompleteDetail ? { incompleteDetail } : {}),
255
258
  metadata: { ...data, quoteUnit: unit, ...(spot && bases ? { spot, basisBlankedUnpaired: unpairedContractCount(bases.values()) } : {}),
256
259
  ...(spotPremium ? { spotPremium } : {}), ...(args.argument ? {} : { defaultArgument: DEFAULT_ROOT }),
257
260
  ...(notices.length ? { notices } : {}),
@@ -957,6 +957,30 @@ export function noTradeChangeNote(rows: readonly Pick<FuturesContract, "symbol"
957
957
  return `Change blank ${named} (no trade since ${data.settlementDate})${options.count ? "" : "."}`;
958
958
  }
959
959
 
960
+ /** Most contract codes a partial curve's status line names before it counts the rest. */
961
+ const NAMED_INCOMPLETE_CONTRACTS = 6;
962
+
963
+ /**
964
+ * What a partial curve leaves out, by contract, for its report's status line:
965
+ * "NGZ31 not resolved", "NGF35, NGG35 unquoted". Null when it names none: a
966
+ * curve from a server that does not list what it could not resolve, or one
967
+ * whose gap is not about a contract.
968
+ */
969
+ export function curveIncompleteDetail(data: Pick<FuturesCurvePayload, "catalogue" | "contracts">): string | null {
970
+ const codes = (symbols: readonly string[]) => {
971
+ const named = symbols.map(curveContractCode);
972
+ return named.length > NAMED_INCOMPLETE_CONTRACTS
973
+ ? `${named.slice(0, NAMED_INCOMPLETE_CONTRACTS).join(", ")} and ${named.length - NAMED_INCOMPLETE_CONTRACTS} more`
974
+ : named.join(", ");
975
+ };
976
+ const unresolved = data.catalogue.unresolved ?? [];
977
+ const unquoted = data.contracts.filter((row) => row.price == null).map((row) => row.symbol);
978
+ return [
979
+ unresolved.length ? `${codes(unresolved)} not resolved` : null,
980
+ unquoted.length ? `${codes(unquoted)} unquoted` : null,
981
+ ].filter((part): part is string => part != null).join(", ") || null;
982
+ }
983
+
960
984
  /**
961
985
  * The archived curve on a past date in the live curve's shape, so the pane
962
986
  * draws it the same way. Its week- and month-back ghosts are the curves as
@@ -33,7 +33,7 @@ function inputEntries(inputs: KellyHistoryInputs, edge: number) {
33
33
  const payoff = inputs.downsideReturn < 0 ? inputs.upsideReturn / -inputs.downsideReturn : null;
34
34
  return [
35
35
  { key: "window", label: "Window", value: { start: inputs.start, end: inputs.end, months: inputs.periods },
36
- formatted: `${inputs.start} to ${inputs.end}, ${inputs.periods} monthly returns` },
36
+ formatted: `${inputs.start} to ${inputs.end}, ${inputs.periods} monthly returns${inputs.rollNote ? `, ${inputs.rollNote}` : ""}` },
37
37
  { key: "winRate", label: "Win rate", value: inputs.winProbability,
38
38
  formatted: `${formatPct(inputs.winProbability)} (${inputs.wins} of ${inputs.periods} months up)` },
39
39
  { key: "averageGain", label: "Average gain", value: inputs.upsideReturn, formatted: `${formatSignedPct(inputs.upsideReturn)} a month` },
@@ -111,7 +111,7 @@ export const kellyHeadless: HeadlessPaneDefinition<"bundle"> = {
111
111
  ]);
112
112
  const history = resolveEntryValue(entry) ?? [];
113
113
  ctx.signal.throwIfAborted();
114
- const inputs = estimateKellyHistoryInputs(history, years, { exchange });
114
+ const inputs = estimateKellyHistoryInputs(history, years, { exchange, symbol });
115
115
  if (!inputs) {
116
116
  return {
117
117
  complete: false,
@@ -2,6 +2,7 @@ import type { PricePoint } from "../../../types/financials";
2
2
  import type { ChartRequest, InstrumentRef } from "../../../market-data/request-types";
3
3
  import { dailyBarDate, getPricePointTimestamp } from "../../../utils/price-history";
4
4
  import { calendarMonthReturnsRequest, trailingDailyClosesRequest, venueMonth } from "../../../time-series/calendar-month-returns";
5
+ import { rollAdjustedHistory } from "../../../market-data/futures-roll-returns";
5
6
 
6
7
  export const KELLY_HISTORY_DEFAULT_YEARS = 5;
7
8
  export const KELLY_HISTORY_MAX_YEARS = 5;
@@ -24,6 +25,8 @@ export interface KellyHistoryInputs {
24
25
  /** The newest daily close read, which a month in progress may follow, as YYYY-MM-DD. */
25
26
  latest: string;
26
27
  years: number;
28
+ /** A continuous future's months read within one contract at each roll: "rolls back-adjusted" (rollAdjustedHistory). */
29
+ rollNote?: string;
27
30
  }
28
31
 
29
32
  export function clampKellyHistoryYears(value: unknown): number {
@@ -50,13 +53,16 @@ export function kellyTrailingHistoryRequest(instrument: InstrumentRef, years: nu
50
53
  * months are used. Days and the month now are the venue's (`exchange`), a
51
54
  * coin's UTC, so a month that has ended in Tokyo counts before it has in UTC. Null
52
55
  * when that leaves fewer than `KELLY_HISTORY_MIN_PERIODS` returns, or every
53
- * one of them is a gain, or every one of them is a loss.
56
+ * one of them is a gain, or every one of them is a loss. A continuous future
57
+ * (`symbol` NG=F) is read within one contract at each roll.
54
58
  */
55
59
  export function estimateKellyHistoryInputs(
56
- points: readonly PricePoint[],
60
+ served: readonly PricePoint[],
57
61
  yearsInput: number,
58
- options: { exchange?: string; now?: number } = {},
62
+ options: { exchange?: string; now?: number; symbol?: string } = {},
59
63
  ): KellyHistoryInputs | null {
64
+ const adjusted = options.symbol ? rollAdjustedHistory(served, options.symbol) : { points: served, note: null };
65
+ const points = adjusted.points;
60
66
  const years = clampKellyHistoryYears(yearsInput);
61
67
  const now = venueMonth(options.now ?? Date.now(), options.exchange ?? "");
62
68
  const thisMonth = `${now.year}-${String(now.month).padStart(2, "0")}`;
@@ -87,5 +93,6 @@ export function estimateKellyHistoryInputs(
87
93
  end: picks.at(-1)!.day,
88
94
  latest: dailyBarDate(closes.at(-1)!.time, options.exchange ?? ""),
89
95
  years,
96
+ ...(adjusted.note ? { rollNote: adjusted.note } : {}),
90
97
  };
91
98
  }
@@ -323,9 +323,9 @@ export function KellySizerPane({ focused, width, height }: PaneProps) {
323
323
  const historyPoints = useResolvedEntryValue(historyEntry);
324
324
  const historyInputs = useMemo(
325
325
  () => historyPoints
326
- ? estimateKellyHistoryInputs(historyPoints, historyYears, { exchange: ticker?.metadata.exchange ?? "" })
326
+ ? estimateKellyHistoryInputs(historyPoints, historyYears, { exchange: ticker?.metadata.exchange ?? "", symbol: ticker?.metadata.ticker })
327
327
  : null,
328
- [historyPoints, historyYears, ticker?.metadata.exchange],
328
+ [historyPoints, historyYears, ticker?.metadata.exchange, ticker?.metadata.ticker],
329
329
  );
330
330
  const rawActiveDraft = drafts[sizingMode] ?? DEFAULT_KELLY_DRAFTS[sizingMode];
331
331
  const { commonAssumptions, updateCommon } = useKellyCommonAssumptions(rawActiveDraft);
@@ -25,7 +25,7 @@ export function buildKellyHistoryItems(inputs: KellyHistoryInputs): StatItem[] {
25
25
  const payoff = inputs.downsideReturn < 0 ? inputs.upsideReturn / -inputs.downsideReturn : null;
26
26
  return [
27
27
  // The dates take a row of their own so a narrow pane never cuts them.
28
- { id: "window", label: "Window", value: `${inputs.start} to ${inputs.end}`, detail: `${inputs.periods} monthly returns`, wide: true },
28
+ { id: "window", label: "Window", value: `${inputs.start} to ${inputs.end}`, detail: `${inputs.periods} monthly returns${inputs.rollNote ? `, ${inputs.rollNote}` : ""}`, wide: true },
29
29
  { id: "winRate", label: "Win rate", value: formatPct(inputs.winProbability, 1), detail: `${inputs.wins}/${inputs.periods}` },
30
30
  { id: "avgGain", label: "Avg gain", value: formatSignedPct(inputs.upsideReturn), color: priceColor(inputs.upsideReturn) },
31
31
  { id: "avgLoss", label: "Avg loss", value: formatSignedPct(inputs.downsideReturn), color: priceColor(inputs.downsideReturn) },
@@ -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: "10,30,90", description: "Comma-separated bar windows: 10,20,30,60,90,180,260" },
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
- const windows = selectedWindows(args.options.windows);
53
- if (!windows.length || String(args.options.windows).split(",").some((value) => !windows.includes(Number(value)))) {
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, lookbackYears: Number(args.options.lookbackYears) === 2 ? 2 : 1 });
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.historyNote ? [model.historyNote] : [], ...proxy?.error ? [proxy.error] : [],
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 always includes all seven standard windows, independent of chart selection. */
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(history, { windows, estimator, instrument });
106
- const cone = volatilityCone(cadenceIssue ? [] : history, { estimator, lookbackYears, instrument });
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 ? REALIZED_VOLATILITY_WINDOWS : []) {
111
- const result = realizedVolatilityResult(history, window, estimator, instrument);
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)}` : "daily closes", tone: "muted" as const,
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
  }