T-119: M1.3e — @stock-bot/research: DuckDB SQL planner + injected-executor MarketDataStore adapter for curated daily Parquet (bars 1d, events, shortsAsOf, fx 1d) with mandatory Vault / known_at predicates, tests and local benchmark (no new dependencies)
This commit is contained in:
parent
f9bbc1d4a2
commit
57b398694f
6 changed files with 2406 additions and 0 deletions
|
|
@ -74,3 +74,38 @@ Fixed-seed (`20260402`) end-to-end `analyzeSignal` benchmark covering `5,040` bu
|
|||
|
||||
- **Command:** `bun run libs/research/scripts/benchmark-signal-study.ts`
|
||||
- **Observed (Bun 1.2.16):** `elapsedMs = 1691.13 ms`, `rowsPerSec = 8,940,793 rows/s` (`2,980 dates/s`, `nObs = 5040`, `meanRankIc = 0.057294`, `recencyGatePassed = true`)
|
||||
|
||||
## DuckDB Curated Parquet Query Planner & `MarketDataStore` Adapter
|
||||
|
||||
Exported from both `@stock-bot/research` and `@stock-bot/research/market-data-store-duckdb` (`libs/research/src/market-data-store-duckdb.ts`). The module is dependency-free and browser-safe; DuckDB execution is injected via `DuckDbExecutor` (`{ run(sql), query(sql, params) }`) so parameter values are always bound separately from SQL text.
|
||||
|
||||
### API
|
||||
|
||||
- **`planBars1dQuery(q, ctx)`** — Plans a fenced query over `<curatedRoot>/bars_1d/year=*/part.parquet` (`hive_partitioning = true`) for `timeframe: '1d'` and `adjustment: 'raw' | 'split' | 'total'`. Rejects `'1m' | '5m' | '1h'` with `MarketDataStoreNotImplementedError`.
|
||||
- **`planEventsQuery(q, ctx)`** — Plans a `'vault_fenced'` query over `<curatedRoot>/events/year=*/part.parquet` (`hive_partitioning = true`) filtered by allow-listed `kinds` and optional `listingIds`.
|
||||
- **`planShortsAsOfQuery(q, ctx)`** — Plans a `'vault_fenced'` query over `<curatedRoot>/shorts/part.parquet`, binding UTC `YYYY-MM-DD` `report_date` bounds and ISO-8601 `known_at <= ?`.
|
||||
- **`planFx1dQuery(q, ctx)`** — Plans a `'vault_fenced'` query (with default `asOf = vaultCutoffTs - 1`) over `<curatedRoot>/fx_1d/part.parquet` for `timeframe: '1d'`, mapping `'USD.CAD'` to the stored bound parameter `'USDCAD'`. Rejects `'1m'` with `MarketDataStoreNotImplementedError`.
|
||||
- **`createDuckDbMarketDataStore({ executor, curatedRoot, vaultCutoffTs, vaultOperatorAuthorized?, env?, barBatchSize? })`** — Returns a `MarketDataStore` adapter that eagerly validates options and `resolveDuckDbConnectionBudget(env)`, lazily executes the three budget `SET` statements sequentially and at most once before the first `executor.query(...)` (including under concurrent first calls, with clean retry if initialization fails), maps validated rows into `BarBatch` / `Table`, and rejects out-of-slice methods (`bars` `1m`/`5m`/`1h`, `fx` `1m`, `crossSection`, `fundamentalsAsOf`, `macroAsOf`, `universe`) with `MarketDataStoreNotImplementedError` and zero executor calls.
|
||||
|
||||
### Mandatory Vault, PIT & Boundary Validation Rules
|
||||
|
||||
- Every planner delegates unconditionally to `applyVaultFence`, binding `ts`/`report_date` bounds and `known_at <= ?` in UTC (`TZ`-invariant). Under `'vault_fenced'`, `from >= vaultCutoffTs` throws `VaultHoldoutFenceError` and `to`/`asOf` clamp to `vaultCutoffTs - 1`; `'vault_evaluation_only'` requires `vaultOperatorAuthorized === true` (only on `bars`; `events`, `shortsAsOf`, and `fx` are always `'vault_fenced'`).
|
||||
- `curatedRoot` is the only value embedded in SQL text and must be an absolute POSIX path free of control characters (`<= 0x1f`, `0x7f`), `'`, `;`, and glob metacharacters (`*`, `?`, `[`, `]`).
|
||||
- All caller values (`listingIds` as `INT32` safe integers, allow-listed `kinds`, `'USD.CAD' -> 'USDCAD'`, and UTC date/timestamp bounds) are validated upfront and passed strictly as bound `?` parameters.
|
||||
|
||||
### `bars` 1d Adjustment Formulas & `asOf` Anchoring Caveat
|
||||
|
||||
`bars_1d` stores raw OHLC, optional `vwap`, and split-unadjusted raw share `volume`. For `'split'` and `'total'`, `bars_1d` is joined via `ASOF LEFT JOIN` against `<curatedRoot>/adj_factors/part.parquet` (filtered to `listing_id IN (...) AND known_at <= ?`) on `b.listing_id = a.listing_id AND b.session_date < a.ex_date` (matching the first `adj_factors` row with `ex_date > session_date` per `tools/curate-etl/README.md`):
|
||||
|
||||
- **`'raw'`**: OHLC, `vwap`, and `volume` are returned unadjusted.
|
||||
- **`'split'`**: `open`, `high`, `low`, `close`, and `vwap` are divided by `COALESCE(a.cum_split_factor, 1.0)`; `volume` is multiplied by `COALESCE(a.cum_split_factor, 1.0)`.
|
||||
- **`'total'`**: `open`, `high`, `low`, `close`, and `vwap` are divided by `COALESCE(a.cum_total_factor, 1.0)`; `volume` is multiplied by `COALESCE(a.cum_split_factor, 1.0)`.
|
||||
|
||||
> **Point-in-time `asOf` anchoring caveat:** `tools/curate-etl` writes full-horizon curation-time suffix products into `cum_split_factor` and `cum_total_factor`. Filtering `adj_factors` by `known_at <= asOf` excludes post-`asOf` corporate-action rows (so bars on/after the last visible `ex_date` fall back to `1.0`), while earlier surviving rows still carry the curation-time suffix product (introducing a scale jump across the last visible `ex_date` if an excluded future split or dividend exists). Full historical re-anchoring to `asOf` requires a separate `curate-etl` schema/query enhancement.
|
||||
|
||||
### Local Query-Planner Benchmark
|
||||
|
||||
Fixed-seed (`20261129`) local benchmark planning `120,000` mixed queries across `bars` 1d (`raw`/`split`/`total`), `events` (with and without `listingIds`), `shortsAsOf`, and `fx` 1d with no database dependency:
|
||||
|
||||
- **Command:** `bun run libs/research/scripts/benchmark-market-data-store-duckdb.ts`
|
||||
- **Observed (Bun 1.2.16):** `elapsedMs = 178.15 ms`, `queriesPerSec = 673,600 queries/s` (`120,000` queries, `758,061` bound params, deterministic checksum `0d85763b`)
|
||||
|
|
|
|||
|
|
@ -11,6 +11,7 @@
|
|||
"./dataset-contracts": "./src/dataset-contracts.ts",
|
||||
"./datasets": "./src/datasets.ts",
|
||||
"./market-data-store": "./src/market-data-store.ts",
|
||||
"./market-data-store-duckdb": "./src/market-data-store-duckdb.ts",
|
||||
"./results": "./src/results.ts",
|
||||
"./signal-study": "./src/signal-study.ts",
|
||||
"./strategy-api": "./src/strategy-api.ts",
|
||||
|
|
|
|||
172
libs/research/scripts/benchmark-market-data-store-duckdb.ts
Normal file
172
libs/research/scripts/benchmark-market-data-store-duckdb.ts
Normal file
|
|
@ -0,0 +1,172 @@
|
|||
import {
|
||||
BARS_ADJUSTMENTS,
|
||||
type BarsQuery,
|
||||
type DuckDbPlanContext,
|
||||
EVENT_KINDS,
|
||||
type EventsQuery,
|
||||
type FxQuery,
|
||||
type PlannedDuckDbQuery,
|
||||
type ShortsAsOfQuery,
|
||||
planBars1dQuery,
|
||||
planEventsQuery,
|
||||
planFx1dQuery,
|
||||
planShortsAsOfQuery,
|
||||
} from '../src/market-data-store-duckdb';
|
||||
|
||||
const SEED = 20261129;
|
||||
const QUERY_COUNT = 120_000;
|
||||
const CURATED_ROOT = '/mnt/data/stockbot/curated';
|
||||
const VAULT_CUTOFF_TS = Date.UTC(2026, 4, 28, 0, 0, 0, 0);
|
||||
|
||||
const CTX: DuckDbPlanContext = {
|
||||
curatedRoot: CURATED_ROOT,
|
||||
vaultCutoffTs: VAULT_CUTOFF_TS,
|
||||
};
|
||||
|
||||
function createMulberry32(seed: number): () => number {
|
||||
let state = seed >>> 0;
|
||||
return () => {
|
||||
state = (state + 0x6d2b79f5) >>> 0;
|
||||
let t = Math.imul(state ^ (state >>> 15), 1 | state);
|
||||
t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;
|
||||
return ((t ^ (t >>> 14)) >>> 0) / 4_294_967_296;
|
||||
};
|
||||
}
|
||||
|
||||
type WorkloadItem =
|
||||
| { readonly kind: 'bars'; readonly q: BarsQuery }
|
||||
| { readonly kind: 'events'; readonly q: EventsQuery }
|
||||
| { readonly kind: 'shorts'; readonly q: ShortsAsOfQuery }
|
||||
| { readonly kind: 'fx'; readonly q: FxQuery };
|
||||
|
||||
const rng = createMulberry32(SEED);
|
||||
const startBaseMs = Date.UTC(2016, 0, 1, 0, 0, 0, 0);
|
||||
const preCutoffSpanMs = VAULT_CUTOFF_TS - startBaseMs - 86_400_000;
|
||||
const postCutoffSpanMs = 180 * 86_400_000;
|
||||
|
||||
function randomDateOrIso(epochMs: number): string {
|
||||
const iso = new Date(epochMs).toISOString();
|
||||
return rng() < 0.5 ? iso.slice(0, 10) : iso;
|
||||
}
|
||||
|
||||
function randomListingIds(): number[] {
|
||||
const count = 1 + Math.floor(rng() * 4);
|
||||
const ids: number[] = new Array(count);
|
||||
for (let i = 0; i < count; i += 1) {
|
||||
ids[i] = 1 + Math.floor(rng() * 50_000);
|
||||
}
|
||||
return ids;
|
||||
}
|
||||
|
||||
const workload: WorkloadItem[] = new Array(QUERY_COUNT);
|
||||
for (let i = 0; i < QUERY_COUNT; i += 1) {
|
||||
const fromMs = startBaseMs + Math.floor(rng() * preCutoffSpanMs);
|
||||
const toMs = fromMs + Math.floor(rng() * (VAULT_CUTOFF_TS - fromMs + postCutoffSpanMs));
|
||||
const asOfMs =
|
||||
rng() < 0.35
|
||||
? undefined
|
||||
: startBaseMs + Math.floor(rng() * (VAULT_CUTOFF_TS - startBaseMs + postCutoffSpanMs));
|
||||
|
||||
const from = randomDateOrIso(fromMs);
|
||||
const to = randomDateOrIso(toMs);
|
||||
const asOf = asOfMs === undefined ? undefined : randomDateOrIso(asOfMs);
|
||||
|
||||
const slot = i % 7;
|
||||
if (slot < 3) {
|
||||
const adjustment = BARS_ADJUSTMENTS[slot] ?? 'raw';
|
||||
workload[i] = {
|
||||
kind: 'bars',
|
||||
q: {
|
||||
listingIds: randomListingIds(),
|
||||
timeframe: '1d',
|
||||
from,
|
||||
to,
|
||||
adjustment,
|
||||
asOf,
|
||||
},
|
||||
};
|
||||
} else if (slot === 3 || slot === 4) {
|
||||
const kindA = EVENT_KINDS[Math.floor(rng() * EVENT_KINDS.length)] ?? 'filing';
|
||||
const kindB = EVENT_KINDS[Math.floor(rng() * EVENT_KINDS.length)] ?? 'earnings';
|
||||
workload[i] = {
|
||||
kind: 'events',
|
||||
q: {
|
||||
kinds: slot === 3 ? [kindA] : [kindA, kindB],
|
||||
listingIds: slot === 3 ? randomListingIds() : undefined,
|
||||
from,
|
||||
to,
|
||||
asOf,
|
||||
},
|
||||
};
|
||||
} else if (slot === 5) {
|
||||
workload[i] = {
|
||||
kind: 'shorts',
|
||||
q: {
|
||||
listingIds: randomListingIds(),
|
||||
from,
|
||||
to,
|
||||
asOf,
|
||||
},
|
||||
};
|
||||
} else {
|
||||
workload[i] = {
|
||||
kind: 'fx',
|
||||
q: {
|
||||
pair: 'USD.CAD',
|
||||
timeframe: '1d',
|
||||
from,
|
||||
to,
|
||||
},
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
function mixFnv1a(hash: number, value: number): number {
|
||||
let h = (hash ^ (value >>> 0)) >>> 0;
|
||||
h = Math.imul(h, 0x01000193) >>> 0;
|
||||
return h;
|
||||
}
|
||||
|
||||
let checksum = 0x811c9dc5;
|
||||
let totalParams = 0;
|
||||
|
||||
const started = performance.now();
|
||||
for (const item of workload) {
|
||||
let planned: PlannedDuckDbQuery;
|
||||
switch (item.kind) {
|
||||
case 'bars':
|
||||
planned = planBars1dQuery(item.q, CTX);
|
||||
break;
|
||||
case 'events':
|
||||
planned = planEventsQuery(item.q, CTX);
|
||||
break;
|
||||
case 'shorts':
|
||||
planned = planShortsAsOfQuery(item.q, CTX);
|
||||
break;
|
||||
case 'fx':
|
||||
planned = planFx1dQuery(item.q, CTX);
|
||||
break;
|
||||
}
|
||||
totalParams += planned.params.length;
|
||||
checksum = mixFnv1a(checksum, planned.sql.length);
|
||||
checksum = mixFnv1a(checksum, planned.params.length);
|
||||
checksum = mixFnv1a(checksum, Math.trunc(planned.fenced.toMs / 1000));
|
||||
checksum = mixFnv1a(checksum, Math.trunc(planned.fenced.asOfMs / 1000));
|
||||
}
|
||||
const elapsedMs = performance.now() - started;
|
||||
const queriesPerSec = Math.round(QUERY_COUNT / (elapsedMs / 1000));
|
||||
|
||||
console.log(
|
||||
JSON.stringify(
|
||||
{
|
||||
seed: SEED,
|
||||
queries: QUERY_COUNT,
|
||||
totalParams,
|
||||
elapsedMs: Number(elapsedMs.toFixed(2)),
|
||||
queriesPerSec,
|
||||
checksum: checksum.toString(16).padStart(8, '0'),
|
||||
},
|
||||
null,
|
||||
2
|
||||
)
|
||||
);
|
||||
|
|
@ -1,5 +1,6 @@
|
|||
// The default entrypoint is browser safe; server validation is an explicit subpath.
|
||||
export * from './dataset-contracts';
|
||||
export * from './market-data-store';
|
||||
export * from './market-data-store-duckdb';
|
||||
export * from './signal-study';
|
||||
export * from './trial-ledger';
|
||||
|
|
|
|||
851
libs/research/src/market-data-store-duckdb.ts
Normal file
851
libs/research/src/market-data-store-duckdb.ts
Normal file
|
|
@ -0,0 +1,851 @@
|
|||
/**
|
||||
* Pure, dependency-free DuckDB SQL query planner and injected-executor
|
||||
* `MarketDataStore` adapter for curated daily Parquet datasets
|
||||
* (`design/DATA-CONTRACTS.md` §3.A & §4).
|
||||
*
|
||||
* Browser-safe and dependency-free: zero `node:*` imports, zero DuckDB driver
|
||||
* dependency, zero bare `process` access. SQL execution is injected via
|
||||
* {@link DuckDbExecutor}, mirroring `TrialLedgerExecutor` in `./trial-ledger`.
|
||||
*
|
||||
* Curated Parquet layout under `curatedRoot` (`design/DATA-CONTRACTS.md` §3.A):
|
||||
* - `<curatedRoot>/bars_1d/year=*\/part.parquet` (`hive_partitioning = true`)
|
||||
* - `<curatedRoot>/adj_factors/part.parquet`
|
||||
* - `<curatedRoot>/events/year=*\/part.parquet` (`hive_partitioning = true`)
|
||||
* - `<curatedRoot>/shorts/part.parquet`
|
||||
* - `<curatedRoot>/fx_1d/part.parquet`
|
||||
*
|
||||
* `bars` (`timeframe: '1d'`) adjustment formulas (`tools/curate-etl/README.md`):
|
||||
* - `bars_1d` stores raw OHLC, optional `vwap`, and split-unadjusted raw share
|
||||
* `volume`.
|
||||
* - `adj_factors` stores per-`(listing_id, ex_date)` cumulative back-adjustment
|
||||
* divisors (`cum_split_factor`, `cum_total_factor`) and `known_at`.
|
||||
* - For `'raw'`, `open`, `high`, `low`, `close`, `volume`, and `vwap` are
|
||||
* projected directly from `bars_1d`.
|
||||
* - For `'split'` and `'total'`, `bars_1d` is joined via `ASOF LEFT JOIN`
|
||||
* against `adj_factors` filtered to `listing_id IN (...) AND known_at <= ?`
|
||||
* on `b.listing_id = a.listing_id AND b.session_date < a.ex_date` (selecting
|
||||
* the first `adj_factors` row with `ex_date > session_date` and
|
||||
* `known_at <= asOf`):
|
||||
* - `'split'`:
|
||||
* - `price_adj = price_raw / COALESCE(a.cum_split_factor, 1.0)` for
|
||||
* `open`, `high`, `low`, `close`, and `vwap` (preserving `NULL` `vwap`).
|
||||
* - `volume_adj = volume_raw * COALESCE(a.cum_split_factor, 1.0)`.
|
||||
* - `'total'`:
|
||||
* - `price_adj = price_raw / COALESCE(a.cum_total_factor, 1.0)` for
|
||||
* `open`, `high`, `low`, `close`, and `vwap` (preserving `NULL` `vwap`).
|
||||
* - `volume_adj = volume_raw * COALESCE(a.cum_split_factor, 1.0)` (share
|
||||
* volume scales only by splits, not cash dividends).
|
||||
*
|
||||
* Point-in-time suffix-product `asOf` anchoring caveat:
|
||||
* - `tools/curate-etl` writes full-horizon curation-time suffix products into
|
||||
* `cum_split_factor` and `cum_total_factor`. Filtering `adj_factors` by
|
||||
* `known_at <= asOf` excludes post-`asOf` corporate-action rows, so bars on
|
||||
* or after the last visible `ex_date` fall back to `1.0`, while earlier
|
||||
* surviving rows still carry the curation-time suffix product (introducing a
|
||||
* scale jump across the last visible `ex_date` whenever an excluded future
|
||||
* split or dividend exists). Full historical re-anchoring to `asOf` requires
|
||||
* a separate `curate-etl` schema/query enhancement.
|
||||
*/
|
||||
|
||||
import {
|
||||
type BarBatch,
|
||||
type BarRecord,
|
||||
type EventKind,
|
||||
type FencedTimeRange,
|
||||
type MarketDataStore,
|
||||
MarketDataStoreValidationError,
|
||||
type Table,
|
||||
type TableCell,
|
||||
type TableRow,
|
||||
applyVaultFence,
|
||||
resolveDuckDbConnectionBudget,
|
||||
} from './market-data-store';
|
||||
|
||||
const INT32_MIN = -2_147_483_648;
|
||||
const INT32_MAX = 2_147_483_647;
|
||||
const MAX_ECMASCRIPT_EPOCH_MS = 8_640_000_000_000_000;
|
||||
|
||||
export const EVENT_KINDS = ['filing', 'earnings', 'ceo_post', 'corporate_action'] as const;
|
||||
const EVENT_KIND_SET: ReadonlySet<string> = new Set<string>(EVENT_KINDS);
|
||||
|
||||
export const FX_PAIR_MAP = {
|
||||
'USD.CAD': 'USDCAD',
|
||||
} as const;
|
||||
|
||||
export const BARS_ADJUSTMENTS = ['raw', 'split', 'total'] as const;
|
||||
const BARS_ADJUSTMENT_SET: ReadonlySet<string> = new Set<string>(BARS_ADJUSTMENTS);
|
||||
|
||||
export const EVENTS_COLUMNS = [
|
||||
'listing_id',
|
||||
'ts',
|
||||
'known_at',
|
||||
'known_at_source',
|
||||
'kind',
|
||||
'subtype',
|
||||
'payload_json',
|
||||
] as const;
|
||||
|
||||
export const SHORTS_COLUMNS = [
|
||||
'listing_id',
|
||||
'report_date',
|
||||
'known_at',
|
||||
'shares_short',
|
||||
'net_change',
|
||||
'pct_float',
|
||||
'source',
|
||||
] as const;
|
||||
|
||||
export const FX_1D_COLUMNS = [
|
||||
'pair',
|
||||
'session_date',
|
||||
'ts',
|
||||
'open',
|
||||
'high',
|
||||
'low',
|
||||
'close',
|
||||
'source',
|
||||
'known_at',
|
||||
] as const;
|
||||
|
||||
/** Scalar parameter value bound separately from SQL text. */
|
||||
export type DuckDbParam = string | number | boolean | null;
|
||||
|
||||
/**
|
||||
* Injected DuckDB SQL executor interface. Parameter values are always passed
|
||||
* separately from SQL text via `params`.
|
||||
*/
|
||||
export interface DuckDbExecutor {
|
||||
run(sql: string): Promise<void>;
|
||||
query(sql: string, params: readonly DuckDbParam[]): Promise<readonly TableRow[]>;
|
||||
}
|
||||
|
||||
/** Pure output of a DuckDB query planner. */
|
||||
export interface PlannedDuckDbQuery {
|
||||
readonly sql: string;
|
||||
readonly params: readonly DuckDbParam[];
|
||||
readonly fenced: FencedTimeRange;
|
||||
}
|
||||
|
||||
/** Context required to plan fenced DuckDB queries against curated Parquet. */
|
||||
export interface DuckDbPlanContext {
|
||||
readonly curatedRoot: string;
|
||||
readonly vaultCutoffTs: number;
|
||||
readonly vaultOperatorAuthorized?: boolean;
|
||||
}
|
||||
|
||||
/** Configuration for {@link createDuckDbMarketDataStore}. */
|
||||
export interface DuckDbMarketDataStoreOptions extends DuckDbPlanContext {
|
||||
readonly executor: DuckDbExecutor;
|
||||
readonly env?: Readonly<Record<string, string | undefined>>;
|
||||
readonly barBatchSize?: number;
|
||||
}
|
||||
|
||||
export type BarsQuery = Parameters<MarketDataStore['bars']>[0];
|
||||
export type EventsQuery = Parameters<MarketDataStore['events']>[0];
|
||||
export type ShortsAsOfQuery = Parameters<MarketDataStore['shortsAsOf']>[0];
|
||||
export type FxQuery = Parameters<MarketDataStore['fx']>[0];
|
||||
|
||||
/**
|
||||
* Thrown when a `MarketDataStore` method or timeframe is outside the curated
|
||||
* daily DuckDB Parquet adapter slice.
|
||||
*/
|
||||
export class MarketDataStoreNotImplementedError extends Error {
|
||||
override readonly name = 'MarketDataStoreNotImplementedError';
|
||||
readonly method: keyof MarketDataStore;
|
||||
readonly detail?: string;
|
||||
|
||||
constructor(method: keyof MarketDataStore, detail?: string) {
|
||||
super(
|
||||
detail !== undefined
|
||||
? `MarketDataStore.${method} is not implemented by the DuckDB daily Parquet adapter: ${detail}`
|
||||
: `MarketDataStore.${method} is not implemented by the DuckDB daily Parquet adapter.`
|
||||
);
|
||||
this.method = method;
|
||||
this.detail = detail;
|
||||
Object.setPrototypeOf(this, new.target.prototype);
|
||||
}
|
||||
}
|
||||
|
||||
function isPlainRecord(value: unknown): value is Record<string, unknown> {
|
||||
return typeof value === 'object' && value !== null && !Array.isArray(value);
|
||||
}
|
||||
|
||||
function hasForbiddenCuratedRootChar(value: string): boolean {
|
||||
for (let i = 0; i < value.length; i += 1) {
|
||||
const code = value.charCodeAt(i);
|
||||
// Reject ASCII control chars (0x00..0x1f, 0x7f), SQL quote/separator (', ;),
|
||||
// and DuckDB read_parquet glob metacharacters (*, ?, [, ]).
|
||||
if (
|
||||
code <= 0x1f ||
|
||||
code === 0x7f ||
|
||||
code === 0x27 ||
|
||||
code === 0x3b ||
|
||||
code === 0x2a ||
|
||||
code === 0x3f ||
|
||||
code === 0x5b ||
|
||||
code === 0x5d
|
||||
) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Strictly validates `curatedRoot` as an absolute POSIX path with no control
|
||||
* characters, single quotes, semicolons, or glob metacharacters, normalizing
|
||||
* trailing slashes (except `'/'`).
|
||||
*/
|
||||
export function validateCuratedRoot(raw: string): string {
|
||||
if (
|
||||
typeof raw !== 'string' ||
|
||||
raw.length === 0 ||
|
||||
!raw.startsWith('/') ||
|
||||
hasForbiddenCuratedRootChar(raw)
|
||||
) {
|
||||
throw new MarketDataStoreValidationError(
|
||||
`Invalid curatedRoot "${String(raw)}". Expected a non-empty absolute POSIX path without quotes, semicolons, control characters, or glob characters (*, ?, [, ]).`,
|
||||
'curatedRoot'
|
||||
);
|
||||
}
|
||||
|
||||
let end = raw.length;
|
||||
while (end > 1 && raw.charCodeAt(end - 1) === 0x2f) {
|
||||
end -= 1;
|
||||
}
|
||||
return end === raw.length ? raw : raw.slice(0, end);
|
||||
}
|
||||
|
||||
function joinCuratedPath(normalizedRoot: string, relativePath: string): string {
|
||||
return normalizedRoot === '/' ? `/${relativePath}` : `${normalizedRoot}/${relativePath}`;
|
||||
}
|
||||
|
||||
function validateListingIds(raw: readonly number[], field = 'listingIds'): number[] {
|
||||
if (!Array.isArray(raw) || raw.length === 0) {
|
||||
throw new MarketDataStoreValidationError(
|
||||
`Expected a non-empty array of INT32 listing IDs for "${field}".`,
|
||||
field
|
||||
);
|
||||
}
|
||||
|
||||
if (raw.length === 1) {
|
||||
const id = raw[0];
|
||||
if (
|
||||
typeof id !== 'number' ||
|
||||
!Number.isSafeInteger(id) ||
|
||||
id < INT32_MIN ||
|
||||
id > INT32_MAX
|
||||
) {
|
||||
throw new MarketDataStoreValidationError(
|
||||
`Invalid INT32 listing ID at ${field}[0]: ${String(id)}.`,
|
||||
field
|
||||
);
|
||||
}
|
||||
return [id === 0 ? 0 : id];
|
||||
}
|
||||
|
||||
const seen = new Set<number>();
|
||||
const normalized: number[] = [];
|
||||
for (let i = 0; i < raw.length; i += 1) {
|
||||
const id = raw[i];
|
||||
if (
|
||||
typeof id !== 'number' ||
|
||||
!Number.isSafeInteger(id) ||
|
||||
id < INT32_MIN ||
|
||||
id > INT32_MAX
|
||||
) {
|
||||
throw new MarketDataStoreValidationError(
|
||||
`Invalid INT32 listing ID at ${field}[${i}]: ${String(id)}.`,
|
||||
field
|
||||
);
|
||||
}
|
||||
const clean = id === 0 ? 0 : id;
|
||||
if (!seen.has(clean)) {
|
||||
seen.add(clean);
|
||||
normalized.push(clean);
|
||||
}
|
||||
}
|
||||
return normalized;
|
||||
}
|
||||
|
||||
function validateEventKinds(raw: readonly EventKind[], field = 'kinds'): EventKind[] {
|
||||
if (!Array.isArray(raw) || raw.length === 0) {
|
||||
throw new MarketDataStoreValidationError(
|
||||
`Expected a non-empty array of EventKind values for "${field}".`,
|
||||
field
|
||||
);
|
||||
}
|
||||
|
||||
if (raw.length === 1) {
|
||||
const kind = raw[0];
|
||||
if (typeof kind !== 'string' || !EVENT_KIND_SET.has(kind)) {
|
||||
throw new MarketDataStoreValidationError(
|
||||
`Unknown EventKind "${String(kind)}". Expected one of: ${EVENT_KINDS.join(', ')}.`,
|
||||
field
|
||||
);
|
||||
}
|
||||
return [kind as EventKind];
|
||||
}
|
||||
|
||||
const seen = new Set<string>();
|
||||
const normalized: EventKind[] = [];
|
||||
for (let i = 0; i < raw.length; i += 1) {
|
||||
const kind = raw[i];
|
||||
if (typeof kind !== 'string' || !EVENT_KIND_SET.has(kind)) {
|
||||
throw new MarketDataStoreValidationError(
|
||||
`Unknown EventKind "${String(kind)}". Expected one of: ${EVENT_KINDS.join(', ')}.`,
|
||||
field
|
||||
);
|
||||
}
|
||||
if (!seen.has(kind)) {
|
||||
seen.add(kind);
|
||||
normalized.push(kind as EventKind);
|
||||
}
|
||||
}
|
||||
return normalized;
|
||||
}
|
||||
|
||||
function validateAdjustment(raw: unknown): (typeof BARS_ADJUSTMENTS)[number] {
|
||||
if (typeof raw !== 'string' || !BARS_ADJUSTMENT_SET.has(raw)) {
|
||||
throw new MarketDataStoreValidationError(
|
||||
`Invalid adjustment "${String(raw)}". Expected one of: ${BARS_ADJUSTMENTS.join(', ')}.`,
|
||||
'adjustment'
|
||||
);
|
||||
}
|
||||
return raw as (typeof BARS_ADJUSTMENTS)[number];
|
||||
}
|
||||
|
||||
function validateFxPair(raw: unknown): (typeof FX_PAIR_MAP)[keyof typeof FX_PAIR_MAP] {
|
||||
if (typeof raw === 'string' && Object.prototype.hasOwnProperty.call(FX_PAIR_MAP, raw)) {
|
||||
return FX_PAIR_MAP[raw as keyof typeof FX_PAIR_MAP];
|
||||
}
|
||||
throw new MarketDataStoreValidationError(
|
||||
`Unsupported FX pair "${String(raw)}". Expected 'USD.CAD'.`,
|
||||
'pair'
|
||||
);
|
||||
}
|
||||
|
||||
function validateContext(ctx: DuckDbPlanContext): string {
|
||||
if (!isPlainRecord(ctx)) {
|
||||
throw new MarketDataStoreValidationError('Expected a DuckDbPlanContext object.', 'context');
|
||||
}
|
||||
return validateCuratedRoot(ctx.curatedRoot);
|
||||
}
|
||||
|
||||
function buildPlaceholders(count: number): string {
|
||||
if (count === 1) {
|
||||
return '?';
|
||||
}
|
||||
if (count === 2) {
|
||||
return '?, ?';
|
||||
}
|
||||
if (count === 3) {
|
||||
return '?, ?, ?';
|
||||
}
|
||||
let out = '?';
|
||||
for (let i = 1; i < count; i += 1) {
|
||||
out += ', ?';
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
function formatUtcIso(epochMs: number): string {
|
||||
return new Date(epochMs).toISOString();
|
||||
}
|
||||
|
||||
function formatUtcDate(epochMs: number): string {
|
||||
return new Date(epochMs).toISOString().slice(0, 10);
|
||||
}
|
||||
|
||||
/**
|
||||
* Plans a fenced DuckDB SQL query for daily curated OHLCV bars (`bars_1d`) with
|
||||
* optional point-in-time `adj_factors` split or total-return adjustment.
|
||||
*/
|
||||
export function planBars1dQuery(q: BarsQuery, ctx: DuckDbPlanContext): PlannedDuckDbQuery {
|
||||
const curatedRoot = validateContext(ctx);
|
||||
if (!isPlainRecord(q)) {
|
||||
throw new MarketDataStoreValidationError('Expected a bars query object.', 'query');
|
||||
}
|
||||
|
||||
const timeframe: unknown = q.timeframe;
|
||||
if (timeframe === '1m' || timeframe === '5m' || timeframe === '1h') {
|
||||
throw new MarketDataStoreNotImplementedError(
|
||||
'bars',
|
||||
`Timeframe '${timeframe}' is outside the daily Parquet slice.`
|
||||
);
|
||||
}
|
||||
if (timeframe !== '1d') {
|
||||
throw new MarketDataStoreValidationError(
|
||||
`Invalid bars timeframe "${String(timeframe)}". Expected '1d'.`,
|
||||
'timeframe'
|
||||
);
|
||||
}
|
||||
|
||||
const adjustment = validateAdjustment(q.adjustment);
|
||||
const listingIds = validateListingIds(q.listingIds);
|
||||
const fenced = applyVaultFence(
|
||||
{
|
||||
from: q.from,
|
||||
to: q.to,
|
||||
asOf: q.asOf,
|
||||
scope: q.scope,
|
||||
},
|
||||
{
|
||||
vaultCutoffTs: ctx.vaultCutoffTs,
|
||||
vaultOperatorAuthorized: ctx.vaultOperatorAuthorized,
|
||||
}
|
||||
);
|
||||
|
||||
const fromIso = formatUtcIso(fenced.fromMs);
|
||||
const toIso = formatUtcIso(fenced.toMs);
|
||||
const asOfIso = formatUtcIso(fenced.asOfMs);
|
||||
const barsPath = joinCuratedPath(curatedRoot, 'bars_1d/year=*/part.parquet');
|
||||
const listingPlaceholders = buildPlaceholders(listingIds.length);
|
||||
|
||||
if (adjustment === 'raw') {
|
||||
const sql =
|
||||
'SELECT b.listing_id, epoch_ms(b.ts) AS ts, b.open, b.high, b.low, b.close, b.volume, b.vwap, epoch_ms(b.known_at) AS known_at ' +
|
||||
`FROM read_parquet('${barsPath}', hive_partitioning = true) AS b ` +
|
||||
`WHERE b.listing_id IN (${listingPlaceholders}) AND b.ts >= ? AND b.ts <= ? AND b.known_at <= ? ` +
|
||||
'ORDER BY b.listing_id ASC, b.ts ASC';
|
||||
const params: DuckDbParam[] = [...listingIds, fromIso, toIso, asOfIso];
|
||||
return { sql, params, fenced };
|
||||
}
|
||||
|
||||
const adjPath = joinCuratedPath(curatedRoot, 'adj_factors/part.parquet');
|
||||
const priceDivisor =
|
||||
adjustment === 'split'
|
||||
? 'COALESCE(a.cum_split_factor, 1.0)'
|
||||
: 'COALESCE(a.cum_total_factor, 1.0)';
|
||||
const adjSelectCols =
|
||||
adjustment === 'split'
|
||||
? 'listing_id, ex_date, cum_split_factor'
|
||||
: 'listing_id, ex_date, cum_split_factor, cum_total_factor';
|
||||
|
||||
const sql =
|
||||
'SELECT b.listing_id, epoch_ms(b.ts) AS ts, ' +
|
||||
`b.open / ${priceDivisor} AS open, ` +
|
||||
`b.high / ${priceDivisor} AS high, ` +
|
||||
`b.low / ${priceDivisor} AS low, ` +
|
||||
`b.close / ${priceDivisor} AS close, ` +
|
||||
'b.volume * COALESCE(a.cum_split_factor, 1.0) AS volume, ' +
|
||||
`b.vwap / ${priceDivisor} AS vwap, ` +
|
||||
'epoch_ms(b.known_at) AS known_at ' +
|
||||
`FROM read_parquet('${barsPath}', hive_partitioning = true) AS b ` +
|
||||
`ASOF LEFT JOIN (SELECT ${adjSelectCols} FROM read_parquet('${adjPath}') WHERE listing_id IN (${listingPlaceholders}) AND known_at <= ?) AS a ` +
|
||||
'ON b.listing_id = a.listing_id AND b.session_date < a.ex_date ' +
|
||||
`WHERE b.listing_id IN (${listingPlaceholders}) AND b.ts >= ? AND b.ts <= ? AND b.known_at <= ? ` +
|
||||
'ORDER BY b.listing_id ASC, b.ts ASC';
|
||||
|
||||
const params: DuckDbParam[] = [...listingIds, asOfIso, ...listingIds, fromIso, toIso, asOfIso];
|
||||
return { sql, params, fenced };
|
||||
}
|
||||
|
||||
/**
|
||||
* Plans a fenced DuckDB SQL query for point-in-time curated events (`events`).
|
||||
*/
|
||||
export function planEventsQuery(q: EventsQuery, ctx: DuckDbPlanContext): PlannedDuckDbQuery {
|
||||
const curatedRoot = validateContext(ctx);
|
||||
if (!isPlainRecord(q)) {
|
||||
throw new MarketDataStoreValidationError('Expected an events query object.', 'query');
|
||||
}
|
||||
|
||||
const kinds = validateEventKinds(q.kinds);
|
||||
const listingIds =
|
||||
q.listingIds !== undefined ? validateListingIds(q.listingIds) : undefined;
|
||||
const fenced = applyVaultFence(
|
||||
{
|
||||
from: q.from,
|
||||
to: q.to,
|
||||
asOf: q.asOf,
|
||||
scope: 'vault_fenced',
|
||||
},
|
||||
{
|
||||
vaultCutoffTs: ctx.vaultCutoffTs,
|
||||
}
|
||||
);
|
||||
|
||||
const fromIso = formatUtcIso(fenced.fromMs);
|
||||
const toIso = formatUtcIso(fenced.toMs);
|
||||
const asOfIso = formatUtcIso(fenced.asOfMs);
|
||||
const eventsPath = joinCuratedPath(curatedRoot, 'events/year=*/part.parquet');
|
||||
const kindPlaceholders = buildPlaceholders(kinds.length);
|
||||
|
||||
if (listingIds !== undefined) {
|
||||
const listingPlaceholders = buildPlaceholders(listingIds.length);
|
||||
const sql =
|
||||
'SELECT e.listing_id, epoch_ms(e.ts) AS ts, epoch_ms(e.known_at) AS known_at, e.known_at_source, e.kind, e.subtype, e.payload_json ' +
|
||||
`FROM read_parquet('${eventsPath}', hive_partitioning = true) AS e ` +
|
||||
`WHERE e.kind IN (${kindPlaceholders}) AND e.listing_id IN (${listingPlaceholders}) AND e.ts >= ? AND e.ts <= ? AND e.known_at <= ? ` +
|
||||
'ORDER BY e.listing_id ASC, e.ts ASC, e.kind ASC, e.subtype ASC';
|
||||
const params: DuckDbParam[] = [...kinds, ...listingIds, fromIso, toIso, asOfIso];
|
||||
return { sql, params, fenced };
|
||||
}
|
||||
|
||||
const sql =
|
||||
'SELECT e.listing_id, epoch_ms(e.ts) AS ts, epoch_ms(e.known_at) AS known_at, e.known_at_source, e.kind, e.subtype, e.payload_json ' +
|
||||
`FROM read_parquet('${eventsPath}', hive_partitioning = true) AS e ` +
|
||||
`WHERE e.kind IN (${kindPlaceholders}) AND e.ts >= ? AND e.ts <= ? AND e.known_at <= ? ` +
|
||||
'ORDER BY e.listing_id ASC, e.ts ASC, e.kind ASC, e.subtype ASC';
|
||||
const params: DuckDbParam[] = [...kinds, fromIso, toIso, asOfIso];
|
||||
return { sql, params, fenced };
|
||||
}
|
||||
|
||||
/**
|
||||
* Plans a fenced DuckDB SQL query for point-in-time curated short interest (`shorts`).
|
||||
*/
|
||||
export function planShortsAsOfQuery(
|
||||
q: ShortsAsOfQuery,
|
||||
ctx: DuckDbPlanContext
|
||||
): PlannedDuckDbQuery {
|
||||
const curatedRoot = validateContext(ctx);
|
||||
if (!isPlainRecord(q)) {
|
||||
throw new MarketDataStoreValidationError('Expected a shortsAsOf query object.', 'query');
|
||||
}
|
||||
|
||||
const listingIds = validateListingIds(q.listingIds);
|
||||
const fenced = applyVaultFence(
|
||||
{
|
||||
from: q.from,
|
||||
to: q.to,
|
||||
asOf: q.asOf,
|
||||
scope: 'vault_fenced',
|
||||
},
|
||||
{
|
||||
vaultCutoffTs: ctx.vaultCutoffTs,
|
||||
}
|
||||
);
|
||||
|
||||
const fromDate = formatUtcDate(fenced.fromMs);
|
||||
const toDate = formatUtcDate(fenced.toMs);
|
||||
const asOfIso = formatUtcIso(fenced.asOfMs);
|
||||
const shortsPath = joinCuratedPath(curatedRoot, 'shorts/part.parquet');
|
||||
const listingPlaceholders = buildPlaceholders(listingIds.length);
|
||||
|
||||
const sql =
|
||||
'SELECT s.listing_id, CAST(s.report_date AS VARCHAR) AS report_date, epoch_ms(s.known_at) AS known_at, s.shares_short, s.net_change, s.pct_float, s.source ' +
|
||||
`FROM read_parquet('${shortsPath}') AS s ` +
|
||||
`WHERE s.listing_id IN (${listingPlaceholders}) AND s.report_date >= ? AND s.report_date <= ? AND s.known_at <= ? ` +
|
||||
'ORDER BY s.listing_id ASC, s.report_date ASC';
|
||||
const params: DuckDbParam[] = [...listingIds, fromDate, toDate, asOfIso];
|
||||
return { sql, params, fenced };
|
||||
}
|
||||
|
||||
/**
|
||||
* Plans a fenced DuckDB SQL query for daily curated FX bars (`fx_1d`).
|
||||
* `fx` has no `asOf`/`scope` in `MarketDataStore`, so it is always planned
|
||||
* under `'vault_fenced'` with default `asOf = vaultCutoffTs - 1`.
|
||||
*/
|
||||
export function planFx1dQuery(q: FxQuery, ctx: DuckDbPlanContext): PlannedDuckDbQuery {
|
||||
const curatedRoot = validateContext(ctx);
|
||||
if (!isPlainRecord(q)) {
|
||||
throw new MarketDataStoreValidationError('Expected an fx query object.', 'query');
|
||||
}
|
||||
|
||||
const timeframe: unknown = q.timeframe;
|
||||
if (timeframe === '1m') {
|
||||
throw new MarketDataStoreNotImplementedError(
|
||||
'fx',
|
||||
"Timeframe '1m' is outside the daily Parquet slice."
|
||||
);
|
||||
}
|
||||
if (timeframe !== '1d') {
|
||||
throw new MarketDataStoreValidationError(
|
||||
`Invalid fx timeframe "${String(timeframe)}". Expected '1d'.`,
|
||||
'timeframe'
|
||||
);
|
||||
}
|
||||
|
||||
const storedPair = validateFxPair(q.pair);
|
||||
const fenced = applyVaultFence(
|
||||
{
|
||||
from: q.from,
|
||||
to: q.to,
|
||||
scope: 'vault_fenced',
|
||||
},
|
||||
{
|
||||
vaultCutoffTs: ctx.vaultCutoffTs,
|
||||
}
|
||||
);
|
||||
|
||||
const fromIso = formatUtcIso(fenced.fromMs);
|
||||
const toIso = formatUtcIso(fenced.toMs);
|
||||
const asOfIso = formatUtcIso(fenced.asOfMs);
|
||||
const fxPath = joinCuratedPath(curatedRoot, 'fx_1d/part.parquet');
|
||||
|
||||
const sql =
|
||||
'SELECT f.pair, CAST(f.session_date AS VARCHAR) AS session_date, epoch_ms(f.ts) AS ts, f.open, f.high, f.low, f.close, f.source, epoch_ms(f.known_at) AS known_at ' +
|
||||
`FROM read_parquet('${fxPath}') AS f ` +
|
||||
'WHERE f.pair = ? AND f.ts >= ? AND f.ts <= ? AND f.known_at <= ? ' +
|
||||
'ORDER BY f.session_date ASC';
|
||||
const params: DuckDbParam[] = [storedPair, fromIso, toIso, asOfIso];
|
||||
return { sql, params, fenced };
|
||||
}
|
||||
|
||||
function readRequiredInt32(row: Record<string, unknown>, key: string, rowIndex: number): number {
|
||||
const val = row[key];
|
||||
if (typeof val !== 'number' || !Number.isSafeInteger(val) || val < INT32_MIN || val > INT32_MAX) {
|
||||
throw new MarketDataStoreValidationError(
|
||||
`Invalid INT32 column "${key}" in result row ${rowIndex}: ${String(val)}.`,
|
||||
key
|
||||
);
|
||||
}
|
||||
return val === 0 ? 0 : val;
|
||||
}
|
||||
|
||||
function readRequiredSafeInt(row: Record<string, unknown>, key: string, rowIndex: number): number {
|
||||
const val = row[key];
|
||||
if (typeof val !== 'number' || !Number.isSafeInteger(val)) {
|
||||
throw new MarketDataStoreValidationError(
|
||||
`Invalid integer timestamp column "${key}" in result row ${rowIndex}: ${String(val)}.`,
|
||||
key
|
||||
);
|
||||
}
|
||||
return val === 0 ? 0 : val;
|
||||
}
|
||||
|
||||
function readRequiredFiniteNumber(
|
||||
row: Record<string, unknown>,
|
||||
key: string,
|
||||
rowIndex: number
|
||||
): number {
|
||||
const val = row[key];
|
||||
if (typeof val !== 'number' || !Number.isFinite(val)) {
|
||||
throw new MarketDataStoreValidationError(
|
||||
`Invalid numeric column "${key}" in result row ${rowIndex}: ${String(val)}.`,
|
||||
key
|
||||
);
|
||||
}
|
||||
return val === 0 ? 0 : val;
|
||||
}
|
||||
|
||||
function readNullableFiniteNumber(
|
||||
row: Record<string, unknown>,
|
||||
key: string,
|
||||
rowIndex: number
|
||||
): number | null {
|
||||
const val = row[key];
|
||||
if (val === null || val === undefined) {
|
||||
return null;
|
||||
}
|
||||
if (typeof val !== 'number' || !Number.isFinite(val)) {
|
||||
throw new MarketDataStoreValidationError(
|
||||
`Invalid nullable numeric column "${key}" in result row ${rowIndex}: ${String(val)}.`,
|
||||
key
|
||||
);
|
||||
}
|
||||
return val === 0 ? 0 : val;
|
||||
}
|
||||
|
||||
function mapBarRows(rows: readonly TableRow[]): BarRecord[] {
|
||||
if (!Array.isArray(rows)) {
|
||||
throw new MarketDataStoreValidationError('Executor returned a non-array bars result.', 'rows');
|
||||
}
|
||||
const out: BarRecord[] = new Array(rows.length);
|
||||
for (let i = 0; i < rows.length; i += 1) {
|
||||
const raw = rows[i];
|
||||
if (!isPlainRecord(raw)) {
|
||||
throw new MarketDataStoreValidationError(
|
||||
`Executor returned a non-object bar row at index ${i}.`,
|
||||
'rows'
|
||||
);
|
||||
}
|
||||
out[i] = {
|
||||
listingId: readRequiredInt32(raw, 'listing_id', i),
|
||||
ts: readRequiredSafeInt(raw, 'ts', i),
|
||||
open: readRequiredFiniteNumber(raw, 'open', i),
|
||||
high: readRequiredFiniteNumber(raw, 'high', i),
|
||||
low: readRequiredFiniteNumber(raw, 'low', i),
|
||||
close: readRequiredFiniteNumber(raw, 'close', i),
|
||||
volume: readRequiredFiniteNumber(raw, 'volume', i),
|
||||
vwap: readNullableFiniteNumber(raw, 'vwap', i),
|
||||
knownAt: readRequiredSafeInt(raw, 'known_at', i),
|
||||
};
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
function isValidTableCell(value: unknown): value is TableCell {
|
||||
if (value === null || typeof value === 'string' || typeof value === 'boolean') {
|
||||
return true;
|
||||
}
|
||||
return typeof value === 'number' && Number.isFinite(value);
|
||||
}
|
||||
|
||||
function mapTableRows(columns: readonly string[], rows: readonly TableRow[]): Table {
|
||||
if (!Array.isArray(rows)) {
|
||||
throw new MarketDataStoreValidationError('Executor returned a non-array table result.', 'rows');
|
||||
}
|
||||
const mappedRows: TableRow[] = new Array(rows.length);
|
||||
for (let i = 0; i < rows.length; i += 1) {
|
||||
const raw = rows[i];
|
||||
if (!isPlainRecord(raw)) {
|
||||
throw new MarketDataStoreValidationError(
|
||||
`Executor returned a non-object table row at index ${i}.`,
|
||||
'rows'
|
||||
);
|
||||
}
|
||||
const cleanRow: Record<string, TableCell> = {};
|
||||
for (const col of columns) {
|
||||
if (!Object.prototype.hasOwnProperty.call(raw, col)) {
|
||||
throw new MarketDataStoreValidationError(
|
||||
`Missing expected column "${col}" in result row ${i}.`,
|
||||
col
|
||||
);
|
||||
}
|
||||
const cell = raw[col];
|
||||
if (!isValidTableCell(cell)) {
|
||||
throw new MarketDataStoreValidationError(
|
||||
`Invalid scalar cell value for column "${col}" in result row ${i}: ${String(cell)}.`,
|
||||
col
|
||||
);
|
||||
}
|
||||
cleanRow[col] = cell;
|
||||
}
|
||||
mappedRows[i] = cleanRow;
|
||||
}
|
||||
return {
|
||||
columns: [...columns],
|
||||
rows: mappedRows,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a `MarketDataStore` backed by an injected {@link DuckDbExecutor}
|
||||
* over curated daily Parquet files.
|
||||
*
|
||||
* The three `resolveDuckDbConnectionBudget(env).statements` are executed
|
||||
* sequentially, at most once, strictly after the first query plans cleanly and
|
||||
* strictly before the first `executor.query(...)` call.
|
||||
*/
|
||||
export function createDuckDbMarketDataStore(options: DuckDbMarketDataStoreOptions): MarketDataStore {
|
||||
if (!isPlainRecord(options)) {
|
||||
throw new MarketDataStoreValidationError(
|
||||
'Expected a DuckDbMarketDataStoreOptions object.',
|
||||
'options'
|
||||
);
|
||||
}
|
||||
|
||||
const executor: unknown = options.executor;
|
||||
if (
|
||||
!isPlainRecord(executor) ||
|
||||
typeof executor.run !== 'function' ||
|
||||
typeof executor.query !== 'function'
|
||||
) {
|
||||
throw new MarketDataStoreValidationError(
|
||||
'Expected `executor` with `run(sql)` and `query(sql, params)` methods.',
|
||||
'executor'
|
||||
);
|
||||
}
|
||||
const typedExecutor = executor as unknown as DuckDbExecutor;
|
||||
|
||||
const curatedRoot = validateCuratedRoot(options.curatedRoot);
|
||||
|
||||
const vaultCutoffTs = options.vaultCutoffTs;
|
||||
if (
|
||||
typeof vaultCutoffTs !== 'number' ||
|
||||
!Number.isSafeInteger(vaultCutoffTs) ||
|
||||
Math.abs(vaultCutoffTs) > MAX_ECMASCRIPT_EPOCH_MS ||
|
||||
vaultCutoffTs <= -MAX_ECMASCRIPT_EPOCH_MS
|
||||
) {
|
||||
throw new MarketDataStoreValidationError(
|
||||
`Invalid epoch millisecond timestamp for "vaultCutoffTs": ${String(vaultCutoffTs)}.`,
|
||||
'vaultCutoffTs'
|
||||
);
|
||||
}
|
||||
|
||||
const barBatchSize = options.barBatchSize;
|
||||
if (
|
||||
barBatchSize !== undefined &&
|
||||
(typeof barBatchSize !== 'number' || !Number.isSafeInteger(barBatchSize) || barBatchSize < 1)
|
||||
) {
|
||||
throw new MarketDataStoreValidationError(
|
||||
`Invalid barBatchSize "${String(barBatchSize)}". Expected a positive safe integer.`,
|
||||
'barBatchSize'
|
||||
);
|
||||
}
|
||||
|
||||
const budget = resolveDuckDbConnectionBudget(options.env);
|
||||
const planCtx: DuckDbPlanContext = {
|
||||
curatedRoot,
|
||||
vaultCutoffTs: vaultCutoffTs === 0 ? 0 : vaultCutoffTs,
|
||||
vaultOperatorAuthorized: options.vaultOperatorAuthorized,
|
||||
};
|
||||
|
||||
let budgetInitialized = false;
|
||||
let budgetInitPromise: Promise<void> | null = null;
|
||||
|
||||
function ensureBudgetInitialized(): Promise<void> {
|
||||
if (budgetInitialized) {
|
||||
return Promise.resolve();
|
||||
}
|
||||
if (budgetInitPromise === null) {
|
||||
budgetInitPromise = (async () => {
|
||||
for (const statement of budget.statements) {
|
||||
await typedExecutor.run(statement);
|
||||
}
|
||||
budgetInitialized = true;
|
||||
})().catch((err: unknown) => {
|
||||
budgetInitPromise = null;
|
||||
throw err;
|
||||
});
|
||||
}
|
||||
return budgetInitPromise;
|
||||
}
|
||||
|
||||
return {
|
||||
async *bars(q: BarsQuery): AsyncIterable<BarBatch> {
|
||||
const planned = planBars1dQuery(q, planCtx);
|
||||
await ensureBudgetInitialized();
|
||||
const rawRows = await typedExecutor.query(planned.sql, planned.params);
|
||||
const mapped = mapBarRows(rawRows);
|
||||
if (mapped.length === 0) {
|
||||
return;
|
||||
}
|
||||
if (barBatchSize === undefined || mapped.length <= barBatchSize) {
|
||||
yield { rows: mapped };
|
||||
return;
|
||||
}
|
||||
for (let offset = 0; offset < mapped.length; offset += barBatchSize) {
|
||||
yield { rows: mapped.slice(offset, offset + barBatchSize) };
|
||||
}
|
||||
},
|
||||
|
||||
async events(q: EventsQuery): Promise<Table> {
|
||||
const planned = planEventsQuery(q, planCtx);
|
||||
await ensureBudgetInitialized();
|
||||
const rawRows = await typedExecutor.query(planned.sql, planned.params);
|
||||
return mapTableRows(EVENTS_COLUMNS, rawRows);
|
||||
},
|
||||
|
||||
async shortsAsOf(q: ShortsAsOfQuery): Promise<Table> {
|
||||
const planned = planShortsAsOfQuery(q, planCtx);
|
||||
await ensureBudgetInitialized();
|
||||
const rawRows = await typedExecutor.query(planned.sql, planned.params);
|
||||
return mapTableRows(SHORTS_COLUMNS, rawRows);
|
||||
},
|
||||
|
||||
async fx(q: FxQuery): Promise<Table> {
|
||||
const planned = planFx1dQuery(q, planCtx);
|
||||
await ensureBudgetInitialized();
|
||||
const rawRows = await typedExecutor.query(planned.sql, planned.params);
|
||||
return mapTableRows(FX_1D_COLUMNS, rawRows);
|
||||
},
|
||||
|
||||
crossSection(): Promise<Table> {
|
||||
return Promise.reject(new MarketDataStoreNotImplementedError('crossSection'));
|
||||
},
|
||||
|
||||
fundamentalsAsOf(): Promise<Table> {
|
||||
return Promise.reject(new MarketDataStoreNotImplementedError('fundamentalsAsOf'));
|
||||
},
|
||||
|
||||
macroAsOf(): Promise<Table> {
|
||||
return Promise.reject(new MarketDataStoreNotImplementedError('macroAsOf'));
|
||||
},
|
||||
|
||||
universe(): Promise<number[]> {
|
||||
return Promise.reject(new MarketDataStoreNotImplementedError('universe'));
|
||||
},
|
||||
};
|
||||
}
|
||||
1346
libs/research/test/market-data-store-duckdb.test.ts
Normal file
1346
libs/research/test/market-data-store-duckdb.test.ts
Normal file
File diff suppressed because it is too large
Load diff
Loading…
Add table
Add a link
Reference in a new issue