T-85: M1.4c — analyzeSignal / runEventStudy study runners in @stock-bot/research: analyzer math + automatic trial_ledger write + cluster N̂-deflated Sharpe (no new dependencies)
This commit is contained in:
parent
9d8dfc9bc8
commit
f130b239fe
2 changed files with 158 additions and 20 deletions
|
|
@ -169,31 +169,53 @@ type NumericTypedArray =
|
|||
| Uint8Array
|
||||
| Uint8ClampedArray;
|
||||
|
||||
const NUMERIC_TYPED_ARRAY_TAGS = new Set<string>([
|
||||
'[object Float64Array]',
|
||||
'[object Float32Array]',
|
||||
'[object Int32Array]',
|
||||
'[object Uint32Array]',
|
||||
'[object Int16Array]',
|
||||
'[object Uint16Array]',
|
||||
'[object Int8Array]',
|
||||
'[object Uint8Array]',
|
||||
'[object Uint8ClampedArray]',
|
||||
]);
|
||||
|
||||
function isNumericTypedArray(value: unknown): value is NumericTypedArray {
|
||||
return (
|
||||
value instanceof Float64Array ||
|
||||
value instanceof Float32Array ||
|
||||
value instanceof Int32Array ||
|
||||
value instanceof Uint32Array ||
|
||||
value instanceof Int16Array ||
|
||||
value instanceof Uint16Array ||
|
||||
value instanceof Int8Array ||
|
||||
value instanceof Uint8Array ||
|
||||
value instanceof Uint8ClampedArray
|
||||
);
|
||||
if (!ArrayBuffer.isView(value)) {
|
||||
return false;
|
||||
}
|
||||
const tag = Object.prototype.toString.call(value);
|
||||
if (!NUMERIC_TYPED_ARRAY_TAGS.has(tag)) {
|
||||
return false;
|
||||
}
|
||||
return typeof (value as { subarray?: unknown }).subarray === 'function';
|
||||
}
|
||||
|
||||
function isSupportedVector(value: unknown): value is readonly unknown[] | NumericTypedArray {
|
||||
return Array.isArray(value) || isNumericTypedArray(value);
|
||||
}
|
||||
|
||||
function isReadonlyMapLike(value: unknown): value is ReadonlyMap<unknown, unknown> {
|
||||
if (typeof value !== 'object' || value === null || Array.isArray(value)) {
|
||||
return false;
|
||||
}
|
||||
const candidate = value as {
|
||||
get?: unknown;
|
||||
has?: unknown;
|
||||
[Symbol.iterator]?: unknown;
|
||||
};
|
||||
return (
|
||||
typeof candidate.get === 'function' &&
|
||||
typeof candidate.has === 'function' &&
|
||||
typeof candidate[Symbol.iterator] === 'function'
|
||||
);
|
||||
}
|
||||
|
||||
function sliceNumericSeries(series: NumericSeries, length: number): NumericSeries {
|
||||
if (series.length === length) {
|
||||
return series;
|
||||
}
|
||||
if (series instanceof Float64Array) {
|
||||
return series.subarray(0, length);
|
||||
}
|
||||
if (Array.isArray(series)) {
|
||||
return series.slice(0, length);
|
||||
}
|
||||
|
|
@ -630,12 +652,9 @@ export async function runEventStudy(
|
|||
|
||||
// Validate return series shapes against the full calendar before slicing to the pre-cutoff
|
||||
// prefix so excluded Vault-tail values (e.g. non-finite returns) never leak into or break
|
||||
// the pre-Vault study.
|
||||
if (
|
||||
typeof entityReturns !== 'object' ||
|
||||
entityReturns === null ||
|
||||
typeof (entityReturns as { [Symbol.iterator]?: unknown })[Symbol.iterator] !== 'function'
|
||||
) {
|
||||
// the pre-Vault study. Require the ReadonlyMap lookup interface (get/has/iterator) so
|
||||
// serialized pair arrays with duplicate keys are rejected rather than coerced into a Map.
|
||||
if (!isReadonlyMapLike(entityReturns)) {
|
||||
throw new SignalStudyError(
|
||||
'invalid_panel',
|
||||
'request.input.entityReturns must be a ReadonlyMap of entityId to return series.'
|
||||
|
|
@ -693,6 +712,12 @@ export async function runEventStudy(
|
|||
);
|
||||
}
|
||||
if (fencedEntityReturns !== null) {
|
||||
if (fencedEntityReturns.has(entityId)) {
|
||||
throw new SignalStudyError(
|
||||
'invalid_panel',
|
||||
`Duplicate entityId "${String(entityId)}" in request.input.entityReturns.`
|
||||
);
|
||||
}
|
||||
fencedEntityReturns.set(
|
||||
entityId,
|
||||
sliceNumericSeries(series as NumericSeries, preCutoffLength)
|
||||
|
|
|
|||
|
|
@ -1,4 +1,5 @@
|
|||
import { describe, expect, it } from 'bun:test';
|
||||
import vm from 'node:vm';
|
||||
import type { EventStudyInput, SignalCrossSection } from '@stock-bot/calculations';
|
||||
import {
|
||||
SignalStudyError,
|
||||
|
|
@ -926,4 +927,116 @@ describe('runEventStudy', () => {
|
|||
const result = await runEventStudy(okStore.executor, frozenReq);
|
||||
expect(result.status).toBe('ok');
|
||||
});
|
||||
|
||||
it('rejects serialized entityReturns pair arrays (including duplicate keys) with invalid_panel and zero queries when calendar spans vaultCutoffDate', async () => {
|
||||
const baseReq = makeEventStudyRequest();
|
||||
const cutoffDate = baseReq.input.sessionDates[baseReq.input.sessionDates.length - 5];
|
||||
expect(cutoffDate).toBeDefined();
|
||||
if (cutoffDate === undefined) {
|
||||
throw new Error('Expected sessionDates to have at least 5 dates');
|
||||
}
|
||||
const vaultSpanningReq = { ...baseReq, vaultCutoffDate: cutoffDate };
|
||||
|
||||
// Confirm the uncorrupted Map request succeeds under this Vault-spanning cutoff.
|
||||
const validStore = createInMemoryTrialExecutor();
|
||||
const validRes = await runEventStudy(validStore.executor, vaultSpanningReq);
|
||||
expect(validRes.status).toBe('ok');
|
||||
|
||||
const existingEntries = Array.from(baseReq.input.entityReturns.entries());
|
||||
const firstEntry = existingEntries[0];
|
||||
expect(firstEntry).toBeDefined();
|
||||
if (!firstEntry) {
|
||||
throw new Error('Expected at least one entityReturns entry');
|
||||
}
|
||||
const [dupEntityId, firstSeries] = firstEntry;
|
||||
const duplicateSeries = Array.from(firstSeries, value => value + 0.05);
|
||||
// Serialized JSON [entityId, series][] pair array with duplicate entityId key.
|
||||
const serializedPairsWithDuplicate = [...existingEntries, [dupEntityId, duplicateSeries]];
|
||||
|
||||
const { executor, calls } = createInMemoryTrialExecutor();
|
||||
await expectStudyError(
|
||||
() =>
|
||||
runEventStudy(executor, {
|
||||
...vaultSpanningReq,
|
||||
input: {
|
||||
...baseReq.input,
|
||||
entityReturns: serializedPairsWithDuplicate as unknown as EventStudyInput['entityReturns'],
|
||||
},
|
||||
}),
|
||||
'invalid_panel'
|
||||
);
|
||||
expect(calls).toHaveLength(0);
|
||||
});
|
||||
|
||||
it('accepts cross-realm typed arrays in both analyzeSignal and runEventStudy (including Vault-trimmed prefixes)', async () => {
|
||||
const toCrossRealmFloat64 = (values: readonly number[]): Float64Array =>
|
||||
vm.runInNewContext('new Float64Array(values)', { values }) as Float64Array;
|
||||
const toCrossRealmInt32 = (values: readonly number[]): Int32Array =>
|
||||
vm.runInNewContext('new Int32Array(values)', { values }) as Int32Array;
|
||||
|
||||
// Confirm the VM-created typed array fails same-realm instanceof.
|
||||
const probeF64 = toCrossRealmFloat64([1, 2]);
|
||||
expect(probeF64 instanceof Float64Array).toBe(false);
|
||||
|
||||
// 1. analyzeSignal with cross-realm Int32Array ids and Float64Array signal/forwardReturn
|
||||
const baseSignalReq = makeSignalRequest();
|
||||
const crossRealmPanel: SignalCrossSection[] = baseSignalReq.panel.map(slice => ({
|
||||
date: slice.date,
|
||||
ids: toCrossRealmInt32(Array.from(slice.ids, id => Number(id))),
|
||||
signal: toCrossRealmFloat64(Array.from(slice.signal)),
|
||||
forwardReturn: toCrossRealmFloat64(Array.from(slice.forwardReturn)),
|
||||
}));
|
||||
|
||||
const baseSignalStore = createInMemoryTrialExecutor();
|
||||
const baseSignalRes = await analyzeSignal(baseSignalStore.executor, baseSignalReq);
|
||||
const crossSignalStore = createInMemoryTrialExecutor();
|
||||
const crossSignalRes = await analyzeSignal(crossSignalStore.executor, {
|
||||
...baseSignalReq,
|
||||
panel: crossRealmPanel,
|
||||
});
|
||||
expect(baseSignalRes.status).toBe('ok');
|
||||
expect(crossSignalRes.status).toBe('ok');
|
||||
if (baseSignalRes.status === 'ok' && crossSignalRes.status === 'ok') {
|
||||
expect(crossSignalRes.trial.expressionHash).toBe(baseSignalRes.trial.expressionHash);
|
||||
expect(crossSignalRes.analysis.rankIcSeries).toEqual(baseSignalRes.analysis.rankIcSeries);
|
||||
}
|
||||
|
||||
// 2. runEventStudy with cross-realm Float64Array returns and a calendar spanning vaultCutoffDate
|
||||
const rawEventReq = makeEventStudyRequest();
|
||||
const cutoffDate = rawEventReq.input.sessionDates[rawEventReq.input.sessionDates.length - 5];
|
||||
expect(cutoffDate).toBeDefined();
|
||||
if (cutoffDate === undefined) {
|
||||
throw new Error('Expected sessionDates to have at least 5 dates');
|
||||
}
|
||||
const baseEventReq: RunEventStudyRequest = { ...rawEventReq, vaultCutoffDate: cutoffDate };
|
||||
const crossRealmEntityReturns = new Map<string | number, Float64Array>();
|
||||
for (const [entityId, series] of baseEventReq.input.entityReturns) {
|
||||
crossRealmEntityReturns.set(entityId, toCrossRealmFloat64(Array.from(series)));
|
||||
}
|
||||
const crossRealmBenchmark =
|
||||
baseEventReq.input.benchmarkReturns !== undefined
|
||||
? toCrossRealmFloat64(Array.from(baseEventReq.input.benchmarkReturns))
|
||||
: undefined;
|
||||
|
||||
const baseEventStore = createInMemoryTrialExecutor();
|
||||
const baseEventRes = await runEventStudy(baseEventStore.executor, baseEventReq);
|
||||
const crossEventStore = createInMemoryTrialExecutor();
|
||||
const crossEventRes = await runEventStudy(crossEventStore.executor, {
|
||||
...baseEventReq,
|
||||
input: {
|
||||
...baseEventReq.input,
|
||||
entityReturns: crossRealmEntityReturns,
|
||||
...(crossRealmBenchmark !== undefined ? { benchmarkReturns: crossRealmBenchmark } : {}),
|
||||
},
|
||||
});
|
||||
expect(baseEventRes.status).toBe('ok');
|
||||
expect(crossEventRes.status).toBe('ok');
|
||||
if (baseEventRes.status === 'ok' && crossEventRes.status === 'ok') {
|
||||
expect(crossEventRes.trial.expressionHash).toBe(baseEventRes.trial.expressionHash);
|
||||
expect(crossEventRes.study.clustered.meanCars).toEqual(
|
||||
baseEventRes.study.clustered.meanCars
|
||||
);
|
||||
expect(crossEventRes.vaultExcludedEvents).toBe(baseEventRes.vaultExcludedEvents);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue