T-122: M1.3g — @stock-bot/research: Vault-fenced universe planner + adapter method (survivorship-free active listings on a date from curated bars_1d Parquet, US_EQ / CA_EQ / US_CA_EQ) with tests and local benchmark (no new dependencies)
This commit is contained in:
parent
aecafdebe1
commit
91c7411ed9
4 changed files with 675 additions and 23 deletions
|
|
@ -81,6 +81,7 @@ import {
|
|||
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;
|
||||
const MS_PER_DAY = 86_400_000;
|
||||
const DATE_ONLY_RE = /^\d{4}-\d{2}-\d{2}$/;
|
||||
const ISO_FRACTIONAL_RE = /\.(\d+)(?:Z|[+-]\d{2}:\d{2})$/;
|
||||
const STRICT_INT_RE = /^-?\d+$/;
|
||||
|
|
@ -108,6 +109,16 @@ export const FX_PAIR_MAP = {
|
|||
export const BARS_ADJUSTMENTS = ['raw', 'split', 'total'] as const;
|
||||
const BARS_ADJUSTMENT_SET: ReadonlySet<string> = new Set<string>(BARS_ADJUSTMENTS);
|
||||
|
||||
export const UNIVERSE_REFS = ['US_EQ', 'CA_EQ', 'US_CA_EQ'] as const;
|
||||
export type SupportedUniverseRef = (typeof UNIVERSE_REFS)[number];
|
||||
export const DEFAULT_UNIVERSE_LOOKBACK_DAYS = 7;
|
||||
|
||||
const UNIVERSE_CURRENCY_MAP: Readonly<Record<SupportedUniverseRef, readonly string[]>> = {
|
||||
US_EQ: ['USD'],
|
||||
CA_EQ: ['CAD'],
|
||||
US_CA_EQ: ['USD', 'CAD'],
|
||||
};
|
||||
|
||||
export const EVENTS_COLUMNS = [
|
||||
'listing_id',
|
||||
'ts',
|
||||
|
|
@ -263,6 +274,12 @@ export interface DuckDbPlanContext {
|
|||
readonly curatedRoot: string;
|
||||
readonly vaultCutoffTs: number;
|
||||
readonly vaultOperatorAuthorized?: boolean;
|
||||
/**
|
||||
* Optional calendar-day lookback window for {@link planUniverseQuery}
|
||||
* (`[date - universeLookbackDays, date]`). Defaults to
|
||||
* {@link DEFAULT_UNIVERSE_LOOKBACK_DAYS} (`7`).
|
||||
*/
|
||||
readonly universeLookbackDays?: number;
|
||||
/**
|
||||
* Verified `adj_factors` snapshot metadata bound to the `.parquet` file to
|
||||
* be read. Required for `'split'` and `'total'` `bars` queries; rejected if
|
||||
|
|
@ -335,6 +352,7 @@ 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];
|
||||
export type UniverseQuery = Parameters<MarketDataStore['universe']>[0];
|
||||
|
||||
/**
|
||||
* Thrown when a `MarketDataStore` method or timeframe is outside the curated
|
||||
|
|
@ -575,6 +593,29 @@ function validateFxPair(raw: unknown): (typeof FX_PAIR_MAP)[keyof typeof FX_PAIR
|
|||
);
|
||||
}
|
||||
|
||||
function validateUniverseRef(raw: unknown): readonly string[] {
|
||||
if (typeof raw === 'string' && Object.prototype.hasOwnProperty.call(UNIVERSE_CURRENCY_MAP, raw)) {
|
||||
return UNIVERSE_CURRENCY_MAP[raw as SupportedUniverseRef];
|
||||
}
|
||||
throw new MarketDataStoreValidationError(
|
||||
`Unsupported universe ref "${String(raw)}". Expected one of: ${UNIVERSE_REFS.join(', ')}.`,
|
||||
'ref'
|
||||
);
|
||||
}
|
||||
|
||||
function validateUniverseLookbackDays(raw: unknown): number {
|
||||
if (raw === undefined) {
|
||||
return DEFAULT_UNIVERSE_LOOKBACK_DAYS;
|
||||
}
|
||||
if (typeof raw !== 'number' || !Number.isSafeInteger(raw) || raw < 1) {
|
||||
throw new MarketDataStoreValidationError(
|
||||
`Invalid universeLookbackDays "${String(raw)}". Expected a positive safe integer.`,
|
||||
'universeLookbackDays'
|
||||
);
|
||||
}
|
||||
return raw;
|
||||
}
|
||||
|
||||
function validateContext(ctx: DuckDbPlanContext): string {
|
||||
if (!isPlainRecord(ctx)) {
|
||||
throw new MarketDataStoreValidationError('Expected a DuckDbPlanContext object.', 'context');
|
||||
|
|
@ -1419,6 +1460,99 @@ export function planFx1dQuery(q: FxQuery, ctx: DuckDbPlanContext): PlannedDuckDb
|
|||
return { sql, params, fenced };
|
||||
}
|
||||
|
||||
/**
|
||||
* Plans a Vault-fenced, survivorship-free DuckDB SQL query resolving active
|
||||
* listing IDs on `q.date` from curated `bars_1d` Parquet (`US_EQ`, `CA_EQ`,
|
||||
* `US_CA_EQ`).
|
||||
*
|
||||
* A listing is considered active on `q.date` when it has at least one `bars_1d`
|
||||
* row with `session_date` in `[date - lookbackDays, date]` (default `7`
|
||||
* calendar days), bounded by `b.ts <= ?` and `b.known_at <= ?` under
|
||||
* `'vault_fenced'` scope so no post-date or Vault rows can ever be read.
|
||||
*/
|
||||
export function planUniverseQuery(q: UniverseQuery, ctx: DuckDbPlanContext): PlannedDuckDbQuery {
|
||||
const curatedRoot = validateContext(ctx);
|
||||
const lookbackDays = validateUniverseLookbackDays(ctx.universeLookbackDays);
|
||||
if (!isPlainRecord(q)) {
|
||||
throw new MarketDataStoreValidationError('Expected a universe query object.', 'query');
|
||||
}
|
||||
|
||||
const currencies = validateUniverseRef(q.ref);
|
||||
if (typeof q.date !== 'string' || !DATE_ONLY_RE.test(q.date)) {
|
||||
throw new MarketDataStoreValidationError(
|
||||
`Invalid universe date "${String(q.date)}". Expected a UTC calendar date in YYYY-MM-DD format.`,
|
||||
'date'
|
||||
);
|
||||
}
|
||||
|
||||
let fencedDate: FencedTimeRange;
|
||||
try {
|
||||
fencedDate = applyVaultFence(
|
||||
{
|
||||
from: q.date,
|
||||
to: q.date,
|
||||
asOf: q.date,
|
||||
scope: 'vault_fenced',
|
||||
},
|
||||
{
|
||||
vaultCutoffTs: ctx.vaultCutoffTs,
|
||||
}
|
||||
);
|
||||
} catch (err: unknown) {
|
||||
if (
|
||||
err instanceof MarketDataStoreValidationError &&
|
||||
(err.field === 'from' || err.field === 'to' || err.field === 'asOf')
|
||||
) {
|
||||
throw new MarketDataStoreValidationError(err.message, 'date');
|
||||
}
|
||||
throw err;
|
||||
}
|
||||
|
||||
const lookbackMs = lookbackDays * MS_PER_DAY;
|
||||
if (!Number.isSafeInteger(lookbackMs)) {
|
||||
throw new MarketDataStoreValidationError(
|
||||
`Invalid universeLookbackDays "${lookbackDays}". Lookback window overflows safe millisecond range.`,
|
||||
'universeLookbackDays'
|
||||
);
|
||||
}
|
||||
const lookbackStartMs = fencedDate.fromMs - lookbackMs;
|
||||
if (!Number.isSafeInteger(lookbackStartMs) || lookbackStartMs < -MAX_ECMASCRIPT_EPOCH_MS) {
|
||||
throw new MarketDataStoreValidationError(
|
||||
`Invalid universeLookbackDays "${lookbackDays}". Lookback start precedes supported UTC date range.`,
|
||||
'universeLookbackDays'
|
||||
);
|
||||
}
|
||||
|
||||
const lookbackStartDate = formatUtcDate(lookbackStartMs);
|
||||
const endDate = formatUtcDate(fencedDate.toMs);
|
||||
const toIso = formatUtcIsoWithMicros(fencedDate.toMs, resolveToSubMsMicros(q.date, fencedDate));
|
||||
const asOfIso = formatUtcIsoWithMicros(
|
||||
fencedDate.asOfMs,
|
||||
resolveAsOfSubMsMicros(q.date, q.date, fencedDate)
|
||||
);
|
||||
const barsPath = joinCuratedPath(curatedRoot, 'bars_1d/year=*/part.parquet');
|
||||
const currencyPredicate =
|
||||
currencies.length === 1
|
||||
? 'b.currency = ?'
|
||||
: `b.currency IN (${buildPlaceholders(currencies.length)})`;
|
||||
|
||||
const sql =
|
||||
'SELECT DISTINCT b.listing_id ' +
|
||||
`FROM read_parquet('${barsPath}', hive_partitioning = true) AS b ` +
|
||||
`WHERE ${currencyPredicate} AND b.session_date >= ? AND b.session_date <= ? AND b.ts <= ? AND b.known_at <= ? ` +
|
||||
'ORDER BY b.listing_id ASC';
|
||||
const params: DuckDbParam[] = [...currencies, lookbackStartDate, endDate, toIso, asOfIso];
|
||||
|
||||
return {
|
||||
sql,
|
||||
params,
|
||||
fenced: {
|
||||
...fencedDate,
|
||||
fromMs: lookbackStartMs,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
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) {
|
||||
|
|
@ -1594,6 +1728,50 @@ function mapTableRows(
|
|||
};
|
||||
}
|
||||
|
||||
function mapUniverseRows(rows: readonly TableRow[]): number[] {
|
||||
if (!Array.isArray(rows)) {
|
||||
throw new MarketDataStoreValidationError(
|
||||
'Executor returned a non-array universe result.',
|
||||
'rows'
|
||||
);
|
||||
}
|
||||
const out: number[] = new Array(rows.length);
|
||||
let prev: number | undefined;
|
||||
for (let i = 0; i < rows.length; i += 1) {
|
||||
const raw = rows[i];
|
||||
if (!isPlainRecord(raw)) {
|
||||
throw new MarketDataStoreValidationError(
|
||||
`Executor returned a non-object universe row at index ${i}.`,
|
||||
'rows'
|
||||
);
|
||||
}
|
||||
if (!Object.prototype.hasOwnProperty.call(raw, 'listing_id')) {
|
||||
throw new MarketDataStoreValidationError(
|
||||
`Missing expected column "listing_id" in universe result row ${i}.`,
|
||||
'listing_id'
|
||||
);
|
||||
}
|
||||
const id = readRequiredInt32(raw, 'listing_id', i);
|
||||
if (prev !== undefined) {
|
||||
if (id === prev) {
|
||||
throw new MarketDataStoreValidationError(
|
||||
`Duplicate listing_id ${id} in universe result row ${i}.`,
|
||||
'listing_id'
|
||||
);
|
||||
}
|
||||
if (id < prev) {
|
||||
throw new MarketDataStoreValidationError(
|
||||
`Unsorted listing_id ${id} after ${prev} in universe result row ${i}. Expected strictly ascending order.`,
|
||||
'listing_id'
|
||||
);
|
||||
}
|
||||
}
|
||||
prev = id;
|
||||
out[i] = id;
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a `MarketDataStore` backed by an injected {@link DuckDbExecutor}
|
||||
* over curated daily Parquet files.
|
||||
|
|
@ -1697,11 +1875,14 @@ export function createDuckDbMarketDataStore(options: DuckDbMarketDataStoreOption
|
|||
);
|
||||
}
|
||||
|
||||
const universeLookbackDays = validateUniverseLookbackDays(options.universeLookbackDays);
|
||||
|
||||
const budget = resolveDuckDbConnectionBudget(options.env);
|
||||
const planCtx: DuckDbPlanContext = {
|
||||
curatedRoot,
|
||||
vaultCutoffTs: vaultCutoffTs === 0 ? 0 : vaultCutoffTs,
|
||||
vaultOperatorAuthorized: options.vaultOperatorAuthorized,
|
||||
universeLookbackDays,
|
||||
};
|
||||
|
||||
let budgetInitialized = false;
|
||||
|
|
@ -1840,8 +2021,11 @@ export function createDuckDbMarketDataStore(options: DuckDbMarketDataStoreOption
|
|||
return Promise.reject(new MarketDataStoreNotImplementedError('macroAsOf'));
|
||||
},
|
||||
|
||||
universe(): Promise<number[]> {
|
||||
return Promise.reject(new MarketDataStoreNotImplementedError('universe'));
|
||||
async universe(q: UniverseQuery): Promise<number[]> {
|
||||
const planned = planUniverseQuery(q, planCtx);
|
||||
await ensureBudgetInitialized();
|
||||
const rawRows = await typedExecutor.query(planned.sql, planned.params);
|
||||
return mapUniverseRows(rawRows);
|
||||
},
|
||||
};
|
||||
}
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue