Separate backtest execution settings from strategy parameters
This commit is contained in:
parent
420c47704e
commit
e4925ecdfe
9 changed files with 283 additions and 48 deletions
|
|
@ -2,8 +2,10 @@ import { describe, expect, test } from 'bun:test';
|
|||
import {
|
||||
BACKTEST_DEFAULTS,
|
||||
BacktestConfigSchema,
|
||||
BacktestExecutionSettingsSchema,
|
||||
backtestRequestFromDefinition,
|
||||
isBacktestRequestError,
|
||||
normalizeBacktestStrategyConfig,
|
||||
parseBacktestRequest,
|
||||
} from '@stock-bot/stock-config/backtest';
|
||||
import { parseBacktestRequest as runnerParser } from '../../apps/stock/orchestrator/src/backtest/BacktestRunner';
|
||||
|
|
@ -31,6 +33,31 @@ const definition = {
|
|||
};
|
||||
|
||||
describe('shared backtest request contract', () => {
|
||||
test('execution-owned fields are classified from their schema, not a second filtering list', () => {
|
||||
const settings = Object.fromEntries(
|
||||
Object.keys(BacktestExecutionSettingsSchema.shape).map(key => [key, 'execution-only'])
|
||||
);
|
||||
const input = {
|
||||
...settings,
|
||||
fastPeriod: 3,
|
||||
slowPeriod: 7,
|
||||
featureWindow: 17,
|
||||
useTypeScriptImplementation: false,
|
||||
};
|
||||
const before = structuredClone(input);
|
||||
expect(normalizeBacktestStrategyConfig(input)).toEqual({
|
||||
parameters: { fastPeriod: 3, slowPeriod: 7, featureWindow: 17 },
|
||||
useTypeScriptImplementation: false,
|
||||
});
|
||||
expect(input).toEqual(before);
|
||||
expect(normalizeBacktestStrategyConfig({ fastPreriod: 3 }).parameters).toEqual({
|
||||
fastPreriod: 3,
|
||||
});
|
||||
expect(() =>
|
||||
normalizeBacktestStrategyConfig({ useTypeScriptImplementation: 'false' })
|
||||
).toThrow();
|
||||
});
|
||||
|
||||
test('runner and legacy schema exports delegate to the same pure contract', () => {
|
||||
expect(orchestratorSchema).toBe(BacktestConfigSchema);
|
||||
expect(runnerParser).toBe(parseBacktestRequest);
|
||||
|
|
|
|||
|
|
@ -24,6 +24,7 @@ import { registerOrchestratorServices } from '../../apps/stock/orchestrator/src/
|
|||
import { DataManager } from '../../apps/stock/orchestrator/src/data/DataManager';
|
||||
import { BacktestHandler } from '../../apps/stock/orchestrator/src/handlers/backtest/backtest.handler';
|
||||
import { StorageService } from '../../apps/stock/orchestrator/src/services/StorageService';
|
||||
import { StrategyRegistry } from '../../apps/stock/orchestrator/src/strategies/StrategyRegistry';
|
||||
import type { OrchestratorServices } from '../../apps/stock/orchestrator/src/types';
|
||||
import { BacktestConfigSchema } from '../../apps/stock/orchestrator/src/types';
|
||||
import { createBacktestRoutes as createV1Routes } from '../../apps/stock/web-api/src/routes/backtest.routes';
|
||||
|
|
@ -34,6 +35,7 @@ import {
|
|||
createWebSocketHandler,
|
||||
type RunUpdateMessage,
|
||||
} from '../../apps/stock/web-api/src/websocket/run-updates';
|
||||
import { CounterStrategy } from '../fixtures/strategy-recovery';
|
||||
|
||||
setLoggerConfig({ logLevel: 'fatal', logConsole: false });
|
||||
const logger = getLogger('workflow-test');
|
||||
|
|
@ -145,7 +147,10 @@ async function fixture(
|
|||
return { postgres, mongodb, storage, engine, repository, runner, services, routes };
|
||||
}
|
||||
|
||||
async function typescriptRuntime(f: Awaited<ReturnType<typeof fixture>>) {
|
||||
async function typescriptRuntime(
|
||||
f: Awaited<ReturnType<typeof fixture>>,
|
||||
strategyRegistry?: StrategyRegistry
|
||||
) {
|
||||
const di = await new ServiceContainerBuilder()
|
||||
.withOptions({
|
||||
enableCache: false,
|
||||
|
|
@ -164,12 +169,111 @@ async function typescriptRuntime(f: Awaited<ReturnType<typeof fixture>>) {
|
|||
custom: {},
|
||||
};
|
||||
di.register({ serviceContainer: asValue(services) });
|
||||
await registerOrchestratorServices(di, { initializeMode: false, useRustEngine: false });
|
||||
await registerOrchestratorServices(di, {
|
||||
initializeMode: false,
|
||||
useRustEngine: false,
|
||||
strategyRegistry,
|
||||
});
|
||||
expect(di.resolve('BacktestRunner')).toBe(services.custom?.BacktestRunner);
|
||||
return services;
|
||||
}
|
||||
|
||||
describe('one backtest execution workflow', () => {
|
||||
for (const backend of ['native', 'typescript'] as const) {
|
||||
test(`${backend} API runs separate mixed execution settings and replay the original configuration`, async () => {
|
||||
const f = await fixture();
|
||||
const services = backend === 'typescript' ? await typescriptRuntime(f) : f.services;
|
||||
const runner = services.custom!.BacktestRunner!;
|
||||
cleanup.unshift(async () => {
|
||||
await runner.shutdown();
|
||||
if (backend === 'typescript')
|
||||
await (services as OrchestratorServices).custom?.ModeManager?.shutdown();
|
||||
});
|
||||
const api = new BacktestServiceV2(services);
|
||||
const parameters = {
|
||||
fastPeriod: 3,
|
||||
slowPeriod: 7,
|
||||
dataFrequency: '1d',
|
||||
commission: 0,
|
||||
slippage: 0,
|
||||
dataPolicy: { adjustment: 'raw', timestamp: 'utc-session-date' },
|
||||
};
|
||||
const definition = await api.createBacktest(
|
||||
{ ...config, name: 'Mixed parameters', config: parameters },
|
||||
{ autoStart: false }
|
||||
);
|
||||
const run = await api.createRun({ backtestId: definition.id });
|
||||
const before = (
|
||||
await f.postgres.query('SELECT request_snapshot FROM runs WHERE id = $1', [run.id])
|
||||
).rows[0]!.request_snapshot;
|
||||
const result = await runner.runQueued(run.id);
|
||||
const saved = (await api.getRunResults(result.runId))!;
|
||||
expect(saved.engine).toBe(backend);
|
||||
expect(saved.trades.length).toBeGreaterThan(0);
|
||||
expect(saved.config.parameters).toEqual(parameters);
|
||||
expect(saved.config.dataFrequency).toBe('1d');
|
||||
expect(saved.config.commission).toBe(0);
|
||||
const request = {
|
||||
...before,
|
||||
runId: undefined,
|
||||
backtestId: undefined,
|
||||
datasetHash: saved.config.dataset!.hash,
|
||||
};
|
||||
const replayed = await runner.runBacktest(request);
|
||||
expect(replayed.config.parameters).toEqual(parameters);
|
||||
expect(replayed.config.dataset).toEqual(saved.config.dataset);
|
||||
expect(replayed.trades).toEqual(saved.trades);
|
||||
expect(replayed.metrics).toEqual(saved.metrics);
|
||||
expect(
|
||||
(await f.postgres.query('SELECT request_snapshot FROM runs WHERE id = $1', [run.id]))
|
||||
.rows[0]!.request_snapshot
|
||||
).toEqual(before);
|
||||
if (backend === 'typescript') {
|
||||
const strategies = (
|
||||
services as OrchestratorServices
|
||||
).custom!.StrategyManager!.getAllStrategies();
|
||||
expect(strategies[0]!.getConfig().parameters).not.toHaveProperty('dataFrequency');
|
||||
expect(strategies[0]!.getCheckpointVersion()).toBe('sma-crossover-fixed/v2');
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
test('custom strategy extension fields survive the full API and TypeScript workflow', async () => {
|
||||
const f = await fixture();
|
||||
const seen: Record<string, unknown>[] = [];
|
||||
const registry = new StrategyRegistry().register(
|
||||
['custom-fixture'],
|
||||
(definition, dependencies) => {
|
||||
seen.push(structuredClone(definition.parameters));
|
||||
return new CounterStrategy(dependencies.execution, definition);
|
||||
}
|
||||
);
|
||||
const services = await typescriptRuntime(f, registry);
|
||||
const runner = services.custom!.BacktestRunner!;
|
||||
cleanup.unshift(async () => {
|
||||
await runner.shutdown();
|
||||
await services.custom?.ModeManager?.shutdown();
|
||||
});
|
||||
const parameters = {
|
||||
vendorFeature: { window: 17, version: 'v1' },
|
||||
dataFrequency: '1d',
|
||||
commission: 0,
|
||||
slippage: 0,
|
||||
};
|
||||
const api = new BacktestServiceV2(services);
|
||||
const definition = await api.createBacktest(
|
||||
{ ...config, name: 'Custom extension', strategy: 'custom-fixture', config: parameters },
|
||||
{ autoStart: false }
|
||||
);
|
||||
const run = await api.createRun({ backtestId: definition.id });
|
||||
await runner.runQueued(run.id);
|
||||
expect((await api.getRunResults(run.id))?.config.parameters).toEqual(parameters);
|
||||
expect(seen[0]).toMatchObject({ ...parameters, initialCapital: config.initialCapital });
|
||||
expect(services.custom!.StrategyManager!.getAllStrategies()[0]!.getCheckpointVersion()).toBe(
|
||||
'counter/v1'
|
||||
);
|
||||
});
|
||||
|
||||
test('V2 rejects ambiguous listing IDs and incompatible timestamp policies before accepting work', async () => {
|
||||
const f = await fixture();
|
||||
const api = createBacktestV2Routes(f.services);
|
||||
|
|
|
|||
|
|
@ -1,9 +1,15 @@
|
|||
import { afterEach, describe, expect, test } from 'bun:test';
|
||||
import {
|
||||
movingAverageCrossover,
|
||||
trailingMean,
|
||||
trailingPopulationDeviation,
|
||||
} from '@stock-bot/calculations/indicators';
|
||||
import {
|
||||
IncrementalSMA,
|
||||
BacktestEngine as NativeEngine,
|
||||
TechnicalIndicators,
|
||||
} from '@stock-bot/engine';
|
||||
import { BacktestExecutionSettingsSchema } from '@stock-bot/stock-config/backtest';
|
||||
import { BacktestEngine } from '../../apps/stock/orchestrator/src/backtest/BacktestEngine';
|
||||
import { resolveNativeStrategies } from '../../apps/stock/orchestrator/src/backtest/native-strategies';
|
||||
import { backtestStrategies } from '../../apps/stock/orchestrator/src/backtest/strategy-plan';
|
||||
|
|
@ -20,11 +26,6 @@ import {
|
|||
normalizeStrategyName,
|
||||
} from '../../apps/stock/orchestrator/src/contracts/strategy-names';
|
||||
import type { ModeManager } from '../../apps/stock/orchestrator/src/core/ModeManager';
|
||||
import {
|
||||
movingAverageCrossover,
|
||||
trailingMean,
|
||||
trailingPopulationDeviation,
|
||||
} from '@stock-bot/calculations/indicators';
|
||||
import { StorageService } from '../../apps/stock/orchestrator/src/services/StorageService';
|
||||
import { MeanReversionStrategy } from '../../apps/stock/orchestrator/src/strategies/builtin/MeanReversionStrategy';
|
||||
import { SmaCrossoverStrategy } from '../../apps/stock/orchestrator/src/strategies/builtin/SmaCrossoverStrategy';
|
||||
|
|
@ -158,6 +159,74 @@ describe('explicit strategy contracts and shared planning', () => {
|
|||
expect(nativeSmaParameters.safeParse({ positionFraction: 0.1 }).success).toBe(false);
|
||||
});
|
||||
|
||||
test('mixed execution settings never reach built-in parameters or alter run-wide precedence', () => {
|
||||
const mixed = {
|
||||
...config,
|
||||
config: {
|
||||
...BacktestExecutionSettingsSchema.parse(config),
|
||||
fastPeriod: 3,
|
||||
slowPeriod: 7,
|
||||
useTypeScriptImplementation: false,
|
||||
},
|
||||
strategies: [
|
||||
{ name: 'disabled', enabled: false, config: {} },
|
||||
{
|
||||
name: 'sma',
|
||||
enabled: true,
|
||||
config: { slowPeriod: 9, dataFrequency: '1m', commission: 0.1 },
|
||||
},
|
||||
{ name: 'sma_crossover', enabled: true, config: { fastPeriod: 2 } },
|
||||
],
|
||||
};
|
||||
const before = structuredClone(mixed);
|
||||
for (const backend of ['native', 'typescript'] as const) {
|
||||
const plan = backtestStrategies(mixed, backend);
|
||||
expect(
|
||||
plan.map(entry => [entry.index, entry.parameters.fastPeriod, entry.parameters.slowPeriod])
|
||||
).toEqual([
|
||||
[0, 3, 9],
|
||||
[1, 2, 7],
|
||||
]);
|
||||
for (const entry of plan) {
|
||||
expect(entry.parameters).not.toHaveProperty('dataFrequency');
|
||||
expect(entry.parameters).not.toHaveProperty('commission');
|
||||
expect(entry.parameters).not.toHaveProperty('useTypeScriptImplementation');
|
||||
if (backend === 'typescript') {
|
||||
expect(entry.parameters.initialCapital).toBe(config.initialCapital);
|
||||
}
|
||||
}
|
||||
for (const parameters of [{ fastPreriod: 3 }, { dataFrequncy: '1d' }]) {
|
||||
expect(() => backtestStrategies({ ...config, config: parameters }, backend)).toThrow(
|
||||
'Unrecognized'
|
||||
);
|
||||
}
|
||||
}
|
||||
expect(resolveNativeStrategies(mixed).map(entry => entry.id)).toEqual([
|
||||
'backtest-strategy-0',
|
||||
'backtest-strategy-1',
|
||||
]);
|
||||
expect(mixed).toEqual(before);
|
||||
expect(mixed.dataFrequency).toBe('1d');
|
||||
});
|
||||
|
||||
test('custom factories retain their existing extension bag, including names also used by execution', () => {
|
||||
const parameters = {
|
||||
vendorOption: { window: 9 },
|
||||
dataFrequency: 'feature cadence',
|
||||
commission: 12,
|
||||
};
|
||||
const custom = backtestStrategies(
|
||||
{ ...config, strategy: 'custom', config: parameters },
|
||||
'typescript'
|
||||
);
|
||||
expect(custom[0]?.parameters).toMatchObject({
|
||||
...parameters,
|
||||
initialCapital: config.initialCapital,
|
||||
});
|
||||
(custom[0]!.parameters.vendorOption as { window: number }).window = 100;
|
||||
expect(parameters.vendorOption.window).toBe(9);
|
||||
});
|
||||
|
||||
test('mean reversion and native-only strategies validate their actual, different contracts', () => {
|
||||
const mean = typescriptMeanReversionParameters.parse({ lookbackPeriod: 80 });
|
||||
expect(mean.trendPeriod).toBe(80);
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue