- Remove ~44k LOC of dead code, legacy v1 TS simulator/strategy stack, event-bus, analytics FastAPI prototype, legacy calculation archives, and unused deps (data-ingestion provider API handlers untouched) - Extract @stock-bot/di/http-security and isolate @stock-bot/browser to data-ingestion via ServiceContainerBuilder.withRegistrations() - Harden @stock-bot/mongodb read-only proxies, flatten @stock-bot/postgres with unified master+research migrations, and fix @stock-bot/config EnvLoader, ServiceApplication worker lifecycle, NamespacedCache.clear(), and BatchProcessor error propagation - Flatten workspace root (remove apps/stock/package.json) and collapse orchestrator re-export shims - Pin all Docker image versions, add shm_size/nofile/RAM caps and docker-compose.quant.yml, fix 05-add-visible-column.sql view recreation, and decouple dev/QA Compose project names for side-by-side execution - Update PLATFORM-PLAN, DATA-CONTRACTS (bars_1m PARTITION BY MONTH, Rust bulk ETL, DuckDB limits), MILESTONES, and servers docs
462 lines
16 KiB
TypeScript
462 lines
16 KiB
TypeScript
import { expect, test } from 'bun:test';
|
|
import { parseFinancialDecimal } from '@stock-bot/types';
|
|
import {
|
|
meanReversionStrategySelectionSchema,
|
|
type MeanReversionSignalParameters,
|
|
type MeanReversionStrategySelection,
|
|
} from '@stock-bot/stock-config/strategy';
|
|
import type {
|
|
StrategyContext,
|
|
StrategyProgram,
|
|
} from '@stock-bot/research/strategy-api';
|
|
import type { PublishedObservation } from '@stock-bot/stock-config/canonical-replay';
|
|
import {
|
|
calculateMeanReversionSignals,
|
|
createMeanReversionStrategy,
|
|
type MeanReversionStrategyState,
|
|
} from '../../apps/stock/orchestrator/src/strategies/canonical-mean-reversion';
|
|
|
|
const d = parseFinancialDecimal;
|
|
function selection(
|
|
parameters: Partial<MeanReversionSignalParameters> = {},
|
|
patch: Partial<MeanReversionStrategySelection> = {}
|
|
) {
|
|
return meanReversionStrategySelectionSchema.parse({
|
|
ownerId: 'A',
|
|
strategyId: 'mean_reversion',
|
|
strategyVersion: 'mean-reversion-regime-long-only/v1',
|
|
seed: 7,
|
|
instrumentId: 'X',
|
|
seriesId: 'X:bar',
|
|
ownerBudget: '80',
|
|
parameters: {
|
|
lookbackPeriod: 2,
|
|
trendPeriod: 3,
|
|
momentumPeriod: 1,
|
|
volatilityPeriod: 2,
|
|
entryZScore: 1,
|
|
exitZScore: 0.2,
|
|
minTrendReturn: -0.9,
|
|
minMomentumReturn: -0.9,
|
|
maxVolatility: 10,
|
|
minNotionalVolume: '0',
|
|
regimeFilter: 'volatility',
|
|
...parameters,
|
|
},
|
|
...patch,
|
|
});
|
|
}
|
|
function observation(
|
|
close: string,
|
|
sequence: number,
|
|
patch: Partial<PublishedObservation> = {}
|
|
): PublishedObservation {
|
|
return {
|
|
series_id: 'X:bar',
|
|
instrument_id: 'X',
|
|
interval_start: sequence,
|
|
interval_end: sequence + 1,
|
|
event_time: sequence + 1,
|
|
available_at: sequence + 1,
|
|
source_sequence: sequence,
|
|
open: d(close),
|
|
high: d(close),
|
|
low: d(close),
|
|
close: d(close),
|
|
volume: d('100'),
|
|
...patch,
|
|
};
|
|
}
|
|
function position(ownerId = 'A', quantity = '2.5', instrumentId = 'X') {
|
|
return {
|
|
ownerId,
|
|
instrumentId,
|
|
quantity: d(quantity),
|
|
remainingCost: d('0'),
|
|
realizedGrossPnl: d('0'),
|
|
};
|
|
}
|
|
function context(
|
|
state: MeanReversionStrategyState,
|
|
observations: PublishedObservation[],
|
|
patch: Partial<StrategyContext<MeanReversionStrategyState>> = {}
|
|
): StrategyContext<MeanReversionStrategyState> {
|
|
const last = observations.at(-1);
|
|
const now = last?.available_at ?? state.lastObservation?.availableAt ?? 0;
|
|
const riskSession = { calendarId: 'test', calendarRevision: '1', sessionId: 'test', startsAt: 0 };
|
|
return {
|
|
ownerId: 'A',
|
|
strategyId: 'mean_reversion',
|
|
strategyVersion: 'mean-reversion-regime-long-only/v1',
|
|
decisionSequence: 0,
|
|
now,
|
|
barrier: {
|
|
barrier_id: 'test',
|
|
at: now,
|
|
revision: 0,
|
|
owner_ids: ['A'],
|
|
observation_count: observations.length,
|
|
inputs: [
|
|
{
|
|
series_id: 'X:bar',
|
|
availability: last
|
|
? { Fresh: { event_time: last.event_time, available_at: last.available_at } }
|
|
: 'Missing',
|
|
},
|
|
],
|
|
},
|
|
portfolio: {
|
|
admissionRevision: 0,
|
|
equity: d('10000'),
|
|
availableCash: d('10000'),
|
|
orders: [],
|
|
reservations: [],
|
|
portfolio: {
|
|
version: 1,
|
|
sessionId: 'test',
|
|
accountId: 'test',
|
|
revision: 0,
|
|
baseCurrency: 'USD',
|
|
reserveOwnerId: 'reserve',
|
|
cash: d('10000'),
|
|
positions: [],
|
|
fees: [],
|
|
riskSession,
|
|
},
|
|
risk: {
|
|
dailyBaseline: d('10000'),
|
|
peakEquity: d('10000'),
|
|
dailyHalted: false,
|
|
drawdownHalted: false,
|
|
riskSession,
|
|
lastEventTime: now,
|
|
},
|
|
},
|
|
positions: [],
|
|
observations,
|
|
previousAdmission: null,
|
|
state,
|
|
random: () => {
|
|
throw new Error('Mean reversion must not consume randomness');
|
|
},
|
|
...patch,
|
|
};
|
|
}
|
|
function decide(
|
|
program: StrategyProgram<MeanReversionStrategyState>,
|
|
closes: string[],
|
|
state = program.initialState,
|
|
offset = 0,
|
|
patch: Partial<StrategyContext<MeanReversionStrategyState>> = {}
|
|
) {
|
|
return program.decide(
|
|
context(
|
|
state,
|
|
closes.map((close, i) => observation(close, offset + i)),
|
|
patch
|
|
)
|
|
);
|
|
}
|
|
const target = (quantity: string) => ({
|
|
mode: 'target' as const,
|
|
targets: [{ instrumentId: 'X', quantity: d(quantity) }],
|
|
});
|
|
const none = { mode: 'target' as const, targets: [] };
|
|
|
|
test('signal_composition_units use population deviation, fractional returns and inclusive volatility regimes', () => {
|
|
const params = selection().parameters;
|
|
const signals = calculateMeanReversionSignals([100, 110, 99], params)!;
|
|
expect(signals.mean).toBe(104.5);
|
|
expect(signals.zScore).toBe(-1);
|
|
expect(signals.trendReturn).toBeCloseTo(104.5 / 103 - 1, 12);
|
|
expect(signals.momentumReturn).toBeCloseTo(-0.1, 12);
|
|
expect(signals.volatility).toBeCloseTo(0.1, 12);
|
|
expect(
|
|
calculateMeanReversionSignals([100, 110, 99], { ...params, maxVolatility: signals.volatility })!
|
|
.regime
|
|
).toBe('low');
|
|
expect(
|
|
calculateMeanReversionSignals([100, 110, 99], {
|
|
...params,
|
|
maxVolatility: signals.volatility - 1e-10,
|
|
})!.regime
|
|
).toBe('high');
|
|
expect(calculateMeanReversionSignals([10, 10, 10], params)).toEqual({
|
|
mean: 10,
|
|
zScore: 0,
|
|
trendReturn: 0,
|
|
momentumReturn: 0,
|
|
volatility: 0,
|
|
regime: 'low',
|
|
});
|
|
for (const close of [0, -1, Number.NaN, Infinity]) {
|
|
expect(() => calculateMeanReversionSignals([10, 10, close], params)).toThrow();
|
|
}
|
|
});
|
|
|
|
test('both ablation modes require identical complete warmup and flat prices create no entry', () => {
|
|
for (const regimeFilter of ['none', 'volatility'] as const) {
|
|
const selected = selection({ momentumPeriod: 4, volatilityPeriod: 6, regimeFilter });
|
|
expect(
|
|
calculateMeanReversionSignals([10, 10, 10, 10, 10, 10], selected.parameters)
|
|
).toBeUndefined();
|
|
expect(
|
|
calculateMeanReversionSignals([10, 10, 10, 10, 10, 10, 10], selected.parameters)
|
|
).toBeDefined();
|
|
const program = createMeanReversionStrategy(selected);
|
|
expect(decide(program, ['10', '10', '10', '10', '10', '8']).intent).toEqual(none);
|
|
expect(decide(program, ['10', '10', '10', '10', '10', '10', '10']).intent).toEqual(none);
|
|
}
|
|
});
|
|
|
|
test('inclusive entry conjunction uses exact notional volume and a fixed whole-share budget', () => {
|
|
const signals = calculateMeanReversionSignals([100, 110, 99], selection().parameters)!;
|
|
const parameters = {
|
|
minTrendReturn: signals.trendReturn,
|
|
minMomentumReturn: signals.momentumReturn,
|
|
maxVolatility: signals.volatility,
|
|
minNotionalVolume: d('198'),
|
|
};
|
|
const run = (overrides: Partial<MeanReversionSignalParameters> = {}) => {
|
|
const program = createMeanReversionStrategy(
|
|
selection({ ...parameters, ...overrides }, { ownerBudget: d('990') })
|
|
);
|
|
return program.decide(
|
|
context(
|
|
program.initialState,
|
|
[100, 110, 99].map((close, i) => observation(String(close), i, { volume: d('2') }))
|
|
)
|
|
);
|
|
};
|
|
expect(run().intent).toEqual(target('10'));
|
|
for (const changed of [
|
|
{ entryZScore: 1.00001 },
|
|
{ minTrendReturn: signals.trendReturn + 1e-6 },
|
|
{ minMomentumReturn: signals.momentumReturn + 1e-6 },
|
|
{ minNotionalVolume: d('198.00000001') },
|
|
{ maxVolatility: signals.volatility - 1e-6 },
|
|
]) {
|
|
expect(run(changed).intent).toEqual(none);
|
|
}
|
|
expect(run({ maxVolatility: 0, regimeFilter: 'none' }).intent).toEqual(target('10'));
|
|
expect(
|
|
run({ maxVolatility: 0, regimeFilter: 'none', minNotionalVolume: d('199') }).intent
|
|
).toEqual(none);
|
|
const poor = createMeanReversionStrategy(selection({}, { ownerBudget: d('7.99') }));
|
|
expect(decide(poor, ['10', '10', '8']).intent).toEqual(target('0'));
|
|
const exact = createMeanReversionStrategy(
|
|
selection(
|
|
{ entryZScore: 0.5, minNotionalVolume: d('900000000.00000003') },
|
|
{ ownerBudget: d('0.0000003') }
|
|
)
|
|
);
|
|
const rows = ['0.00000005', '0.00000005', '0.00000003'].map((close, i) =>
|
|
observation(close, i, { volume: d('30000000000000001') })
|
|
);
|
|
expect(exact.decide(context(exact.initialState, rows)).intent).toEqual(target('10'));
|
|
const insufficient = structuredClone(rows);
|
|
insufficient[2]!.volume = d('30000000000000000');
|
|
expect(exact.decide(context(exact.initialState, insufficient)).intent).toEqual(none);
|
|
});
|
|
|
|
test('only the final fresh prefix can create intent; intermediate entry or exit signals have no phantom effect', () => {
|
|
const program = createMeanReversionStrategy(selection());
|
|
expect(decide(program, ['10', '10', '8', '10']).intent).toEqual(none);
|
|
const entered = decide(program, ['10', '10', '8']);
|
|
expect(entered.intent).toEqual(target('10'));
|
|
// Intermediate 12 would exit, but it was not a decision barrier.
|
|
expect(
|
|
decide(program, ['12', '7'], entered.nextState, 3, { positions: [position('A', '10')] }).intent
|
|
).toEqual(target('10'));
|
|
});
|
|
|
|
test('future suffix changes cannot alter earlier state or decisions; observed gaps do not synthesize history', () => {
|
|
const program = createMeanReversionStrategy(selection());
|
|
const prefix = ['10', '10', '8'];
|
|
const trace = (suffix: string[]) => {
|
|
let state = program.initialState;
|
|
return [...prefix, ...suffix].map((close, index) => {
|
|
const result = decide(program, [close], state, index);
|
|
state = result.nextState;
|
|
return result;
|
|
});
|
|
};
|
|
expect(trace(['7', '10']).slice(0, 3)).toEqual(trace(['700', '0.01']).slice(0, 3));
|
|
const regular = decide(program, prefix);
|
|
const gaps = program.decide(
|
|
context(
|
|
program.initialState,
|
|
prefix.map((close, i) => observation(close, i * 1000))
|
|
)
|
|
);
|
|
expect(gaps.intent).toEqual(regular.intent);
|
|
expect(gaps.nextState.closes).toEqual(regular.nextState.closes);
|
|
});
|
|
|
|
test('stale, missing or mismatched availability only advances history; delayed and duplicate physical bars cannot rewrite it', () => {
|
|
const program = createMeanReversionStrategy(selection());
|
|
const entered = decide(program, ['10', '10', '8']);
|
|
for (const availability of [
|
|
'Missing',
|
|
{ Stale: { event_time: 4, available_at: 4 } },
|
|
{ Fresh: { event_time: 400, available_at: 400 } },
|
|
] as const) {
|
|
const input = context(entered.nextState, [observation('12', 3)]);
|
|
const result = program.decide({
|
|
...input,
|
|
barrier: { ...input.barrier, inputs: [{ series_id: 'X:bar', availability }] },
|
|
});
|
|
expect(result.intent).toEqual(none);
|
|
expect(result.nextState.targetQuantity).toBe(d('10'));
|
|
expect(result.nextState.closes).toEqual([10, 8, 12]);
|
|
}
|
|
const delayed = program.decide(
|
|
context(entered.nextState, [observation('0.01', 1, { available_at: 10 })], { now: 10 })
|
|
);
|
|
expect(delayed.nextState).toEqual(entered.nextState);
|
|
expect(delayed.intent).toEqual(none);
|
|
expect(program.decide(context(entered.nextState, [observation('80', 2)])).nextState).toEqual(
|
|
entered.nextState
|
|
);
|
|
expect(program.decide(context(entered.nextState, [])).intent).toEqual(none);
|
|
for (const row of [
|
|
observation('7', 3, { available_at: 99 }),
|
|
observation('7', 3, { event_time: 99 }),
|
|
observation('7', 3, { instrument_id: 'OTHER' }),
|
|
]) {
|
|
expect(() => program.decide(context(entered.nextState, [row], { now: 4 }))).toThrow();
|
|
}
|
|
});
|
|
|
|
test('entry-only filters cannot block exit or cancel a partially filled exit target', () => {
|
|
const program = createMeanReversionStrategy(
|
|
selection({ maxVolatility: 0.15, minNotionalVolume: d('1') })
|
|
);
|
|
const entered = decide(program, ['10', '10', '8']);
|
|
const exit = program.decide(
|
|
context(entered.nextState, [observation('12', 3, { volume: d('0') })], {
|
|
positions: [position('A', '2.5')],
|
|
})
|
|
);
|
|
expect(exit.intent).toEqual(target('0'));
|
|
const partial = program.decide(
|
|
context(exit.nextState, [observation('1', 4, { volume: d('0') })], {
|
|
positions: [position('A', '1.25')],
|
|
})
|
|
);
|
|
expect(partial.intent).toEqual(target('0'));
|
|
expect(partial.nextState.targetQuantity).toBe(d('0'));
|
|
});
|
|
|
|
test('failed entry gates cancel unfilled remainder permanently; fractional owned exposure does not rebuild on recovery', () => {
|
|
const program = createMeanReversionStrategy(selection({ minNotionalVolume: d('1') }));
|
|
const entered = decide(program, ['10', '10', '8']);
|
|
const rejected = decide(program, ['7'], entered.nextState, 3, {
|
|
previousAdmission: {
|
|
decision: {
|
|
ownerId: 'A',
|
|
decisionId: 'A:0',
|
|
sequence: 0,
|
|
},
|
|
revision: 1,
|
|
orders: [
|
|
{
|
|
orderId: 'denied-entry',
|
|
instrumentId: 'X',
|
|
decision: { ownerId: 'A', decisionId: 'A:0', sequence: 0 },
|
|
status: { Rejected: 'InsufficientCash' },
|
|
},
|
|
],
|
|
},
|
|
});
|
|
expect(rejected.intent).toEqual(target('10'));
|
|
for (const owned of ['0', '2.5']) {
|
|
const clipped = program.decide(
|
|
context(entered.nextState, [observation('7', 3, { volume: d('0') })], {
|
|
positions: owned === '0' ? [] : [position('A', owned)],
|
|
})
|
|
);
|
|
expect(clipped.intent).toEqual(target(owned));
|
|
const recovered = decide(program, ['6'], clipped.nextState, 4, {
|
|
positions: owned === '0' ? [] : [position('A', owned)],
|
|
});
|
|
expect(recovered.intent).toEqual(target(owned === '0' ? '13' : '2.5'));
|
|
}
|
|
});
|
|
|
|
test('trend, momentum, volatility and z-score entry failures also cap pending exposure to actual holdings', () => {
|
|
const cases: {
|
|
parameters: Partial<MeanReversionSignalParameters>;
|
|
prefix: string[];
|
|
next: string;
|
|
}[] = [
|
|
{ parameters: { minTrendReturn: -0.05 }, prefix: ['10', '10', '8'], next: '7' },
|
|
{ parameters: { minMomentumReturn: -0.3 }, prefix: ['10', '10', '8'], next: '4' },
|
|
{ parameters: { maxVolatility: 0.15 }, prefix: ['10', '10', '8'], next: '1' },
|
|
{
|
|
parameters: { lookbackPeriod: 3, trendPeriod: 4 },
|
|
prefix: ['10', '10', '10', '8'],
|
|
next: '7.5',
|
|
},
|
|
];
|
|
for (const { parameters, prefix, next } of cases) {
|
|
const program = createMeanReversionStrategy(selection(parameters));
|
|
const entered = decide(program, prefix);
|
|
expect(entered.intent).toEqual(target('10'));
|
|
expect(
|
|
decide(program, [next], entered.nextState, prefix.length, {
|
|
positions: [position('A', '2.5')],
|
|
}).intent
|
|
).toEqual(target('2.5'));
|
|
}
|
|
});
|
|
|
|
test('owner isolation adopts only existing owned exposure and never pyramids another owner quantity', () => {
|
|
const program = createMeanReversionStrategy(selection({ minNotionalVolume: d('1000000') }));
|
|
expect(
|
|
decide(program, ['10', '10', '8'], program.initialState, 0, {
|
|
positions: [position('B', '99')],
|
|
}).intent
|
|
).toEqual(none);
|
|
expect(
|
|
decide(program, ['10', '10', '8'], program.initialState, 0, {
|
|
positions: [position('B', '99'), position('A', '3.25')],
|
|
}).intent
|
|
).toEqual(target('3.25'));
|
|
expect(
|
|
decide(program, ['10', '8', '10'], program.initialState, 0, {
|
|
positions: [position('A', '3.25')],
|
|
}).intent
|
|
).toEqual(target('0'));
|
|
});
|
|
|
|
test('checkpoint validation and detachment preserve inputs, reject incompatible state, and bound retained history', () => {
|
|
const selected = selection();
|
|
const program = createMeanReversionStrategy(selected);
|
|
selected.parameters.entryZScore = 99;
|
|
const initial = structuredClone(program.initialState);
|
|
const entered = decide(program, ['10', '10', '8']);
|
|
expect(entered.intent).toEqual(target('10'));
|
|
expect(program.initialState).toEqual(initial);
|
|
const restored = JSON.parse(JSON.stringify(entered.nextState)) as MeanReversionStrategyState;
|
|
expect(decide(createMeanReversionStrategy(selection()), ['7'], restored, 3)).toEqual(
|
|
decide(program, ['7'], entered.nextState, 3)
|
|
);
|
|
for (const state of [
|
|
{ ...restored, version: 2 },
|
|
{ ...restored, selectionKey: 'other' },
|
|
{ ...restored, closes: [] },
|
|
{ ...restored, targetQuantity: d('-1') },
|
|
{ ...restored, unknown: true },
|
|
]) {
|
|
expect(() => decide(program, ['7'], state as MeanReversionStrategyState, 3)).toThrow();
|
|
}
|
|
expect(() => program.decide(context(restored, [], { now: 1 }))).toThrow('future');
|
|
const next = decide(program, ['7', '6', '5', '4'], restored, 3);
|
|
expect(next.nextState.closes).toEqual([6, 5, 4]);
|
|
next.nextState.closes[0] = 999;
|
|
expect(restored.closes).toEqual([10, 10, 8]);
|
|
expect(() =>
|
|
decide(createMeanReversionStrategy(selection({}, { ownerId: 'B' })), ['7'], restored, 3)
|
|
).toThrow();
|
|
});
|