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
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "gloomberb",
3
- "version": "0.20.8",
3
+ "version": "0.20.9",
4
4
  "packageManager": "bun@1.3.14",
5
5
  "description": "Market research and portfolio tracker for the terminal",
6
6
  "module": "src/public/index.ts",
@@ -124,7 +124,11 @@ export interface FuturesCurvePayload {
124
124
  fetchedAt: string
125
125
  status: "available" | "partial" | "unavailable"
126
126
  stale: boolean
127
- catalogue: { method: "provider" | "bounded-search"; complete: boolean; horizonEnd: string | null }
127
+ catalogue: {
128
+ method: "provider" | "bounded-search"; complete: boolean; horizonEnd: string | null
129
+ /** The contracts the provider lists that no quote resolved (NGZ31.NYM); absent from older servers. */
130
+ unresolved?: string[]
131
+ }
128
132
  contracts: FuturesContract[]
129
133
  ghosts: Array<{
130
134
  label: "1W" | "1M" | "1Y"
@@ -988,6 +988,8 @@ async function runCorrelation(rawArgs: string[], ctx: Parameters<CliCommandDef["
988
988
  ...[leftSeries, rightSeries].filter((series, index) => index === 0 || left !== right)
989
989
  .map((series) => contradictoryBarsNote(series.symbol, series.integrity?.length ?? 0, series.bars)),
990
990
  thinCorrelationNote({ label: left, closes: leftSeries.prices.length }, { label: right, closes: rightSeries.prices.length }, sampleSize, "1Y"),
991
+ ...[leftSeries, rightSeries].filter((series, index) => index === 0 || left !== right)
992
+ .map((series) => series.rollNote ? `${series.symbol}: ${series.rollNote}` : null),
991
993
  ].filter((note) => note != null);
992
994
  // A bare symbol names no exchange; its quote says where it lists, which sets when its daily close is taken.
993
995
  const [leftQuote, rightQuote] = await Promise.all([leftListing!, rightListing!].map((listing) => loadListingQuote(services.dataProvider, listing)));
@@ -11,7 +11,7 @@ import { parsePublicTickerKey, publicTickerKey } from "../../utils/exchanges";
11
11
  import type { ResolvedPaneFunction } from "./resolver";
12
12
  import { toMarketDataContext } from "../../market-data/selectors";
13
13
  import { quoteMetadataFromQuote } from "../../market-data/quotes/metadata";
14
- import { loadSeasonalityHistory, SEASONALITY_HISTORY_RESOLUTION } from "../../plugins/builtin/seasonality/client";
14
+ import { loadSeasonalityHistory } from "../../plugins/builtin/seasonality/client";
15
15
  import type { InstrumentRef } from "../../market-data/request-types";
16
16
  import { CORRELATION_HISTORY_RESOLUTION, loadCorrelationHistory } from "../../plugins/builtin/correlation/history";
17
17
  import type { TimeRange } from "../../time-series/range";
@@ -106,7 +106,8 @@ export async function withShotSeasonalityHistory(
106
106
  if (history.error || history.stale) {
107
107
  throw new Error(`${instrument.symbol}: ${history.error ?? `${cadence} price history is stale`}`);
108
108
  }
109
- return { ...financials, priceHistory: history.history, priceHistoryResolution: SEASONALITY_HISTORY_RESOLUTION[cadence] };
109
+ // The bars as served: the pane closes a continuous future's rolls itself, from its daily bars.
110
+ return { ...financials, priceHistory: history.served.points, priceHistoryResolution: history.served.resolution };
110
111
  }
111
112
 
112
113
  /**
@@ -745,6 +745,7 @@ function incompleteDetail(
745
745
  status: { complete: boolean; unavailableSymbols: string[] },
746
746
  ): boolean | string {
747
747
  if (status.complete) return false;
748
+ if (result.incompleteDetail) return result.incompleteDetail;
748
749
  const requested = result.metadata?.requested;
749
750
  const available = result.metadata?.available;
750
751
  if (typeof requested === "number" && typeof available === "number" && available < requested) {
@@ -55,6 +55,12 @@ export function isNumberCell(cell: string): boolean {
55
55
  return FIGURE.test(text) && !/^\d+$/.test(text);
56
56
  }
57
57
 
58
+ /** A spreadsheet's error value (`#REF!`, `#N/A`, `#DIV/0!`): a cell the sheet could not fill, never a comment. */
59
+ export function isSheetErrorCell(cell: string): boolean {
60
+ const text = cell.trim();
61
+ return text.startsWith("#") && PLACEHOLDER.test(text);
62
+ }
63
+
58
64
  /** A cell that names nothing: no letter or digit (`$$$`, `--`, `-`, `…`), or a placeholder for a missing value (`N/A`, `#N/A`). */
59
65
  export function isJunkCell(cell: string): boolean {
60
66
  const text = cell.trim();
@@ -2,7 +2,7 @@ import { readFile } from "fs/promises";
2
2
  import { fstatSync } from "fs";
3
3
  import { splitSymbolArgLines, splitSymbolWords, stripStrayEdges, uniqueSymbols } from "./symbol-args";
4
4
  import { foldTypedText } from "../utils/typed-text";
5
- import { hasDecimalCommas, isFigure, isJunkCell, isNumberCell, protectFigureCommas, restoreFigureCommas } from "./symbol-cells";
5
+ import { hasDecimalCommas, isFigure, isJunkCell, isNumberCell, isSheetErrorCell, protectFigureCommas, restoreFigureCommas } from "./symbol-cells";
6
6
  import { endsInLegalForm, readTerminalListingCode, unknownBloombergMarket } from "../tickers/terminal-codes";
7
7
 
8
8
  /** Header cells that name a spreadsheet's symbol column, compared without case, spaces or punctuation. */
@@ -17,8 +17,9 @@ function headerKey(cell: string): string {
17
17
  return cell.toLowerCase().replace(/[^\p{L}\p{N}]/gu, "");
18
18
  }
19
19
 
20
+ /** A line starting with # or //, except a sheet's error value (`#REF!`), which is a cell named as not a symbol. */
20
21
  function isComment(cell: string): boolean {
21
- return cell.startsWith("#") || cell.startsWith("//");
22
+ return (cell.startsWith("#") && !isSheetErrorCell(cell)) || cell.startsWith("//");
22
23
  }
23
24
 
24
25
  /** Whether a quote mark at `index` closes a quoted cell: it is followed by a separator, a line end or the end. */
@@ -320,11 +321,18 @@ export function parseSymbolText(text: string): SymbolText {
320
321
  };
321
322
  }
322
323
 
323
- /** Cells named in a note, split by semicolons when one of them has a comma of its own (`2.582,52; 1.899,21`). */
324
+ /**
325
+ * Cells named in a note, once each in the order first read, a repeated one
326
+ * with its count (`2.582,52 (3 times)`), the rest counted. Split by semicolons
327
+ * when one of them has a comma of its own (`2.582,52; 1.899,21`).
328
+ */
324
329
  function listCells(cells: readonly string[]): string {
325
- const named = cells.slice(0, IGNORED_PREVIEW);
326
- const more = cells.length - IGNORED_PREVIEW;
327
- return `${named.join(named.some((cell) => cell.includes(",")) ? "; " : ", ")}${more > 0 ? ` and ${more} more` : ""}`;
330
+ const counts = new Map<string, number>();
331
+ for (const cell of cells) counts.set(cell, (counts.get(cell) ?? 0) + 1);
332
+ const distinct = [...counts];
333
+ const named = distinct.slice(0, IGNORED_PREVIEW).map(([cell, count]) => count > 1 ? `${cell} (${count} times)` : cell);
334
+ const more = distinct.length - IGNORED_PREVIEW;
335
+ return `${named.join(distinct.some(([cell]) => cell.includes(",")) ? "; " : ", ")}${more > 0 ? ` and ${more} more` : ""}`;
328
336
  }
329
337
 
330
338
  /** "the cell", "the 3 number cells": number when every one is a figure. */
@@ -19,7 +19,7 @@ import {
19
19
  import { isUsSymbolVenue, LOOKUP_TIMEOUT_MS, movedAwayChange, tickerChangeLine, tickerChangeSymbol, type MovedTickerChange } from "../tickers/ticker-changes";
20
20
  import { isVenueAbroad } from "../tickers/listing-fate";
21
21
  import { serviceMarkedOtherListing } from "../tickers/company-name-listing";
22
- import { sameCompany } from "../tickers/company-name";
22
+ import { companyNameCase, sameCompany, shortCompanyName } from "../tickers/company-name";
23
23
  import { tickerHasListingSuffix } from "../sources/listing-symbols";
24
24
  import { canonicalExchange, exchangeLabel, isUsListingExchange, resolveExchangeTimeZone } from "../utils/exchanges";
25
25
  import { isCurrencyPairListing } from "../utils/fx-market-hours";
@@ -292,7 +292,7 @@ function choiceNeeded(
292
292
  if (!found) return null;
293
293
  // The line stopped trading as its company moved on (Rite Aid to RADCQ): one line says both.
294
294
  const moved = resolution.ended ? movedAwayChange(resolution.change) : null;
295
- if (moved) return { message: stoppedTradingLine(symbol, moved), successor: moved.tradesAs };
295
+ if (moved) return { message: stoppedTradingLine(symbol, moved, resolution.ticker.metadata.name), successor: moved.tradesAs };
296
296
  return { message: history ? `${history.note}; ${found}` : found, successor: history?.successor ?? null };
297
297
  }
298
298
 
@@ -315,9 +315,16 @@ function quotelessNote(resolution: CliTicker): string | null {
315
315
  return resolution.noQuote ? "no quote" : null;
316
316
  }
317
317
 
318
- /** "RAD stopped trading 2023-10-17, now RADCQ", the company named first when known: a symbol whose line ended as its company moved. */
319
- function stoppedTradingLine(symbol: string, moved: MovedTickerChange): string {
320
- const who = moved.issuer ? `${moved.issuer} (${symbol})` : symbol;
318
+ /**
319
+ * "Chesapeake Energy (CHK) stopped trading 2024-10-02, now EXE": a symbol
320
+ * whose line ended as its company moved, named first by the listing's own
321
+ * name as its quote gives it, else by the issuer the change names, when known.
322
+ */
323
+ function stoppedTradingLine(symbol: string, moved: MovedTickerChange, name?: string | null): string {
324
+ // Written as a name is, never in a feed's capitals ("CHESAPEAKE ENERGY CORP" is Chesapeake Energy).
325
+ const own = name?.trim() && name.trim().toUpperCase() !== symbol.toUpperCase() ? shortCompanyName(companyNameCase(name.trim())) : null;
326
+ const issuer = own ?? (moved.issuer ? companyNameCase(moved.issuer) : null);
327
+ const who = issuer ? `${issuer} (${symbol})` : symbol;
321
328
  return `${who} stopped trading ${moved.changes[0]!.date}, now ${moved.tradesAs}`;
322
329
  }
323
330
 
@@ -1,8 +1,11 @@
1
1
  import { Box, Text, TextAttributes, useUiHost } from "../../ui";
2
+ import type { BoxRenderable } from "../../ui/host";
2
3
  import { useShortcut } from "../../react/input";
3
- import { useCallback, type ComponentType, type ReactNode } from "react";
4
+ import { useCallback, useLayoutEffect, useRef, useState, type ComponentType, type ReactNode } from "react";
4
5
  import { colors } from "../../theme/colors";
5
6
  import { usePaneShareItem } from "../../shares/pane-item";
7
+ import { observeBoxWidth } from "../../renderers/opentui/box-width";
8
+ import { clipToDisplayWidth } from "../../utils/format";
6
9
  import {
7
10
  isDetailBackNavigationKey,
8
11
  isMouseBackNavigationEvent,
@@ -51,6 +54,25 @@ export function PageStackView({
51
54
  return <OpenTuiPageStackView {...props} />;
52
55
  }
53
56
 
57
+ /**
58
+ * The item's title on the one row Back sits in: a title longer than the room
59
+ * the row leaves ends in an ellipsis, it never wraps. The room is only known
60
+ * once the row is laid out, so until then the whole title is drawn, clipped
61
+ * by its box.
62
+ */
63
+ function StackTitle({ title }: { title: string }) {
64
+ const boxRef = useRef<BoxRenderable>(null);
65
+ const [width, setWidth] = useState<number | null>(null);
66
+ useLayoutEffect(() => observeBoxWidth(boxRef.current, setWidth), []);
67
+ return (
68
+ <Box ref={boxRef} flexGrow={1} flexShrink={1} flexBasis={0} minWidth={0} overflow="hidden">
69
+ <Text fg={colors.textBright} attributes={TextAttributes.BOLD} wrapMode="none">
70
+ {width === null ? title : clipToDisplayWidth(title, width)}
71
+ </Text>
72
+ </Box>
73
+ );
74
+ }
75
+
54
76
  function OpenTuiPageStackView({
55
77
  focused,
56
78
  detailOpen,
@@ -121,11 +143,7 @@ function OpenTuiPageStackView({
121
143
  {detailTitle ? (
122
144
  <>
123
145
  <Box width={1} flexShrink={0} />
124
- <Box flexGrow={1} flexShrink={1} minWidth={0} overflow="hidden">
125
- <Text fg={colors.textBright} attributes={TextAttributes.BOLD}>
126
- {detailTitle}
127
- </Text>
128
- </Box>
146
+ <StackTitle title={detailTitle} />
129
147
  </>
130
148
  ) : (
131
149
  <Box flexGrow={1} />
@@ -0,0 +1,226 @@
1
+ import type { PricePoint } from "../types/financials";
2
+ import { getPricePointTimestamp } from "../utils/price-history";
3
+ import { pricePointOpenWithheld } from "../utils/price-history-integrity";
4
+
5
+ /** What a return-based function says once about a continuous future's series (rollAdjustedHistory). */
6
+ export const ROLLS_BACK_ADJUSTED = "rolls back-adjusted";
7
+ /** What it says of a continuous future whose bars name no contract and whose root the calendar does not have. */
8
+ const ROLLS_LEFT_AS_TRADED = "rolls left as traded";
9
+
10
+ /** A roll in a continuous future's daily bars, as rollAdjustedHistory closed it. */
11
+ interface ReturnRoll {
12
+ /** The first bar on the incoming contract, YYYY-MM-DD. */
13
+ date: string;
14
+ /** The contracts either side (NGX26, NGZ26), from the bars or the contract calendar. */
15
+ from: string;
16
+ to: string;
17
+ /** Where the roll was found: a change of contract in the bars, or the contract calendar before they name one. */
18
+ source: "bars" | "calendar";
19
+ /**
20
+ * What the roll day's return was read from: the incoming contract's own
21
+ * move from the bar's open (its first trade of the session), or none
22
+ * (`flat`) for a bar that has no open to read.
23
+ */
24
+ basis: "open" | "flat";
25
+ }
26
+
27
+ export interface RollAdjustedHistory {
28
+ /**
29
+ * The same bars, every price before a roll scaled by its gap (back-adjusted
30
+ * by ratio), so a return across a roll is one contract's. Volumes and every
31
+ * other field are as served. For returns only: levels, charts and `history`
32
+ * show the prices as traded.
33
+ */
34
+ points: PricePoint[];
35
+ rolls: ReturnRoll[];
36
+ /**
37
+ * "rolls back-adjusted"; from when, when the bars before name no contract
38
+ * and the calendar does not have the root ("rolls back-adjusted from
39
+ * 2026-09-08"); "rolls left as traded" when neither says where a roll is.
40
+ * Null for anything but a continuous future's daily bars.
41
+ */
42
+ note: string | null;
43
+ }
44
+
45
+ const MONTH_CODES = "FGHJKMNQUVXZ";
46
+ const DAY_MS = 86_400_000;
47
+
48
+ /**
49
+ * When a root's front contract stops trading, from the exchange's rule, for
50
+ * the roots whose continuous series (NG=F) rolls on the session after it:
51
+ * - `month-start`: the nth session before the delivery month's first day
52
+ * (Henry Hub gas: three; its E-mini and micro one session earlier);
53
+ * - `before-25th`: the nth session before the 25th of the month before
54
+ * delivery, one more when the 25th is no session (WTI crude: three);
55
+ * - `month-end`: the last session of the month that many months before
56
+ * delivery (heating oil and RBOB one, Brent last day two).
57
+ * Sessions are the series' own bars, so a holiday is skipped as the exchange
58
+ * skips it. Checked against NG=F, QG=F, CL=F, HO=F, RB=F and BZ=F daily bars
59
+ * from 2021 to 2026: the session after each last trade is where their rolls
60
+ * show (NG=F's largest moves on it, 8.9% a day on average against 3.7%).
61
+ */
62
+ type LastTradeRule =
63
+ | { kind: "month-start"; sessions: number }
64
+ | { kind: "before-25th"; sessions: number }
65
+ | { kind: "month-end"; monthsBefore: number };
66
+
67
+ const LAST_TRADE_RULES: Readonly<Record<string, LastTradeRule>> = {
68
+ NG: { kind: "month-start", sessions: 3 },
69
+ HH: { kind: "month-start", sessions: 3 },
70
+ QG: { kind: "month-start", sessions: 4 },
71
+ MNG: { kind: "month-start", sessions: 4 },
72
+ CL: { kind: "before-25th", sessions: 3 },
73
+ HO: { kind: "month-end", monthsBefore: 1 },
74
+ RB: { kind: "month-end", monthsBefore: 1 },
75
+ BZ: { kind: "month-end", monthsBefore: 2 },
76
+ };
77
+
78
+ /** The root of a continuous future's symbol (NG of NG=F), or null for anything else. */
79
+ function continuousRoot(symbol: string): string | null {
80
+ return /^([A-Z0-9]{1,6})=F$/.exec(symbol.trim().toUpperCase().split(":")[0]!)?.[1] ?? null;
81
+ }
82
+
83
+ /** Whether a symbol is a continuous future's (NG=F), whose returns rollAdjustedHistory reads within one contract. */
84
+ export function isContinuousFuture(symbol: string): boolean {
85
+ return continuousRoot(symbol) != null;
86
+ }
87
+
88
+ const monthIndex = (day: string) => Number(day.slice(0, 4)) * 12 + Number(day.slice(5, 7)) - 1;
89
+ const monthDay = (index: number, day: number) =>
90
+ `${Math.floor(index / 12)}-${String((index % 12) + 1).padStart(2, "0")}-${String(day).padStart(2, "0")}`;
91
+ const contractCode = (root: string, delivery: number) =>
92
+ `${root}${MONTH_CODES[delivery % 12]}${String(Math.floor(delivery / 12) % 100).padStart(2, "0")}`;
93
+
94
+ /** The index of the first of the ascending `days` on or after `day`; `days.length` when none is. */
95
+ function firstOnOrAfter(days: readonly string[], day: string): number {
96
+ let low = 0, high = days.length;
97
+ while (low < high) {
98
+ const middle = (low + high) >> 1;
99
+ if (days[middle]! < day) low = middle + 1;
100
+ else high = middle;
101
+ }
102
+ return low;
103
+ }
104
+
105
+ /**
106
+ * The rolls the contract calendar puts in `days` (ascending session dates):
107
+ * for each delivery month, the session after its last trade, from the
108
+ * contract delivered that month to the next. A last trade the sessions do not
109
+ * reach past is left out: the series has not shown it yet.
110
+ */
111
+ function calendarRolls(root: string, rule: LastTradeRule, days: readonly string[]): Array<{ index: number; from: string; to: string }> {
112
+ if (days.length < 2) return [];
113
+ const rolls: Array<{ index: number; from: string; to: string }> = [];
114
+ for (let month = monthIndex(days[0]!); month <= monthIndex(days.at(-1)!); month++) {
115
+ // The month the last trade falls in, and the delivery month of the contract that stops.
116
+ let last: number;
117
+ let delivery: number;
118
+ if (rule.kind === "month-start") {
119
+ delivery = month + 1;
120
+ const anchor = firstOnOrAfter(days, monthDay(delivery, 1));
121
+ if (anchor >= days.length) continue;
122
+ last = anchor - rule.sessions;
123
+ } else if (rule.kind === "before-25th") {
124
+ delivery = month + 1;
125
+ const target = monthDay(month, 25);
126
+ const anchor = firstOnOrAfter(days, target);
127
+ if (anchor >= days.length) continue;
128
+ last = anchor - rule.sessions - (days[anchor] === target ? 0 : 1);
129
+ } else {
130
+ delivery = month + rule.monthsBefore;
131
+ const anchor = firstOnOrAfter(days, monthDay(month + 1, 1));
132
+ if (anchor >= days.length) continue;
133
+ last = anchor - 1;
134
+ }
135
+ if (last < 0 || last + 1 >= days.length) continue;
136
+ rolls.push({ index: last + 1, from: contractCode(root, delivery), to: contractCode(root, delivery + 1) });
137
+ }
138
+ return rolls;
139
+ }
140
+
141
+ /** The median days between bars: daily bars sit one to three days apart. */
142
+ function dailyBars(times: readonly number[]): boolean {
143
+ if (times.length < 2) return false;
144
+ const gaps = times.slice(1).map((time, index) => time - times[index]!).sort((a, b) => a - b);
145
+ const median = gaps[Math.floor(gaps.length / 2)]!;
146
+ return median >= 0.5 * DAY_MS && median <= 4 * DAY_MS;
147
+ }
148
+
149
+ const positive = (value: number | undefined): value is number => typeof value === "number" && Number.isFinite(value) && value > 0;
150
+
151
+ /**
152
+ * A continuous future's daily bars (NG=F) as one series of returns: at every
153
+ * roll, the prices before it are scaled so that the roll day's return is the
154
+ * incoming contract's own, from the roll bar's open (that contract's first
155
+ * trade of the session) to its close, where a front-month series would read
156
+ * the gap between two contracts as a move (NG=F's 26 Oct 2026 roll from
157
+ * NGX26 to NGZ26 as +13.5%). A roll bar without an open is a flat day. Rolls
158
+ * are where the bars change contract; before the bars name one, where the
159
+ * contract calendar (LAST_TRADE_RULES) puts them, for the roots it has. The
160
+ * newest contract's prices are as traded. Anything but a continuous future's
161
+ * daily bars is returned as served, with no note.
162
+ *
163
+ * Every return-based function reads a continuous future through this
164
+ * (volatility, beta and correlation, Kelly sizing, seasonality, backtests);
165
+ * charts and `history` keep the prices as traded.
166
+ */
167
+ export function rollAdjustedHistory(points: readonly PricePoint[], symbol: string): RollAdjustedHistory {
168
+ const asServed = (): RollAdjustedHistory => ({ points: [...points], rolls: [], note: null });
169
+ const root = continuousRoot(symbol);
170
+ if (!root) return asServed();
171
+ const timed = points.map((point) => ({ point, time: getPricePointTimestamp(point) }));
172
+ if (timed.some(({ time }) => !Number.isFinite(time))) return asServed();
173
+ timed.sort((left, right) => left.time - right.time);
174
+ if (!dailyBars(timed.map(({ time }) => time))) return asServed();
175
+ const sorted = timed.map(({ point }) => point);
176
+ const days = timed.map(({ time }) => new Date(time).toISOString().slice(0, 10));
177
+
178
+ const firstNamed = sorted.findIndex((point) => !!point.contract);
179
+ const unnamedEnd = firstNamed < 0 ? sorted.length : firstNamed;
180
+ const found: Array<{ index: number; from: string; to: string; source: ReturnRoll["source"] }> = [];
181
+ const rule = LAST_TRADE_RULES[root];
182
+ if (rule && unnamedEnd > 0) {
183
+ const calendar = calendarRolls(root, rule, days);
184
+ for (const roll of calendar) if (roll.index < unnamedEnd) found.push({ ...roll, source: "calendar" });
185
+ // The bars may start naming a contract other than the one the calendar holds then: the series rolled there.
186
+ const held = calendar.filter((roll) => roll.index < unnamedEnd).at(-1)?.to
187
+ ?? calendar.find((roll) => roll.index >= unnamedEnd)?.from;
188
+ const named = sorted[firstNamed]?.contract;
189
+ if (firstNamed > 0 && held && named && held !== named) found.push({ index: firstNamed, from: held, to: named, source: "bars" });
190
+ }
191
+ let contract: string | null = null;
192
+ for (let index = Math.max(0, firstNamed); firstNamed >= 0 && index < sorted.length; index++) {
193
+ const own = sorted[index]!.contract;
194
+ if (own && contract && own !== contract) found.push({ index, from: contract, to: own, source: "bars" });
195
+ if (own) contract = own;
196
+ }
197
+
198
+ // Each roll's factor: the roll bar's open over the close before it, or 1 (flat) on that day where there is none.
199
+ const rolls: ReturnRoll[] = [];
200
+ const factors: Array<{ index: number; factor: number }> = [];
201
+ for (const roll of found.sort((left, right) => left.index - right.index)) {
202
+ const bar = sorted[roll.index]!;
203
+ let before = roll.index - 1;
204
+ while (before >= 0 && !positive(sorted[before]!.close)) before--;
205
+ if (before < 0 || !positive(bar.close)) continue;
206
+ const open = positive(bar.open) && !pricePointOpenWithheld(bar) ? bar.open : null;
207
+ const factor = (open ?? bar.close) / sorted[before]!.close;
208
+ rolls.push({ date: days[roll.index]!, from: roll.from, to: roll.to, source: roll.source, basis: open != null ? "open" : "flat" });
209
+ factors.push({ index: roll.index, factor });
210
+ }
211
+
212
+ // Newest first: each roll scales every price before it, on top of the rolls after it.
213
+ let scale = 1;
214
+ let next = factors.length - 1;
215
+ const adjusted = new Array<PricePoint>(sorted.length);
216
+ for (let index = sorted.length - 1; index >= 0; index--) {
217
+ while (next >= 0 && index < factors[next]!.index) scale *= factors[next--]!.factor;
218
+ const point = sorted[index]!;
219
+ const move = (price: number | undefined) => typeof price === "number" ? price * scale : price;
220
+ adjusted[index] = scale === 1 ? point
221
+ : { ...point, open: move(point.open), high: move(point.high), low: move(point.low), close: point.close * scale };
222
+ }
223
+ const note = rule || firstNamed === 0 ? ROLLS_BACK_ADJUSTED
224
+ : firstNamed > 0 ? `${ROLLS_BACK_ADJUSTED} from ${days[firstNamed]}` : ROLLS_LEFT_AS_TRADED;
225
+ return { points: adjusted, rolls, note };
226
+ }
@@ -2,6 +2,8 @@ import { canonicalExchange } from "../../utils/exchanges";
2
2
  import { futuresListingVenue } from "../../utils/futures-generic";
3
3
  import { regularSessionCloseUtcMinute } from "./freshness";
4
4
  import { PERPETUAL_EXCHANGES } from "../../tickers/perpetual-listing";
5
+ import { futuresContractByCode } from "../futures-board";
6
+ import { zonedWallClockToUtcMs } from "../../utils/zoned-date-time";
5
7
 
6
8
  interface SessionLeg {
7
9
  symbol: string;
@@ -23,9 +25,37 @@ function offsetText(minutes: number): string {
23
25
  return [hours ? `${hours} h` : "", rest ? `${rest} min` : ""].filter(Boolean).join(" ");
24
26
  }
25
27
 
28
+ /** Metals settle at their own times, New York minutes: gold 13:30, silver 13:25, platinum 13:05, copper and palladium 13:00. */
29
+ const METAL_SETTLEMENTS: Readonly<Record<string, number>> = {
30
+ GC: 13 * 60 + 30, MGC: 13 * 60 + 30, SI: 13 * 60 + 25, SIL: 13 * 60 + 25, PL: 13 * 60 + 5, HG: 13 * 60, PA: 13 * 60,
31
+ };
32
+
33
+ /**
34
+ * When a future's daily settlement is taken, in New York minutes: the time
35
+ * its daily bar closes on, whatever the bar is stamped. From CME Group's and
36
+ * Cboe's settlement procedures: energy 14:30 (NYMEX), grains 14:15 (13:15
37
+ * Chicago), livestock 14:05, Treasuries and currencies 15:00, equity index
38
+ * and VIX futures 16:00. Null for a root whose time is not listed here
39
+ * (Dutch TTF, the ICE softs, lumber, aluminum), whose bar is read as stamped.
40
+ */
41
+ function futuresSettlementMinute(root: string | null): number | null {
42
+ if (!root) return null;
43
+ if (METAL_SETTLEMENTS[root] !== undefined) return METAL_SETTLEMENTS[root]!;
44
+ const contract = futuresContractByCode(root);
45
+ switch (contract?.sector) {
46
+ case "energy": return contract.code === "TTF" ? null : 14 * 60 + 30;
47
+ case "agriculture": return contract.venue === "CBT" ? 14 * 60 + 15 : null;
48
+ case "livestock": return 14 * 60 + 5;
49
+ case "rates": case "currencies": return 15 * 60;
50
+ case "equity-index": case "equity-sectors": case "volatility": return 16 * 60;
51
+ default: return null;
52
+ }
53
+ }
54
+
26
55
  /**
27
56
  * Where a daily bar of the listing falls on its date. A venue with a listed
28
- * regular close closes at that UTC time. Crypto, FX and futures carry a bar
57
+ * regular close closes at that UTC time, and a future at its settlement.
58
+ * Crypto, FX and a future whose settlement time is not listed carry a bar
29
59
  * dated 00:00 UTC, which closes when the next UTC day starts. A venue with
30
60
  * neither is unknown.
31
61
  */
@@ -34,9 +64,16 @@ function dailyBarClose(leg: SessionLeg, time: number): { minute: number; text: s
34
64
  const minute = regularSessionCloseUtcMinute(leg.exchange, time);
35
65
  if (minute !== null) return { minute, text: `${label} closes ${clock(minute)} UTC` };
36
66
  const exchange = canonicalExchange(leg.exchange);
37
- return exchange && (ALWAYS_OPEN_EXCHANGES.has(exchange) || futuresListingVenue(leg.symbol, exchange))
38
- ? { minute: MINUTES_PER_DAY, text: `${label} bar is ${clock(0)} UTC` }
39
- : null;
67
+ if (!exchange) return null;
68
+ const future = futuresListingVenue(leg.symbol, exchange);
69
+ const settles = future ? futuresSettlementMinute(future.root) : null;
70
+ if (settles != null) {
71
+ const day = new Date(time).toISOString().slice(0, 10).split("-").map(Number);
72
+ const at = zonedWallClockToUtcMs("America/New_York", day[0]!, day[1]!, day[2]!, Math.floor(settles / 60), settles % 60, 0);
73
+ const utc = Math.floor(at / 60_000) % MINUTES_PER_DAY;
74
+ return { minute: utc, text: `${label} settles ${clock(utc)} UTC` };
75
+ }
76
+ return future || ALWAYS_OPEN_EXCHANGES.has(exchange) ? { minute: MINUTES_PER_DAY, text: `${label} bar is ${clock(0)} UTC` } : null;
40
77
  }
41
78
 
42
79
  /**
@@ -130,10 +130,14 @@ function datedSheets(financials: Pick<TickerFinancials, "annualStatements" | "qu
130
130
  .sort((a, b) => b.date.localeCompare(a.date));
131
131
  }
132
132
 
133
- /** Total equity including minority interest less common equity; null where either line is missing. */
133
+ /**
134
+ * Total equity including minority interest less common equity, else what the company's filing tags for the date (a
135
+ * quarter read from the filing alone); null where the sheet gives neither.
136
+ */
134
137
  function minorityOnSheet(row: FinancialStatement | undefined): number | null {
135
138
  const gross = row?.totalEquityGrossMinorityInterest, common = row?.commonStockEquity;
136
- return finite(gross) && finite(common) ? Math.max(0, gross - common) : null;
139
+ if (finite(gross) && finite(common)) return Math.max(0, gross - common);
140
+ return finite(row?.minorityAndPreferredEquity) ? Math.max(0, row.minorityAndPreferredEquity) : null;
137
141
  }
138
142
 
139
143
  /** The bridge Gloom Cloud computed beside a withdrawal, its minority interest and cash read as its balance sheet holds them. */
@@ -141,8 +145,8 @@ function checkBridge(check: EnterpriseValueCheck, financials: EnterpriseValueInp
141
145
  const sheetDate = check.balanceSheetDate ?? "";
142
146
  const row = [...financials.quarterlyStatements ?? [], ...financials.annualStatements ?? []]
143
147
  .find((statement) => statement.date.slice(0, 10) === sheetDate);
144
- // Gloom Cloud serves the line only where both equity lines give a positive figure. A sheet on file without them, or
145
- // one that is not on file, is named: never counted as zero.
148
+ // Gloom Cloud serves the line only where the equity lines or the filing give a positive figure. A sheet on file
149
+ // without them, or one that is not on file, is named: never counted as zero.
146
150
  const minority = finite(check.minorityAndPreferred) ? check.minorityAndPreferred : row ? minorityOnSheet(row) : null;
147
151
  return {
148
152
  sheetDate, marketCap: check.marketCap ?? 0, totalDebt: check.totalDebt ?? 0, leases: check.leases ?? 0, cash: check.cash ?? 0,
@@ -5,6 +5,7 @@ import type { DataProvider } from "../../../types/data-provider";
5
5
  import type { ListingDelisting, PricePoint } from "../../../types/financials";
6
6
  import type { BacktestBar } from "./rules";
7
7
  import { isFiniteNumber } from "../../../utils/guards";
8
+ import { rollAdjustedHistory } from "../../../market-data/futures-roll-returns";
8
9
 
9
10
  export interface BacktestHistoryDependencies {
10
11
  loadChart(request: ChartRequest, options?: { forceRefresh?: boolean }): Promise<QueryEntry<PricePoint[]>>;
@@ -29,6 +30,8 @@ export interface BacktestHistory {
29
30
  fetchedAt: number;
30
31
  /** The listing no longer trades: its last bar is its last session, and no later one will come. */
31
32
  delisting?: ListingDelisting;
33
+ /** A continuous future's bars, back-adjusted at each roll: "rolls back-adjusted" (rollAdjustedHistory). */
34
+ rollNote?: string;
32
35
  }
33
36
 
34
37
  /**
@@ -91,8 +94,12 @@ export async function loadBacktestHistory(
91
94
  { forceRefresh: options.forceRefresh },
92
95
  );
93
96
  options.signal?.throwIfAborted();
94
- const history = toBacktestBars(resolveEntryValue(entry) ?? [], entry.history?.nonPositiveCloseDates);
97
+ // A continuous future is tested on one contract's returns at each roll, its earlier prices scaled to the newest
98
+ // contract's: the run's prices (Close, Entry and Exit) are back-adjusted, and the report's headers say so.
99
+ const adjusted = rollAdjustedHistory(resolveEntryValue(entry) ?? [], symbol);
100
+ const history = toBacktestBars(adjusted.points, entry.history?.nonPositiveCloseDates);
95
101
  if (!history.bars.length) throw new Error(entry.error?.message ?? "Daily price history unavailable");
96
102
  const delisting = entry.history?.delisting;
97
- return { symbol, ...history, fetchedAt: entry.fetchedAt ?? Date.now(), ...(delisting ? { delisting } : {}) };
103
+ return { symbol, ...history, fetchedAt: entry.fetchedAt ?? Date.now(), ...(delisting ? { delisting } : {}),
104
+ ...(adjusted.note ? { rollNote: adjusted.note } : {}) };
98
105
  }
@@ -121,7 +121,7 @@ export function BacktestPane({ width, height, focused }: PaneProps) {
121
121
  }
122
122
  }, [history.data, rules, lookback, costBps, runWindow]);
123
123
  const result = run.result;
124
- const continuation = instrument ? continuationNote(instrument.symbol, instrument.exchange) : null;
124
+ const continuation = instrument ? continuationNote(instrument.symbol, instrument.exchange, history.data?.rollNote) : null;
125
125
  // Export CSV writes the daily curve `fn BT --csv --equity` prints for this run, whichever table is in view;
126
126
  // the table reads it when the export runs. Without a run the table's own rows export.
127
127
  const exportCsv = result && symbol ? () => {
@@ -1,5 +1,6 @@
1
1
  import { cleanFloat32Price, historyUnit } from "../../../cli/history-rows";
2
2
  import { barsPerYearLabel } from "../../../market-data/bars-per-year";
3
+ import { ROLLS_BACK_ADJUSTED } from "../../../market-data/futures-roll-returns";
3
4
  import type { HeadlessBundleResult, HeadlessBundleSection, HeadlessPaneColumn, HeadlessPaneFreshness, HeadlessPaneRow } from "../../../types/headless";
4
5
  import { formatStat, formatTradePrice, PRICE_RETURN_LABEL, PRICE_RETURN_NOTE, SUMMARY_ROWS, type StatValue } from "./format";
5
6
  import { continuationNote, type BacktestWindowOptions, type HistoryBacktestResult } from "./window";
@@ -47,7 +48,8 @@ const price = (value: unknown) => typeof value !== "number" || !Number.isFinite(
47
48
  * lines as the growth of 1 on the price alone and the strategy's drawdown in percent. Exports
48
49
  * keep every digit; the text view rounds. The close is the price as `history`
49
50
  * exports it, without a float32 feed's noise (671.29999 is 671.3); the run
50
- * itself used the price as served.
51
+ * itself used the price as served. A continuous future's closes are
52
+ * back-adjusted at its rolls, and its Close header says so (withAdjustedPrices).
51
53
  */
52
54
  const EQUITY_COLUMNS: HeadlessPaneColumn[] = [
53
55
  { key: "date", header: "Date", literalHeader: true, shrink: false },
@@ -66,11 +68,25 @@ const EXPORTED_EQUITY_COLUMNS: HeadlessPaneColumn[] = EQUITY_COLUMNS.map((column
66
68
  ? { ...column, header: column.header.replace(")", ", price return, distributions not included)") }
67
69
  : column);
68
70
 
71
+ /** The price columns a run over back-adjusted bars prints, which are not prices that traded. */
72
+ const ADJUSTED_PRICE_KEYS = new Set(["close", "entryPrice", "exitPrice"]);
73
+
74
+ /**
75
+ * A run's columns with "(back-adjusted)" on each price header when its bars
76
+ * were back-adjusted at a continuous future's rolls (`rollNote`): the
77
+ * returns are one contract's, but a price before the newest roll is scaled to
78
+ * the newest contract's. Any other run's columns as they are.
79
+ */
80
+ function withAdjustedPrices(columns: HeadlessPaneColumn[], result: HistoryBacktestResult): HeadlessPaneColumn[] {
81
+ if (!result.rollNote?.startsWith(ROLLS_BACK_ADJUSTED)) return columns;
82
+ return columns.map((column) => ADJUSTED_PRICE_KEYS.has(column.key) ? { ...column, header: `${column.header} (back-adjusted)` } : column);
83
+ }
84
+
69
85
  function equitySection(result: HistoryBacktestResult, unit: string | null): HeadlessBundleSection {
70
86
  return {
71
87
  title: `Daily curve, ${PRICE_RETURN_LABEL.toLowerCase()} · ${result.start} to ${result.end}`,
72
- columns: EXPORTED_EQUITY_COLUMNS,
73
- textColumns: EQUITY_COLUMNS,
88
+ columns: withAdjustedPrices(EXPORTED_EQUITY_COLUMNS, result),
89
+ textColumns: withAdjustedPrices(EQUITY_COLUMNS, result),
74
90
  rows: result.equity.map((row): HeadlessPaneRow => ({ ...row, close: cleanFloat32Price(row.close), ...(unit ? { currency: unit } : {}) })),
75
91
  ...(unit ? { unit } : {}),
76
92
  interval: INTERVAL,
@@ -112,13 +128,13 @@ function summarySections(input: BacktestReportInput): HeadlessBundleSection[] {
112
128
  {
113
129
  // Prices are in the listing's currency, which the row names; the return and the hold say their own units.
114
130
  title: "Trades",
115
- columns: [
131
+ columns: withAdjustedPrices([
116
132
  { key: "entryDate", header: "Entry" },
117
133
  { key: "entryPrice", header: "Entry price", align: "right", unitKey: "currency", format: tradePrice },
118
134
  { key: "exitDate", header: "Exit" },
119
135
  { key: "exitPrice", header: "Exit price", align: "right", unitKey: "currency", format: tradePrice },
120
136
  { key: "returnPct", header: "Return %", align: "right", format: fixed(2) }, { key: "sessions", header: "Sessions", align: "right" },
121
- ],
137
+ ], result),
122
138
  rows: result.trades.map((trade) => ({
123
139
  entryDate: trade.entryDate, entryPrice: trade.entryPrice,
124
140
  exitDate: trade.open ? "open" : trade.exitDate, exitPrice: trade.exitPrice,
@@ -139,7 +155,7 @@ function summarySections(input: BacktestReportInput): HeadlessBundleSection[] {
139
155
  */
140
156
  export function backtestReport(input: BacktestReportInput): HeadlessBundleResult {
141
157
  const { result } = input;
142
- const continuation = continuationNote(input.symbol, input.exchange);
158
+ const continuation = continuationNote(input.symbol, input.exchange, result.rollNote);
143
159
  const end = input.window.end?.trim() || null;
144
160
  return {
145
161
  complete: true,