feat(research): isolate candidates and add reviewed paper promotion
This commit is contained in:
parent
26b97265c6
commit
25b5cbf481
128 changed files with 13038 additions and 1388 deletions
|
|
@ -348,6 +348,7 @@ function ExperimentDetailView({ experimentId }: { experimentId: string }) {
|
|||
experimentId={experiment.id}
|
||||
backtestId={experiment.backtestId}
|
||||
previewHash={experiment.previewHash}
|
||||
strategyOrigin={experiment.preview.request.strategy.origin}
|
||||
experimentCancelled={experiment.cancelRequested}
|
||||
trial={trial}
|
||||
disabled={mutating || loading}
|
||||
|
|
|
|||
|
|
@ -35,6 +35,7 @@ export function ChronologicalValidationPreflight({
|
|||
backtestId,
|
||||
name,
|
||||
grid,
|
||||
candidate,
|
||||
disabled,
|
||||
eligible,
|
||||
onDirty,
|
||||
|
|
@ -44,6 +45,7 @@ export function ChronologicalValidationPreflight({
|
|||
backtestId: string;
|
||||
name: string;
|
||||
grid: string;
|
||||
candidate?: ChronologicalValidationSubmission['candidate'];
|
||||
disabled: boolean;
|
||||
eligible: boolean;
|
||||
onDirty: (dirty: boolean) => void;
|
||||
|
|
@ -72,7 +74,15 @@ export function ChronologicalValidationPreflight({
|
|||
const request = useRef<AbortController | null>(null);
|
||||
const pending = useRef(false);
|
||||
const alive = useRef(false);
|
||||
const identity = JSON.stringify({ backtestId, name, grid, windows, disabled, eligible });
|
||||
const identity = JSON.stringify({
|
||||
backtestId,
|
||||
name,
|
||||
grid,
|
||||
candidate,
|
||||
windows,
|
||||
disabled,
|
||||
eligible,
|
||||
});
|
||||
const currentIdentity = useRef(identity);
|
||||
currentIdentity.current = identity;
|
||||
const preview =
|
||||
|
|
@ -123,6 +133,7 @@ export function ChronologicalValidationPreflight({
|
|||
backtestId,
|
||||
name,
|
||||
grid: JSON.parse(grid),
|
||||
...(candidate ? { candidate } : {}),
|
||||
recipe: parseValidationWindows(windows),
|
||||
});
|
||||
const value = await chronologicalValidationApi.preview(input, controller.signal);
|
||||
|
|
@ -325,7 +336,9 @@ export function ChronologicalValidationPreflight({
|
|||
</p>
|
||||
<p>
|
||||
Input checks only. Warmup sufficiency is not evidence of profitability or statistical
|
||||
adequacy. Only deterministic, unfitted strategies with zero label horizon are supported.
|
||||
adequacy. Built-in strategies use the declared unfitted model. Candidate warmup is
|
||||
author-declared and candidate behavior is unverified; fitting and nonzero label horizons
|
||||
have no supported validation contract.
|
||||
</p>
|
||||
<div className="grid gap-3 lg:grid-cols-3">
|
||||
{preview.partitions.map(part => (
|
||||
|
|
|
|||
|
|
@ -13,6 +13,10 @@ import {
|
|||
} from '@stock-bot/stock-config/experiments';
|
||||
import { Button } from '@/components/ui/Button';
|
||||
import { backtestApiV2, type Backtest } from '@/features/backtest/services/backtestApiV2';
|
||||
import {
|
||||
StrategySelection,
|
||||
type CatalogSelection,
|
||||
} from '@/features/strategies/components/StrategySelection';
|
||||
import { useUnsavedWarning } from '@/features/strategies/components/useUnsavedWarning';
|
||||
import {
|
||||
experimentApi,
|
||||
|
|
@ -94,6 +98,19 @@ export function ExperimentEditor({
|
|||
const [backtestId, setBacktestId] = useState(initialBacktestId);
|
||||
const [name, setName] = useState('');
|
||||
const [grid, setGrid] = useState('{}');
|
||||
const [useCandidate, setUseCandidate] = useState(false);
|
||||
const [candidateSelection, setCandidateSelection] = useState<CatalogSelection>({});
|
||||
const [candidateValid, setCandidateValid] = useState(false);
|
||||
const candidateRevision = useRef(0);
|
||||
const candidateValidity = useRef(false);
|
||||
const renderedCandidateRevision = candidateRevision.current;
|
||||
const candidate =
|
||||
useCandidate && candidateSelection.strategyVersionId
|
||||
? {
|
||||
versionId: candidateSelection.strategyVersionId,
|
||||
parameters: candidateSelection.strategyParameters ?? {},
|
||||
}
|
||||
: undefined;
|
||||
const [backtests, setBacktests] = useState<Backtest[]>([]);
|
||||
const [templateLoading, setTemplateLoading] = useState(true);
|
||||
const [templateError, setTemplateError] = useState('');
|
||||
|
|
@ -113,6 +130,7 @@ export function ExperimentEditor({
|
|||
walkForwardDirty ||
|
||||
Boolean(
|
||||
name ||
|
||||
useCandidate ||
|
||||
grid !== '{}' ||
|
||||
backtestId !== initialBacktestId ||
|
||||
mode !== 'parameters' ||
|
||||
|
|
@ -179,7 +197,12 @@ export function ExperimentEditor({
|
|||
change();
|
||||
};
|
||||
const prepare = async () => {
|
||||
if (submissionOwner.current || previewLoading) {
|
||||
if (
|
||||
submissionOwner.current ||
|
||||
previewLoading ||
|
||||
candidateRevision.current !== renderedCandidateRevision ||
|
||||
(useCandidate && !candidateValid)
|
||||
) {
|
||||
return;
|
||||
}
|
||||
const current = ++generation.current;
|
||||
|
|
@ -194,11 +217,21 @@ export function ExperimentEditor({
|
|||
const value =
|
||||
modeRef.current === 'cost-sensitivity'
|
||||
? await experimentApi.costPreview(
|
||||
costSensitivityInputSchema.parse({ backtestId, name, scenarios }),
|
||||
costSensitivityInputSchema.parse({
|
||||
backtestId,
|
||||
name,
|
||||
scenarios,
|
||||
...(candidate ? { candidate } : {}),
|
||||
}),
|
||||
controller.signal
|
||||
)
|
||||
: await experimentApi.preview(
|
||||
experimentInputSchema.parse({ backtestId, name, grid: JSON.parse(grid) }),
|
||||
experimentInputSchema.parse({
|
||||
backtestId,
|
||||
name,
|
||||
grid: JSON.parse(grid),
|
||||
...(candidate ? { candidate } : {}),
|
||||
}),
|
||||
controller.signal
|
||||
);
|
||||
if (alive.current && current === generation.current) {
|
||||
|
|
@ -356,6 +389,49 @@ export function ExperimentEditor({
|
|||
Load more backtests
|
||||
</Button>
|
||||
)}
|
||||
<label className="block text-sm">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={useCandidate}
|
||||
disabled={Boolean(lockedBy)}
|
||||
onChange={event => {
|
||||
if (submissionOwner.current) {
|
||||
return;
|
||||
}
|
||||
candidateRevision.current++;
|
||||
invalidate(() => setUseCandidate(event.target.checked));
|
||||
}}
|
||||
/>{' '}
|
||||
Use an isolated candidate version
|
||||
</label>
|
||||
{useCandidate && (
|
||||
<section aria-label="Candidate experiment strategy" className="space-y-2">
|
||||
<p className="text-sm">
|
||||
Select an immutable candidate and validate its base parameters. The saved backtest
|
||||
supplies the dataset, capital and financial policy. Preview checks candidate
|
||||
eligibility.
|
||||
</p>
|
||||
<StrategySelection
|
||||
value={candidateSelection}
|
||||
onChange={value => {
|
||||
if (submissionOwner.current) {
|
||||
return;
|
||||
}
|
||||
candidateRevision.current++;
|
||||
invalidate(() => setCandidateSelection(value));
|
||||
}}
|
||||
onValidityChange={valid => {
|
||||
if (submissionOwner.current || valid === candidateValidity.current) {
|
||||
return;
|
||||
}
|
||||
candidateValidity.current = valid;
|
||||
candidateRevision.current++;
|
||||
invalidate(() => setCandidateValid(valid));
|
||||
}}
|
||||
disabled={Boolean(lockedBy)}
|
||||
/>
|
||||
</section>
|
||||
)}
|
||||
<label className="block text-sm">
|
||||
Experiment type
|
||||
<select
|
||||
|
|
@ -469,6 +545,7 @@ export function ExperimentEditor({
|
|||
disabled={
|
||||
Boolean(lockedBy) ||
|
||||
previewLoading ||
|
||||
(useCandidate && !candidateValid) ||
|
||||
!backtests.some(item => item.id === backtestId) ||
|
||||
!name.trim()
|
||||
}
|
||||
|
|
@ -514,8 +591,13 @@ export function ExperimentEditor({
|
|||
backtestId={backtestId}
|
||||
name={name}
|
||||
grid={grid}
|
||||
candidate={candidate}
|
||||
disabled={mode !== 'parameters' || (lockedBy !== null && lockedBy !== 'chronological')}
|
||||
eligible={!templateLoading && backtests.some(item => item.id === backtestId)}
|
||||
eligible={
|
||||
!templateLoading &&
|
||||
(!useCandidate || candidateValid) &&
|
||||
backtests.some(item => item.id === backtestId)
|
||||
}
|
||||
onDirty={setValidationDirty}
|
||||
claimSubmission={claimSubmission}
|
||||
releaseSubmission={releaseSubmission}
|
||||
|
|
@ -524,8 +606,13 @@ export function ExperimentEditor({
|
|||
backtestId={backtestId}
|
||||
name={name}
|
||||
grid={grid}
|
||||
candidate={candidate}
|
||||
disabled={mode !== 'parameters' || (lockedBy !== null && lockedBy !== 'walk-forward')}
|
||||
eligible={!templateLoading && backtests.some(item => item.id === backtestId)}
|
||||
eligible={
|
||||
!templateLoading &&
|
||||
(!useCandidate || candidateValid) &&
|
||||
backtests.some(item => item.id === backtestId)
|
||||
}
|
||||
onDirty={setWalkForwardDirty}
|
||||
claimSubmission={claimSubmission}
|
||||
releaseSubmission={releaseSubmission}
|
||||
|
|
|
|||
|
|
@ -39,7 +39,7 @@ export function ExperimentInputs({ preview }: { preview: WorkbenchExperimentPrev
|
|||
<dd>{new Date(dataset.bounds.warmupStart).toISOString()}</dd>
|
||||
</div>
|
||||
<div>
|
||||
<dt>Initial capital / owner budget (USD)</dt>
|
||||
<dt>Initial capital / strategy sizing budget (USD)</dt>
|
||||
<dd>
|
||||
{request.policy.matching.risk.ledger.initialCapital} /{' '}
|
||||
{request.strategy.selection.ownerBudget}
|
||||
|
|
@ -50,6 +50,27 @@ export function ExperimentInputs({ preview }: { preview: WorkbenchExperimentPrev
|
|||
<dd>{request.strategy.selection.seed}</dd>
|
||||
</div>
|
||||
</dl>
|
||||
{request.strategy.origin === 'candidate' && (
|
||||
<section aria-label="Isolated candidate execution" className="space-y-1 break-all">
|
||||
<p>
|
||||
Isolated TypeScript candidate ·{' '}
|
||||
{request.strategy.reviewId
|
||||
? `Review ${request.strategy.reviewId}`
|
||||
: 'Unreviewed research candidate'}
|
||||
</p>
|
||||
<p>
|
||||
Author-declared warmup: {request.strategy.package.execution?.warmupBars} bars. Arbitrary
|
||||
code may ignore the seeded RNG; reproduction compares actual economic results.
|
||||
</p>
|
||||
<p>Sandbox image: {request.strategy.execution.imageId}</p>
|
||||
<p>
|
||||
Limits: {request.strategy.execution.profile.limits.memoryBytes / 1048576} MiB memory,{' '}
|
||||
{request.strategy.execution.profile.limits.cpuQuota} CPU,{' '}
|
||||
{request.strategy.execution.profile.limits.wallMs / 1000} seconds per container; an
|
||||
agent attempt deadline may be shorter.
|
||||
</p>
|
||||
</section>
|
||||
)}
|
||||
<p>
|
||||
{costs
|
||||
? 'Template cost diagnostics only. Strategy parameters, dataset, seed, capital, half-spread and risk limits remain fixed; each fee/slippage scenario executes independently. No strategy selection or ranking is performed.'
|
||||
|
|
@ -97,6 +118,13 @@ export function ExperimentInputs({ preview }: { preview: WorkbenchExperimentPrev
|
|||
strategy: {
|
||||
versionId: request.strategy.versionId,
|
||||
reviewId: request.strategy.reviewId,
|
||||
origin: request.strategy.origin,
|
||||
...(request.strategy.origin === 'candidate'
|
||||
? {
|
||||
execution: request.strategy.execution,
|
||||
declaredWarmup: request.strategy.package.execution?.warmupBars,
|
||||
}
|
||||
: {}),
|
||||
selection: request.strategy.selection,
|
||||
artifactHash: request.strategy.package.artifact.sha256,
|
||||
dependencyLockHash: request.strategy.package.dependencyLock.sha256,
|
||||
|
|
|
|||
|
|
@ -16,6 +16,7 @@ interface Props {
|
|||
experimentId: string;
|
||||
backtestId: string;
|
||||
previewHash: string;
|
||||
strategyOrigin?: 'builtin' | 'candidate';
|
||||
experimentCancelled: boolean;
|
||||
trial: ExperimentTrial;
|
||||
disabled: boolean;
|
||||
|
|
@ -39,6 +40,7 @@ export function ExperimentTrialRecovery({
|
|||
experimentId,
|
||||
backtestId,
|
||||
previewHash,
|
||||
strategyOrigin = 'builtin',
|
||||
experimentCancelled,
|
||||
trial,
|
||||
disabled,
|
||||
|
|
@ -92,7 +94,7 @@ export function ExperimentTrialRecovery({
|
|||
setHistoryLoading(true);
|
||||
setHistoryError('');
|
||||
void experimentApi
|
||||
.retryHistory(experimentId, trial.runId, trial.trialKey, controller.signal)
|
||||
.retryHistory(experimentId, trial.runId, trial.trialKey, controller.signal, strategyOrigin)
|
||||
.then(value => {
|
||||
if (current) {
|
||||
setHistory(value);
|
||||
|
|
@ -112,7 +114,15 @@ export function ExperimentTrialRecovery({
|
|||
current = false;
|
||||
controller.abort();
|
||||
};
|
||||
}, [experimentId, trial.runId, trial.trialKey, trial.retryCount, historyOpen, historyReload]);
|
||||
}, [
|
||||
experimentId,
|
||||
trial.runId,
|
||||
trial.trialKey,
|
||||
trial.retryCount,
|
||||
historyOpen,
|
||||
historyReload,
|
||||
strategyOrigin,
|
||||
]);
|
||||
const review = () => {
|
||||
if (disabled || !freshAllowed || !trial.runId || intentRef.current) {
|
||||
return;
|
||||
|
|
@ -323,7 +333,7 @@ export function ExperimentTrialRecovery({
|
|||
</div>
|
||||
<div>
|
||||
<dt>Approval at retry admission</dt>
|
||||
<dd>{item.reviewId}</dd>
|
||||
<dd>{item.reviewId ?? 'Unreviewed isolated candidate'}</dd>
|
||||
</div>
|
||||
</dl>
|
||||
</article>
|
||||
|
|
|
|||
|
|
@ -33,6 +33,7 @@ export function WalkForwardPreflight({
|
|||
backtestId,
|
||||
name,
|
||||
grid,
|
||||
candidate,
|
||||
disabled,
|
||||
eligible,
|
||||
onDirty,
|
||||
|
|
@ -42,6 +43,7 @@ export function WalkForwardPreflight({
|
|||
backtestId: string;
|
||||
name: string;
|
||||
grid: string;
|
||||
candidate?: WalkForwardSubmission['candidate'];
|
||||
disabled: boolean;
|
||||
eligible: boolean;
|
||||
onDirty: (value: boolean) => void;
|
||||
|
|
@ -72,7 +74,15 @@ export function WalkForwardPreflight({
|
|||
posting = useRef(false),
|
||||
generation = useRef(0),
|
||||
read = useRef<AbortController | null>(null);
|
||||
const identity = JSON.stringify({ backtestId, name, grid, windows, disabled, eligible }),
|
||||
const identity = JSON.stringify({
|
||||
backtestId,
|
||||
name,
|
||||
grid,
|
||||
candidate,
|
||||
windows,
|
||||
disabled,
|
||||
eligible,
|
||||
}),
|
||||
currentIdentity = useRef(identity);
|
||||
currentIdentity.current = identity;
|
||||
const preview =
|
||||
|
|
@ -125,6 +135,7 @@ export function WalkForwardPreflight({
|
|||
backtestId,
|
||||
name,
|
||||
grid: JSON.parse(grid),
|
||||
...(candidate ? { candidate } : {}),
|
||||
windows: windows.map((window, index) =>
|
||||
parseValidationWindows(window, `Window ${index + 1} `)
|
||||
),
|
||||
|
|
|
|||
|
|
@ -1,131 +1,18 @@
|
|||
import { z } from 'zod';
|
||||
import { type ChronologicalValidationInput } from '@stock-bot/stock-config/chronological-validation';
|
||||
import {
|
||||
chronologicalValidationInputSchema,
|
||||
chronologicalValidationPolicy,
|
||||
type ChronologicalValidationInput,
|
||||
type ChronologicalValidationPreview,
|
||||
type ValidationPartitionPreview,
|
||||
} from '@stock-bot/stock-config/chronological-validation';
|
||||
import { canonicalStrategyJson } from '@stock-bot/stock-config/strategy';
|
||||
invalidValidationPreview as invalid,
|
||||
parseChronologicalValidationPreview,
|
||||
type ChronologicalValidationPreviewView,
|
||||
} from '@stock-bot/stock-config/research-responses';
|
||||
import { API_BASE_URL, apiFetch } from '@/lib/api';
|
||||
import { parseExperimentPreview, type ExperimentPreviewView } from './experimentApi';
|
||||
|
||||
export type ValidationPartitionView = Omit<ValidationPartitionPreview, 'dataset'> & {
|
||||
dataset: ExperimentPreviewView['dataset'];
|
||||
};
|
||||
export type ChronologicalValidationPreviewView = Omit<
|
||||
ChronologicalValidationPreview,
|
||||
'source' | 'partitions'
|
||||
> & {
|
||||
source: ExperimentPreviewView;
|
||||
partitions: [ValidationPartitionView, ValidationPartitionView, ValidationPartitionView];
|
||||
};
|
||||
const counter = z.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER);
|
||||
const counts = z.object({
|
||||
totalBars: counter,
|
||||
availableWarmup: counter,
|
||||
admittedWarmup: counter,
|
||||
ignoredLateWarmup: counter,
|
||||
availableEvaluation: counter,
|
||||
terminalAtEnd: counter,
|
||||
unavailableAtEnd: counter,
|
||||
});
|
||||
const partition = z.object({
|
||||
phase: z.enum(['train', 'validation', 'test']),
|
||||
dataset: z.unknown(),
|
||||
request: z.unknown(),
|
||||
counts,
|
||||
requiredWarmup: counter.positive(),
|
||||
warnings: z.array(z.string()),
|
||||
});
|
||||
const prepared = z.object({
|
||||
version: z.literal('chronological-validation-preview/v1'),
|
||||
execution: z.literal('preview-only'),
|
||||
previewHash: z.string().regex(/^[a-f0-9]{64}$/),
|
||||
input: chronologicalValidationInputSchema,
|
||||
source: z.unknown(),
|
||||
policy: z.unknown(),
|
||||
partitions: z.tuple([partition, partition, partition]),
|
||||
});
|
||||
const same = (left: unknown, right: unknown) =>
|
||||
canonicalStrategyJson(left) === canonicalStrategyJson(right);
|
||||
const invalid = () =>
|
||||
new Error(
|
||||
'The chronological validation preview could not be verified. Preview the current inputs again.'
|
||||
);
|
||||
export {
|
||||
parseChronologicalValidationPreview,
|
||||
type ChronologicalValidationPreviewView,
|
||||
type ValidationPartitionView,
|
||||
} from '@stock-bot/stock-config/research-responses';
|
||||
|
||||
export function parseChronologicalValidationPreview(
|
||||
body: unknown,
|
||||
input: ChronologicalValidationInput
|
||||
): ChronologicalValidationPreviewView {
|
||||
const value = prepared.parse(z.object({ preview: z.unknown() }).parse(body).preview);
|
||||
const source = parseExperimentPreview(value.source);
|
||||
const { recipe: _recipe, ...sourceInput } = input;
|
||||
if (
|
||||
!same(value.input, input) ||
|
||||
!same(source.input, sourceInput) ||
|
||||
!same(value.policy, chronologicalValidationPolicy)
|
||||
) {
|
||||
throw invalid();
|
||||
}
|
||||
const phases = ['train', 'validation', 'test'] as const;
|
||||
const partitions = value.partitions.map((part, index): ValidationPartitionView => {
|
||||
const phase = phases[index];
|
||||
if (!phase || part.phase !== phase) {
|
||||
throw invalid();
|
||||
}
|
||||
const decoded = parseExperimentPreview({
|
||||
...source,
|
||||
dataset: part.dataset,
|
||||
request: part.request,
|
||||
});
|
||||
const { request, dataset } = decoded;
|
||||
const expected = {
|
||||
...source.request,
|
||||
datasetHash: dataset.hash,
|
||||
policy: {
|
||||
...source.request.policy,
|
||||
risk_boundaries: request.policy.risk_boundaries,
|
||||
matching: {
|
||||
...source.request.policy.matching,
|
||||
risk: {
|
||||
...source.request.policy.matching.risk,
|
||||
ledger: {
|
||||
...source.request.policy.matching.risk.ledger,
|
||||
riskSession: request.policy.matching.risk.ledger.riskSession,
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
};
|
||||
const measured = part.counts;
|
||||
const metadata = (manifest: ExperimentPreviewView['dataset']) => {
|
||||
const { hash: _hash, bounds: _bounds, barCount: _barCount, ...retained } = manifest;
|
||||
return retained;
|
||||
};
|
||||
if (
|
||||
!same(request, expected) ||
|
||||
!same(dataset.bounds, input.recipe[phase]) ||
|
||||
!same(metadata(dataset), metadata(source.dataset)) ||
|
||||
measured.totalBars !== dataset.barCount ||
|
||||
dataset.bounds.warmupStart < source.dataset.bounds.warmupStart ||
|
||||
dataset.bounds.tradeStart < source.dataset.bounds.tradeStart ||
|
||||
dataset.bounds.tradeEnd > source.dataset.bounds.tradeEnd ||
|
||||
measured.totalBars !==
|
||||
measured.availableWarmup +
|
||||
measured.availableEvaluation +
|
||||
measured.terminalAtEnd +
|
||||
measured.unavailableAtEnd ||
|
||||
measured.availableWarmup !== measured.admittedWarmup + measured.ignoredLateWarmup ||
|
||||
measured.admittedWarmup < part.requiredWarmup ||
|
||||
measured.availableEvaluation === 0
|
||||
) {
|
||||
throw invalid();
|
||||
}
|
||||
return { ...part, phase, request, dataset };
|
||||
}) as [ValidationPartitionView, ValidationPartitionView, ValidationPartitionView];
|
||||
return { ...value, source, policy: chronologicalValidationPolicy, partitions };
|
||||
}
|
||||
export const chronologicalValidationApi = {
|
||||
async preview(
|
||||
input: ChronologicalValidationInput,
|
||||
|
|
|
|||
|
|
@ -1,276 +1,30 @@
|
|||
import { z } from 'zod';
|
||||
import {
|
||||
chronologicalValidationInputSchema,
|
||||
type ChronologicalValidationActionReceipt,
|
||||
type ChronologicalValidationDetail,
|
||||
type ChronologicalValidationFinalizationInput,
|
||||
type ChronologicalValidationSelectionInput,
|
||||
type ChronologicalValidationSubmission,
|
||||
type ChronologicalValidationSummary,
|
||||
type ValidationResultEvidence,
|
||||
} from '@stock-bot/stock-config/chronological-validation';
|
||||
import { researchActorSchema } from '@stock-bot/stock-config/research';
|
||||
import { canonicalStrategyJson } from '@stock-bot/stock-config/strategy';
|
||||
import {
|
||||
invalidValidationResponse as invalid,
|
||||
parseValidationDetail,
|
||||
validationReceiptSchema as receipt,
|
||||
sameValidationInput as same,
|
||||
validationSummarySchema as summary,
|
||||
ValidationApiError,
|
||||
} from '@stock-bot/stock-config/research-responses';
|
||||
import { API_BASE_URL, apiFetch } from '@/lib/api';
|
||||
import {
|
||||
parseChronologicalValidationPreview,
|
||||
type ChronologicalValidationPreviewView,
|
||||
} from './chronologicalValidationApi';
|
||||
import {
|
||||
experimentMetricsSchema,
|
||||
parseExperimentDetail,
|
||||
type ExperimentDetailView,
|
||||
} from './experimentApi';
|
||||
|
||||
export type ValidationDetailView = Omit<ChronologicalValidationDetail, 'preview' | 'phases'> & {
|
||||
preview: ChronologicalValidationPreviewView;
|
||||
phases: Array<{
|
||||
phase: 'train' | 'validation' | 'test';
|
||||
status: 'not-admitted' | 'admitted' | 'missing';
|
||||
experimentId: string | null;
|
||||
experiment: ExperimentDetailView | null;
|
||||
}>;
|
||||
};
|
||||
export class ValidationApiError extends Error {
|
||||
constructor(
|
||||
message: string,
|
||||
public readonly status: number | null
|
||||
) {
|
||||
super(message);
|
||||
}
|
||||
get ambiguous() {
|
||||
return this.status === null || this.status >= 500;
|
||||
}
|
||||
}
|
||||
const hash = z.string().regex(/^[a-f0-9]{64}$/),
|
||||
uuid = z.string().uuid(),
|
||||
count = z.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER);
|
||||
const candidate = z.object({
|
||||
index: count,
|
||||
trialKey: hash,
|
||||
parameters: z.record(z.union([z.string(), z.number().finite(), z.boolean()])),
|
||||
});
|
||||
const actor = researchActorSchema;
|
||||
const summary = z.object({
|
||||
id: uuid,
|
||||
name: z.string().min(1),
|
||||
backtestId: uuid,
|
||||
createdAt: z.string().min(1),
|
||||
cancelRequested: z.boolean(),
|
||||
previewHash: hash,
|
||||
trainingCandidateCount: count.min(1).max(100),
|
||||
stage: z.enum(['training', 'holdouts', 'reported']),
|
||||
});
|
||||
export const validationEvidenceSchema = z.object({
|
||||
phase: z.enum(['train', 'validation', 'test']),
|
||||
experimentId: uuid,
|
||||
runId: uuid,
|
||||
sourceCandidateIndex: count,
|
||||
trialKey: hash,
|
||||
parameters: candidate.shape.parameters,
|
||||
datasetHash: hash,
|
||||
requestHash: hash,
|
||||
economicHash: hash,
|
||||
metrics: experimentMetricsSchema,
|
||||
unavailable: z.record(z.string()),
|
||||
completePeriodCount: count,
|
||||
periodicSampleCount: count,
|
||||
fillCount: count,
|
||||
limitations: z.array(z.string()),
|
||||
});
|
||||
const selection = z.object({
|
||||
version: z.literal('chronological-validation-selection/v1'),
|
||||
id: uuid,
|
||||
validationId: uuid,
|
||||
previewHash: hash,
|
||||
selectionHash: hash,
|
||||
createdAt: z.string().min(1),
|
||||
principal: actor,
|
||||
reviewId: uuid,
|
||||
winner: candidate,
|
||||
training: z.array(validationEvidenceSchema).min(1).max(100),
|
||||
holdoutExperimentIds: z.object({ validation: uuid, test: uuid }),
|
||||
});
|
||||
const report = z.object({
|
||||
version: z.literal('chronological-validation-report/v1'),
|
||||
id: uuid,
|
||||
validationId: uuid,
|
||||
previewHash: hash,
|
||||
selectionHash: hash,
|
||||
reportHash: hash,
|
||||
createdAt: z.string().min(1),
|
||||
principal: actor,
|
||||
reset: z.literal('initial-capital-empty-positions'),
|
||||
training: z.array(validationEvidenceSchema).min(1).max(100),
|
||||
validation: validationEvidenceSchema,
|
||||
test: validationEvidenceSchema,
|
||||
limitations: z.array(z.string()),
|
||||
});
|
||||
const capability = z.object({ available: z.boolean(), reason: z.string().nullable() });
|
||||
const phase = z.object({
|
||||
phase: z.enum(['train', 'validation', 'test']),
|
||||
status: z.enum(['not-admitted', 'admitted', 'missing']),
|
||||
experimentId: uuid.nullable(),
|
||||
experiment: z.unknown(),
|
||||
});
|
||||
const detail = summary.extend({
|
||||
preview: z.unknown(),
|
||||
phases: z.tuple([phase, phase, phase]),
|
||||
selection: selection.nullable(),
|
||||
report: report.nullable(),
|
||||
actions: z.object({ select: capability, finalize: capability }),
|
||||
});
|
||||
const receipt = z.object({
|
||||
id: uuid,
|
||||
validationId: uuid,
|
||||
operation: z.enum(['select-and-admit-holdouts', 'finalize-report']),
|
||||
previewHash: hash,
|
||||
selectionHash: hash,
|
||||
createdAt: z.string().min(1),
|
||||
principal: actor,
|
||||
});
|
||||
const same = (a: unknown, b: unknown) => canonicalStrategyJson(a) === canonicalStrategyJson(b);
|
||||
const invalid = () =>
|
||||
new ValidationApiError(
|
||||
'The saved validation response could not be verified. Refresh or retry the same request.',
|
||||
null
|
||||
);
|
||||
export function parseValidationDetail(raw: unknown): ValidationDetailView {
|
||||
const value = detail.parse(raw);
|
||||
const rawPreview = z.object({ input: chronologicalValidationInputSchema }).parse(value.preview);
|
||||
const preview = parseChronologicalValidationPreview({ preview: value.preview }, rawPreview.input);
|
||||
if (
|
||||
value.backtestId !== preview.input.backtestId ||
|
||||
value.name !== preview.input.name ||
|
||||
value.previewHash !== preview.previewHash ||
|
||||
value.trainingCandidateCount !== preview.source.candidates.length ||
|
||||
(value.stage === 'training') !== (value.selection === null) ||
|
||||
(value.stage === 'reported') !== (value.report !== null)
|
||||
) {
|
||||
throw invalid();
|
||||
}
|
||||
const phases = value.phases.map((item, index) => {
|
||||
const name = (['train', 'validation', 'test'] as const)[index];
|
||||
if (item.phase !== name || (item.status === 'admitted') !== (item.experiment !== null)) {
|
||||
throw invalid();
|
||||
}
|
||||
const expectedId =
|
||||
name === 'train'
|
||||
? value.id
|
||||
: (value.selection?.holdoutExperimentIds[name ?? 'validation'] ?? null);
|
||||
if (
|
||||
item.experimentId !== expectedId ||
|
||||
(item.status === 'not-admitted') !== (expectedId === null)
|
||||
) {
|
||||
throw invalid();
|
||||
}
|
||||
const experiment = item.experiment === null ? null : parseExperimentDetail(item.experiment);
|
||||
if (experiment) {
|
||||
const prototype = preview.partitions[index];
|
||||
const parameters =
|
||||
name === 'train'
|
||||
? prototype?.request.strategy.selection.parameters
|
||||
: value.selection?.winner.parameters;
|
||||
if (!prototype || !parameters) {
|
||||
throw invalid();
|
||||
}
|
||||
const expectedRequest = {
|
||||
...prototype.request,
|
||||
strategy: {
|
||||
...prototype.request.strategy,
|
||||
reviewId:
|
||||
name === 'train' ? prototype.request.strategy.reviewId : value.selection?.reviewId,
|
||||
selection: { ...prototype.request.strategy.selection, parameters },
|
||||
},
|
||||
};
|
||||
const expectedCandidates =
|
||||
name === 'train' ? preview.source.candidates : [{ ...value.selection?.winner, index: 0 }];
|
||||
if (
|
||||
experiment.id !== expectedId ||
|
||||
experiment.backtestId !== value.backtestId ||
|
||||
!same(experiment.preview.request, expectedRequest) ||
|
||||
!same(experiment.preview.dataset, prototype.dataset) ||
|
||||
!same(experiment.preview.candidates, expectedCandidates) ||
|
||||
!same(experiment.preview.input.grid, name === 'train' ? preview.input.grid : {})
|
||||
) {
|
||||
throw invalid();
|
||||
}
|
||||
}
|
||||
return { ...item, experiment };
|
||||
});
|
||||
const validateEvidence = (
|
||||
item: z.infer<typeof validationEvidenceSchema>,
|
||||
expectedPhase: 'train' | 'validation' | 'test'
|
||||
) => {
|
||||
const index = ['train', 'validation', 'test'].indexOf(expectedPhase);
|
||||
const candidateValue = preview.source.candidates[item.sourceCandidateIndex];
|
||||
const phaseValue = phases[index];
|
||||
const trial = phaseValue?.experiment?.trials.find(
|
||||
trial => trial.runId === item.runId && trial.trialKey === item.trialKey
|
||||
);
|
||||
if (
|
||||
!candidateValue ||
|
||||
!phaseValue ||
|
||||
item.phase !== expectedPhase ||
|
||||
item.experimentId !== phaseValue.experimentId ||
|
||||
item.trialKey !== candidateValue.trialKey ||
|
||||
!same(item.parameters, candidateValue.parameters) ||
|
||||
item.datasetHash !== preview.partitions[index]?.dataset.hash ||
|
||||
(expectedPhase !== 'train' && item.sourceCandidateIndex !== value.selection?.winner.index) ||
|
||||
(phaseValue.experiment &&
|
||||
(!trial ||
|
||||
trial.status !== 'completed' ||
|
||||
!trial.comparable ||
|
||||
!same(trial.metrics, item.metrics) ||
|
||||
!same(trial.unavailable, item.unavailable) ||
|
||||
!same(trial.limitations, item.limitations)))
|
||||
) {
|
||||
throw invalid();
|
||||
}
|
||||
};
|
||||
if (value.selection) {
|
||||
const chosen = value.selection;
|
||||
if (
|
||||
chosen.validationId !== value.id ||
|
||||
chosen.previewHash !== value.previewHash ||
|
||||
!same(chosen.winner, preview.source.candidates[chosen.winner.index]) ||
|
||||
chosen.training.length !== value.trainingCandidateCount ||
|
||||
chosen.training.some((item, index) => item.sourceCandidateIndex !== index) ||
|
||||
new Set([value.id, chosen.holdoutExperimentIds.validation, chosen.holdoutExperimentIds.test])
|
||||
.size !== 3
|
||||
) {
|
||||
throw invalid();
|
||||
}
|
||||
for (const item of chosen.training) {
|
||||
validateEvidence(item, 'train');
|
||||
if (item.metrics.totalReturn === null) {
|
||||
throw invalid();
|
||||
}
|
||||
}
|
||||
}
|
||||
if (value.report) {
|
||||
const saved = value.report;
|
||||
if (
|
||||
!value.selection ||
|
||||
saved.validationId !== value.id ||
|
||||
saved.previewHash !== value.previewHash ||
|
||||
saved.selectionHash !== value.selection.selectionHash ||
|
||||
!same(saved.training, value.selection.training)
|
||||
) {
|
||||
throw invalid();
|
||||
}
|
||||
validateEvidence(saved.validation, 'validation');
|
||||
validateEvidence(saved.test, 'test');
|
||||
}
|
||||
if (
|
||||
(value.actions.select.available && (value.selection || value.cancelRequested)) ||
|
||||
(value.actions.finalize.available &&
|
||||
(!value.selection || value.report || value.cancelRequested))
|
||||
) {
|
||||
throw invalid();
|
||||
}
|
||||
return { ...value, preview, phases } as ValidationDetailView;
|
||||
}
|
||||
export {
|
||||
parseValidationDetail,
|
||||
ValidationApiError,
|
||||
validationEvidenceSchema,
|
||||
type ValidationDetailView,
|
||||
} from '@stock-bot/stock-config/research-responses';
|
||||
export type { ValidationResultEvidence };
|
||||
|
||||
const envelope = (body: unknown, key: string) => z.record(z.unknown()).parse(body)[key];
|
||||
async function request<T>(
|
||||
path: string,
|
||||
|
|
@ -386,4 +140,3 @@ export const chronologicalValidationDurableApi = {
|
|||
return value;
|
||||
}),
|
||||
};
|
||||
export type { ValidationResultEvidence };
|
||||
|
|
|
|||
|
|
@ -1,341 +1,46 @@
|
|||
import { z } from 'zod';
|
||||
import { canonicalRunRequestSchema } from '@stock-bot/stock-config/canonical-research';
|
||||
import {
|
||||
costScenarioSchema,
|
||||
costSensitivityInputSchema,
|
||||
type CostSensitivityDetail,
|
||||
type CostSensitivityInput,
|
||||
type CostSensitivityPreview,
|
||||
type CostSensitivitySubmission,
|
||||
} from '@stock-bot/stock-config/cost-sensitivity';
|
||||
import {
|
||||
experimentInputSchema,
|
||||
experimentRetrySchema,
|
||||
MAX_EXPERIMENT_TRIALS,
|
||||
type ExperimentDetail,
|
||||
type ExperimentInput,
|
||||
type ExperimentPreview,
|
||||
type ExperimentRetryInput,
|
||||
type ExperimentSubmission,
|
||||
type ExperimentSummary,
|
||||
type ExperimentTrialRetry,
|
||||
} from '@stock-bot/stock-config/experiments';
|
||||
import { researchActorSchema } from '@stock-bot/stock-config/research';
|
||||
import { canonicalStrategyJson } from '@stock-bot/stock-config/strategy';
|
||||
import {
|
||||
ExperimentApiError,
|
||||
invalidExperimentResponse as invalid,
|
||||
parseCostSensitivityPreview,
|
||||
parseExperimentDetail,
|
||||
parseExperimentPreview,
|
||||
parseExperimentSummary as parseSummary,
|
||||
parseWorkbenchExperimentDetail,
|
||||
experimentRetryReceiptSchema as retryReceipt,
|
||||
sameExperimentInput as same,
|
||||
type ExperimentRetryTarget,
|
||||
} from '@stock-bot/stock-config/research-responses';
|
||||
import { API_BASE_URL, apiFetch } from '@/lib/api';
|
||||
|
||||
export class ExperimentApiError extends Error {
|
||||
constructor(
|
||||
message: string,
|
||||
public readonly status: number | null
|
||||
) {
|
||||
super(message);
|
||||
}
|
||||
get ambiguous() {
|
||||
return this.status === null || this.status >= 500;
|
||||
}
|
||||
}
|
||||
const hash = z.string().regex(/^[a-f0-9]{64}$/);
|
||||
const count = z.number().int().nonnegative().max(MAX_EXPERIMENT_TRIALS);
|
||||
const counter = z.number().int().nonnegative().max(2147483647);
|
||||
const scalar = z.union([z.string(), z.number().finite(), z.boolean()]);
|
||||
const candidate = z
|
||||
.object({
|
||||
index: count,
|
||||
trialKey: hash,
|
||||
parameters: z.record(scalar),
|
||||
})
|
||||
.strict();
|
||||
const statuses = ['pending', 'running', 'paused', 'completed', 'failed', 'cancelled'] as const;
|
||||
const counts = z.object({
|
||||
pending: count,
|
||||
running: count,
|
||||
paused: count,
|
||||
completed: count,
|
||||
failed: count,
|
||||
cancelled: count,
|
||||
});
|
||||
const summary = z.object({
|
||||
kind: z.enum(['parameters', 'cost-sensitivity']).optional(),
|
||||
id: z.string().uuid(),
|
||||
name: z.string().min(1),
|
||||
backtestId: z.string().uuid(),
|
||||
createdAt: z.string().min(1),
|
||||
cancelRequested: z.boolean(),
|
||||
trialCount: count.min(1),
|
||||
counts,
|
||||
datasetHash: hash,
|
||||
strategyVersionId: z.string().uuid(),
|
||||
previewHash: hash,
|
||||
});
|
||||
const timestamp = z.number().int().min(-8640000000000000).max(8640000000000000);
|
||||
const dataset = z
|
||||
.object({
|
||||
version: z.literal(2),
|
||||
hash,
|
||||
bounds: z.object({
|
||||
warmupStart: timestamp,
|
||||
tradeStart: timestamp,
|
||||
tradeEnd: timestamp,
|
||||
}),
|
||||
series: z.array(
|
||||
z.object({ id: z.string(), instrumentId: z.string(), interval: z.string() }).passthrough()
|
||||
),
|
||||
})
|
||||
.passthrough();
|
||||
/** Only the manifest fields consumed by this UI are structurally decoded here. */
|
||||
export type ExperimentPreviewView = Omit<ExperimentPreview, 'dataset'> & {
|
||||
dataset: z.infer<typeof dataset>;
|
||||
};
|
||||
export type ExperimentDetailView = Omit<ExperimentDetail, 'preview'> & {
|
||||
preview: ExperimentPreviewView;
|
||||
};
|
||||
export type CostSensitivityPreviewView = Omit<CostSensitivityPreview, 'dataset' | 'source'> & {
|
||||
dataset: ExperimentPreviewView['dataset'];
|
||||
source: ExperimentPreviewView;
|
||||
};
|
||||
export type WorkbenchExperimentPreviewView = ExperimentPreviewView | CostSensitivityPreviewView;
|
||||
export type CostSensitivityDetailView = Omit<CostSensitivityDetail, 'preview'> & {
|
||||
preview: CostSensitivityPreviewView;
|
||||
};
|
||||
export type WorkbenchExperimentDetailView = ExperimentDetailView | CostSensitivityDetailView;
|
||||
const preview = z
|
||||
.object({
|
||||
version: z.literal('research-experiment-preview/v1'),
|
||||
previewHash: hash,
|
||||
input: experimentInputSchema,
|
||||
request: canonicalRunRequestSchema,
|
||||
dataset,
|
||||
candidates: z.array(candidate).min(1).max(MAX_EXPERIMENT_TRIALS),
|
||||
})
|
||||
.strict();
|
||||
const metric = z.number().finite().nullable();
|
||||
export const experimentMetricsSchema = z.object({
|
||||
totalReturn: metric,
|
||||
cagr: metric,
|
||||
maxDrawdown: metric,
|
||||
exposureTime: metric,
|
||||
volatility: metric,
|
||||
downsideDeviation: metric,
|
||||
sharpeRatio: metric,
|
||||
sortinoRatio: metric,
|
||||
var95: metric,
|
||||
cvar95: metric,
|
||||
var99: metric,
|
||||
alpha: z.null(),
|
||||
beta: z.null(),
|
||||
informationRatio: z.null(),
|
||||
roundTripCount: z.null(),
|
||||
winRate: z.null(),
|
||||
profitFactor: z.null(),
|
||||
avgWin: z.null(),
|
||||
avgLoss: z.null(),
|
||||
});
|
||||
const trial = candidate.extend({
|
||||
runId: z.string().uuid().nullable(),
|
||||
attemptNumber: counter,
|
||||
retryCount: counter,
|
||||
status: z.enum([...statuses, 'missing']),
|
||||
progress: z.number().finite().min(0).max(100),
|
||||
cancelRequested: z.boolean(),
|
||||
error: z.string().nullable(),
|
||||
comparable: z.boolean(),
|
||||
diagnostic: z.string().nullable(),
|
||||
metrics: experimentMetricsSchema.nullable(),
|
||||
unavailable: z.record(z.string()).nullable(),
|
||||
limitations: z.array(z.string()),
|
||||
});
|
||||
const detail = summary.extend({
|
||||
standalone: z.boolean().optional(),
|
||||
preview,
|
||||
trials: z.array(trial).max(MAX_EXPERIMENT_TRIALS),
|
||||
});
|
||||
const retryReceipt = z.object({
|
||||
id: z.string().uuid(),
|
||||
experimentId: z.string().uuid(),
|
||||
runId: z.string().uuid(),
|
||||
trialKey: hash,
|
||||
retryNumber: counter.min(1),
|
||||
previousAttemptNumber: counter,
|
||||
previousAttemptId: z.string().uuid().nullable(),
|
||||
error: z.string().nullable(),
|
||||
progress: z.number().finite().min(0).max(100),
|
||||
currentDate: z.string().nullable(),
|
||||
startedAt: z.string().nullable(),
|
||||
completedAt: z.string().nullable(),
|
||||
pausedAt: z.string().nullable(),
|
||||
failureUpdatedAt: z.string().min(1),
|
||||
recordedAt: z.string().min(1),
|
||||
principal: researchActorSchema,
|
||||
reviewId: z.string().uuid(),
|
||||
});
|
||||
/** Immutable source identity captured when the operator reviews a failed trial. */
|
||||
export interface ExperimentRetryTarget {
|
||||
experimentId: string;
|
||||
backtestId: string;
|
||||
previewHash: string;
|
||||
runId: string;
|
||||
trialKey: string;
|
||||
}
|
||||
const same = (left: unknown, right: unknown) =>
|
||||
canonicalStrategyJson(left) === canonicalStrategyJson(right);
|
||||
const invalid = () =>
|
||||
new ExperimentApiError(
|
||||
'The experiment response could not be verified. Refresh or retry the same submission.',
|
||||
null
|
||||
);
|
||||
export {
|
||||
ExperimentApiError,
|
||||
experimentMetricsSchema,
|
||||
parseCostSensitivityPreview,
|
||||
parseExperimentDetail,
|
||||
parseExperimentPreview,
|
||||
parseWorkbenchExperimentDetail,
|
||||
type CostSensitivityDetailView,
|
||||
type CostSensitivityPreviewView,
|
||||
type ExperimentDetailView,
|
||||
type ExperimentPreviewView,
|
||||
type ExperimentRetryTarget,
|
||||
type WorkbenchExperimentDetailView,
|
||||
type WorkbenchExperimentPreviewView,
|
||||
} from '@stock-bot/stock-config/research-responses';
|
||||
|
||||
function parseSummary(value: unknown): ExperimentSummary {
|
||||
const parsed = summary.parse(value);
|
||||
if (Object.values(parsed.counts).reduce((sum, value) => sum + value, 0) > parsed.trialCount) {
|
||||
throw invalid();
|
||||
}
|
||||
return parsed;
|
||||
}
|
||||
export function parseExperimentPreview(value: unknown): ExperimentPreviewView {
|
||||
const parsed = preview.parse(value);
|
||||
if (
|
||||
parsed.input.backtestId !== parsed.request.backtestId ||
|
||||
parsed.dataset.hash !== parsed.request.datasetHash ||
|
||||
parsed.dataset.bounds.warmupStart > parsed.dataset.bounds.tradeStart ||
|
||||
parsed.dataset.bounds.tradeStart >= parsed.dataset.bounds.tradeEnd ||
|
||||
!parsed.dataset.series.some(
|
||||
series =>
|
||||
series.id === parsed.request.strategy.selection.seriesId &&
|
||||
series.instrumentId === parsed.request.strategy.selection.instrumentId
|
||||
) ||
|
||||
parsed.candidates.some((item, index) => item.index !== index) ||
|
||||
new Set(parsed.candidates.map(item => item.trialKey)).size !== parsed.candidates.length
|
||||
) {
|
||||
throw invalid();
|
||||
}
|
||||
// The server retains and verifies the complete manifest; the browser only renders its identity/window.
|
||||
return parsed;
|
||||
}
|
||||
const costCandidate = candidate.extend({ costs: costScenarioSchema });
|
||||
const costPreview = preview
|
||||
.omit({ version: true, input: true, candidates: true })
|
||||
.extend({
|
||||
version: z.literal('cost-sensitivity-preview/v1'),
|
||||
input: costSensitivityInputSchema,
|
||||
source: z.unknown(),
|
||||
candidates: z.array(costCandidate).min(2).max(MAX_EXPERIMENT_TRIALS),
|
||||
})
|
||||
.strict();
|
||||
const costDetail = summary.extend({
|
||||
kind: z.literal('cost-sensitivity'),
|
||||
standalone: z.boolean().optional(),
|
||||
preview: z.unknown(),
|
||||
trials: z.array(trial.extend({ costs: costScenarioSchema })).max(MAX_EXPERIMENT_TRIALS),
|
||||
});
|
||||
export function parseCostSensitivityPreview(raw: unknown): CostSensitivityPreviewView {
|
||||
const parsed = costPreview.parse(raw),
|
||||
source = parseExperimentPreview(parsed.source);
|
||||
const costs = [
|
||||
{
|
||||
feeRate: source.request.policy.matching.risk.feeRate,
|
||||
slippageRate: source.request.policy.matching.slippageRate,
|
||||
},
|
||||
...parsed.input.scenarios,
|
||||
];
|
||||
if (
|
||||
!same(source.input, {
|
||||
backtestId: parsed.input.backtestId,
|
||||
name: parsed.input.name,
|
||||
grid: {},
|
||||
}) ||
|
||||
source.candidates.length !== 1 ||
|
||||
!same(source.candidates[0]?.parameters, source.request.strategy.selection.parameters) ||
|
||||
!same(parsed.request, source.request) ||
|
||||
!same(parsed.dataset, source.dataset) ||
|
||||
parsed.candidates.length !== costs.length ||
|
||||
new Set(costs.map(canonicalStrategyJson)).size !== costs.length ||
|
||||
new Set(parsed.candidates.map(item => item.trialKey)).size !== costs.length ||
|
||||
parsed.candidates.some(
|
||||
(item, index) =>
|
||||
item.index !== index ||
|
||||
!same(item.parameters, source.request.strategy.selection.parameters) ||
|
||||
!same(item.costs, costs[index])
|
||||
)
|
||||
) {
|
||||
throw invalid();
|
||||
}
|
||||
return { ...parsed, source } as CostSensitivityPreviewView;
|
||||
}
|
||||
function checkDetail(
|
||||
parsed: z.infer<typeof detail> | z.infer<typeof costDetail>,
|
||||
retained: WorkbenchExperimentPreviewView
|
||||
) {
|
||||
parseSummary(parsed);
|
||||
if (
|
||||
parsed.backtestId !== retained.input.backtestId ||
|
||||
parsed.name !== retained.input.name ||
|
||||
parsed.previewHash !== retained.previewHash ||
|
||||
parsed.datasetHash !== retained.request.datasetHash ||
|
||||
parsed.strategyVersionId !== retained.request.strategy.versionId ||
|
||||
parsed.trialCount !== retained.candidates.length ||
|
||||
parsed.trials.length !== parsed.trialCount
|
||||
) {
|
||||
throw invalid();
|
||||
}
|
||||
const costKind = retained.version === 'cost-sensitivity-preview/v1';
|
||||
if (
|
||||
(costKind && parsed.kind !== 'cost-sensitivity') ||
|
||||
(!costKind && parsed.kind === 'cost-sensitivity')
|
||||
) {
|
||||
throw invalid();
|
||||
}
|
||||
const runIds = new Set<string>();
|
||||
for (const [index, item] of parsed.trials.entries()) {
|
||||
const expected = retained.candidates[index];
|
||||
if (
|
||||
!expected ||
|
||||
item.index !== expected.index ||
|
||||
item.trialKey !== expected.trialKey ||
|
||||
!same(item.parameters, expected.parameters) ||
|
||||
(costKind &&
|
||||
(!('costs' in item) || !('costs' in expected) || !same(item.costs, expected.costs))) ||
|
||||
(item.status === 'missing') !== (item.runId === null) ||
|
||||
(item.status === 'missing' && (item.attemptNumber !== 0 || item.retryCount !== 0)) ||
|
||||
(item.comparable && (item.status !== 'completed' || !item.metrics || !item.unavailable)) ||
|
||||
(item.runId !== null && runIds.has(item.runId))
|
||||
) {
|
||||
throw invalid();
|
||||
}
|
||||
if (item.runId) {
|
||||
runIds.add(item.runId);
|
||||
}
|
||||
}
|
||||
if (
|
||||
statuses.some(
|
||||
status =>
|
||||
parsed.counts[status] !== parsed.trials.filter(item => item.status === status).length
|
||||
)
|
||||
) {
|
||||
throw invalid();
|
||||
}
|
||||
|
||||
return { ...parsed, preview: retained };
|
||||
}
|
||||
export function parseExperimentDetail(value: unknown): ExperimentDetailView {
|
||||
const parsed = detail.parse(value);
|
||||
return checkDetail(parsed, parseExperimentPreview(parsed.preview)) as ExperimentDetailView;
|
||||
}
|
||||
export function parseWorkbenchExperimentDetail(value: unknown): WorkbenchExperimentDetailView {
|
||||
const version = z.object({ preview: z.object({ version: z.string() }) }).parse(value)
|
||||
.preview.version;
|
||||
if (version === 'research-experiment-preview/v1') {
|
||||
return parseExperimentDetail(value);
|
||||
}
|
||||
if (version !== 'cost-sensitivity-preview/v1') {
|
||||
throw invalid();
|
||||
}
|
||||
const parsed = costDetail.parse(value);
|
||||
return checkDetail(
|
||||
parsed,
|
||||
parseCostSensitivityPreview(parsed.preview)
|
||||
) as CostSensitivityDetailView;
|
||||
}
|
||||
async function request<T>(
|
||||
path: string,
|
||||
init: RequestInit,
|
||||
|
|
@ -433,6 +138,8 @@ export const experimentApi = {
|
|||
experiment.id !== target.experimentId ||
|
||||
experiment.backtestId !== target.backtestId ||
|
||||
experiment.previewHash !== target.previewHash ||
|
||||
(receipt.reviewId === null &&
|
||||
experiment.preview.request.strategy.origin !== 'candidate') ||
|
||||
!current ||
|
||||
current.retryCount < receipt.retryNumber ||
|
||||
current.attemptNumber < receipt.previousAttemptNumber
|
||||
|
|
@ -443,7 +150,13 @@ export const experimentApi = {
|
|||
return { retry: receipt as ExperimentTrialRetry, experiment };
|
||||
}
|
||||
),
|
||||
retryHistory: (experimentId: string, runId: string, trialKey: string, signal?: AbortSignal) =>
|
||||
retryHistory: (
|
||||
experimentId: string,
|
||||
runId: string,
|
||||
trialKey: string,
|
||||
signal?: AbortSignal,
|
||||
origin: 'builtin' | 'candidate' = 'builtin'
|
||||
) =>
|
||||
request(
|
||||
`/${encodeURIComponent(experimentId)}/trials/${encodeURIComponent(runId)}/retries`,
|
||||
{ signal },
|
||||
|
|
@ -457,6 +170,7 @@ export const experimentApi = {
|
|||
item.experimentId !== experimentId ||
|
||||
item.runId !== runId ||
|
||||
item.trialKey !== trialKey ||
|
||||
(item.reviewId === null && origin !== 'candidate') ||
|
||||
item.retryNumber !== index + 1
|
||||
)
|
||||
) {
|
||||
|
|
|
|||
|
|
@ -1,119 +1,20 @@
|
|||
import { z } from 'zod';
|
||||
import {
|
||||
experimentComparisonDimensions,
|
||||
experimentComparisonInputSchema,
|
||||
type ExperimentComparison,
|
||||
type ExperimentComparisonInput,
|
||||
} from '@stock-bot/stock-config/experiment-comparison';
|
||||
import { API_BASE_URL, apiFetch } from '@/lib/api';
|
||||
import {
|
||||
parseWorkbenchExperimentDetail,
|
||||
type WorkbenchExperimentDetailView,
|
||||
} from './experimentApi';
|
||||
invalidExperimentComparison as invalid,
|
||||
parseExperimentComparison,
|
||||
type ExperimentComparisonView,
|
||||
} from '@stock-bot/stock-config/research-responses';
|
||||
import { API_BASE_URL, apiFetch } from '@/lib/api';
|
||||
|
||||
export type ExperimentComparisonView = Omit<ExperimentComparison, 'experiments'> & {
|
||||
experiments: [WorkbenchExperimentDetailView, WorkbenchExperimentDetailView];
|
||||
};
|
||||
const hash = z.string().regex(/^[a-f0-9]{64}$/),
|
||||
uuid = z.string().uuid();
|
||||
const schema = z.object({
|
||||
version: z.literal('experiment-comparison/v1'),
|
||||
policy: z.literal('retained-input-compatibility/v1'),
|
||||
selection: z.object({ leftId: uuid, rightId: uuid, referenceTrialKey: hash }).strict(),
|
||||
reference: z.object({
|
||||
experimentId: uuid,
|
||||
trialKey: hash,
|
||||
index: z.number().int().nonnegative(),
|
||||
runId: uuid.nullable(),
|
||||
summaryAvailable: z.boolean(),
|
||||
diagnostic: z.string().nullable(),
|
||||
}),
|
||||
experiments: z.tuple([z.unknown(), z.unknown()]),
|
||||
rows: z
|
||||
.array(
|
||||
z.object({
|
||||
experimentId: uuid,
|
||||
trialKey: hash,
|
||||
inputCompatibility: z.enum(['match', 'mismatch']),
|
||||
differences: z.array(z.enum(experimentComparisonDimensions)),
|
||||
summaryAvailable: z.boolean(),
|
||||
ready: z.boolean(),
|
||||
})
|
||||
)
|
||||
.min(2)
|
||||
.max(200),
|
||||
limitations: z.array(z.string().min(1)).min(1),
|
||||
});
|
||||
const invalid = () =>
|
||||
new Error('The experiment comparison could not be verified. Refresh the same selection.');
|
||||
export function parseComparisonQuery(params: URLSearchParams): ExperimentComparisonInput {
|
||||
const allowed = ['leftId', 'rightId', 'referenceTrialKey'];
|
||||
for (const key of params.keys()) {
|
||||
if (!allowed.includes(key) || params.getAll(key).length !== 1) {
|
||||
throw new Error(
|
||||
'Comparison URL requires two different experiment IDs and at most one reference trial key. Unknown or repeated query fields are not supported.'
|
||||
);
|
||||
}
|
||||
}
|
||||
const result = experimentComparisonInputSchema.safeParse(Object.fromEntries(params));
|
||||
if (!result.success) {
|
||||
throw new Error(
|
||||
'Select two different saved experiments to compare. The URL must contain valid leftId and rightId values and, when supplied, a valid referenceTrialKey.'
|
||||
);
|
||||
}
|
||||
return result.data;
|
||||
}
|
||||
export function parseExperimentComparison(
|
||||
raw: unknown,
|
||||
input: ExperimentComparisonInput
|
||||
): ExperimentComparisonView {
|
||||
const value = schema.parse(raw),
|
||||
experiments = value.experiments.map(
|
||||
parseWorkbenchExperimentDetail
|
||||
) as ExperimentComparisonView['experiments'];
|
||||
const [left, right] = experiments;
|
||||
const expectedKey = input.referenceTrialKey ?? left.trials[0]?.trialKey;
|
||||
const reference = left.trials.find(trial => trial.trialKey === expectedKey);
|
||||
if (
|
||||
!reference ||
|
||||
left.id !== input.leftId ||
|
||||
right.id !== input.rightId ||
|
||||
value.selection.leftId !== input.leftId ||
|
||||
value.selection.rightId !== input.rightId ||
|
||||
value.selection.referenceTrialKey !== expectedKey ||
|
||||
value.reference.experimentId !== left.id ||
|
||||
value.reference.trialKey !== reference.trialKey ||
|
||||
value.reference.index !== reference.index ||
|
||||
value.reference.runId !== reference.runId ||
|
||||
value.reference.summaryAvailable !== reference.comparable ||
|
||||
value.reference.diagnostic !== reference.diagnostic
|
||||
) {
|
||||
throw invalid();
|
||||
}
|
||||
const expectedRows = experiments.flatMap(experiment =>
|
||||
experiment.trials.map(trial => ({ experimentId: experiment.id, trial }))
|
||||
);
|
||||
if (value.rows.length !== expectedRows.length) {
|
||||
throw invalid();
|
||||
}
|
||||
value.rows.forEach((row, index) => {
|
||||
const expected = expectedRows[index],
|
||||
order = row.differences.map(key => experimentComparisonDimensions.indexOf(key));
|
||||
if (
|
||||
!expected ||
|
||||
row.experimentId !== expected.experimentId ||
|
||||
row.trialKey !== expected.trial.trialKey ||
|
||||
order.some((position, i) => i > 0 && position <= (order[i - 1] ?? -1)) ||
|
||||
(row.inputCompatibility === 'match') !== (row.differences.length === 0) ||
|
||||
row.summaryAvailable !== expected.trial.comparable ||
|
||||
row.ready !==
|
||||
(row.inputCompatibility === 'match' && row.summaryAvailable && reference.comparable)
|
||||
) {
|
||||
throw invalid();
|
||||
}
|
||||
});
|
||||
return { ...value, experiments };
|
||||
}
|
||||
export {
|
||||
parseExperimentComparison,
|
||||
parseComparisonQuery,
|
||||
type ExperimentComparisonView,
|
||||
} from '@stock-bot/stock-config/research-responses';
|
||||
export const experimentComparisonApi = {
|
||||
async get(
|
||||
input: ExperimentComparisonInput,
|
||||
|
|
|
|||
|
|
@ -1,312 +1,31 @@
|
|||
import { z } from 'zod';
|
||||
import { researchActorSchema } from '@stock-bot/stock-config/research';
|
||||
import { canonicalStrategyJson } from '@stock-bot/stock-config/strategy';
|
||||
import {
|
||||
MAX_WALK_FORWARD_RUNS,
|
||||
MAX_WALK_FORWARD_WINDOWS,
|
||||
walkForwardInputSchema,
|
||||
walkForwardPolicy,
|
||||
type WalkForwardDetail,
|
||||
walkForwardHashSchema as hash,
|
||||
invalidWalkForwardResponse as invalid,
|
||||
parseWalkForwardDetail,
|
||||
parseWalkForwardPreview,
|
||||
sameWalkForwardInput as same,
|
||||
walkForwardSummarySchema as summary,
|
||||
walkForwardIdSchema as uuid,
|
||||
WalkForwardApiError,
|
||||
} from '@stock-bot/stock-config/research-responses';
|
||||
import {
|
||||
type WalkForwardFinalizationInput,
|
||||
type WalkForwardInput,
|
||||
type WalkForwardSubmission,
|
||||
type WalkForwardSummary,
|
||||
} from '@stock-bot/stock-config/walk-forward';
|
||||
import { API_BASE_URL, apiFetch } from '@/lib/api';
|
||||
import {
|
||||
parseChronologicalValidationPreview,
|
||||
type ChronologicalValidationPreviewView,
|
||||
} from './chronologicalValidationApi';
|
||||
import {
|
||||
parseValidationDetail,
|
||||
validationEvidenceSchema,
|
||||
type ValidationDetailView,
|
||||
} from './chronologicalValidationDurableApi';
|
||||
import { parseExperimentPreview, type ExperimentPreviewView } from './experimentApi';
|
||||
|
||||
export type WalkForwardPreviewView = {
|
||||
version: 'walk-forward-preview/v1';
|
||||
execution: 'preview-only';
|
||||
previewHash: string;
|
||||
input: WalkForwardInput;
|
||||
source: ExperimentPreviewView;
|
||||
policy: typeof walkForwardPolicy;
|
||||
windows: { index: number; preview: ChronologicalValidationPreviewView }[];
|
||||
counts: {
|
||||
windows: number;
|
||||
trainingRuns: number;
|
||||
holdoutRuns: number;
|
||||
totalRuns: number;
|
||||
maxRuns: number;
|
||||
};
|
||||
};
|
||||
export type WalkForwardDetailView = Omit<WalkForwardDetail, 'preview' | 'windows'> & {
|
||||
preview: WalkForwardPreviewView;
|
||||
windows: {
|
||||
index: number;
|
||||
validationId: string;
|
||||
status: 'admitted' | 'missing';
|
||||
validation: ValidationDetailView | null;
|
||||
}[];
|
||||
};
|
||||
export class WalkForwardApiError extends Error {
|
||||
constructor(
|
||||
message: string,
|
||||
public readonly status: number | null
|
||||
) {
|
||||
super(message);
|
||||
}
|
||||
get ambiguous() {
|
||||
return this.status === null || this.status >= 500;
|
||||
}
|
||||
}
|
||||
const hash = z.string().regex(/^[a-f0-9]{64}$/),
|
||||
uuid = z.string().uuid(),
|
||||
count = z.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER);
|
||||
const same = (left: unknown, right: unknown) =>
|
||||
canonicalStrategyJson(left) === canonicalStrategyJson(right);
|
||||
const invalid = () =>
|
||||
new WalkForwardApiError(
|
||||
'The walk-forward response could not be verified. Refresh or retry the same request.',
|
||||
null
|
||||
);
|
||||
const prepared = z.object({
|
||||
version: z.literal('walk-forward-preview/v1'),
|
||||
execution: z.literal('preview-only'),
|
||||
previewHash: hash,
|
||||
input: walkForwardInputSchema,
|
||||
source: z.unknown(),
|
||||
policy: z.unknown(),
|
||||
windows: z
|
||||
.array(z.object({ index: count, preview: z.unknown() }))
|
||||
.min(2)
|
||||
.max(MAX_WALK_FORWARD_WINDOWS),
|
||||
counts: z.object({
|
||||
windows: count,
|
||||
trainingRuns: count,
|
||||
holdoutRuns: count,
|
||||
totalRuns: count,
|
||||
maxRuns: count,
|
||||
}),
|
||||
});
|
||||
export function parseWalkForwardPreview(
|
||||
raw: unknown,
|
||||
expected?: WalkForwardInput
|
||||
): WalkForwardPreviewView {
|
||||
const value = prepared.parse(raw),
|
||||
source = parseExperimentPreview(value.source);
|
||||
const { windows: recipes, ...sourceInput } = value.input;
|
||||
const size = recipes.length,
|
||||
candidates = source.candidates.length;
|
||||
if (
|
||||
(expected && !same(value.input, expected)) ||
|
||||
!same(source.input, sourceInput) ||
|
||||
!same(value.policy, walkForwardPolicy) ||
|
||||
value.windows.length !== size ||
|
||||
!same(value.counts, {
|
||||
windows: size,
|
||||
trainingRuns: size * candidates,
|
||||
holdoutRuns: size * 2,
|
||||
totalRuns: size * (candidates + 2),
|
||||
maxRuns: MAX_WALK_FORWARD_RUNS,
|
||||
}) ||
|
||||
value.counts.totalRuns > MAX_WALK_FORWARD_RUNS
|
||||
) {
|
||||
throw invalid();
|
||||
}
|
||||
const windows = value.windows.map((item, index) => {
|
||||
const recipe = recipes[index],
|
||||
previous = recipes[index - 1];
|
||||
if (
|
||||
!recipe ||
|
||||
item.index !== index ||
|
||||
(previous &&
|
||||
(recipe.train.tradeStart < previous.train.tradeStart ||
|
||||
recipe.train.tradeEnd <= previous.train.tradeEnd ||
|
||||
recipe.validation.tradeStart < previous.test.tradeEnd))
|
||||
) {
|
||||
throw invalid();
|
||||
}
|
||||
const name = `${value.input.name} · window ${index + 1}`;
|
||||
const preview = parseChronologicalValidationPreview(
|
||||
{ preview: item.preview },
|
||||
{ ...sourceInput, name, recipe }
|
||||
);
|
||||
const { previewHash: _windowHash, ...childSource } = preview.source;
|
||||
const { previewHash: _sourceHash, ...originalSource } = source;
|
||||
if (!same(childSource, { ...originalSource, input: { ...sourceInput, name } })) {
|
||||
throw invalid();
|
||||
}
|
||||
return { index, preview };
|
||||
});
|
||||
return { ...value, source, windows, policy: walkForwardPolicy };
|
||||
}
|
||||
const summary = z
|
||||
.object({
|
||||
id: uuid,
|
||||
backtestId: uuid,
|
||||
name: z.string().min(1),
|
||||
previewHash: hash,
|
||||
createdAt: z.string().min(1),
|
||||
cancelRequested: z.boolean(),
|
||||
windowCount: count.min(2).max(MAX_WALK_FORWARD_WINDOWS),
|
||||
reportedWindowCount: count,
|
||||
trainingRunCount: count,
|
||||
plannedRunCount: count.max(MAX_WALK_FORWARD_RUNS),
|
||||
stage: z.enum(['windows', 'reported']),
|
||||
})
|
||||
.superRefine((item, context) => {
|
||||
if (
|
||||
item.reportedWindowCount > item.windowCount ||
|
||||
item.trainingRunCount < item.windowCount ||
|
||||
item.plannedRunCount !== item.trainingRunCount + 2 * item.windowCount
|
||||
) {
|
||||
context.addIssue({
|
||||
code: z.ZodIssueCode.custom,
|
||||
message: 'Inconsistent walk-forward counts',
|
||||
});
|
||||
}
|
||||
});
|
||||
const report = z.object({
|
||||
version: z.literal('walk-forward-report/v1'),
|
||||
id: uuid,
|
||||
walkForwardId: uuid,
|
||||
previewHash: hash,
|
||||
reportHash: hash,
|
||||
createdAt: z.string().min(1),
|
||||
principal: researchActorSchema,
|
||||
reset: z.literal('initial-capital-empty-positions'),
|
||||
segments: z
|
||||
.array(
|
||||
z.object({
|
||||
index: count,
|
||||
validationId: uuid,
|
||||
previewHash: hash,
|
||||
selectionHash: hash,
|
||||
reportId: uuid,
|
||||
reportHash: hash,
|
||||
validation: validationEvidenceSchema,
|
||||
test: validationEvidenceSchema,
|
||||
})
|
||||
)
|
||||
.min(2)
|
||||
.max(MAX_WALK_FORWARD_WINDOWS),
|
||||
limitations: z.array(z.string()),
|
||||
});
|
||||
const detail = z.object({
|
||||
preview: z.unknown(),
|
||||
windows: z.array(
|
||||
z.object({
|
||||
index: count,
|
||||
validationId: uuid,
|
||||
status: z.enum(['admitted', 'missing']),
|
||||
validation: z.unknown(),
|
||||
})
|
||||
),
|
||||
report: report.nullable(),
|
||||
actions: z.object({
|
||||
finalize: z.object({ available: z.boolean(), reason: z.string().nullable() }),
|
||||
}),
|
||||
});
|
||||
export function parseWalkForwardDetail(raw: unknown): WalkForwardDetailView {
|
||||
const base = summary.parse(raw),
|
||||
value = detail.parse(raw),
|
||||
preview = parseWalkForwardPreview(value.preview);
|
||||
if (
|
||||
base.backtestId !== preview.input.backtestId ||
|
||||
base.name !== preview.input.name ||
|
||||
base.previewHash !== preview.previewHash ||
|
||||
base.windowCount !== preview.counts.windows ||
|
||||
base.trainingRunCount !== preview.counts.trainingRuns ||
|
||||
base.plannedRunCount !== preview.counts.totalRuns ||
|
||||
value.windows.length !== base.windowCount ||
|
||||
new Set(value.windows.map(item => item.validationId)).size !== base.windowCount ||
|
||||
(base.stage === 'reported') !== (value.report !== null)
|
||||
) {
|
||||
throw invalid();
|
||||
}
|
||||
const windows = value.windows.map((item, index) => {
|
||||
if (item.index !== index || (item.status === 'missing') !== (item.validation === null)) {
|
||||
throw invalid();
|
||||
}
|
||||
const validation = item.validation === null ? null : parseValidationDetail(item.validation);
|
||||
if (
|
||||
validation &&
|
||||
(validation.id !== item.validationId ||
|
||||
validation.backtestId !== base.backtestId ||
|
||||
!same(validation.preview, preview.windows[index]?.preview))
|
||||
) {
|
||||
throw invalid();
|
||||
}
|
||||
return { ...item, validation };
|
||||
});
|
||||
if (
|
||||
base.reportedWindowCount !== windows.filter(item => item.validation?.report).length ||
|
||||
(value.actions.finalize.available &&
|
||||
(base.cancelRequested ||
|
||||
value.report ||
|
||||
windows.some(
|
||||
item =>
|
||||
!item.validation?.report ||
|
||||
item.validation.cancelRequested ||
|
||||
item.validation.phases.some(
|
||||
phase =>
|
||||
phase.status !== 'admitted' ||
|
||||
!phase.experiment ||
|
||||
phase.experiment.cancelRequested ||
|
||||
phase.experiment.trials.some(
|
||||
trial =>
|
||||
trial.status !== 'completed' || !trial.comparable || trial.cancelRequested
|
||||
)
|
||||
)
|
||||
)))
|
||||
) {
|
||||
throw invalid();
|
||||
}
|
||||
if (value.report) {
|
||||
const saved = value.report;
|
||||
if (
|
||||
saved.walkForwardId !== base.id ||
|
||||
saved.previewHash !== base.previewHash ||
|
||||
saved.segments.length !== base.windowCount
|
||||
) {
|
||||
throw invalid();
|
||||
}
|
||||
for (const [index, segment] of saved.segments.entries()) {
|
||||
const member = windows[index],
|
||||
frozen = preview.windows[index]?.preview,
|
||||
child = member?.validation?.report;
|
||||
const candidate = frozen?.source.candidates[segment.validation.sourceCandidateIndex];
|
||||
if (
|
||||
!member ||
|
||||
!frozen ||
|
||||
!candidate ||
|
||||
segment.index !== index ||
|
||||
segment.validationId !== member.validationId ||
|
||||
segment.previewHash !== frozen.previewHash ||
|
||||
segment.validation.phase !== 'validation' ||
|
||||
segment.test.phase !== 'test' ||
|
||||
segment.validation.sourceCandidateIndex !== segment.test.sourceCandidateIndex ||
|
||||
segment.validation.datasetHash !== frozen.partitions[1].dataset.hash ||
|
||||
segment.test.datasetHash !== frozen.partitions[2].dataset.hash ||
|
||||
[segment.validation, segment.test].some(
|
||||
item =>
|
||||
item.trialKey !== candidate.trialKey || !same(item.parameters, candidate.parameters)
|
||||
) ||
|
||||
(member.validation &&
|
||||
(!child ||
|
||||
segment.reportId !== child.id ||
|
||||
segment.reportHash !== child.reportHash ||
|
||||
segment.selectionHash !== child.selectionHash ||
|
||||
!same(segment.validation, child.validation) ||
|
||||
!same(segment.test, child.test)))
|
||||
) {
|
||||
throw invalid();
|
||||
}
|
||||
}
|
||||
}
|
||||
return { ...base, ...value, preview, windows };
|
||||
}
|
||||
export {
|
||||
WalkForwardApiError,
|
||||
parseWalkForwardDetail,
|
||||
parseWalkForwardPreview,
|
||||
type WalkForwardDetailView,
|
||||
type WalkForwardPreviewView,
|
||||
} from '@stock-bot/stock-config/research-responses';
|
||||
|
||||
const envelope = (body: unknown, key: string) => z.record(z.unknown()).parse(body)[key];
|
||||
async function request<T>(
|
||||
path: string,
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue