stock-bot/test/integration/canonical-regime-research.test.ts
Boki 4cd6038063 refactor: pre-M0 cleanup, core library hardening, and isolated dev/QA Docker stack
- 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
2026-11-27 00:11:50 -05:00

417 lines
16 KiB
TypeScript

import { createHash } from 'node:crypto';
import { expect, test } from 'bun:test';
import { parseFinancialDecimal, type FinancialStrategyIntent } from '@stock-bot/types';
import { prepareReplayLoad } from '../../apps/stock/orchestrator/src/backtest/native-replay';
import { NativeBacktestWorker } from '../../apps/stock/orchestrator/src/backtest/NativeBacktestWorker';
import { runStrategyReplay } from '../../apps/stock/orchestrator/src/backtest/strategy-runtime';
import { smaStrategySelectionSchema } from '@stock-bot/stock-config/strategy';
import type {
StrategyContext,
StrategyProgram,
} from '@stock-bot/research/strategy-api';
import type {
ReplayProjectionResult,
ReplayReportResult,
} from '@stock-bot/stock-config/canonical-replay';
import {
parseStrategyReplayResult,
strategyReplayRequestSchema,
} from '../../apps/stock/orchestrator/src/contracts/strategy-replay';
import {
createBuiltinStrategy,
validateBuiltinStrategyBindings,
} from '../../apps/stock/orchestrator/src/strategies/canonical-builtins';
import {
canonicalRegimeResearchFixture,
canonicalRegimeSelection,
} from '../fixtures/canonical-regime-research';
const d = parseFinancialDecimal;
type Fixture = ReturnType<typeof canonicalRegimeResearchFixture>;
type DecisionRecord = {
ownerId: string;
at: number;
sequence: number;
observed: { eventTime: number; availableAt: number; close: string }[];
positions: StrategyContext['positions'];
portfolio: StrategyContext['portfolio'];
state: unknown;
intent: FinancialStrategyIntent;
};
function run(fixture: Fixture, eventBudget = 1) {
const load = prepareReplayLoad(fixture.dataset, fixture.config);
validateBuiltinStrategyBindings(fixture.selections, load);
const records: DecisionRecord[] = [];
const programs = fixture.selections.map(selection => {
const strategy = createBuiltinStrategy(selection);
return {
...strategy,
decide(context: StrategyContext) {
const output = strategy.decide(context);
records.push({
ownerId: context.ownerId,
at: context.now,
sequence: context.decisionSequence,
observed: context.observations.map(row => ({
eventTime: row.event_time,
availableAt: row.available_at,
close: row.close,
})),
positions: context.positions,
portfolio: context.portfolio,
state: structuredClone(output.nextState),
intent: structuredClone(output.intent),
});
return output;
},
} satisfies StrategyProgram;
});
return {
...runStrategyReplay(load, programs, { resultFormat: 'report', eventBudget }),
records,
};
}
function economicHash(result: ReplayProjectionResult | ReplayReportResult): string {
return createHash('sha256')
.update(JSON.stringify({ projection: result.projection, view: result.view }))
.digest('hex');
}
function target(record: DecisionRecord) {
return record.intent.mode === 'target' ? record.intent.targets[0]?.quantity : undefined;
}
test('MR hand oracle buys and exits at next opens with authoritative basis, commissions and terminal equity', () => {
const fixture = canonicalRegimeResearchFixture();
const result = run(fixture);
expect(
result.records.filter(row => row.at < fixture.start + 3 * fixture.minute).map(target)
).toEqual([undefined, undefined]);
expect(target(result.records.find(row => row.at === fixture.start + 3 * fixture.minute)!)).toBe(
d('10')
);
expect(
result.result.projection.fills.map(fill => ({
at: fill.eventTime,
quantity: fill.quantityDelta,
price: fill.price,
fee: fill.fee.amount,
releasedBasis: fill.releasedBasis,
realizedGrossPnl: fill.realizedGrossPnl,
}))
).toEqual([
{
at: fixture.start + 3 * fixture.minute,
quantity: d('10'),
price: d('7'),
fee: d('0.7'),
releasedBasis: d('0'),
realizedGrossPnl: d('0'),
},
{
at: fixture.start + 5 * fixture.minute,
quantity: d('-10'),
price: d('11'),
fee: d('1.1'),
releasedBasis: d('70'),
realizedGrossPnl: d('40'),
},
]);
expect(result.result.projection.valuation).toMatchObject({
cash: d('10038.2'),
equity: d('10038.2'),
markedHoldings: d('0'),
remainingCost: d('0'),
realizedGrossPnl: d('40'),
fees: d('1.8'),
});
expect(result.diagnostics.strategies[0]!.state).toMatchObject({ targetQuantity: d('0') });
});
test('two differently configured MR owners share native portfolio barriers but retain independent history, inventory, basis and fees', () => {
const fixture = canonicalRegimeResearchFixture({
selections: [
canonicalRegimeSelection('B', {
ownerBudget: '35',
parameters: { lookbackPeriod: 3, trendPeriod: 4 },
}),
canonicalRegimeSelection('A'),
],
});
const result = run(fixture);
const beforeExit = result.records.filter(row => row.at === fixture.start + 5 * fixture.minute);
expect(beforeExit).toHaveLength(2);
expect(beforeExit[0]!.portfolio).toBe(beforeExit[1]!.portfolio);
expect(
beforeExit.map(row => [
row.ownerId,
row.positions.map(position => [position.ownerId, position.quantity, position.remainingCost]),
])
).toEqual([
['B', [['B', d('5'), d('45')]]],
['A', [['A', d('10'), d('70')]]],
]);
expect(
result.result.projection.fills.map(fill => [
fill.ownerId,
fill.quantityDelta,
fill.price,
fill.releasedBasis,
])
).toEqual([
['A', d('10'), d('7'), d('0')],
['B', d('5'), d('9'), d('0')],
['A', d('-10'), d('11'), d('70')],
['B', d('-5'), d('11'), d('45')],
]);
expect(
result.result.projection.valuation.owners
.filter(owner => owner.ownerId !== 'reserve')
.map(owner => [owner.ownerId, owner.realizedGrossPnl, owner.fees, owner.remainingCost])
).toEqual([
['A', d('40'), d('1.8'), d('0')],
['B', d('10'), d('1'), d('0')],
]);
expect(result.result.projection.valuation.equity).toBe(d('10047.2'));
const [a, b] = result.diagnostics.strategies;
// The terminal close marks equity; tradeEnd itself does not create another decision.
expect(a!.state).toMatchObject({ closes: [8, 7, 10], targetQuantity: d('0') });
expect(b!.state).toMatchObject({ closes: [10, 8, 7, 10], targetQuantity: d('0') });
expect(a!.state).not.toEqual(b!.state);
expect(
result.records.every(row => row.positions.every(position => position.ownerId === row.ownerId))
).toBe(true);
});
test.each(['trace', 'projection', 'report'] as const)(
'actual %s worker supports mixed MR/SMA selections with the same native decisions and finance as direct replay',
async resultFormat => {
const fixture = canonicalRegimeResearchFixture({
selections: [
canonicalRegimeSelection('A'),
smaStrategySelectionSchema.parse({
ownerId: 'B',
strategyId: 'sma',
strategyVersion: 'sma-crossover-long-only/v1',
seed: 43,
instrumentId: 'X0.US',
seriesId: 'X0.US:1m',
ownerBudget: '30',
parameters: { fastPeriod: 1, slowPeriod: 2 },
}),
],
});
const input = strategyReplayRequestSchema.parse({
type: 'runStrategyReplay',
version: 1,
dataset: fixture.dataset,
config: fixture.config,
strategies: fixture.selections,
eventBudget: 2,
resultFormat,
});
const load = prepareReplayLoad(fixture.dataset, input.config);
const expected = runStrategyReplay(load, input.strategies.map(createBuiltinStrategy), {
resultFormat,
eventBudget: 1,
});
const worker = new NativeBacktestWorker();
const output = await worker.execute(input, new AbortController().signal, () => {});
const parsed = parseStrategyReplayResult(output, {
strategies: input.strategies,
identity: load.identity,
policy: input.config,
format: resultFormat,
});
expect(parsed.result).toEqual(expected.result);
expect(parsed.strategies.map(item => [item.ownerId, item.strategyId])).toEqual([
['A', 'mean_reversion'],
['B', 'sma_crossover'],
]);
expect(
parsed.result.view.portfolio.positions.find(position => position.ownerId === 'B')
).toMatchObject({ quantity: d('3'), remainingCost: d('33') });
if ('projection' in parsed.result) {
expect(parsed.result.projection.valuation).toMatchObject({
equity: d('10034.87'),
fees: d('2.13'),
remainingCost: d('33'),
unrealizedPnl: d('-3'),
});
}
if (resultFormat === 'report') {
expect(await worker.execute(input, new AbortController().signal, () => {})).toBe(output);
}
}
);
test('fee-inclusive cash and portfolio risk rejections remain Rust authority for MR targets', () => {
for (const mode of ['fee-funding', 'position-limit'] as const) {
const fixture = canonicalRegimeResearchFixture();
if (mode === 'fee-funding') {
fixture.config.matching.risk.ledger.initialCapital = '80';
} else {
fixture.config.matching.risk.maxPositionQuantity = '5';
}
const result = run(fixture);
expect(result.records.some(row => target(row) === d('10'))).toBe(true);
expect(result.result.projection.fills).toEqual([]);
expect(result.result.projection.valuation).toMatchObject({
cash: d(mode === 'fee-funding' ? '80' : '10000'),
fees: d('0'),
remainingCost: d('0'),
});
const trace = runStrategyReplay(
prepareReplayLoad(fixture.dataset, fixture.config),
fixture.selections.map(createBuiltinStrategy),
{ resultFormat: 'trace' }
);
expect(JSON.stringify(trace.result.receipts)).toContain(
mode === 'fee-funding' ? 'InsufficientCash' : 'PositionSize'
);
}
});
test('partial entry commitments are cancelled when gates fail, never rebuilt while held, and low-volume exits still fill', () => {
const fixture = canonicalRegimeResearchFixture({
selections: [canonicalRegimeSelection('A', { parameters: { minNotionalVolume: d('200') } })],
closes: [10, 10, 8, 7, 6, 10, 10, 10],
opens: [10, 10, 10, 7, 6, 9, 11, 11],
volumes: [1000, 1000, 30, 10, 1000, 10, 1000, 1000],
});
// Native Open mode uses previously available completed volume: 30*.1 fills
// three shares, then the later low-volume exit fills one and two at11.
fixture.config.participation_rate = '0.1';
const result = run(fixture);
expect(
result.records.filter(row => row.at >= fixture.start + 3 * fixture.minute).map(target)
).toEqual([d('10'), d('3'), d('3'), d('0'), d('0')]);
expect(result.result.projection.fills.map(fill => [fill.quantityDelta, fill.price])).toEqual([
[d('3'), d('7')],
[d('-1'), d('11')],
[d('-2'), d('11')],
]);
expect(result.result.projection.valuation).toMatchObject({
equity: d('10011.46'),
fees: d('0.54'),
remainingCost: d('0'),
});
});
test('future suffix mutations cannot alter earlier MR decisions, observation availability or held inventory', () => {
const original = canonicalRegimeResearchFixture();
const mutated = canonicalRegimeResearchFixture({
closes: [10, 10, 8, 7, 1, 500],
opens: [10, 10, 10, 7, 80, 100],
});
expect(mutated.dataset.manifest.hash).not.toBe(original.dataset.manifest.hash);
const baseline = run(original),
changed = run(mutated);
const prefix = (records: DecisionRecord[]) =>
records
.filter(row => row.at <= original.start + 4 * original.minute)
.map(({ ownerId, at, sequence, observed, positions, state, intent }) => ({
ownerId,
at,
sequence,
observed,
positions,
state,
intent,
}));
expect(prefix(changed.records)).toEqual(prefix(baseline.records));
for (const row of [...baseline.records, ...changed.records]) {
expect(row.observed.every(observation => observation.availableAt <= row.at)).toBe(true);
}
expect(
changed.result.projection.fills.filter(
fill => fill.eventTime <= original.start + 3 * original.minute
)
).toEqual(
baseline.result.projection.fills.filter(
fill => fill.eventTime <= original.start + 3 * original.minute
)
);
});
test('fixed versioned inputs reproduce identical strategy state, economic hashes and native finance across event budgets', () => {
const fixture = canonicalRegimeResearchFixture();
const before = JSON.stringify(fixture);
const first = run(fixture, 1),
second = run(fixture, 64),
third = run(canonicalRegimeResearchFixture(), 3);
expect(JSON.stringify(fixture)).toBe(before);
expect(second.result).toEqual(first.result);
expect(third.result).toEqual(first.result);
expect(second.diagnostics).toEqual(first.diagnostics);
expect(third.diagnostics).toEqual(first.diagnostics);
expect(economicHash(second.result)).toBe(economicHash(first.result));
expect(economicHash(third.result)).toBe(economicHash(first.result));
});
test('no-regime ablation changes only the volatility entry gate and retains identical observation warmup', () => {
const filtered = canonicalRegimeSelection('A', { parameters: { maxVolatility: 0.05 } });
const unfiltered = canonicalRegimeSelection('A', {
parameters: { maxVolatility: 0.05, regimeFilter: 'none' },
});
expect(unfiltered).toEqual({
...filtered,
parameters: { ...filtered.parameters, regimeFilter: 'none' },
});
const filteredFixture = canonicalRegimeResearchFixture({ selections: [filtered] });
const unfilteredFixture = canonicalRegimeResearchFixture({ selections: [unfiltered] });
expect(filteredFixture.dataset.manifest.hash).toBe(unfilteredFixture.dataset.manifest.hash);
expect(filteredFixture.config).toEqual(unfilteredFixture.config);
const withRegime = run(filteredFixture),
withoutRegime = run(unfilteredFixture);
expect(withRegime.records.map(row => [row.at, row.observed])).toEqual(
withoutRegime.records.map(row => [row.at, row.observed])
);
expect(withRegime.records.slice(0, 2).map(target)).toEqual([undefined, undefined]);
expect(withoutRegime.records.slice(0, 2).map(target)).toEqual([undefined, undefined]);
expect(withRegime.records[2]!.state).toMatchObject({ closes: [10, 10, 8] });
expect(withoutRegime.records[2]!.state).toMatchObject({ closes: [10, 10, 8] });
expect(target(withRegime.records[2]!)).toBeUndefined();
expect(target(withoutRegime.records[2]!)).toBe(d('10'));
expect(withRegime.result.projection.fills.map(fill => [fill.quantityDelta, fill.price])).toEqual([
[d('11'), d('9')],
[d('-11'), d('11')],
]);
expect(
withoutRegime.result.projection.fills.map(fill => [fill.quantityDelta, fill.price])
).toEqual([
[d('10'), d('7')],
[d('-10'), d('11')],
]);
});
test('fixed fee and slippage alternatives retain provenance and give hand-computed native cost sensitivity', () => {
const recipes = [
{ feeRate: '0', slippageRate: '0', equity: '10040', fees: '0', prices: ['7', '11'] },
{ feeRate: '0.01', slippageRate: '0', equity: '10038.2', fees: '1.8', prices: ['7', '11'] },
{
feeRate: '0.01',
slippageRate: '0.01',
equity: '10036.404',
fees: '1.796',
prices: ['7.07', '10.89'],
},
];
const baseline = canonicalRegimeResearchFixture();
for (const recipe of recipes) {
const fixture = canonicalRegimeResearchFixture(recipe);
expect(fixture.dataset.manifest.hash).toBe(baseline.dataset.manifest.hash);
expect(fixture.selections).toEqual(baseline.selections);
const result = run(fixture);
expect(result.result.projection.valuation).toMatchObject({
equity: d(recipe.equity),
fees: d(recipe.fees),
});
expect(result.result.projection.fills.map(fill => fill.price)).toEqual(recipe.prices.map(d));
expect(economicHash(run(canonicalRegimeResearchFixture(recipe)).result)).toBe(
economicHash(result.result)
);
}
});