T-210: M2.3s — Implement MarketDataStore.macroAsOf, crossSection, QuestDB fx('1m'), and copilot 1m routing
This commit is contained in:
parent
a3a31f7562
commit
0c33d8ae19
23 changed files with 2440 additions and 82 deletions
|
|
@ -61,10 +61,12 @@ export type FeatureKind = (typeof FEATURE_KINDS)[number];
|
|||
export const FEATURE_INPUT_DATASETS = [
|
||||
'bars_1d',
|
||||
'adj_factors',
|
||||
'corporate_actions',
|
||||
'events',
|
||||
'shorts',
|
||||
'fx_1d',
|
||||
'fundamentals_pit',
|
||||
'macro',
|
||||
] as const;
|
||||
export type FeatureInputDataset = (typeof FEATURE_INPUT_DATASETS)[number];
|
||||
|
||||
|
|
@ -553,7 +555,7 @@ type SqlToken =
|
|||
interface DatasetScanSpec {
|
||||
readonly relativePath: string;
|
||||
readonly hivePartitioning: boolean;
|
||||
readonly predicateKind: 'ts_and_known_at' | 'known_at' | 'effective_known_at';
|
||||
readonly predicateKind: 'ts_and_known_at' | 'known_at' | 'effective_known_at' | 'macro_known_at';
|
||||
}
|
||||
|
||||
const DATASET_SCAN_SPECS: Readonly<Record<FeatureInputDataset, DatasetScanSpec>> = {
|
||||
|
|
@ -567,6 +569,11 @@ const DATASET_SCAN_SPECS: Readonly<Record<FeatureInputDataset, DatasetScanSpec>>
|
|||
hivePartitioning: false,
|
||||
predicateKind: 'known_at',
|
||||
},
|
||||
corporate_actions: {
|
||||
relativePath: 'corporate_actions/part.parquet',
|
||||
hivePartitioning: false,
|
||||
predicateKind: 'known_at',
|
||||
},
|
||||
events: {
|
||||
relativePath: 'events/year=*/part.parquet',
|
||||
hivePartitioning: true,
|
||||
|
|
@ -587,6 +594,11 @@ const DATASET_SCAN_SPECS: Readonly<Record<FeatureInputDataset, DatasetScanSpec>>
|
|||
hivePartitioning: true,
|
||||
predicateKind: 'effective_known_at',
|
||||
},
|
||||
macro: {
|
||||
relativePath: 'macro/part.parquet',
|
||||
hivePartitioning: false,
|
||||
predicateKind: 'macro_known_at',
|
||||
},
|
||||
};
|
||||
|
||||
function isPlainRecord(value: unknown): value is Record<string, unknown> {
|
||||
|
|
@ -1959,6 +1971,11 @@ function expandSqlForYear(
|
|||
} else if (spec.predicateKind === 'effective_known_at') {
|
||||
parts.push(`(SELECT * FROM ${readCall} WHERE effective_known_at <= ?)`);
|
||||
scanParams.push(knownAtUpperIso);
|
||||
} else if (spec.predicateKind === 'macro_known_at') {
|
||||
parts.push(
|
||||
`(SELECT * FROM ${readCall} WHERE known_at <= ? AND known_at_source = 'publication_lag_estimate')`
|
||||
);
|
||||
scanParams.push(knownAtUpperIso);
|
||||
} else {
|
||||
parts.push(`(SELECT * FROM ${readCall} WHERE known_at <= ?)`);
|
||||
scanParams.push(knownAtUpperIso);
|
||||
|
|
|
|||
|
|
@ -94,6 +94,8 @@ const STRICT_INT_RE = /^-?\d+$/;
|
|||
const STRICT_UINT_RE = /^\d+$/;
|
||||
const SNAPSHOT_CHECKSUM_RE = /^0x[0-9a-f]{16}$/;
|
||||
const FD_HANDLE_PATH_RE = /^\/(?:proc\/self|dev)\/fd\/[1-9]\d*$/;
|
||||
const CROSS_SECTION_FEATURE_REF_RE = /^([a-z][a-z0-9_]{0,62})@v([1-9]\d*)$/;
|
||||
const MACRO_REQUIRED_KNOWN_AT_SOURCE = 'publication_lag_estimate';
|
||||
|
||||
export const ADJ_SNAPSHOT_FORMAT_VERSION = 1;
|
||||
export const ADJ_SNAPSHOT_KV_PREFIX = 'stock_bot.adj_factors.';
|
||||
|
|
@ -157,6 +159,15 @@ export const FX_1D_COLUMNS = [
|
|||
'known_at',
|
||||
] as const;
|
||||
|
||||
export const MACRO_COLUMNS = [
|
||||
'country_iso',
|
||||
'indicator',
|
||||
'period_date',
|
||||
'known_at',
|
||||
'known_at_source',
|
||||
'value',
|
||||
] as const;
|
||||
|
||||
export const FUNDAMENTALS_PIT_VALUE_FIELDS = [
|
||||
'revenue',
|
||||
'net_income',
|
||||
|
|
@ -219,6 +230,15 @@ const FX_1D_SCHEMA: readonly TableColumnSpec[] = [
|
|||
{ name: 'known_at', kind: 'safe_int', nullable: false },
|
||||
];
|
||||
|
||||
const MACRO_SCHEMA: readonly TableColumnSpec[] = [
|
||||
{ name: 'country_iso', kind: 'string', nullable: false },
|
||||
{ name: 'indicator', kind: 'string', nullable: false },
|
||||
{ name: 'period_date', kind: 'string', nullable: false },
|
||||
{ name: 'known_at', kind: 'safe_int', nullable: false },
|
||||
{ name: 'known_at_source', kind: 'string', nullable: false },
|
||||
{ name: 'value', kind: 'number', nullable: false },
|
||||
];
|
||||
|
||||
const FUNDAMENTALS_BASE_SCHEMA: readonly TableColumnSpec[] = [
|
||||
{ name: 'listing_id', kind: 'int32', nullable: false },
|
||||
{ name: 'effective_known_at', kind: 'safe_int', nullable: false },
|
||||
|
|
@ -399,6 +419,8 @@ 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];
|
||||
export type MacroAsOfQuery = Parameters<MarketDataStore['macroAsOf']>[0];
|
||||
export type CrossSectionQuery = Parameters<MarketDataStore['crossSection']>[0];
|
||||
|
||||
/**
|
||||
* Thrown when a `MarketDataStore` method or timeframe is outside the curated
|
||||
|
|
@ -683,16 +705,89 @@ function validateFxPair(raw: unknown): (typeof FX_PAIR_MAP)[keyof typeof FX_PAIR
|
|||
);
|
||||
}
|
||||
|
||||
function validateUniverseRef(raw: unknown): readonly string[] {
|
||||
function validateUniverseRef(raw: unknown, field = 'ref'): 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'
|
||||
field
|
||||
);
|
||||
}
|
||||
|
||||
function validateNonEmptyStringArray(raw: unknown, field: 'countries' | 'indicators'): string[] {
|
||||
if (!Array.isArray(raw) || raw.length === 0) {
|
||||
throw new MarketDataStoreValidationError(
|
||||
`Expected a non-empty array of non-empty strings for "${field}".`,
|
||||
field
|
||||
);
|
||||
}
|
||||
|
||||
const seen = new Set<string>();
|
||||
const normalized: string[] = [];
|
||||
for (let i = 0; i < raw.length; i += 1) {
|
||||
const item: unknown = raw[i];
|
||||
if (typeof item !== 'string' || item.trim().length === 0) {
|
||||
throw new MarketDataStoreValidationError(
|
||||
`Invalid non-empty string at ${field}[${i}]: ${String(item)}.`,
|
||||
field
|
||||
);
|
||||
}
|
||||
if (!seen.has(item)) {
|
||||
seen.add(item);
|
||||
normalized.push(item);
|
||||
}
|
||||
}
|
||||
return normalized;
|
||||
}
|
||||
|
||||
interface ParsedCrossSectionFeatureRef {
|
||||
readonly ref: string;
|
||||
readonly name: string;
|
||||
readonly version: number;
|
||||
}
|
||||
|
||||
function validateCrossSectionFeatures(raw: unknown): ParsedCrossSectionFeatureRef[] {
|
||||
if (!Array.isArray(raw) || raw.length === 0) {
|
||||
throw new MarketDataStoreValidationError(
|
||||
'Expected a non-empty array of versioned feature refs ("<name>@v<version>") for "features".',
|
||||
'features'
|
||||
);
|
||||
}
|
||||
|
||||
const seen = new Set<string>();
|
||||
const parsed: ParsedCrossSectionFeatureRef[] = [];
|
||||
for (let i = 0; i < raw.length; i += 1) {
|
||||
const item: unknown = raw[i];
|
||||
if (typeof item !== 'string') {
|
||||
throw new MarketDataStoreValidationError(
|
||||
`Invalid feature ref at features[${i}]: ${String(item)}. Expected "<name>@v<version>".`,
|
||||
'features'
|
||||
);
|
||||
}
|
||||
const match = CROSS_SECTION_FEATURE_REF_RE.exec(item);
|
||||
if (match === null) {
|
||||
throw new MarketDataStoreValidationError(
|
||||
`Invalid feature ref "${item}" at features[${i}]. Expected "<name>@v<version>" with lowercase name and canonical positive integer version.`,
|
||||
'features'
|
||||
);
|
||||
}
|
||||
const name = match[1] as string;
|
||||
const version = Number(match[2]);
|
||||
if (!Number.isSafeInteger(version) || version < 1) {
|
||||
throw new MarketDataStoreValidationError(
|
||||
`Invalid feature version in ref "${item}" at features[${i}]. Expected a positive safe integer.`,
|
||||
'features'
|
||||
);
|
||||
}
|
||||
if (!seen.has(item)) {
|
||||
seen.add(item);
|
||||
parsed.push({ ref: item, name, version });
|
||||
}
|
||||
}
|
||||
return parsed;
|
||||
}
|
||||
|
||||
function validateUniverseLookbackDays(raw: unknown, vaultCutoffTs?: number): number {
|
||||
const days = raw === undefined ? DEFAULT_UNIVERSE_LOOKBACK_DAYS : raw;
|
||||
if (typeof days !== 'number' || !Number.isSafeInteger(days) || days < 1) {
|
||||
|
|
@ -1813,6 +1908,172 @@ export function planFundamentalsAsOfQuery(
|
|||
return planFundamentalsAsOfInternal(q, ctx).planned;
|
||||
}
|
||||
|
||||
/**
|
||||
* Plans a Vault-fenced DuckDB SQL query for point-in-time curated macro series
|
||||
* (`macro/part.parquet`).
|
||||
*/
|
||||
export function planMacroAsOfQuery(q: MacroAsOfQuery, ctx: DuckDbPlanContext): PlannedDuckDbQuery {
|
||||
const curatedRoot = validateContext(ctx);
|
||||
if (!isPlainRecord(q)) {
|
||||
throw new MarketDataStoreValidationError('Expected a macroAsOf query object.', 'query');
|
||||
}
|
||||
|
||||
const countries = validateNonEmptyStringArray(q.countries, 'countries');
|
||||
const indicators = validateNonEmptyStringArray(q.indicators, 'indicators');
|
||||
const fenced = applyVaultFence(
|
||||
{
|
||||
from: q.from,
|
||||
to: q.to,
|
||||
asOf: q.asOf,
|
||||
scope: 'vault_fenced',
|
||||
},
|
||||
{
|
||||
vaultCutoffTs: ctx.vaultCutoffTs,
|
||||
}
|
||||
);
|
||||
|
||||
const asOfSubMs = resolveAsOfSubMsMicros(q.asOf, q.to, fenced);
|
||||
const fromDate = formatUtcDate(fenced.fromMs);
|
||||
const toDate = formatUtcDate(fenced.toMs);
|
||||
const asOfIso = formatUtcIsoWithMicros(fenced.asOfMs, asOfSubMs);
|
||||
const macroPath = joinCuratedPath(curatedRoot, 'macro/part.parquet');
|
||||
const countryPlaceholders = buildPlaceholders(countries.length);
|
||||
const indicatorPlaceholders = buildPlaceholders(indicators.length);
|
||||
|
||||
const sql =
|
||||
'SELECT m.country_iso, m.indicator, CAST(m.period_date AS VARCHAR) AS period_date, epoch_ms(m.known_at) AS known_at, m.known_at_source, m.value ' +
|
||||
`FROM read_parquet('${macroPath}') AS m ` +
|
||||
`WHERE m.country_iso IN (${countryPlaceholders}) AND m.indicator IN (${indicatorPlaceholders}) AND m.period_date >= ? AND m.period_date <= ? AND m.known_at <= ? ` +
|
||||
'ORDER BY m.country_iso ASC, m.indicator ASC, m.period_date ASC';
|
||||
const params: DuckDbParam[] = [...countries, ...indicators, fromDate, toDate, asOfIso];
|
||||
return { sql, params, fenced };
|
||||
}
|
||||
|
||||
interface PlannedCrossSectionInternal {
|
||||
readonly planned: PlannedDuckDbQuery;
|
||||
readonly columns: readonly string[];
|
||||
readonly schema: readonly TableColumnSpec[];
|
||||
}
|
||||
|
||||
function planCrossSectionInternal(
|
||||
q: CrossSectionQuery,
|
||||
ctx: DuckDbPlanContext
|
||||
): PlannedCrossSectionInternal {
|
||||
const curatedRoot = validateContext(ctx);
|
||||
const lookbackDays = validateUniverseLookbackDays(ctx.universeLookbackDays);
|
||||
if (!isPlainRecord(q)) {
|
||||
throw new MarketDataStoreValidationError('Expected a crossSection query object.', 'query');
|
||||
}
|
||||
|
||||
const features = validateCrossSectionFeatures(q.features);
|
||||
const currencies = validateUniverseRef(q.universe, 'universe');
|
||||
if (typeof q.date !== 'string' || !DATE_ONLY_RE.test(q.date)) {
|
||||
throw new MarketDataStoreValidationError(
|
||||
`Invalid crossSection date "${String(q.date)}". Expected a UTC calendar date in YYYY-MM-DD format.`,
|
||||
'date'
|
||||
);
|
||||
}
|
||||
|
||||
const rawAsOf = q.asOf ?? q.date;
|
||||
let fenced: FencedTimeRange;
|
||||
try {
|
||||
fenced = applyVaultFence(
|
||||
{
|
||||
from: q.date,
|
||||
to: q.date,
|
||||
asOf: rawAsOf,
|
||||
scope: 'vault_fenced',
|
||||
},
|
||||
{
|
||||
vaultCutoffTs: ctx.vaultCutoffTs,
|
||||
}
|
||||
);
|
||||
} catch (err: unknown) {
|
||||
if (
|
||||
err instanceof MarketDataStoreValidationError &&
|
||||
(err.field === 'from' || err.field === 'to' || (err.field === 'asOf' && q.asOf === undefined))
|
||||
) {
|
||||
throw new MarketDataStoreValidationError(err.message, 'date');
|
||||
}
|
||||
throw err;
|
||||
}
|
||||
|
||||
const lookbackStartMs = fenced.fromMs - lookbackDays * MS_PER_DAY;
|
||||
if (!Number.isSafeInteger(lookbackStartMs) || lookbackStartMs < MIN_ISO_DATE_EPOCH_MS) {
|
||||
throw new MarketDataStoreValidationError(
|
||||
`Invalid universeLookbackDays "${lookbackDays}". Lookback start precedes supported YYYY-MM-DD UTC date range.`,
|
||||
'universeLookbackDays'
|
||||
);
|
||||
}
|
||||
|
||||
const lookbackStartDate = formatUtcDate(lookbackStartMs);
|
||||
const endDate = formatUtcDate(fenced.toMs);
|
||||
const fromIso = formatUtcIsoWithMicros(fenced.fromMs, 0);
|
||||
const toIso = formatUtcIsoWithMicros(fenced.toMs, resolveToSubMsMicros(q.date, fenced));
|
||||
const asOfIso = formatUtcIsoWithMicros(
|
||||
fenced.asOfMs,
|
||||
resolveAsOfSubMsMicros(rawAsOf, q.date, fenced)
|
||||
);
|
||||
const featureYear = new Date(fenced.fromMs).getUTCFullYear();
|
||||
|
||||
const barsPath = joinCuratedPath(curatedRoot, 'bars_1d/year=*/part.parquet');
|
||||
const currencyPredicate =
|
||||
currencies.length === 1
|
||||
? 'b.currency = ?'
|
||||
: `b.currency IN (${buildPlaceholders(currencies.length)})`;
|
||||
|
||||
const ctes: string[] = [
|
||||
`u AS (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 <= ?)`,
|
||||
];
|
||||
const params: DuckDbParam[] = [...currencies, lookbackStartDate, endDate, toIso, asOfIso];
|
||||
|
||||
const selectCols: string[] = ['u.listing_id'];
|
||||
const joins: string[] = [];
|
||||
const columns: string[] = ['listing_id'];
|
||||
const schema: TableColumnSpec[] = [{ name: 'listing_id', kind: 'int32', nullable: false }];
|
||||
|
||||
for (let i = 0; i < features.length; i += 1) {
|
||||
const feat = features[i] as ParsedCrossSectionFeatureRef;
|
||||
const alias = `f_${i}`;
|
||||
const featurePath = joinCuratedPath(
|
||||
curatedRoot,
|
||||
`features/${feat.name}/v${feat.version}/year=*/part.parquet`
|
||||
);
|
||||
ctes.push(
|
||||
`${alias} AS (SELECT f.listing_id, f.value FROM read_parquet('${featurePath}', hive_partitioning = true) AS f WHERE CAST(f.year AS BIGINT) = ? AND f.ts >= ? AND f.ts <= ? AND f.known_at <= ? QUALIFY ROW_NUMBER() OVER (PARTITION BY f.listing_id ORDER BY f.ts DESC, f.known_at DESC) = 1)`
|
||||
);
|
||||
params.push(featureYear, fromIso, toIso, asOfIso);
|
||||
selectCols.push(`${alias}.value AS "${feat.ref}"`);
|
||||
joins.push(`LEFT JOIN ${alias} ON u.listing_id = ${alias}.listing_id`);
|
||||
columns.push(feat.ref);
|
||||
schema.push({ name: feat.ref, kind: 'number', nullable: true });
|
||||
}
|
||||
|
||||
const sql =
|
||||
`WITH ${ctes.join(', ')} ` +
|
||||
`SELECT ${selectCols.join(', ')} ` +
|
||||
`FROM u ${joins.join(' ')} ` +
|
||||
'ORDER BY u.listing_id ASC';
|
||||
|
||||
return {
|
||||
planned: { sql, params, fenced },
|
||||
columns,
|
||||
schema,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Plans a Vault-fenced DuckDB SQL query joining versioned curated feature
|
||||
* Parquet datasets (`features/<name>/v<version>/year=*\/part.parquet`) onto the
|
||||
* survivorship-free active universe on `q.date`.
|
||||
*/
|
||||
export function planCrossSectionQuery(
|
||||
q: CrossSectionQuery,
|
||||
ctx: DuckDbPlanContext
|
||||
): PlannedDuckDbQuery {
|
||||
return planCrossSectionInternal(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) {
|
||||
|
|
@ -1996,6 +2257,66 @@ function mapTableRows(
|
|||
};
|
||||
}
|
||||
|
||||
function parseStrictPeriodDateMs(periodDate: string, rowIndex: number): number {
|
||||
if (!DATE_ONLY_RE.test(periodDate)) {
|
||||
throw new MarketDataStoreValidationError(
|
||||
`Invalid macro period_date "${periodDate}" in result row ${rowIndex}. Expected YYYY-MM-DD.`,
|
||||
'period_date'
|
||||
);
|
||||
}
|
||||
try {
|
||||
return applyVaultFence(
|
||||
{ from: periodDate, to: periodDate, scope: 'vault_evaluation_only' },
|
||||
{ vaultCutoffTs: 0, vaultOperatorAuthorized: true }
|
||||
).fromMs;
|
||||
} catch {
|
||||
throw new MarketDataStoreValidationError(
|
||||
`Invalid macro period_date "${periodDate}" in result row ${rowIndex}.`,
|
||||
'period_date'
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
function mapMacroRows(
|
||||
rows: readonly TableRow[],
|
||||
vaultCutoffTs: number,
|
||||
asOfMs: number
|
||||
): Table {
|
||||
const table = mapTableRows(MACRO_COLUMNS, MACRO_SCHEMA, rows);
|
||||
for (let i = 0; i < table.rows.length; i += 1) {
|
||||
const row = table.rows[i] as TableRow;
|
||||
const knownAtSource = row.known_at_source as string;
|
||||
if (knownAtSource !== MACRO_REQUIRED_KNOWN_AT_SOURCE) {
|
||||
throw new MarketDataStoreValidationError(
|
||||
`Invalid macro provenance known_at_source "${knownAtSource}" in result row ${i}. Expected "${MACRO_REQUIRED_KNOWN_AT_SOURCE}".`,
|
||||
'known_at_source'
|
||||
);
|
||||
}
|
||||
const periodDate = row.period_date as string;
|
||||
const periodDateMs = parseStrictPeriodDateMs(periodDate, i);
|
||||
const knownAt = row.known_at as number;
|
||||
if (knownAt < periodDateMs + MS_PER_DAY) {
|
||||
throw new MarketDataStoreValidationError(
|
||||
`Unlagged macro row ${i}: known_at (${knownAt}) precedes period_date + 1d (${periodDateMs + MS_PER_DAY}).`,
|
||||
'known_at'
|
||||
);
|
||||
}
|
||||
if (knownAt >= vaultCutoffTs) {
|
||||
throw new MarketDataStoreValidationError(
|
||||
`Macro row ${i} known_at (${knownAt}) reaches or exceeds Vault cutoff (${vaultCutoffTs}).`,
|
||||
'known_at'
|
||||
);
|
||||
}
|
||||
if (knownAt > asOfMs) {
|
||||
throw new MarketDataStoreValidationError(
|
||||
`Macro row ${i} known_at (${knownAt}) exceeds fenced asOf (${asOfMs}).`,
|
||||
'known_at'
|
||||
);
|
||||
}
|
||||
}
|
||||
return table;
|
||||
}
|
||||
|
||||
function mapUniverseRows(rows: readonly TableRow[]): number[] {
|
||||
if (!Array.isArray(rows)) {
|
||||
throw new MarketDataStoreValidationError(
|
||||
|
|
@ -2280,8 +2601,11 @@ export function createDuckDbMarketDataStore(options: DuckDbMarketDataStoreOption
|
|||
return mapTableRows(FX_1D_COLUMNS, FX_1D_SCHEMA, rawRows);
|
||||
},
|
||||
|
||||
crossSection(): Promise<Table> {
|
||||
return Promise.reject(new MarketDataStoreNotImplementedError('crossSection'));
|
||||
async crossSection(q: CrossSectionQuery): Promise<Table> {
|
||||
const { planned, columns, schema } = planCrossSectionInternal(q, planCtx);
|
||||
await ensureBudgetInitialized();
|
||||
const rawRows = await typedExecutor.query(planned.sql, planned.params);
|
||||
return mapTableRows(columns, schema, rawRows);
|
||||
},
|
||||
|
||||
async fundamentalsAsOf(q: FundamentalsAsOfQuery): Promise<Table> {
|
||||
|
|
@ -2291,8 +2615,11 @@ export function createDuckDbMarketDataStore(options: DuckDbMarketDataStoreOption
|
|||
return mapTableRows(columns, schema, rawRows);
|
||||
},
|
||||
|
||||
macroAsOf(): Promise<Table> {
|
||||
return Promise.reject(new MarketDataStoreNotImplementedError('macroAsOf'));
|
||||
async macroAsOf(q: MacroAsOfQuery): Promise<Table> {
|
||||
const planned = planMacroAsOfQuery(q, planCtx);
|
||||
await ensureBudgetInitialized();
|
||||
const rawRows = await typedExecutor.query(planned.sql, planned.params);
|
||||
return mapMacroRows(rawRows, planCtx.vaultCutoffTs, planned.fenced.asOfMs);
|
||||
},
|
||||
|
||||
async universe(q: UniverseQuery): Promise<number[]> {
|
||||
|
|
|
|||
|
|
@ -29,6 +29,8 @@ import {
|
|||
type FencedTimeRange,
|
||||
type MarketDataStore,
|
||||
MarketDataStoreValidationError,
|
||||
type Table,
|
||||
type TableRow,
|
||||
type VaultFenceContext,
|
||||
applyVaultFence,
|
||||
} from './market-data-store';
|
||||
|
|
@ -42,9 +44,17 @@ const CANONICAL_SIGNED_INT_RE = /^-?(?:0|[1-9]\d*)$/;
|
|||
/** Default maximum number of `BarRecord` rows yielded per `BarBatch`. */
|
||||
export const DEFAULT_QUESTDB_BARS_BATCH_SIZE = 50_000;
|
||||
|
||||
/** Output columns for QuestDB `fx_1m` queries. */
|
||||
export const FX_1M_COLUMNS = ['pair', 'ts', 'open', 'high', 'low', 'close', 'source'] as const;
|
||||
|
||||
const FX_1M_ACCEPTED_PAIRS: ReadonlySet<string> = new Set(['USDCAD', 'USD.CAD']);
|
||||
|
||||
/** Input query type derived from `MarketDataStore['bars']`. */
|
||||
export type QuestDbBars1mQuery = Parameters<MarketDataStore['bars']>[0];
|
||||
|
||||
/** Input query type derived from `MarketDataStore['fx']`. */
|
||||
export type QuestDbFx1mQuery = Parameters<MarketDataStore['fx']>[0];
|
||||
|
||||
/**
|
||||
* Injected PGWire SQL executor port, structurally compatible with
|
||||
* `QuestDBClient.query(sql, params)` in `libs/data/questdb/src/client.ts`.
|
||||
|
|
@ -63,6 +73,13 @@ export interface PlannedQuestDbBars1mQuery {
|
|||
readonly fence: FencedTimeRange;
|
||||
}
|
||||
|
||||
/** Pure output of {@link planFx1mQuery}. */
|
||||
export interface PlannedQuestDbFx1mQuery {
|
||||
readonly sql: string;
|
||||
readonly params: readonly string[];
|
||||
readonly fence: FencedTimeRange;
|
||||
}
|
||||
|
||||
/** Configuration for {@link createQuestDbIntradayBarsReader}. */
|
||||
export interface QuestDbIntradayBarsReaderOptions extends VaultFenceContext {
|
||||
readonly executor: QuestDbQueryExecutor;
|
||||
|
|
@ -70,6 +87,11 @@ export interface QuestDbIntradayBarsReaderOptions extends VaultFenceContext {
|
|||
readonly batchSize?: number;
|
||||
}
|
||||
|
||||
/** Configuration for {@link createQuestDbIntradayFxReader}. */
|
||||
export interface QuestDbIntradayFxReaderOptions extends VaultFenceContext {
|
||||
readonly executor: QuestDbQueryExecutor;
|
||||
}
|
||||
|
||||
interface InternalPlannedBars1mQuery {
|
||||
readonly planned: PlannedQuestDbBars1mQuery;
|
||||
readonly requestedListingIds: ReadonlySet<number>;
|
||||
|
|
@ -215,6 +237,67 @@ export function planBars1mQuery(
|
|||
return planBars1mQueryInternal(q, ctx).planned;
|
||||
}
|
||||
|
||||
/**
|
||||
* Pure, Vault-fenced, parameterized SQL planner for QuestDB `fx_1m`.
|
||||
*
|
||||
* Always fences under `scope: 'vault_fenced'` with `vaultOperatorAuthorized: false`
|
||||
* and binds both `'USDCAD'` and `'USD.CAD'` pair symbols via `$3, $4`.
|
||||
*/
|
||||
export function planFx1mQuery(
|
||||
q: QuestDbFx1mQuery,
|
||||
ctx: VaultFenceContext
|
||||
): PlannedQuestDbFx1mQuery {
|
||||
if (!isPlainRecord(ctx)) {
|
||||
throw new MarketDataStoreValidationError('Expected a VaultFenceContext object.', 'ctx');
|
||||
}
|
||||
if (!isPlainRecord(q)) {
|
||||
throw new MarketDataStoreValidationError('Expected an fx query object.', 'query');
|
||||
}
|
||||
|
||||
const timeframe: unknown = q.timeframe;
|
||||
if (timeframe !== '1m') {
|
||||
throw new MarketDataStoreValidationError(
|
||||
`Invalid fx timeframe "${String(timeframe)}". Expected '1m'.`,
|
||||
'timeframe'
|
||||
);
|
||||
}
|
||||
|
||||
const pair: unknown = q.pair;
|
||||
if (pair !== 'USD.CAD') {
|
||||
throw new MarketDataStoreValidationError(
|
||||
`Unsupported FX pair "${String(pair)}". Expected 'USD.CAD'.`,
|
||||
'pair'
|
||||
);
|
||||
}
|
||||
|
||||
const fence = applyVaultFence(
|
||||
{
|
||||
from: q.from,
|
||||
to: q.to,
|
||||
scope: 'vault_fenced',
|
||||
},
|
||||
{
|
||||
vaultCutoffTs: ctx.vaultCutoffTs,
|
||||
vaultOperatorAuthorized: false,
|
||||
}
|
||||
);
|
||||
|
||||
const sql =
|
||||
'SELECT pair, CAST(ts AS LONG) AS ts_us, open, high, low, close, source ' +
|
||||
'FROM fx_1m ' +
|
||||
'WHERE ts >= $1 AND ts <= $2 AND pair IN ($3, $4) ' +
|
||||
'ORDER BY ts ASC';
|
||||
|
||||
const params: string[] = [
|
||||
formatUtcIsoMs(fence.fromMs),
|
||||
formatUtcIsoMs(fence.toMs),
|
||||
'USDCAD',
|
||||
'USD.CAD',
|
||||
];
|
||||
|
||||
return { sql, params, fence };
|
||||
}
|
||||
|
||||
function parseListingIdSymbol(
|
||||
row: Record<string, unknown>,
|
||||
rowIndex: number,
|
||||
|
|
@ -460,3 +543,140 @@ export function createQuestDbIntradayBarsReader(
|
|||
},
|
||||
};
|
||||
}
|
||||
|
||||
function mapFx1mRows(
|
||||
rows: readonly Record<string, unknown>[],
|
||||
fence: FencedTimeRange,
|
||||
vaultCutoffTs: number
|
||||
): Table {
|
||||
const fromUs = BigInt(fence.fromMs) * 1000n;
|
||||
const toUs = BigInt(fence.toMs) * 1000n;
|
||||
const vaultCutoffUs = BigInt(vaultCutoffTs) * 1000n;
|
||||
|
||||
const out: 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 fx_1m row at index ${i}.`,
|
||||
'rows'
|
||||
);
|
||||
}
|
||||
|
||||
const pair = raw.pair;
|
||||
if (typeof pair !== 'string' || !FX_1M_ACCEPTED_PAIRS.has(pair)) {
|
||||
throw new MarketDataStoreValidationError(
|
||||
`Invalid fx_1m pair in result row ${i}: ${String(pair)}.`,
|
||||
'pair'
|
||||
);
|
||||
}
|
||||
|
||||
const tsUs = parseTimestampMicros(raw, 'ts_us', 'ts', i);
|
||||
if (tsUs < fromUs || tsUs > toUs || tsUs >= vaultCutoffUs) {
|
||||
throw new MarketDataStoreValidationError(
|
||||
`Row ${i} timestamp ts (${tsUs.toString()} us) is outside fenced range [${fromUs.toString()}, ${toUs.toString()}] us (cutoff ${vaultCutoffUs.toString()} us).`,
|
||||
'ts'
|
||||
);
|
||||
}
|
||||
|
||||
const source = raw.source;
|
||||
if (typeof source !== 'string' || source.length === 0) {
|
||||
throw new MarketDataStoreValidationError(
|
||||
`Invalid fx_1m source in result row ${i}: ${String(source)}.`,
|
||||
'source'
|
||||
);
|
||||
}
|
||||
|
||||
out[i] = {
|
||||
pair,
|
||||
ts: microsToEpochMs(tsUs, 'ts', i, 'floor'),
|
||||
open: readRequiredFiniteNumber(raw, 'open', i),
|
||||
high: readRequiredFiniteNumber(raw, 'high', i),
|
||||
low: readRequiredFiniteNumber(raw, 'low', i),
|
||||
close: readRequiredFiniteNumber(raw, 'close', i),
|
||||
source,
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
columns: [...FX_1M_COLUMNS],
|
||||
rows: out,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a read-only Vault-fenced intraday `fx` reader backed by an injected
|
||||
* {@link QuestDbQueryExecutor} over QuestDB `fx_1m`.
|
||||
*/
|
||||
export function createQuestDbIntradayFxReader(
|
||||
options: QuestDbIntradayFxReaderOptions
|
||||
): Pick<MarketDataStore, 'fx'> {
|
||||
if (!isPlainRecord(options)) {
|
||||
throw new MarketDataStoreValidationError(
|
||||
'Expected a QuestDbIntradayFxReaderOptions object.',
|
||||
'options'
|
||||
);
|
||||
}
|
||||
|
||||
const executor: unknown = options.executor;
|
||||
if (!isPlainRecord(executor) || typeof executor.query !== 'function') {
|
||||
throw new MarketDataStoreValidationError(
|
||||
'Expected `executor` with a `query(sql, params)` method.',
|
||||
'executor'
|
||||
);
|
||||
}
|
||||
const typedExecutor = executor as unknown as QuestDbQueryExecutor;
|
||||
const vaultCutoffTs = validateVaultCutoffTs(options.vaultCutoffTs);
|
||||
|
||||
if (
|
||||
options.vaultOperatorAuthorized !== undefined &&
|
||||
typeof options.vaultOperatorAuthorized !== 'boolean'
|
||||
) {
|
||||
throw new MarketDataStoreValidationError(
|
||||
`Invalid vaultOperatorAuthorized "${String(options.vaultOperatorAuthorized)}". Expected a boolean.`,
|
||||
'vaultOperatorAuthorized'
|
||||
);
|
||||
}
|
||||
|
||||
const planCtx: VaultFenceContext = {
|
||||
vaultCutoffTs,
|
||||
vaultOperatorAuthorized: false,
|
||||
};
|
||||
|
||||
return {
|
||||
async fx(q: QuestDbFx1mQuery): Promise<Table> {
|
||||
const planned = planFx1mQuery(q, planCtx);
|
||||
const result: unknown = await typedExecutor.query(planned.sql, [...planned.params]);
|
||||
if (!isPlainRecord(result) || !Array.isArray(result.rows)) {
|
||||
throw new MarketDataStoreValidationError(
|
||||
'Executor returned a malformed result; expected `{ rows: Record<string, unknown>[] }`.',
|
||||
'rows'
|
||||
);
|
||||
}
|
||||
return mapFx1mRows(
|
||||
result.rows as readonly Record<string, unknown>[],
|
||||
planned.fence,
|
||||
vaultCutoffTs
|
||||
);
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a combined read-only intraday `bars` + `fx` reader backed by an
|
||||
* injected {@link QuestDbQueryExecutor} over QuestDB `bars_1m` and `fx_1m`.
|
||||
*/
|
||||
export function createQuestDbIntradayReader(
|
||||
options: QuestDbIntradayBarsReaderOptions
|
||||
): Pick<MarketDataStore, 'bars' | 'fx'> {
|
||||
const barsReader = createQuestDbIntradayBarsReader(options);
|
||||
const fxReader = createQuestDbIntradayFxReader(options);
|
||||
return {
|
||||
bars(q) {
|
||||
return barsReader.bars(q);
|
||||
},
|
||||
fx(q) {
|
||||
return fxReader.fx(q);
|
||||
},
|
||||
};
|
||||
}
|
||||
|
|
|
|||
|
|
@ -28,8 +28,8 @@ import { type MarketDataStore, MarketDataStoreValidationError } from './market-d
|
|||
export interface RoutedMarketDataStoreOptions {
|
||||
/** Backing store for daily (`'1d'`) and non-`'1m'` bars plus all other `MarketDataStore` methods. */
|
||||
readonly daily: MarketDataStore;
|
||||
/** Backing intraday reader for `bars` queries with `timeframe: '1m'`. */
|
||||
readonly intraday: Pick<MarketDataStore, 'bars'>;
|
||||
/** Backing intraday reader for `bars` (and optional `fx`) queries with `timeframe: '1m'`. */
|
||||
readonly intraday: Pick<MarketDataStore, 'bars'> & Partial<Pick<MarketDataStore, 'fx'>>;
|
||||
}
|
||||
|
||||
const REQUIRED_DAILY_METHODS = [
|
||||
|
|
@ -55,7 +55,7 @@ function isDelegateObject(value: unknown): value is Record<string, unknown> {
|
|||
return typeof value === 'object' && value !== null && !Array.isArray(value);
|
||||
}
|
||||
|
||||
function isIntraday1mBarsQuery(q: unknown): boolean {
|
||||
function isIntraday1mQuery(q: unknown): boolean {
|
||||
return (
|
||||
typeof q === 'object' &&
|
||||
q !== null &&
|
||||
|
|
@ -150,12 +150,19 @@ export function createRoutedMarketDataStore(
|
|||
);
|
||||
}
|
||||
|
||||
if (rawIntraday.fx !== undefined && typeof rawIntraday.fx !== 'function') {
|
||||
throw new MarketDataStoreValidationError(
|
||||
'Expected `intraday.fx` to be a function when provided.',
|
||||
'intraday.fx'
|
||||
);
|
||||
}
|
||||
|
||||
const daily = options.daily;
|
||||
const intraday = options.intraday;
|
||||
|
||||
return {
|
||||
bars(q) {
|
||||
if (isIntraday1mBarsQuery(q)) {
|
||||
if (isIntraday1mQuery(q)) {
|
||||
return intraday.bars(q);
|
||||
}
|
||||
return daily.bars(q);
|
||||
|
|
@ -182,6 +189,9 @@ export function createRoutedMarketDataStore(
|
|||
},
|
||||
|
||||
fx(q) {
|
||||
if (intraday.fx !== undefined && isIntraday1mQuery(q)) {
|
||||
return intraday.fx(q);
|
||||
}
|
||||
return daily.fx(q);
|
||||
},
|
||||
|
||||
|
|
|
|||
|
|
@ -54,6 +54,17 @@ const ENV_PRINCIPAL_ID = 'RESEARCH_MCP_PRINCIPAL_ID';
|
|||
const ENV_LIBRARY_ROOT = 'RESEARCH_MCP_LIBRARY_ROOT';
|
||||
const ENV_SESSION_REFERENCE_LISTINGS = 'RESEARCH_MCP_SESSION_REFERENCE_LISTINGS';
|
||||
const ENV_EARLY_CLOSES = 'RESEARCH_MCP_EARLY_CLOSES';
|
||||
const ENV_QUESTDB_URL = 'RESEARCH_MCP_QUESTDB_URL';
|
||||
const ENV_QUESTDB_HOST = 'RESEARCH_MCP_QUESTDB_HOST';
|
||||
const ENV_QUESTDB_PG_PORT = 'RESEARCH_MCP_QUESTDB_PG_PORT';
|
||||
const ENV_QUESTDB_DATABASE = 'RESEARCH_MCP_QUESTDB_DATABASE';
|
||||
const ENV_QUESTDB_USER = 'RESEARCH_MCP_QUESTDB_USER';
|
||||
const ENV_QUESTDB_PASSWORD = 'RESEARCH_MCP_QUESTDB_PASSWORD';
|
||||
const ENV_QUESTDB_SSL = 'RESEARCH_MCP_QUESTDB_SSL';
|
||||
|
||||
const DEFAULT_QUESTDB_PG_PORT = 8812;
|
||||
const DEFAULT_QUESTDB_DATABASE = 'qdb';
|
||||
const STRICT_UINT_PORT_RE = /^\d+$/;
|
||||
|
||||
const SCHEMA_IDENT_RE = /^[a-z_][a-z0-9_]*$/;
|
||||
const AGENT_PRINCIPAL_RE =
|
||||
|
|
@ -75,9 +86,27 @@ const rawHostEnvSchema = z
|
|||
[ENV_LIBRARY_ROOT]: nonBlankEnvString,
|
||||
[ENV_SESSION_REFERENCE_LISTINGS]: nonBlankEnvString,
|
||||
[ENV_EARLY_CLOSES]: nonBlankEnvString.optional(),
|
||||
[ENV_QUESTDB_URL]: nonBlankEnvString.optional(),
|
||||
[ENV_QUESTDB_HOST]: nonBlankEnvString.optional(),
|
||||
[ENV_QUESTDB_PG_PORT]: nonBlankEnvString.optional(),
|
||||
[ENV_QUESTDB_DATABASE]: nonBlankEnvString.optional(),
|
||||
[ENV_QUESTDB_USER]: nonBlankEnvString.optional(),
|
||||
[ENV_QUESTDB_PASSWORD]: nonBlankEnvString.optional(),
|
||||
[ENV_QUESTDB_SSL]: nonBlankEnvString.optional(),
|
||||
})
|
||||
.strict();
|
||||
|
||||
/** Optional QuestDB intraday connection settings parsed from `RESEARCH_MCP_QUESTDB_*`. */
|
||||
export interface ResearchCopilotQuestDbConfig {
|
||||
readonly url?: string;
|
||||
readonly host?: string;
|
||||
readonly port?: number;
|
||||
readonly database?: string;
|
||||
readonly user?: string;
|
||||
readonly password?: string;
|
||||
readonly ssl?: boolean;
|
||||
}
|
||||
|
||||
/** Validated configuration parsed from `RESEARCH_MCP_*` environment variables. */
|
||||
export interface ResearchCopilotHostConfig {
|
||||
readonly postgresUrl: string;
|
||||
|
|
@ -88,6 +117,7 @@ export interface ResearchCopilotHostConfig {
|
|||
readonly libraryRoot: string;
|
||||
readonly referenceListingIds: BarSessionDatesPortOptions['referenceListingIds'];
|
||||
readonly earlyCloses?: EarlyCloseOverrides;
|
||||
readonly questdb?: ResearchCopilotQuestDbConfig;
|
||||
}
|
||||
|
||||
/**
|
||||
|
|
@ -175,11 +205,11 @@ function defineDataProperty<T>(target: Record<string, T>, key: string, value: T)
|
|||
});
|
||||
}
|
||||
|
||||
function parsePostgresUrl(raw: string): string {
|
||||
function parsePgWireUrl(raw: string, variable: string): string {
|
||||
if (raw !== raw.trim()) {
|
||||
throw new ResearchCopilotHostConfigError(
|
||||
ENV_POSTGRES_URL,
|
||||
`Invalid configuration variable "${ENV_POSTGRES_URL}": expected a valid postgres:// or postgresql:// URL without surrounding whitespace.`
|
||||
variable,
|
||||
`Invalid configuration variable "${variable}": expected a valid postgres:// or postgresql:// URL without surrounding whitespace.`
|
||||
);
|
||||
}
|
||||
let parsed: URL;
|
||||
|
|
@ -187,8 +217,8 @@ function parsePostgresUrl(raw: string): string {
|
|||
parsed = new URL(raw);
|
||||
} catch {
|
||||
throw new ResearchCopilotHostConfigError(
|
||||
ENV_POSTGRES_URL,
|
||||
`Invalid configuration variable "${ENV_POSTGRES_URL}": expected a valid postgres:// or postgresql:// URL.`
|
||||
variable,
|
||||
`Invalid configuration variable "${variable}": expected a valid postgres:// or postgresql:// URL.`
|
||||
);
|
||||
}
|
||||
if (
|
||||
|
|
@ -196,8 +226,8 @@ function parsePostgresUrl(raw: string): string {
|
|||
parsed.hostname.length === 0
|
||||
) {
|
||||
throw new ResearchCopilotHostConfigError(
|
||||
ENV_POSTGRES_URL,
|
||||
`Invalid configuration variable "${ENV_POSTGRES_URL}": expected a postgres:// or postgresql:// URL with a non-empty host.`
|
||||
variable,
|
||||
`Invalid configuration variable "${variable}": expected a postgres:// or postgresql:// URL with a non-empty host.`
|
||||
);
|
||||
}
|
||||
try {
|
||||
|
|
@ -209,13 +239,124 @@ function parsePostgresUrl(raw: string): string {
|
|||
}
|
||||
} catch {
|
||||
throw new ResearchCopilotHostConfigError(
|
||||
ENV_POSTGRES_URL,
|
||||
`Invalid configuration variable "${ENV_POSTGRES_URL}": URL credentials contain invalid percent-encoding.`
|
||||
variable,
|
||||
`Invalid configuration variable "${variable}": URL credentials contain invalid percent-encoding.`
|
||||
);
|
||||
}
|
||||
return raw;
|
||||
}
|
||||
|
||||
function parsePostgresUrl(raw: string): string {
|
||||
return parsePgWireUrl(raw, ENV_POSTGRES_URL);
|
||||
}
|
||||
|
||||
function parseQuestDbSsl(raw: string): boolean {
|
||||
const normalized = raw.trim().toLowerCase();
|
||||
if (normalized === 'true' || normalized === '1') {
|
||||
return true;
|
||||
}
|
||||
if (normalized === 'false' || normalized === '0') {
|
||||
return false;
|
||||
}
|
||||
throw new ResearchCopilotHostConfigError(
|
||||
ENV_QUESTDB_SSL,
|
||||
`Invalid configuration variable "${ENV_QUESTDB_SSL}": expected "true", "false", "1", or "0".`
|
||||
);
|
||||
}
|
||||
|
||||
function parseQuestDbPort(raw: string): number {
|
||||
const trimmed = raw.trim();
|
||||
if (!STRICT_UINT_PORT_RE.test(trimmed)) {
|
||||
throw new ResearchCopilotHostConfigError(
|
||||
ENV_QUESTDB_PG_PORT,
|
||||
`Invalid configuration variable "${ENV_QUESTDB_PG_PORT}": expected an integer port from 1 through 65535.`
|
||||
);
|
||||
}
|
||||
const port = Number(trimmed);
|
||||
if (!Number.isSafeInteger(port) || port < 1 || port > 65535) {
|
||||
throw new ResearchCopilotHostConfigError(
|
||||
ENV_QUESTDB_PG_PORT,
|
||||
`Invalid configuration variable "${ENV_QUESTDB_PG_PORT}": expected an integer port from 1 through 65535.`
|
||||
);
|
||||
}
|
||||
return port;
|
||||
}
|
||||
|
||||
function parseQuestDbConfig(data: {
|
||||
readonly [ENV_QUESTDB_URL]?: string;
|
||||
readonly [ENV_QUESTDB_HOST]?: string;
|
||||
readonly [ENV_QUESTDB_PG_PORT]?: string;
|
||||
readonly [ENV_QUESTDB_DATABASE]?: string;
|
||||
readonly [ENV_QUESTDB_USER]?: string;
|
||||
readonly [ENV_QUESTDB_PASSWORD]?: string;
|
||||
readonly [ENV_QUESTDB_SSL]?: string;
|
||||
}): ResearchCopilotQuestDbConfig | undefined {
|
||||
const rawUrl = data[ENV_QUESTDB_URL];
|
||||
const rawHost = data[ENV_QUESTDB_HOST];
|
||||
const rawPort = data[ENV_QUESTDB_PG_PORT];
|
||||
const rawDatabase = data[ENV_QUESTDB_DATABASE];
|
||||
const rawUser = data[ENV_QUESTDB_USER];
|
||||
const rawPassword = data[ENV_QUESTDB_PASSWORD];
|
||||
const rawSsl = data[ENV_QUESTDB_SSL];
|
||||
|
||||
const hasAnyDiscrete =
|
||||
rawHost !== undefined ||
|
||||
rawPort !== undefined ||
|
||||
rawDatabase !== undefined ||
|
||||
rawUser !== undefined ||
|
||||
rawPassword !== undefined;
|
||||
|
||||
if (rawUrl === undefined && !hasAnyDiscrete && rawSsl === undefined) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
const ssl = rawSsl !== undefined ? parseQuestDbSsl(rawSsl) : undefined;
|
||||
|
||||
if (rawUrl !== undefined) {
|
||||
if (hasAnyDiscrete) {
|
||||
throw new ResearchCopilotHostConfigError(
|
||||
ENV_QUESTDB_URL,
|
||||
`Conflicting configuration variable "${ENV_QUESTDB_URL}": cannot be combined with discrete RESEARCH_MCP_QUESTDB_HOST/PG_PORT/DATABASE/USER/PASSWORD variables.`
|
||||
);
|
||||
}
|
||||
const url = parsePgWireUrl(rawUrl, ENV_QUESTDB_URL);
|
||||
return {
|
||||
url,
|
||||
...(ssl !== undefined ? { ssl } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
if (rawHost === undefined) {
|
||||
throw new ResearchCopilotHostConfigError(
|
||||
ENV_QUESTDB_HOST,
|
||||
`Missing required configuration variable "${ENV_QUESTDB_HOST}" when other RESEARCH_MCP_QUESTDB_* variables are set.`
|
||||
);
|
||||
}
|
||||
|
||||
const host = rawHost.trim();
|
||||
if (host !== rawHost || /\s/.test(host)) {
|
||||
throw new ResearchCopilotHostConfigError(
|
||||
ENV_QUESTDB_HOST,
|
||||
`Invalid configuration variable "${ENV_QUESTDB_HOST}": expected a hostname without whitespace.`
|
||||
);
|
||||
}
|
||||
|
||||
const port = rawPort !== undefined ? parseQuestDbPort(rawPort) : DEFAULT_QUESTDB_PG_PORT;
|
||||
const database =
|
||||
rawDatabase !== undefined ? rawDatabase.trim() : DEFAULT_QUESTDB_DATABASE;
|
||||
const user = rawUser !== undefined ? rawUser.trim() : undefined;
|
||||
const password = rawPassword;
|
||||
|
||||
return {
|
||||
host,
|
||||
port,
|
||||
database,
|
||||
...(user !== undefined ? { user } : {}),
|
||||
...(password !== undefined ? { password } : {}),
|
||||
...(ssl !== undefined ? { ssl } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
function parsePostgresSchema(raw: string): string {
|
||||
if (!SCHEMA_IDENT_RE.test(raw)) {
|
||||
throw new ResearchCopilotHostConfigError(
|
||||
|
|
@ -526,6 +667,7 @@ export function parseResearchCopilotHostConfig(
|
|||
data[ENV_EARLY_CLOSES] !== undefined
|
||||
? parseEarlyClosesEnv(data[ENV_EARLY_CLOSES])
|
||||
: undefined;
|
||||
const questdb = parseQuestDbConfig(data);
|
||||
|
||||
return {
|
||||
postgresUrl,
|
||||
|
|
@ -536,6 +678,7 @@ export function parseResearchCopilotHostConfig(
|
|||
libraryRoot,
|
||||
referenceListingIds,
|
||||
...(earlyCloses !== undefined ? { earlyCloses } : {}),
|
||||
...(questdb !== undefined ? { questdb } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
|
|
@ -554,13 +697,12 @@ function addRawAndDecodedNeedle(needles: Set<string>, raw: string): void {
|
|||
}
|
||||
}
|
||||
|
||||
function collectSecretNeedles(postgresUrl: string): readonly string[] {
|
||||
const needles = new Set<string>();
|
||||
if (postgresUrl.length > 0) {
|
||||
needles.add(postgresUrl);
|
||||
function collectUrlSecretNeedles(needles: Set<string>, rawUrl: string): void {
|
||||
if (rawUrl.length > 0) {
|
||||
needles.add(rawUrl);
|
||||
}
|
||||
try {
|
||||
const parsed = new URL(postgresUrl);
|
||||
const parsed = new URL(rawUrl);
|
||||
if (parsed.href.length > 0) {
|
||||
needles.add(parsed.href);
|
||||
}
|
||||
|
|
@ -591,7 +733,23 @@ function collectSecretNeedles(postgresUrl: string): readonly string[] {
|
|||
}
|
||||
}
|
||||
} catch {
|
||||
// Non-URL postgresUrl passed directly to runResearchCopilotStdioHost: raw string is covered.
|
||||
// Non-URL string passed directly: raw string is already covered.
|
||||
}
|
||||
}
|
||||
|
||||
function collectSecretNeedles(
|
||||
postgresUrl: string,
|
||||
questdb?: ResearchCopilotQuestDbConfig
|
||||
): readonly string[] {
|
||||
const needles = new Set<string>();
|
||||
collectUrlSecretNeedles(needles, postgresUrl);
|
||||
if (questdb !== undefined) {
|
||||
if (typeof questdb.url === 'string' && questdb.url.length > 0) {
|
||||
collectUrlSecretNeedles(needles, questdb.url);
|
||||
}
|
||||
if (typeof questdb.password === 'string' && questdb.password.length > 0) {
|
||||
addRawAndDecodedNeedle(needles, questdb.password);
|
||||
}
|
||||
}
|
||||
return Array.from(needles);
|
||||
}
|
||||
|
|
@ -708,7 +866,8 @@ export async function runResearchCopilotStdioHost(
|
|||
|
||||
const { config } = deps;
|
||||
const secretNeedles = collectSecretNeedles(
|
||||
typeof config.postgresUrl === 'string' ? config.postgresUrl : ''
|
||||
typeof config.postgresUrl === 'string' ? config.postgresUrl : '',
|
||||
config.questdb
|
||||
);
|
||||
|
||||
const closers: Array<() => Promise<void> | void> = [];
|
||||
|
|
|
|||
|
|
@ -6,12 +6,14 @@ import {
|
|||
analyzeSignalPanel,
|
||||
} from '@stock-bot/calculations';
|
||||
import { z } from 'zod';
|
||||
import { parseFeatureRef } from '../../feature-library';
|
||||
import {
|
||||
type BarRecord,
|
||||
type MarketDataStore,
|
||||
MarketDataStoreValidationError,
|
||||
type Table,
|
||||
type TableRow,
|
||||
type UniverseRef,
|
||||
type VaultFenceContext,
|
||||
} from '../../market-data-store';
|
||||
import {
|
||||
|
|
@ -77,6 +79,9 @@ export const ANALYZE_SIGNAL_MAX_SERIES_POINTS = 100;
|
|||
/** Hard maximum number of UTC month-end fundamentals snapshots queried in a single study. */
|
||||
export const ANALYZE_SIGNAL_MAX_FUNDAMENTAL_SNAPSHOTS = 120;
|
||||
|
||||
/** Hard maximum number of per-session feature cross-section queries in a single study. */
|
||||
export const ANALYZE_SIGNAL_MAX_FEATURE_SESSION_QUERIES = 5_500;
|
||||
|
||||
const LEDGER_UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
|
||||
const AGENT_PRINCIPAL_RE =
|
||||
/^agent:[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/;
|
||||
|
|
@ -90,6 +95,15 @@ function canonicalDailyHorizonBucket(horizonSessions: number): HorizonBucket {
|
|||
|
||||
const utcBoundStringSchema = z.string().min(1).refine(isValidUtcBoundString, UTC_BOUND_ERROR_MESSAGE);
|
||||
|
||||
function isValidFeatureRef(raw: string): boolean {
|
||||
try {
|
||||
parseFeatureRef(raw);
|
||||
return true;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
const shortsSignalSpecSchema = z
|
||||
.object({
|
||||
source: z.literal('shorts').describe('Signal data source ("shorts").'),
|
||||
|
|
@ -118,9 +132,30 @@ const fundamentalsSignalSpecSchema = z
|
|||
.strict()
|
||||
.describe('Point-in-time fundamentals signal specification.');
|
||||
|
||||
const featureSignalSpecSchema = z
|
||||
.object({
|
||||
source: z.literal('feature').describe('Signal data source ("feature").'),
|
||||
featureRef: z
|
||||
.string()
|
||||
.min(1)
|
||||
.refine(
|
||||
isValidFeatureRef,
|
||||
'Expected canonical versioned feature reference "<name>@v<version>" (e.g. "ret_1d@v1").'
|
||||
)
|
||||
.describe('Canonical versioned feature reference ("<name>@v<version>"), e.g. "ret_1d@v1".'),
|
||||
})
|
||||
.strict()
|
||||
.describe('Versioned curated feature signal specification.');
|
||||
|
||||
const signalSpecSchema = z
|
||||
.discriminatedUnion('source', [shortsSignalSpecSchema, fundamentalsSignalSpecSchema])
|
||||
.describe('Discriminated signal source and field specification ("shorts" or "fundamentals").');
|
||||
.discriminatedUnion('source', [
|
||||
shortsSignalSpecSchema,
|
||||
fundamentalsSignalSpecSchema,
|
||||
featureSignalSpecSchema,
|
||||
])
|
||||
.describe(
|
||||
'Discriminated signal source specification ("shorts", "fundamentals", or "feature").'
|
||||
);
|
||||
|
||||
const analyzeSignalSharedFieldsSchema = z
|
||||
.object({
|
||||
|
|
@ -227,7 +262,9 @@ export const analyzeSignalInputSchema = analyzeSignalSharedFieldsSchema
|
|||
message:
|
||||
data.signal.source === 'shorts'
|
||||
? 'Short-interest signal studies require an equity universeMarket (US_EQ, CA_EQ, or US_CA_EQ).'
|
||||
: 'Fundamentals signal studies require an equity universeMarket (US_EQ, CA_EQ, or US_CA_EQ).',
|
||||
: data.signal.source === 'fundamentals'
|
||||
? 'Fundamentals signal studies require an equity universeMarket (US_EQ, CA_EQ, or US_CA_EQ).'
|
||||
: 'Feature signal studies require an equity universeMarket (US_EQ, CA_EQ, or US_CA_EQ).',
|
||||
});
|
||||
}
|
||||
});
|
||||
|
|
@ -238,29 +275,35 @@ function buildAnalyzeSignalJsonSchema(): JsonSchemaObject {
|
|||
const sharedSchema = zodObjectToJsonSchema(analyzeSignalSharedFieldsSchema);
|
||||
const shortsBranch = zodObjectToJsonSchema(shortsSignalSpecSchema);
|
||||
const fundamentalsBranch = zodObjectToJsonSchema(fundamentalsSignalSpecSchema);
|
||||
const featureBranch = zodObjectToJsonSchema(featureSignalSpecSchema);
|
||||
const allowEstimatedLagProp = fundamentalsBranch.properties.allowEstimatedLag ?? {
|
||||
type: 'boolean' as const,
|
||||
default: false,
|
||||
};
|
||||
const featureRefProp = featureBranch.properties.featureRef ?? {
|
||||
type: 'string' as const,
|
||||
minLength: 1,
|
||||
};
|
||||
const signalProperty: JsonSchemaProperty = {
|
||||
type: 'object',
|
||||
description: signalSpecSchema.description,
|
||||
properties: {
|
||||
source: {
|
||||
type: 'string',
|
||||
enum: ['shorts', 'fundamentals'],
|
||||
description: 'Signal data source ("shorts" or "fundamentals").',
|
||||
enum: ['shorts', 'fundamentals', 'feature'],
|
||||
description: 'Signal data source ("shorts", "fundamentals", or "feature").',
|
||||
},
|
||||
field: {
|
||||
type: 'string',
|
||||
enum: [...SHORTS_SIGNAL_FIELDS, ...FUNDAMENTALS_PIT_VALUE_FIELDS],
|
||||
description: 'Signal field name valid for the chosen source.',
|
||||
description: 'Signal field name valid for "shorts" or "fundamentals".',
|
||||
},
|
||||
allowEstimatedLag: allowEstimatedLagProp,
|
||||
featureRef: featureRefProp,
|
||||
},
|
||||
required: ['source', 'field'],
|
||||
required: ['source'],
|
||||
additionalProperties: false,
|
||||
anyOf: [shortsBranch, fundamentalsBranch],
|
||||
anyOf: [shortsBranch, fundamentalsBranch, featureBranch],
|
||||
};
|
||||
|
||||
return {
|
||||
|
|
@ -732,6 +775,94 @@ function appendEligibleFundamentalsObservations(params: {
|
|||
return latestKnownAtByListing;
|
||||
}
|
||||
|
||||
function deriveFeatureSessionQueries(
|
||||
bars: readonly BarRecord[],
|
||||
fencedAsOfMs: number,
|
||||
vaultCutoffTs: number,
|
||||
vaultCutoffDate: string
|
||||
): Array<{ readonly sessionDate: string; readonly asOfMs: number }> {
|
||||
const unique = new Map<string, { readonly sessionDate: string; readonly asOfMs: number }>();
|
||||
for (let i = 0; i < bars.length; i += 1) {
|
||||
const bar = bars[i];
|
||||
if (
|
||||
typeof bar !== 'object' ||
|
||||
bar === null ||
|
||||
typeof bar.ts !== 'number' ||
|
||||
!Number.isFinite(bar.ts)
|
||||
) {
|
||||
continue;
|
||||
}
|
||||
const sessionDate = utcDateOf(bar.ts);
|
||||
if (sessionDate >= vaultCutoffDate) {
|
||||
continue;
|
||||
}
|
||||
const asOfMs = Math.min(bar.ts, fencedAsOfMs);
|
||||
if (asOfMs >= vaultCutoffTs) {
|
||||
continue;
|
||||
}
|
||||
const key = `${sessionDate}:${asOfMs}`;
|
||||
if (!unique.has(key)) {
|
||||
unique.set(key, { sessionDate, asOfMs });
|
||||
}
|
||||
}
|
||||
return [...unique.values()].sort((a, b) =>
|
||||
a.sessionDate !== b.sessionDate ? (a.sessionDate < b.sessionDate ? -1 : 1) : a.asOfMs - b.asOfMs
|
||||
);
|
||||
}
|
||||
|
||||
function appendEligibleFeatureObservations(params: {
|
||||
readonly table: Table;
|
||||
readonly featureRef: string;
|
||||
readonly listingIdSet: ReadonlySet<number>;
|
||||
readonly sessionQueryAsOfMs: number;
|
||||
readonly seenKeys: Set<string>;
|
||||
readonly out: SignalObservation[];
|
||||
}): void {
|
||||
const { table, featureRef, listingIdSet, sessionQueryAsOfMs, seenKeys, out } = params;
|
||||
if (
|
||||
typeof table !== 'object' ||
|
||||
table === null ||
|
||||
!Array.isArray(table.columns) ||
|
||||
!Array.isArray(table.rows)
|
||||
) {
|
||||
throw new SignalPanelError(
|
||||
'invalid_input',
|
||||
'Expected a crossSection Table object with array columns and rows.'
|
||||
);
|
||||
}
|
||||
|
||||
const normalizedKnownAt = sessionQueryAsOfMs === 0 ? 0 : sessionQueryAsOfMs;
|
||||
for (let i = 0; i < table.rows.length; i += 1) {
|
||||
const row = table.rows[i];
|
||||
if (typeof row !== 'object' || row === null) {
|
||||
continue;
|
||||
}
|
||||
const listingId = row.listing_id;
|
||||
if (
|
||||
typeof listingId !== 'number' ||
|
||||
!Number.isSafeInteger(listingId) ||
|
||||
!listingIdSet.has(listingId)
|
||||
) {
|
||||
continue;
|
||||
}
|
||||
const rawValue = row[featureRef];
|
||||
if (typeof rawValue !== 'number' || !Number.isFinite(rawValue)) {
|
||||
continue;
|
||||
}
|
||||
const normalizedListingId = listingId === 0 ? 0 : listingId;
|
||||
const dedupeKey = `${normalizedListingId}:${normalizedKnownAt}`;
|
||||
if (seenKeys.has(dedupeKey)) {
|
||||
continue;
|
||||
}
|
||||
seenKeys.add(dedupeKey);
|
||||
out.push({
|
||||
listingId: normalizedListingId,
|
||||
knownAt: normalizedKnownAt,
|
||||
value: rawValue === 0 ? 0 : rawValue,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
function buildCanonicalStudyExpression(params: {
|
||||
readonly input: AnalyzeSignalInput;
|
||||
readonly listingIds: readonly number[];
|
||||
|
|
@ -742,15 +873,23 @@ function buildCanonicalStudyExpression(params: {
|
|||
}): SignalStudyExpression {
|
||||
const { input, listingIds, universeSnapshotDate, effectiveFrom, effectiveTo, effectiveAsOf } =
|
||||
params;
|
||||
const signalExprSuffix =
|
||||
input.signal.source === 'feature'
|
||||
? `feature:${input.signal.featureRef}`
|
||||
: `${input.signal.source}:${input.signal.field}`;
|
||||
return {
|
||||
expression: `mcp:analyze_signal:v1:${input.signal.source}:${input.signal.field}`,
|
||||
expression: `mcp:analyze_signal:v1:${signalExprSuffix}`,
|
||||
params: {
|
||||
version: 1,
|
||||
signalSource: input.signal.source,
|
||||
signalField: input.signal.field,
|
||||
...(input.signal.source === 'fundamentals'
|
||||
? { allowEstimatedLag: input.signal.allowEstimatedLag }
|
||||
: {}),
|
||||
...(input.signal.source === 'feature'
|
||||
? { featureRef: input.signal.featureRef }
|
||||
: {
|
||||
signalField: input.signal.field,
|
||||
...(input.signal.source === 'fundamentals'
|
||||
? { allowEstimatedLag: input.signal.allowEstimatedLag }
|
||||
: {}),
|
||||
}),
|
||||
horizonSessions: input.horizonSessions,
|
||||
maxSignalAgeSessions: input.maxSignalAgeSessions ?? null,
|
||||
adjustment: input.adjustment,
|
||||
|
|
@ -824,12 +963,13 @@ function validateFactoryOptions(options: AnalyzeSignalToolOptions): number {
|
|||
typeof options.store !== 'object' ||
|
||||
options.store === null ||
|
||||
typeof options.store.bars !== 'function' ||
|
||||
typeof options.store.crossSection !== 'function' ||
|
||||
typeof options.store.shortsAsOf !== 'function' ||
|
||||
typeof options.store.fundamentalsAsOf !== 'function' ||
|
||||
typeof options.store.universe !== 'function'
|
||||
) {
|
||||
throw new MarketDataStoreValidationError(
|
||||
'Invalid `store`: expected a MarketDataStore implementing `bars`, `shortsAsOf`, `fundamentalsAsOf`, and `universe`.',
|
||||
'Invalid `store`: expected a MarketDataStore implementing `bars`, `crossSection`, `shortsAsOf`, `fundamentalsAsOf`, and `universe`.',
|
||||
'store'
|
||||
);
|
||||
}
|
||||
|
|
@ -875,7 +1015,7 @@ export function createAnalyzeSignalTool(options: AnalyzeSignalToolOptions): McpT
|
|||
return defineMcpTool({
|
||||
name: 'analyze_signal',
|
||||
description:
|
||||
'Run a Vault-fenced cross-sectional short-interest or point-in-time fundamentals signal study and record eligible trials to trial_ledger.',
|
||||
'Run a Vault-fenced cross-sectional short-interest, point-in-time fundamentals, or versioned feature signal study and record eligible trials to trial_ledger.',
|
||||
inputSchema: analyzeSignalInputSchema,
|
||||
jsonSchema: ANALYZE_SIGNAL_JSON_SCHEMA,
|
||||
async handler(input: AnalyzeSignalInput): Promise<McpToolCallResult> {
|
||||
|
|
@ -913,11 +1053,16 @@ export function createAnalyzeSignalTool(options: AnalyzeSignalToolOptions): McpT
|
|||
source: 'shorts',
|
||||
field: input.signal.field,
|
||||
}
|
||||
: {
|
||||
source: 'fundamentals',
|
||||
field: input.signal.field,
|
||||
allowEstimatedLag: input.signal.allowEstimatedLag,
|
||||
};
|
||||
: input.signal.source === 'fundamentals'
|
||||
? {
|
||||
source: 'fundamentals',
|
||||
field: input.signal.field,
|
||||
allowEstimatedLag: input.signal.allowEstimatedLag,
|
||||
}
|
||||
: {
|
||||
source: 'feature',
|
||||
featureRef: input.signal.featureRef,
|
||||
};
|
||||
|
||||
const basePayloadFields = {
|
||||
scope: 'vault_fenced' as const,
|
||||
|
|
@ -996,6 +1141,50 @@ export function createAnalyzeSignalTool(options: AnalyzeSignalToolOptions): McpT
|
|||
fenced.vaultCutoffDate
|
||||
);
|
||||
signals = shortsTableToSignalRows(eligibleShortsTable, input.signal.field);
|
||||
} else if (input.signal.source === 'feature') {
|
||||
const { featureRef } = input.signal;
|
||||
const sessionQueries = deriveFeatureSessionQueries(
|
||||
eligibleBars,
|
||||
fenced.asOfMs,
|
||||
vaultCutoffTs,
|
||||
fenced.vaultCutoffDate
|
||||
);
|
||||
if (sessionQueries.length > ANALYZE_SIGNAL_MAX_FEATURE_SESSION_QUERIES) {
|
||||
return {
|
||||
content: [
|
||||
{
|
||||
type: 'text',
|
||||
text: `Invalid arguments for tool "analyze_signal": Feature study exceeds maximum of ${ANALYZE_SIGNAL_MAX_FEATURE_SESSION_QUERIES} session queries.`,
|
||||
},
|
||||
],
|
||||
isError: true,
|
||||
};
|
||||
}
|
||||
|
||||
const featureUniverse: UniverseRef =
|
||||
input.universe ?? (input.universeMarket as UniverseRef);
|
||||
signals = [];
|
||||
const seenKeys = new Set<string>();
|
||||
for (const sessionQuery of sessionQueries) {
|
||||
const sessionQueryAsOfIso =
|
||||
sessionQuery.asOfMs === fenced.asOfMs
|
||||
? fenced.canonicalAsOf
|
||||
: formatUtcIsoWithMicros(sessionQuery.asOfMs, 0);
|
||||
const rawCrossSection = await store.crossSection({
|
||||
features: [featureRef],
|
||||
date: sessionQuery.sessionDate,
|
||||
universe: featureUniverse,
|
||||
asOf: sessionQueryAsOfIso,
|
||||
});
|
||||
appendEligibleFeatureObservations({
|
||||
table: rawCrossSection,
|
||||
featureRef,
|
||||
listingIdSet,
|
||||
sessionQueryAsOfMs: sessionQuery.asOfMs,
|
||||
seenKeys,
|
||||
out: signals,
|
||||
});
|
||||
}
|
||||
} else {
|
||||
const { field: fundamentalsField, allowEstimatedLag } = input.signal;
|
||||
const snapshotDates = deriveMonthlySnapshotDates(eligibleBars);
|
||||
|
|
|
|||
|
|
@ -249,6 +249,10 @@ const SAFE_VALIDATION_FIELDS: ReadonlySet<string> = new Set([
|
|||
'adjustment',
|
||||
'scope',
|
||||
'limit',
|
||||
'countries',
|
||||
'indicators',
|
||||
'features',
|
||||
'universe',
|
||||
]);
|
||||
|
||||
const SAFE_STORE_METHODS: ReadonlySet<string> = new Set([
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue