feat(research): inspect scoped stored market data (RP01)
This commit is contained in:
parent
b4ac6460ef
commit
5bfaf37d08
12 changed files with 1592 additions and 3 deletions
|
|
@ -64,6 +64,10 @@
|
|||
"./paper-deployments": {
|
||||
"types": "./dist/contracts/paper-deployments.d.ts",
|
||||
"import": "./dist/contracts/paper-deployments.js"
|
||||
},
|
||||
"./stored-source": {
|
||||
"types": "./dist/contracts/stored-source.d.ts",
|
||||
"default": "./dist/contracts/stored-source.js"
|
||||
}
|
||||
},
|
||||
"scripts": {
|
||||
|
|
|
|||
89
apps/stock/config/src/contracts/stored-source.ts
Normal file
89
apps/stock/config/src/contracts/stored-source.ts
Normal file
|
|
@ -0,0 +1,89 @@
|
|||
/** Read-only source diagnostics. These do not certify a dataset or retain source evidence. */
|
||||
import { z } from 'zod';
|
||||
import { parseInstrumentId } from '@stock-bot/types';
|
||||
|
||||
const count = z.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER);
|
||||
const instant = z.number().int().nonnegative().max(8_640_000_000_000_000);
|
||||
export const storedSourceIntervalSchema = z.enum(['1m', '5m', '1h']);
|
||||
const instrument = z.string().refine(value => {
|
||||
try {
|
||||
return parseInstrumentId(value).id === value;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}, 'Expected a provider instrument identity, for example AAPL.US');
|
||||
export const storedSourceSelectionSchema = z
|
||||
.object({ instrumentId: instrument, interval: storedSourceIntervalSchema })
|
||||
.strict();
|
||||
export type StoredSourceSelection = z.infer<typeof storedSourceSelectionSchema>;
|
||||
export const storedSourceQuerySchema = storedSourceSelectionSchema
|
||||
.extend({
|
||||
start: instant,
|
||||
end: instant,
|
||||
})
|
||||
.strict()
|
||||
.refine(value => value.start < value.end, 'End must be after start');
|
||||
export type StoredSourceQuery = z.infer<typeof storedSourceQuerySchema>;
|
||||
export const storedSourceCoverageSchema = z
|
||||
.object({
|
||||
version: z.literal('stored-eod-coverage/v1'),
|
||||
observedAt: instant,
|
||||
query: storedSourceSelectionSchema,
|
||||
series: z
|
||||
.array(
|
||||
z
|
||||
.object({
|
||||
instrumentId: instrument,
|
||||
interval: storedSourceIntervalSchema,
|
||||
rowCount: count,
|
||||
firstTimestamp: instant.nullable(),
|
||||
lastTimestamp: instant.nullable(),
|
||||
invalidTimestampRows: count,
|
||||
})
|
||||
.strict()
|
||||
)
|
||||
.max(1),
|
||||
})
|
||||
.strict();
|
||||
export type StoredSourceCoverage = z.infer<typeof storedSourceCoverageSchema>;
|
||||
export const storedSourceIssueSchema = z.enum([
|
||||
'identity-mismatch',
|
||||
'invalid-timestamp',
|
||||
'outside-range',
|
||||
'invalid-prices',
|
||||
'null-volume',
|
||||
'invalid-volume',
|
||||
'duplicate-timestamp',
|
||||
]);
|
||||
export const storedSourceInspectionSchema = z
|
||||
.object({
|
||||
version: z.literal('stored-eod-inspection/v1'),
|
||||
observedAt: instant,
|
||||
query: storedSourceQuerySchema,
|
||||
rowCount: count,
|
||||
invalidRows: count,
|
||||
nullVolumeRows: count,
|
||||
duplicateRows: count,
|
||||
firstTimestamp: instant.nullable(),
|
||||
lastTimestamp: instant.nullable(),
|
||||
days: z.array(
|
||||
z
|
||||
.object({
|
||||
date: z.string().regex(/^\d{4}-\d{2}-\d{2}$/),
|
||||
rowCount: count,
|
||||
invalidRows: count,
|
||||
})
|
||||
.strict()
|
||||
),
|
||||
issues: z.array(
|
||||
z
|
||||
.object({
|
||||
code: storedSourceIssueSchema,
|
||||
rowCount: count,
|
||||
timestamps: z.array(instant.nullable()),
|
||||
})
|
||||
.strict()
|
||||
),
|
||||
})
|
||||
.strict();
|
||||
export type StoredSourceInspection = z.infer<typeof storedSourceInspectionSchema>;
|
||||
|
|
@ -14,6 +14,11 @@ import {
|
|||
prepareStoredDataset,
|
||||
StoredDatasetPreparationError,
|
||||
} from '../services/stored-dataset-preparation';
|
||||
import {
|
||||
inspectStoredSource,
|
||||
storedSourceCoverage,
|
||||
StoredSourceInspectionError,
|
||||
} from '../services/stored-source-inspection';
|
||||
|
||||
const logger = getLogger('dataset-catalog-routes');
|
||||
|
||||
|
|
@ -28,6 +33,47 @@ export function createDatasetRoutes(container: IServiceContainer) {
|
|||
throw new DatasetPreparationError(400, 'Invalid JSON request');
|
||||
}
|
||||
};
|
||||
app.get('/api/v2/datasets/stored-eod/coverage', async c => {
|
||||
c.header('Cache-Control', 'no-store');
|
||||
try {
|
||||
return c.json(await storedSourceCoverage(container.mongodb, c.req.query(), c.req.raw.signal));
|
||||
} catch (error) {
|
||||
if (c.req.raw.signal.aborted) {
|
||||
return Response.json(
|
||||
{ error: 'Stored source inspection cancelled' },
|
||||
{ status: 499, headers: { 'Cache-Control': 'no-store' } }
|
||||
);
|
||||
}
|
||||
if (error instanceof StoredSourceInspectionError) {
|
||||
return c.json({ error: error.message }, error.status);
|
||||
}
|
||||
logger.error('Failed to inspect stored source coverage', error);
|
||||
return c.json({ error: 'Stored source coverage unavailable' }, 500);
|
||||
}
|
||||
});
|
||||
app.post('/api/v2/datasets/stored-eod/inspect', async c => {
|
||||
c.header('Cache-Control', 'no-store');
|
||||
try {
|
||||
return c.json(
|
||||
await inspectStoredSource(container.mongodb, await readBody(c.req.raw), c.req.raw.signal)
|
||||
);
|
||||
} catch (error) {
|
||||
if (c.req.raw.signal.aborted) {
|
||||
return Response.json(
|
||||
{ error: 'Stored source inspection cancelled' },
|
||||
{ status: 499, headers: { 'Cache-Control': 'no-store' } }
|
||||
);
|
||||
}
|
||||
if (
|
||||
error instanceof StoredSourceInspectionError ||
|
||||
error instanceof DatasetPreparationError
|
||||
) {
|
||||
return c.json({ error: error.message }, error.status);
|
||||
}
|
||||
logger.error('Failed to inspect stored source quality', error);
|
||||
return c.json({ error: 'Stored source inspection unavailable' }, 500);
|
||||
}
|
||||
});
|
||||
app.post('/api/v2/datasets/canonical/stored-source', async c => {
|
||||
c.header('Cache-Control', 'no-store');
|
||||
try {
|
||||
|
|
|
|||
269
apps/stock/web-api/src/services/stored-source-inspection.ts
Normal file
269
apps/stock/web-api/src/services/stored-source-inspection.ts
Normal file
|
|
@ -0,0 +1,269 @@
|
|||
import type { MongoDBClient } from '@stock-bot/services';
|
||||
import {
|
||||
storedSourceCoverageSchema,
|
||||
storedSourceInspectionSchema,
|
||||
storedSourceQuerySchema,
|
||||
storedSourceSelectionSchema,
|
||||
type StoredSourceCoverage,
|
||||
type StoredSourceInspection,
|
||||
} from '@stock-bot/stock-config/stored-source';
|
||||
import { parseInstrumentId } from '@stock-bot/types';
|
||||
import {
|
||||
PREPARATION_BATCH_SIZE,
|
||||
preparationCheckpoint,
|
||||
} from '../../../orchestrator/src/data/preparation';
|
||||
|
||||
const collections = {
|
||||
'1m': 'eodIntraday1M',
|
||||
'5m': 'eodIntraday5M',
|
||||
'1h': 'eodIntraday1H',
|
||||
} as const;
|
||||
type Store = Pick<MongoDBClient, 'find' | 'aggregate'>;
|
||||
type Row = Record<string, unknown>;
|
||||
type Code = StoredSourceInspection['issues'][number]['code'];
|
||||
export class StoredSourceInspectionError extends Error {
|
||||
constructor(
|
||||
readonly status: 400 | 503,
|
||||
message: string
|
||||
) {
|
||||
super(message);
|
||||
}
|
||||
}
|
||||
function required(store: Store | null | undefined): Store {
|
||||
if (!store) {
|
||||
throw new StoredSourceInspectionError(503, 'Stored EOD data is unavailable');
|
||||
}
|
||||
return store;
|
||||
}
|
||||
function timestamp(value: unknown): number | null {
|
||||
return typeof value === 'number' &&
|
||||
Number.isSafeInteger(value) &&
|
||||
value >= 0 &&
|
||||
Number.isSafeInteger(value * 1000) &&
|
||||
Number.isFinite(new Date(value * 1000).getTime())
|
||||
? value * 1000
|
||||
: null;
|
||||
}
|
||||
|
||||
/** Inspect one indexed source series; first/last rows do not establish complete sessions. */
|
||||
export async function storedSourceCoverage(
|
||||
store: Store | null | undefined,
|
||||
input: unknown,
|
||||
signal: AbortSignal
|
||||
): Promise<StoredSourceCoverage> {
|
||||
signal.throwIfAborted();
|
||||
const parsed = storedSourceSelectionSchema.safeParse(input);
|
||||
if (!parsed.success) {
|
||||
throw new StoredSourceInspectionError(
|
||||
400,
|
||||
'Select one qualified instrument and supported timeframe'
|
||||
);
|
||||
}
|
||||
const query = parsed.data;
|
||||
const groups = await required(store).aggregate<Row>(collections[query.interval], [
|
||||
{ $match: { eodSearchCode: query.instrumentId } },
|
||||
{
|
||||
$project: {
|
||||
_id: 0,
|
||||
validTimestamp: {
|
||||
$cond: [
|
||||
// Decimal128 remains an object in the JS reader. Only these BSON types
|
||||
// can become its finite integer Unix-seconds number.
|
||||
{ $in: [{ $type: '$timestamp' }, ['double', 'int', 'long']] },
|
||||
{
|
||||
$cond: [
|
||||
{
|
||||
$and: [
|
||||
{ $gte: ['$timestamp', 0] },
|
||||
{ $lte: ['$timestamp', 8_640_000_000_000] },
|
||||
{ $eq: ['$timestamp', { $trunc: '$timestamp' }] },
|
||||
],
|
||||
},
|
||||
'$timestamp',
|
||||
null,
|
||||
],
|
||||
},
|
||||
null,
|
||||
],
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
$group: {
|
||||
_id: null,
|
||||
rowCount: { $sum: 1 },
|
||||
firstTimestamp: { $min: '$validTimestamp' },
|
||||
lastTimestamp: { $max: '$validTimestamp' },
|
||||
invalidTimestampRows: { $sum: { $cond: [{ $eq: ['$validTimestamp', null] }, 1, 0] } },
|
||||
},
|
||||
},
|
||||
]);
|
||||
signal.throwIfAborted();
|
||||
const series = groups.map(group => {
|
||||
if (
|
||||
!Number.isSafeInteger(group.rowCount) ||
|
||||
Number(group.rowCount) < 0 ||
|
||||
!Number.isSafeInteger(group.invalidTimestampRows) ||
|
||||
Number(group.invalidTimestampRows) < 0 ||
|
||||
Number(group.invalidTimestampRows) > Number(group.rowCount)
|
||||
) {
|
||||
throw new Error('Invalid stored source coverage');
|
||||
}
|
||||
return {
|
||||
...query,
|
||||
rowCount: Number(group.rowCount),
|
||||
firstTimestamp: timestamp(group.firstTimestamp),
|
||||
lastTimestamp: timestamp(group.lastTimestamp),
|
||||
invalidTimestampRows: Number(group.invalidTimestampRows),
|
||||
};
|
||||
});
|
||||
return storedSourceCoverageSchema.parse({
|
||||
version: 'stored-eod-coverage/v1',
|
||||
observedAt: Date.now(),
|
||||
query,
|
||||
series,
|
||||
});
|
||||
}
|
||||
|
||||
/** Explain raw field problems without changing rows or making financial eligibility decisions. */
|
||||
export async function inspectStoredSource(
|
||||
store: Store | null | undefined,
|
||||
input: unknown,
|
||||
signal: AbortSignal
|
||||
): Promise<StoredSourceInspection> {
|
||||
signal.throwIfAborted();
|
||||
const parsed = storedSourceQuerySchema.safeParse(input);
|
||||
if (!parsed.success) {
|
||||
throw new StoredSourceInspectionError(
|
||||
400,
|
||||
'Select an instrument, supported timeframe and valid UTC start/end range'
|
||||
);
|
||||
}
|
||||
const query = parsed.data;
|
||||
const identity = parseInstrumentId(query.instrumentId);
|
||||
const rows = await required(store).find<Row>(
|
||||
collections[query.interval],
|
||||
{
|
||||
eodSearchCode: identity.id,
|
||||
timestamp: { $gte: query.start / 1000, $lt: query.end / 1000 },
|
||||
},
|
||||
{
|
||||
sort: { timestamp: 1 },
|
||||
projection: {
|
||||
_id: 0,
|
||||
eodSearchCode: 1,
|
||||
symbol: 1,
|
||||
exchange: 1,
|
||||
timestamp: 1,
|
||||
open: 1,
|
||||
high: 1,
|
||||
low: 1,
|
||||
close: 1,
|
||||
volume: 1,
|
||||
},
|
||||
}
|
||||
);
|
||||
signal.throwIfAborted();
|
||||
const bad = new Set<number>();
|
||||
const issues = new Map<Code, { rowCount: number; timestamps: Array<number | null> }>();
|
||||
const byTimestamp = new Map<number, number[]>();
|
||||
const instants: Array<number | null> = [];
|
||||
const issue = (code: Code, index: number, at: number | null) => {
|
||||
bad.add(index);
|
||||
const existing = issues.get(code) ?? { rowCount: 0, timestamps: [] };
|
||||
existing.rowCount++;
|
||||
existing.timestamps.push(at);
|
||||
issues.set(code, existing);
|
||||
};
|
||||
const numeric = (value: unknown) =>
|
||||
typeof value === 'number'
|
||||
? value
|
||||
: typeof value === 'string' && value.trim()
|
||||
? Number(value)
|
||||
: NaN;
|
||||
let nullVolumeRows = 0;
|
||||
for (const [index, row] of rows.entries()) {
|
||||
const at = timestamp(row.timestamp);
|
||||
instants.push(at);
|
||||
if (
|
||||
row.eodSearchCode !== identity.id ||
|
||||
row.symbol !== identity.symbol ||
|
||||
row.exchange !== identity.exchange
|
||||
) {
|
||||
issue('identity-mismatch', index, at);
|
||||
}
|
||||
if (at === null) {
|
||||
issue('invalid-timestamp', index, at);
|
||||
} else {
|
||||
if (at < query.start || at >= query.end) {
|
||||
issue('outside-range', index, at);
|
||||
}
|
||||
const same = byTimestamp.get(at) ?? [];
|
||||
same.push(index);
|
||||
byTimestamp.set(at, same);
|
||||
}
|
||||
const open = numeric(row.open);
|
||||
const high = numeric(row.high);
|
||||
const low = numeric(row.low);
|
||||
const close = numeric(row.close);
|
||||
if (
|
||||
![open, high, low, close].every(
|
||||
value => typeof value === 'number' && Number.isFinite(value) && value > 0
|
||||
) ||
|
||||
high < Math.max(open, close) ||
|
||||
low > Math.min(open, close)
|
||||
) {
|
||||
issue('invalid-prices', index, at);
|
||||
}
|
||||
if (row.volume === null || row.volume === undefined) {
|
||||
nullVolumeRows++;
|
||||
issue('null-volume', index, at);
|
||||
} else if (!Number.isFinite(numeric(row.volume)) || numeric(row.volume) < 0) {
|
||||
issue('invalid-volume', index, at);
|
||||
}
|
||||
if ((index + 1) % PREPARATION_BATCH_SIZE === 0) {
|
||||
await preparationCheckpoint(signal);
|
||||
}
|
||||
}
|
||||
let duplicateRows = 0;
|
||||
for (const [at, indices] of byTimestamp) {
|
||||
if (indices.length > 1) {
|
||||
duplicateRows += indices.length - 1;
|
||||
for (const index of indices) {
|
||||
issue('duplicate-timestamp', index, at);
|
||||
}
|
||||
}
|
||||
}
|
||||
const days = new Map<string, { date: string; rowCount: number; invalidRows: number }>();
|
||||
let firstTimestamp: number | null = null,
|
||||
lastTimestamp: number | null = null;
|
||||
for (let index = 0; index < instants.length; index++) {
|
||||
const at = instants[index];
|
||||
if (at === null || at === undefined) {
|
||||
continue;
|
||||
}
|
||||
firstTimestamp = firstTimestamp === null ? at : Math.min(firstTimestamp, at);
|
||||
lastTimestamp = lastTimestamp === null ? at : Math.max(lastTimestamp, at);
|
||||
const date = new Date(at).toISOString().slice(0, 10);
|
||||
const day = days.get(date) ?? { date, rowCount: 0, invalidRows: 0 };
|
||||
day.rowCount++;
|
||||
if (bad.has(index)) {
|
||||
day.invalidRows++;
|
||||
}
|
||||
days.set(date, day);
|
||||
}
|
||||
signal.throwIfAborted();
|
||||
return storedSourceInspectionSchema.parse({
|
||||
version: 'stored-eod-inspection/v1',
|
||||
observedAt: Date.now(),
|
||||
query,
|
||||
rowCount: rows.length,
|
||||
invalidRows: bad.size,
|
||||
nullVolumeRows,
|
||||
duplicateRows,
|
||||
firstTimestamp,
|
||||
lastTimestamp,
|
||||
days: [...days.values()].sort((a, b) => a.date.localeCompare(b.date)),
|
||||
issues: [...issues].map(([code, detail]) => ({ code, ...detail })),
|
||||
});
|
||||
}
|
||||
|
|
@ -3,6 +3,7 @@ import type { CanonicalDatasetPreparation } from '@stock-bot/stock-config/canoni
|
|||
import { canonicalStrategyJson } from '@stock-bot/stock-config/strategy';
|
||||
import { actionClass, fieldClass } from '@/features/strategies/components/StrategyParameterForm';
|
||||
import { backtestApiV2, DatasetPreparationRequestError } from '../services/backtestApiV2';
|
||||
import { StoredSourceInspector } from './StoredSourceInspector';
|
||||
|
||||
export interface DatasetPreparationState {
|
||||
busy: boolean;
|
||||
|
|
@ -268,6 +269,9 @@ export function DatasetPreparation({ disabled, begin, onStateChange, onRetained
|
|||
uses that captured snapshot without querying storage again.
|
||||
</p>
|
||||
)}
|
||||
{mode === 'stored-eod' && (
|
||||
<StoredSourceInspector disabled={disabled || Boolean(intent) || Boolean(phase)} />
|
||||
)}
|
||||
<label className="block">
|
||||
{mode === 'export' ? 'Source dataset JSON' : 'Source metadata JSON'}
|
||||
<input
|
||||
|
|
|
|||
|
|
@ -0,0 +1,364 @@
|
|||
import { useEffect, useRef, useState } from 'react';
|
||||
import type {
|
||||
StoredSourceCoverage,
|
||||
StoredSourceInspection,
|
||||
StoredSourceQuery,
|
||||
} from '@stock-bot/stock-config/stored-source';
|
||||
import { actionClass, fieldClass } from '@/features/strategies/components/StrategyParameterForm';
|
||||
import { storedSourceApi } from '../services/storedSourceApi';
|
||||
|
||||
const instant = (value: number | null) =>
|
||||
value === null ? 'Unavailable' : new Date(value).toISOString();
|
||||
const inputTime = (value: number | null) =>
|
||||
value === null ? '' : new Date(value).toISOString().slice(0, 19);
|
||||
const labels: Record<StoredSourceInspection['issues'][number]['code'], string> = {
|
||||
'identity-mismatch': 'Instrument identity mismatch',
|
||||
'invalid-timestamp': 'Invalid Unix-seconds timestamp',
|
||||
'outside-range': 'Returned outside the selected window',
|
||||
'invalid-prices': 'Invalid OHLC prices',
|
||||
'null-volume': 'Missing or null volume',
|
||||
'invalid-volume': 'Invalid volume',
|
||||
'duplicate-timestamp': 'Duplicate timestamp',
|
||||
};
|
||||
|
||||
/** Read-only diagnostics have their own request lifetime, never a dataset retention receipt. */
|
||||
export function StoredSourceInspector({ disabled }: { disabled: boolean }) {
|
||||
const [coverage, setCoverage] = useState<StoredSourceCoverage | null>(null);
|
||||
const [result, setResult] = useState<StoredSourceInspection | null>(null);
|
||||
const [draft, setDraft] = useState({
|
||||
instrumentId: '',
|
||||
interval: '5m' as StoredSourceQuery['interval'],
|
||||
start: '',
|
||||
end: '',
|
||||
});
|
||||
const [phase, setPhase] = useState<'coverage' | 'inspection' | null>(null);
|
||||
const [error, setError] = useState('');
|
||||
const current = useRef(draft);
|
||||
const generation = useRef(0),
|
||||
active = useRef(false),
|
||||
abort = useRef<AbortController | null>(null);
|
||||
useEffect(() => {
|
||||
active.current = true;
|
||||
return () => {
|
||||
active.current = false;
|
||||
generation.current++;
|
||||
abort.current?.abort();
|
||||
};
|
||||
}, []);
|
||||
const cancel = () => {
|
||||
generation.current++;
|
||||
abort.current?.abort();
|
||||
abort.current = null;
|
||||
setPhase(null);
|
||||
};
|
||||
const change = (next: typeof draft) => {
|
||||
if (disabled) {
|
||||
return;
|
||||
}
|
||||
cancel();
|
||||
if (
|
||||
next.instrumentId !== current.current.instrumentId ||
|
||||
next.interval !== current.current.interval
|
||||
) {
|
||||
setCoverage(null);
|
||||
}
|
||||
current.current = next;
|
||||
setDraft(next);
|
||||
setResult(null);
|
||||
setError('');
|
||||
};
|
||||
const run = async (kind: 'coverage' | 'inspection') => {
|
||||
if (disabled) {
|
||||
return;
|
||||
}
|
||||
const selected = { ...current.current };
|
||||
cancel();
|
||||
const revision = generation.current;
|
||||
const controller = new AbortController();
|
||||
abort.current = controller;
|
||||
setPhase(kind);
|
||||
setError('');
|
||||
if (kind === 'inspection') {
|
||||
setResult(null);
|
||||
} else {
|
||||
setCoverage(null);
|
||||
}
|
||||
try {
|
||||
if (kind === 'coverage') {
|
||||
const value = await storedSourceApi.coverage(
|
||||
{ instrumentId: selected.instrumentId, interval: selected.interval },
|
||||
controller.signal
|
||||
);
|
||||
if (active.current && generation.current === revision) {
|
||||
setCoverage(value);
|
||||
}
|
||||
} else {
|
||||
if (!selected.start || !selected.end) {
|
||||
throw new Error('Select UTC start and end times');
|
||||
}
|
||||
const value = await storedSourceApi.inspect(
|
||||
{
|
||||
instrumentId: selected.instrumentId,
|
||||
interval: selected.interval,
|
||||
start: Date.parse(`${selected.start}Z`),
|
||||
end: Date.parse(`${selected.end}Z`),
|
||||
},
|
||||
controller.signal
|
||||
);
|
||||
if (active.current && generation.current === revision) {
|
||||
setResult(value);
|
||||
}
|
||||
}
|
||||
} catch (cause) {
|
||||
if (active.current && generation.current === revision && !controller.signal.aborted) {
|
||||
setError(cause instanceof Error ? cause.message : 'Source inspection failed');
|
||||
}
|
||||
} finally {
|
||||
if (active.current && generation.current === revision) {
|
||||
abort.current = null;
|
||||
setPhase(null);
|
||||
}
|
||||
}
|
||||
};
|
||||
return (
|
||||
<section
|
||||
aria-label="Stored source inspection"
|
||||
className="space-y-3 rounded border p-3"
|
||||
onChange={event => event.stopPropagation()}
|
||||
onKeyDown={event => {
|
||||
if (event.key === 'Enter' && (event.target as HTMLElement).tagName === 'INPUT') {
|
||||
event.preventDefault();
|
||||
}
|
||||
}}
|
||||
>
|
||||
<p>
|
||||
Choose one qualified instrument and timeframe to inspect its stored coverage and field
|
||||
problems. Coverage examines only that series. First and last bars do not establish complete
|
||||
sessions. Unlocatable timestamps are counted in coverage; window diagnostics inspect rows
|
||||
returned by the time query. These diagnostics do not retain data or establish trading
|
||||
eligibility.
|
||||
</p>
|
||||
<div className="grid gap-2 sm:grid-cols-2">
|
||||
<label>
|
||||
Instrument
|
||||
<input
|
||||
className={fieldClass}
|
||||
aria-label="Inspect instrument"
|
||||
value={draft.instrumentId}
|
||||
disabled={disabled}
|
||||
onChange={event => change({ ...current.current, instrumentId: event.target.value })}
|
||||
placeholder="AAPL.US"
|
||||
/>
|
||||
</label>
|
||||
<label>
|
||||
Timeframe
|
||||
<select
|
||||
className={fieldClass}
|
||||
aria-label="Inspect timeframe"
|
||||
value={draft.interval}
|
||||
disabled={disabled}
|
||||
onChange={event =>
|
||||
change({
|
||||
...current.current,
|
||||
interval: event.target.value as StoredSourceQuery['interval'],
|
||||
})
|
||||
}
|
||||
>
|
||||
{['1m', '5m', '1h'].map(value => (
|
||||
<option key={value}>{value}</option>
|
||||
))}
|
||||
</select>
|
||||
</label>
|
||||
</div>
|
||||
<button
|
||||
type="button"
|
||||
className={actionClass}
|
||||
disabled={disabled || phase !== null || !draft.instrumentId}
|
||||
onClick={() => void run('coverage')}
|
||||
>
|
||||
Load selected coverage
|
||||
</button>
|
||||
{coverage && (
|
||||
<>
|
||||
{coverage.series.length === 0 ? (
|
||||
<p>
|
||||
No stored bars found for {coverage.query.instrumentId} {coverage.query.interval}.
|
||||
</p>
|
||||
) : (
|
||||
<div className="overflow-x-auto">
|
||||
<table className="w-full text-left">
|
||||
<caption>Stored bar coverage (UTC)</caption>
|
||||
<thead>
|
||||
<tr>
|
||||
<th>Instrument</th>
|
||||
<th>Timeframe</th>
|
||||
<th>Rows</th>
|
||||
<th>First bar</th>
|
||||
<th>Last bar</th>
|
||||
<th>Invalid timestamps</th>
|
||||
<th>Window</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{coverage.series.map(item => (
|
||||
<tr key={`${item.instrumentId}:${item.interval}`}>
|
||||
<td>{item.instrumentId}</td>
|
||||
<td>{item.interval}</td>
|
||||
<td>{item.rowCount}</td>
|
||||
<td>{instant(item.firstTimestamp)}</td>
|
||||
<td>{instant(item.lastTimestamp)}</td>
|
||||
<td>{item.invalidTimestampRows}</td>
|
||||
<td>
|
||||
<button
|
||||
type="button"
|
||||
className={actionClass}
|
||||
disabled={disabled}
|
||||
onClick={() =>
|
||||
change({
|
||||
instrumentId: item.instrumentId,
|
||||
interval: item.interval,
|
||||
start: inputTime(item.firstTimestamp),
|
||||
end: inputTime(
|
||||
item.lastTimestamp === null
|
||||
? null
|
||||
: Math.min(
|
||||
8_640_000_000_000_000,
|
||||
item.lastTimestamp +
|
||||
{ '1m': 60000, '5m': 300000, '1h': 3600000 }[item.interval]
|
||||
)
|
||||
),
|
||||
})
|
||||
}
|
||||
>
|
||||
Use coverage dates
|
||||
</button>
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
<div className="grid gap-2 sm:grid-cols-2">
|
||||
<label>
|
||||
Start UTC (inclusive)
|
||||
<input
|
||||
type="datetime-local"
|
||||
step="1"
|
||||
className={fieldClass}
|
||||
aria-label="Inspect start UTC"
|
||||
value={draft.start}
|
||||
disabled={disabled}
|
||||
onChange={event => change({ ...current.current, start: event.target.value })}
|
||||
/>
|
||||
</label>
|
||||
<label>
|
||||
End UTC (exclusive)
|
||||
<input
|
||||
type="datetime-local"
|
||||
step="1"
|
||||
className={fieldClass}
|
||||
aria-label="Inspect end UTC"
|
||||
value={draft.end}
|
||||
disabled={disabled}
|
||||
onChange={event => change({ ...current.current, end: event.target.value })}
|
||||
/>
|
||||
</label>
|
||||
</div>
|
||||
<div className="flex gap-2">
|
||||
<button
|
||||
type="button"
|
||||
className={actionClass}
|
||||
disabled={disabled || phase !== null}
|
||||
onClick={() => void run('inspection')}
|
||||
>
|
||||
Inspect source window
|
||||
</button>
|
||||
{phase && (
|
||||
<button type="button" className={actionClass} onClick={cancel}>
|
||||
Cancel inspection
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
{phase && (
|
||||
<p role="status">
|
||||
{phase === 'coverage' ? 'Loading stored coverage...' : 'Inspecting source window...'}
|
||||
</p>
|
||||
)}
|
||||
{error && <p role="alert">{error}</p>}
|
||||
{result && (
|
||||
<div className="space-y-2" aria-label="Source inspection result">
|
||||
<p>
|
||||
{result.query.instrumentId} · {result.query.interval} · {instant(result.query.start)} to{' '}
|
||||
{instant(result.query.end)} (exclusive)
|
||||
</p>
|
||||
{result.rowCount === 0 ? (
|
||||
<p>No stored bars in this window.</p>
|
||||
) : (
|
||||
<>
|
||||
<p>
|
||||
{result.rowCount} rows · {result.invalidRows} rows with detected problems ·{' '}
|
||||
{result.nullVolumeRows} missing/null volumes · {result.duplicateRows} extra rows at
|
||||
duplicate timestamps
|
||||
</p>
|
||||
<p>
|
||||
First bar: {instant(result.firstTimestamp)} · Last bar:{' '}
|
||||
{instant(result.lastTimestamp)}
|
||||
</p>
|
||||
{result.issues.length === 0 ? (
|
||||
<p>
|
||||
No listed field problems detected. Calendar, availability, corporate actions and
|
||||
full dataset validation are still required.
|
||||
</p>
|
||||
) : (
|
||||
<ul>
|
||||
{result.issues.map(issue => (
|
||||
<li key={issue.code}>
|
||||
<details>
|
||||
<summary>
|
||||
{labels[issue.code]}: {issue.rowCount} rows
|
||||
</summary>
|
||||
<ul>
|
||||
{issue.timestamps.map((at, index) => (
|
||||
<li key={index}>{instant(at)}</li>
|
||||
))}
|
||||
</ul>
|
||||
</details>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
)}
|
||||
<details>
|
||||
<summary>Rows by UTC date</summary>
|
||||
<table>
|
||||
<thead>
|
||||
<tr>
|
||||
<th>Date</th>
|
||||
<th>Rows</th>
|
||||
<th>Rows with problems</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{result.days.map(day => (
|
||||
<tr key={day.date}>
|
||||
<td>{day.date}</td>
|
||||
<td>{day.rowCount}</td>
|
||||
<td>{day.invalidRows}</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</details>
|
||||
</>
|
||||
)}
|
||||
<p>
|
||||
No rows were changed or excluded. Use reviewed source metadata with the existing preview
|
||||
below.
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
|
@ -0,0 +1,60 @@
|
|||
import {
|
||||
storedSourceCoverageSchema,
|
||||
storedSourceInspectionSchema,
|
||||
storedSourceQuerySchema,
|
||||
storedSourceSelectionSchema,
|
||||
type StoredSourceQuery,
|
||||
type StoredSourceSelection,
|
||||
} from '@stock-bot/stock-config/stored-source';
|
||||
import { API_BASE_URL, apiFetch } from '@/lib/api';
|
||||
|
||||
async function read(path: string, init: RequestInit): Promise<unknown> {
|
||||
const response = await apiFetch(`${API_BASE_URL}/api/v2/datasets/stored-eod/${path}`, init);
|
||||
const body: unknown = await response.json().catch(error => {
|
||||
if (init.signal?.aborted) {
|
||||
throw error;
|
||||
}
|
||||
return null;
|
||||
});
|
||||
init.signal?.throwIfAborted();
|
||||
if (!response.ok) {
|
||||
throw new Error(
|
||||
body && typeof body === 'object' && 'error' in body && typeof body.error === 'string'
|
||||
? body.error
|
||||
: `Source inspection failed (${response.status})`
|
||||
);
|
||||
}
|
||||
return body;
|
||||
}
|
||||
export const storedSourceApi = {
|
||||
async coverage(input: StoredSourceSelection, signal: AbortSignal) {
|
||||
const query = storedSourceSelectionSchema.parse(input);
|
||||
const result = storedSourceCoverageSchema.parse(
|
||||
await read(`coverage?${new URLSearchParams(query)}`, { signal })
|
||||
);
|
||||
if (
|
||||
JSON.stringify(result.query) !== JSON.stringify(query) ||
|
||||
result.series.some(
|
||||
item => item.instrumentId !== query.instrumentId || item.interval !== query.interval
|
||||
)
|
||||
) {
|
||||
throw new Error('Source coverage differs from the selected instrument and timeframe');
|
||||
}
|
||||
return result;
|
||||
},
|
||||
async inspect(input: StoredSourceQuery, signal: AbortSignal) {
|
||||
const query = storedSourceQuerySchema.parse(input);
|
||||
const result = storedSourceInspectionSchema.parse(
|
||||
await read('inspect', {
|
||||
method: 'POST',
|
||||
signal,
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(query),
|
||||
})
|
||||
);
|
||||
if (JSON.stringify(result.query) !== JSON.stringify(query)) {
|
||||
throw new Error('Source inspection differs from the selected window');
|
||||
}
|
||||
return result;
|
||||
},
|
||||
};
|
||||
Loading…
Add table
Add a link
Reference in a new issue