T-145: M2.2d — fundamentalsAsOf in the DuckDB MarketDataStore: Vault-fenced point-in-time read of fundamentals_pit/year=*/part.parquet with a real-DuckDB restatement fixture test (no new deps)
This commit is contained in:
parent
1a318f0773
commit
dd8dc692af
4 changed files with 1096 additions and 13 deletions
|
|
@ -14,6 +14,7 @@
|
|||
* - `<curatedRoot>/events/year=*\/part.parquet` (`hive_partitioning = true`)
|
||||
* - `<curatedRoot>/shorts/part.parquet`
|
||||
* - `<curatedRoot>/fx_1d/part.parquet`
|
||||
* - `<curatedRoot>/fundamentals_pit/year=*\/part.parquet` (`hive_partitioning = true`)
|
||||
*
|
||||
* `bars` (`timeframe: '1d'`) adjustment formulas (`tools/curate-etl/README.md`):
|
||||
* - `bars_1d` stores raw OHLC, optional `vwap`, and split-unadjusted raw share
|
||||
|
|
@ -74,6 +75,7 @@ import {
|
|||
type Table,
|
||||
type TableCell,
|
||||
type TableRow,
|
||||
VaultHoldoutFenceError,
|
||||
applyVaultFence,
|
||||
resolveDuckDbConnectionBudget,
|
||||
} from './market-data-store';
|
||||
|
|
@ -155,7 +157,29 @@ export const FX_1D_COLUMNS = [
|
|||
'known_at',
|
||||
] as const;
|
||||
|
||||
type ColumnScalarKind = 'int32' | 'safe_int' | 'number' | 'string';
|
||||
export const FUNDAMENTALS_PIT_VALUE_FIELDS = [
|
||||
'revenue',
|
||||
'net_income',
|
||||
'operating_cash_flow',
|
||||
'total_assets',
|
||||
'total_equity',
|
||||
'shares_outstanding',
|
||||
'ttm_revenue',
|
||||
'ttm_net_income',
|
||||
'ttm_operating_cash_flow',
|
||||
] as const;
|
||||
export type FundamentalsPitValueField = (typeof FUNDAMENTALS_PIT_VALUE_FIELDS)[number];
|
||||
|
||||
const FUNDAMENTALS_PIT_VALUE_FIELD_MAP: ReadonlyMap<string, FundamentalsPitValueField> = new Map(
|
||||
FUNDAMENTALS_PIT_VALUE_FIELDS.map(field => [field, field])
|
||||
);
|
||||
const FUNDAMENTALS_TTM_VALUE_FIELD_SET: ReadonlySet<FundamentalsPitValueField> = new Set([
|
||||
'ttm_revenue',
|
||||
'ttm_net_income',
|
||||
'ttm_operating_cash_flow',
|
||||
]);
|
||||
|
||||
type ColumnScalarKind = 'int32' | 'safe_int' | 'number' | 'string' | 'boolean';
|
||||
|
||||
interface TableColumnSpec {
|
||||
readonly name: string;
|
||||
|
|
@ -195,6 +219,23 @@ const FX_1D_SCHEMA: readonly TableColumnSpec[] = [
|
|||
{ name: 'known_at', kind: 'safe_int', nullable: false },
|
||||
];
|
||||
|
||||
const FUNDAMENTALS_BASE_SCHEMA: readonly TableColumnSpec[] = [
|
||||
{ name: 'listing_id', kind: 'int32', nullable: false },
|
||||
{ name: 'effective_known_at', kind: 'safe_int', nullable: false },
|
||||
{ name: 'known_at_source', kind: 'string', nullable: false },
|
||||
{ name: 'has_estimated_lag', kind: 'boolean', nullable: false },
|
||||
{ name: 'period_end', kind: 'string', nullable: false },
|
||||
{ name: 'fiscal_period', kind: 'string', nullable: false },
|
||||
{ name: 'currency', kind: 'string', nullable: false },
|
||||
{ name: 'period_known_at', kind: 'safe_int', nullable: false },
|
||||
];
|
||||
|
||||
const FUNDAMENTALS_TTM_META_SCHEMA: readonly TableColumnSpec[] = [
|
||||
{ name: 'ttm_period_end', kind: 'string', nullable: true },
|
||||
{ name: 'ttm_currency', kind: 'string', nullable: true },
|
||||
{ name: 'ttm_has_estimated_lag', kind: 'boolean', nullable: true },
|
||||
];
|
||||
|
||||
/** Scalar parameter value bound separately from SQL text. */
|
||||
export type DuckDbParam = string | number | boolean | null;
|
||||
|
||||
|
|
@ -357,6 +398,7 @@ 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];
|
||||
export type FundamentalsAsOfQuery = Parameters<MarketDataStore['fundamentalsAsOf']>[0];
|
||||
|
||||
/**
|
||||
* Thrown when a `MarketDataStore` method or timeframe is outside the curated
|
||||
|
|
@ -577,6 +619,50 @@ function validateEventKinds(raw: readonly EventKind[], field = 'kinds'): EventKi
|
|||
return normalized;
|
||||
}
|
||||
|
||||
function validateFundamentalsFields(
|
||||
raw: readonly string[],
|
||||
field = 'fields'
|
||||
): FundamentalsPitValueField[] {
|
||||
if (!Array.isArray(raw) || raw.length === 0) {
|
||||
throw new MarketDataStoreValidationError(
|
||||
`Expected a non-empty array of fundamentals value fields for "${field}".`,
|
||||
field
|
||||
);
|
||||
}
|
||||
|
||||
const seen = new Set<FundamentalsPitValueField>();
|
||||
const normalized: FundamentalsPitValueField[] = [];
|
||||
for (let i = 0; i < raw.length; i += 1) {
|
||||
const name: unknown = raw[i];
|
||||
const canonical =
|
||||
typeof name === 'string' ? FUNDAMENTALS_PIT_VALUE_FIELD_MAP.get(name) : undefined;
|
||||
if (canonical === undefined) {
|
||||
throw new MarketDataStoreValidationError(
|
||||
`Unknown fundamentals field "${String(name)}". Expected one of: ${FUNDAMENTALS_PIT_VALUE_FIELDS.join(', ')}.`,
|
||||
field
|
||||
);
|
||||
}
|
||||
if (!seen.has(canonical)) {
|
||||
seen.add(canonical);
|
||||
normalized.push(canonical);
|
||||
}
|
||||
}
|
||||
return normalized;
|
||||
}
|
||||
|
||||
function validateAllowEstimatedLag(raw: unknown): boolean {
|
||||
if (raw === undefined) {
|
||||
return true;
|
||||
}
|
||||
if (typeof raw !== 'boolean') {
|
||||
throw new MarketDataStoreValidationError(
|
||||
`Invalid allowEstimatedLag "${String(raw)}". Expected a boolean.`,
|
||||
'allowEstimatedLag'
|
||||
);
|
||||
}
|
||||
return raw;
|
||||
}
|
||||
|
||||
function validateAdjustment(raw: unknown): (typeof BARS_ADJUSTMENTS)[number] {
|
||||
if (typeof raw !== 'string' || !BARS_ADJUSTMENT_SET.has(raw)) {
|
||||
throw new MarketDataStoreValidationError(
|
||||
|
|
@ -1575,6 +1661,158 @@ export function planUniverseQuery(q: UniverseQuery, ctx: DuckDbPlanContext): Pla
|
|||
};
|
||||
}
|
||||
|
||||
interface PlannedFundamentalsAsOfInternal {
|
||||
readonly planned: PlannedDuckDbQuery;
|
||||
readonly columns: readonly string[];
|
||||
readonly schema: readonly TableColumnSpec[];
|
||||
}
|
||||
|
||||
function planFundamentalsAsOfInternal(
|
||||
q: FundamentalsAsOfQuery,
|
||||
ctx: DuckDbPlanContext
|
||||
): PlannedFundamentalsAsOfInternal {
|
||||
const curatedRoot = validateContext(ctx);
|
||||
if (!isPlainRecord(q)) {
|
||||
throw new MarketDataStoreValidationError(
|
||||
'Expected a fundamentalsAsOf query object.',
|
||||
'query'
|
||||
);
|
||||
}
|
||||
|
||||
const listingIds = validateListingIds(q.listingIds);
|
||||
const fields = validateFundamentalsFields(q.fields);
|
||||
const allowEstimatedLag = validateAllowEstimatedLag(q.allowEstimatedLag);
|
||||
|
||||
let fenced: FencedTimeRange;
|
||||
try {
|
||||
fenced = applyVaultFence(
|
||||
{
|
||||
from: q.asOf,
|
||||
to: q.asOf,
|
||||
asOf: q.asOf,
|
||||
scope: 'vault_fenced',
|
||||
},
|
||||
{
|
||||
vaultCutoffTs: ctx.vaultCutoffTs,
|
||||
}
|
||||
);
|
||||
} catch (err: unknown) {
|
||||
if (err instanceof VaultHoldoutFenceError) {
|
||||
const maxAllowedMs = ctx.vaultCutoffTs - 1;
|
||||
fenced = {
|
||||
fromMs: maxAllowedMs,
|
||||
toMs: maxAllowedMs,
|
||||
asOfMs: maxAllowedMs,
|
||||
scope: 'vault_fenced',
|
||||
clampedTo: true,
|
||||
clampedAsOf: true,
|
||||
};
|
||||
} else if (
|
||||
err instanceof MarketDataStoreValidationError &&
|
||||
(err.field === 'from' || err.field === 'to')
|
||||
) {
|
||||
throw new MarketDataStoreValidationError(err.message, 'asOf');
|
||||
} else {
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
|
||||
const asOfSubMs = resolveAsOfSubMsMicros(q.asOf, q.asOf, fenced);
|
||||
const asOfIso = formatUtcIsoWithMicros(fenced.asOfMs, asOfSubMs);
|
||||
const fundamentalsPath = joinCuratedPath(curatedRoot, 'fundamentals_pit/year=*/part.parquet');
|
||||
const listingPlaceholders = buildPlaceholders(listingIds.length);
|
||||
|
||||
let hasTtmField = false;
|
||||
for (const field of fields) {
|
||||
if (FUNDAMENTALS_TTM_VALUE_FIELD_SET.has(field)) {
|
||||
hasTtmField = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
const innerCols: string[] = [
|
||||
'f.listing_id',
|
||||
'f.effective_known_at',
|
||||
'f.known_at_source',
|
||||
'f.has_estimated_lag',
|
||||
'f.period_end',
|
||||
'f.fiscal_period',
|
||||
'f.currency',
|
||||
'f.period_known_at',
|
||||
];
|
||||
const outerCols: string[] = [
|
||||
's.listing_id',
|
||||
'epoch_ms(s.effective_known_at) AS effective_known_at',
|
||||
's.known_at_source',
|
||||
's.has_estimated_lag',
|
||||
'CAST(s.period_end AS VARCHAR) AS period_end',
|
||||
's.fiscal_period',
|
||||
's.currency',
|
||||
'epoch_ms(s.period_known_at) AS period_known_at',
|
||||
];
|
||||
const schema: TableColumnSpec[] = [...FUNDAMENTALS_BASE_SCHEMA];
|
||||
|
||||
for (const field of fields) {
|
||||
innerCols.push(`f.${field}`);
|
||||
if (FUNDAMENTALS_TTM_VALUE_FIELD_SET.has(field)) {
|
||||
outerCols.push(
|
||||
`CASE WHEN opts.allow_estimated_lag OR NOT COALESCE(s.ttm_has_estimated_lag, FALSE) THEN s.${field} ELSE NULL END AS ${field}`
|
||||
);
|
||||
} else {
|
||||
outerCols.push(`s.${field}`);
|
||||
}
|
||||
schema.push({ name: field, kind: 'number', nullable: true });
|
||||
}
|
||||
|
||||
if (hasTtmField) {
|
||||
innerCols.push('f.ttm_period_end', 'f.ttm_currency', 'f.ttm_has_estimated_lag');
|
||||
outerCols.push(
|
||||
'CASE WHEN opts.allow_estimated_lag OR NOT COALESCE(s.ttm_has_estimated_lag, FALSE) THEN CAST(s.ttm_period_end AS VARCHAR) ELSE NULL END AS ttm_period_end',
|
||||
'CASE WHEN opts.allow_estimated_lag OR NOT COALESCE(s.ttm_has_estimated_lag, FALSE) THEN s.ttm_currency ELSE NULL END AS ttm_currency',
|
||||
's.ttm_has_estimated_lag'
|
||||
);
|
||||
schema.push(...FUNDAMENTALS_TTM_META_SCHEMA);
|
||||
}
|
||||
|
||||
const columns = schema.map(spec => spec.name);
|
||||
const sql =
|
||||
`WITH latest AS (SELECT ${innerCols.join(', ')} ` +
|
||||
'FROM read_parquet(?, hive_partitioning = true) AS f ' +
|
||||
`WHERE f.listing_id IN (${listingPlaceholders}) AND f.effective_known_at <= CAST(? AS TIMESTAMPTZ) ` +
|
||||
'QUALIFY ROW_NUMBER() OVER (PARTITION BY f.listing_id ORDER BY f.effective_known_at DESC) = 1) ' +
|
||||
`SELECT ${outerCols.join(', ')} ` +
|
||||
'FROM latest AS s ' +
|
||||
'CROSS JOIN (SELECT CAST(? AS BOOLEAN) AS allow_estimated_lag) AS opts ' +
|
||||
'WHERE (opts.allow_estimated_lag OR NOT s.has_estimated_lag) ' +
|
||||
'ORDER BY s.listing_id ASC';
|
||||
const params: DuckDbParam[] = [fundamentalsPath, ...listingIds, asOfIso, allowEstimatedLag];
|
||||
|
||||
return {
|
||||
planned: { sql, params, fenced },
|
||||
columns,
|
||||
schema,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Plans a Vault-fenced point-in-time DuckDB SQL query over curated
|
||||
* `fundamentals_pit/year=*\/part.parquet` snapshots.
|
||||
*
|
||||
* Selects at most one snapshot per requested `listing_id` — the latest with
|
||||
* `effective_known_at <= asOf` (clamped strictly below `vaultCutoffTs`). When
|
||||
* `allowEstimatedLag` is `false`, listings whose selected snapshot has
|
||||
* `has_estimated_lag = true` are omitted without falling back to an older
|
||||
* snapshot, and requested `ttm_*` value fields plus `ttm_period_end` /
|
||||
* `ttm_currency` are masked to `NULL` when `ttm_has_estimated_lag` is `true`
|
||||
* while preserving `ttm_has_estimated_lag`.
|
||||
*/
|
||||
export function planFundamentalsAsOfQuery(
|
||||
q: FundamentalsAsOfQuery,
|
||||
ctx: DuckDbPlanContext
|
||||
): PlannedDuckDbQuery {
|
||||
return planFundamentalsAsOfInternal(q, ctx).planned;
|
||||
}
|
||||
|
||||
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) {
|
||||
|
|
@ -1712,6 +1950,14 @@ function readValidatedTableCell(
|
|||
);
|
||||
}
|
||||
return val;
|
||||
case 'boolean':
|
||||
if (typeof val !== 'boolean') {
|
||||
throw new MarketDataStoreValidationError(
|
||||
`Expected boolean for column "${spec.name}" in result row ${rowIndex}, got ${typeof val} (${String(val)}).`,
|
||||
spec.name
|
||||
);
|
||||
}
|
||||
return val;
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -2038,8 +2284,11 @@ export function createDuckDbMarketDataStore(options: DuckDbMarketDataStoreOption
|
|||
return Promise.reject(new MarketDataStoreNotImplementedError('crossSection'));
|
||||
},
|
||||
|
||||
fundamentalsAsOf(): Promise<Table> {
|
||||
return Promise.reject(new MarketDataStoreNotImplementedError('fundamentalsAsOf'));
|
||||
async fundamentalsAsOf(q: FundamentalsAsOfQuery): Promise<Table> {
|
||||
const { planned, columns, schema } = planFundamentalsAsOfInternal(q, planCtx);
|
||||
await ensureBudgetInitialized();
|
||||
const rawRows = await typedExecutor.query(planned.sql, planned.params);
|
||||
return mapTableRows(columns, schema, rawRows);
|
||||
},
|
||||
|
||||
macroAsOf(): Promise<Table> {
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue