create-tradejs 3.1.29-beta.291 → 3.1.29-beta.296

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (22) hide show
  1. package/dist/skill-bundle/.codex/skills/ai-train-local-research/SKILL.md +15 -7
  2. package/dist/skill-bundle/.codex/skills/ai-train-local-research/references/gate-ablation.md +35 -0
  3. package/dist/skill-bundle/.codex/skills/strategy-backtest-research/SKILL.md +8 -0
  4. package/dist/skill-bundle/.codex/skills/strategy-backtest-research/references/production-baseline.md +52 -0
  5. package/dist/skill-bundle/.codex/skills/strategy-backtest-research/references/research-comparison-charts.md +113 -0
  6. package/dist/skill-bundle/.codex/skills/strategy-backtest-research/references/research-retention.md +6 -0
  7. package/dist/skill-bundle/.codex/skills/strategy-backtest-research/scripts/research-comparison-chart.mjs +597 -0
  8. package/dist/skill-bundle/.codex/skills/strategy-backtest-research/scripts/research-comparison-chart.test.mjs +144 -0
  9. package/dist/skill-bundle/.codex/skills/strategy-backtest-research/scripts/retire-worktree.py +6 -1
  10. package/dist/skill-bundle/.codex/skills/strategy-backtest-research/scripts/retire-worktree.test.py +25 -0
  11. package/dist/skill-bundle/.codex/skills/strategy-candidate-compare/SKILL.md +14 -0
  12. package/dist/skill-bundle/.codex/skills/strategy-candidate-report/SKILL.md +12 -2
  13. package/dist/skill-bundle/.codex/skills/strategy-forward-start/SKILL.md +13 -0
  14. package/dist/skill-bundle/.codex/skills/strategy-improvement-plan/SKILL.md +6 -0
  15. package/dist/skill-bundle/.codex/skills/strategy-improvement-research/SKILL.md +35 -11
  16. package/dist/skill-bundle/.codex/skills/strategy-improvement-research/references/final-composition-board.md +33 -7
  17. package/dist/skill-bundle/.codex/skills/strategy-improvement-research/scripts/final-composition-board.mjs +74 -203
  18. package/dist/skill-bundle/.codex/skills/strategy-improvement-research/scripts/final-composition-board.test.mjs +23 -9
  19. package/dist/skill-bundle/.codex/skills/strategy-period-revalidate/SKILL.md +14 -1
  20. package/dist/skill-bundle/.codex/skills/strategy-research/SKILL.md +12 -1
  21. package/dist/skill-bundle/.codex/tradejs-skill-bundle.json +21 -17
  22. package/package.json +1 -1
@@ -0,0 +1,597 @@
1
+ #!/usr/bin/env node
2
+
3
+ import { createHash } from 'node:crypto';
4
+ import { mkdir, readFile, writeFile } from 'node:fs/promises';
5
+ import path from 'node:path';
6
+ import { pathToFileURL } from 'node:url';
7
+
8
+ const SCHEMA = 'tradejs-research-comparison-chart/v1';
9
+ const SUMMARY_SCHEMA = 'tradejs-research-comparison-chart-summary/v1';
10
+ const MAX_SERIES = 24;
11
+ const MAX_INPUT_POINTS = 200_000;
12
+ const MAX_RENDER_POINTS = 1_200;
13
+ const ROLES = new Set(['baseline', 'candidate', 'reference', 'diagnostic']);
14
+ const EQUITY_STATUSES = new Set(['observed', 'verified-empty', 'unavailable']);
15
+ const ROLE_LABELS = {
16
+ baseline: 'BASELINE',
17
+ candidate: 'CANDIDATE',
18
+ reference: 'REFERENCE',
19
+ diagnostic: 'DIAGNOSTIC',
20
+ };
21
+ const DEFAULT_COLORS = [
22
+ '#1e456a',
23
+ '#087d69',
24
+ '#8b5cf6',
25
+ '#d97706',
26
+ '#b42318',
27
+ '#2563eb',
28
+ '#64748b',
29
+ '#be185d',
30
+ ];
31
+
32
+ const fail = (message) => {
33
+ throw new Error(message);
34
+ };
35
+
36
+ const textValue = (value, name) => {
37
+ if (typeof value !== 'string' || !value.trim()) {
38
+ fail(`${name} must be a non-empty string`);
39
+ }
40
+ return value.trim();
41
+ };
42
+
43
+ const finite = (value, name) => {
44
+ if (typeof value !== 'number' || !Number.isFinite(value)) {
45
+ fail(`${name} must be a finite number`);
46
+ }
47
+ return value;
48
+ };
49
+
50
+ const integer = (value, name) => {
51
+ const resolved = finite(value, name);
52
+ if (!Number.isInteger(resolved)) fail(`${name} must be an integer`);
53
+ return resolved;
54
+ };
55
+
56
+ const nonNegativeInteger = (value, name) => {
57
+ const resolved = integer(value, name);
58
+ if (resolved < 0) fail(`${name} must be non-negative`);
59
+ return resolved;
60
+ };
61
+
62
+ const escapeXml = (value) =>
63
+ String(value)
64
+ .replaceAll('&', '&amp;')
65
+ .replaceAll('<', '&lt;')
66
+ .replaceAll('>', '&gt;')
67
+ .replaceAll('"', '&quot;')
68
+ .replaceAll("'", '&apos;');
69
+
70
+ const sha256 = (value) => createHash('sha256').update(value).digest('hex');
71
+
72
+ const stableValue = (value) => {
73
+ if (Array.isArray(value)) return value.map(stableValue);
74
+ if (value && typeof value === 'object') {
75
+ return Object.fromEntries(
76
+ Object.entries(value)
77
+ .sort(([left], [right]) => left.localeCompare(right))
78
+ .map(([key, nested]) => [key, stableValue(nested)]),
79
+ );
80
+ }
81
+ return value;
82
+ };
83
+
84
+ const stableStringify = (value) => JSON.stringify(stableValue(value));
85
+
86
+ const resolveColor = (value, index) => {
87
+ const color = value ?? DEFAULT_COLORS[index % DEFAULT_COLORS.length];
88
+ if (typeof color !== 'string' || !/^#[0-9a-fA-F]{6}$/u.test(color)) {
89
+ fail(`series[${index}].color must be a six-digit hex color`);
90
+ }
91
+ return color.toLowerCase();
92
+ };
93
+
94
+ const validatePoint = (point, name) => {
95
+ if (!Array.isArray(point) || point.length !== 2) {
96
+ fail(`${name} must be [timestamp, value]`);
97
+ }
98
+ return [integer(point[0], `${name}[0]`), finite(point[1], `${name}[1]`)];
99
+ };
100
+
101
+ const buildTradeCurve = ({ trades, start, end, name }) => {
102
+ if (!Array.isArray(trades)) fail(`${name}.trades must be an array`);
103
+ if (trades.length > MAX_INPUT_POINTS) {
104
+ fail(`${name}.trades exceeds the ${MAX_INPUT_POINTS} point limit`);
105
+ }
106
+ const ordered = trades
107
+ .map((point, index) => {
108
+ const [timestamp, pnl] = validatePoint(point, `${name}.trades[${index}]`);
109
+ if (timestamp < start || timestamp >= end) {
110
+ fail(`${name}.trades[${index}] is outside the comparison window`);
111
+ }
112
+ return { timestamp, pnl, index };
113
+ })
114
+ .sort(
115
+ (left, right) =>
116
+ left.timestamp - right.timestamp || left.index - right.index,
117
+ );
118
+ let cumulative = 0;
119
+ let peak = 0;
120
+ let streak = 0;
121
+ const points = [[start, 0, 0, 0]];
122
+ for (const trade of ordered) {
123
+ cumulative += trade.pnl;
124
+ peak = Math.max(peak, cumulative);
125
+ streak = trade.pnl < 0 ? streak + 1 : 0;
126
+ points.push([trade.timestamp, cumulative, peak - cumulative, streak]);
127
+ }
128
+ points.push([end, cumulative, peak - cumulative, streak]);
129
+ return {
130
+ points,
131
+ trades: ordered.length,
132
+ pnl: cumulative,
133
+ renderStatus: 'observed',
134
+ streakSemantics: 'consecutive losing completed trades',
135
+ };
136
+ };
137
+
138
+ const buildEquityCurve = ({
139
+ equity,
140
+ equityStatus,
141
+ metrics,
142
+ start,
143
+ end,
144
+ name,
145
+ }) => {
146
+ if (!Array.isArray(equity)) fail(`${name}.equity must be an array`);
147
+ if (equity.length > MAX_INPUT_POINTS) {
148
+ fail(`${name}.equity exceeds the ${MAX_INPUT_POINTS} point limit`);
149
+ }
150
+ const renderStatus = equityStatus ?? 'observed';
151
+ if (!EQUITY_STATUSES.has(renderStatus)) {
152
+ fail(`${name}.equityStatus is invalid`);
153
+ }
154
+ if (renderStatus === 'observed' && equity.length === 0) {
155
+ fail(`${name}.equity must be non-empty when observed`);
156
+ }
157
+ if (renderStatus !== 'observed' && equity.length !== 0) {
158
+ fail(`${name}.equity must be empty unless equityStatus is observed`);
159
+ }
160
+ const trades = nonNegativeInteger(metrics?.trades, `${name}.metrics.trades`);
161
+ const metricPnl = finite(metrics?.pnl, `${name}.metrics.pnl`);
162
+ if (renderStatus === 'verified-empty') {
163
+ if (trades !== 0 || metricPnl !== 0) {
164
+ fail(`${name} verified-empty equity requires zero trades and PnL`);
165
+ }
166
+ return {
167
+ points: [
168
+ [start, 0, 0, 0],
169
+ [end, 0, 0, 0],
170
+ ],
171
+ trades,
172
+ pnl: metricPnl,
173
+ renderStatus,
174
+ streakSemantics: 'no observed completed trades',
175
+ };
176
+ }
177
+ if (renderStatus === 'unavailable') {
178
+ return {
179
+ points: [],
180
+ trades,
181
+ pnl: metricPnl,
182
+ renderStatus,
183
+ streakSemantics: 'unavailable',
184
+ };
185
+ }
186
+ let previousTimestamp = -Infinity;
187
+ let previousPnl = 0;
188
+ let peak = 0;
189
+ let streak = 0;
190
+ const points = [];
191
+ for (const [index, rawPoint] of equity.entries()) {
192
+ const [timestamp, cumulative] = validatePoint(
193
+ rawPoint,
194
+ `${name}.equity[${index}]`,
195
+ );
196
+ if (timestamp < start || timestamp >= end) {
197
+ fail(`${name}.equity[${index}] is outside the comparison window`);
198
+ }
199
+ if (timestamp <= previousTimestamp) {
200
+ fail(`${name}.equity timestamps must be strictly increasing`);
201
+ }
202
+ const delta = cumulative - previousPnl;
203
+ peak = Math.max(peak, cumulative);
204
+ streak = delta < 0 ? streak + 1 : 0;
205
+ points.push([timestamp, cumulative, peak - cumulative, streak]);
206
+ previousTimestamp = timestamp;
207
+ previousPnl = cumulative;
208
+ }
209
+ return {
210
+ points,
211
+ trades,
212
+ pnl: previousPnl,
213
+ renderStatus,
214
+ streakSemantics: 'consecutive negative realized-equity steps',
215
+ };
216
+ };
217
+
218
+ export const validateResearchComparisonSpec = (input) => {
219
+ if (!input || typeof input !== 'object') fail('spec must be an object');
220
+ if (input.schema !== SCHEMA) fail(`spec.schema must be ${SCHEMA}`);
221
+ const window = {
222
+ start: integer(input.window?.start, 'window.start'),
223
+ end: integer(input.window?.end, 'window.end'),
224
+ ...(input.window?.highlightStart === undefined
225
+ ? {}
226
+ : {
227
+ highlightStart: integer(
228
+ input.window.highlightStart,
229
+ 'window.highlightStart',
230
+ ),
231
+ }),
232
+ };
233
+ if (window.end <= window.start) fail('window.end must be after window.start');
234
+ if (
235
+ window.highlightStart !== undefined &&
236
+ (window.highlightStart <= window.start ||
237
+ window.highlightStart >= window.end)
238
+ ) {
239
+ fail('window.highlightStart must be inside the comparison window');
240
+ }
241
+ if (
242
+ !Array.isArray(input.series) ||
243
+ input.series.length < 1 ||
244
+ input.series.length > MAX_SERIES
245
+ ) {
246
+ fail(`series must contain between 1 and ${MAX_SERIES} entries`);
247
+ }
248
+ const ids = new Set();
249
+ const series = input.series.map((entry, index) => {
250
+ const name = `series[${index}]`;
251
+ const id = textValue(entry?.id, `${name}.id`);
252
+ if (ids.has(id)) fail(`duplicate series id: ${id}`);
253
+ ids.add(id);
254
+ const role = textValue(entry.role, `${name}.role`);
255
+ if (!ROLES.has(role)) fail(`${name}.role is invalid`);
256
+ if ((entry.trades === undefined) === (entry.equity === undefined)) {
257
+ fail(`${name} must declare exactly one of trades or equity`);
258
+ }
259
+ const curve =
260
+ entry.trades !== undefined
261
+ ? buildTradeCurve({
262
+ trades: entry.trades,
263
+ start: window.start,
264
+ end: window.end,
265
+ name,
266
+ })
267
+ : buildEquityCurve({
268
+ equity: entry.equity,
269
+ equityStatus: entry.equityStatus,
270
+ metrics: entry.metrics,
271
+ start: window.start,
272
+ end: window.end,
273
+ name,
274
+ });
275
+ if (entry.metrics !== undefined) {
276
+ const expectedTrades = nonNegativeInteger(
277
+ entry.metrics.trades,
278
+ `${name}.metrics.trades`,
279
+ );
280
+ const expectedPnl = finite(entry.metrics.pnl, `${name}.metrics.pnl`);
281
+ if (entry.trades !== undefined && expectedTrades !== curve.trades) {
282
+ fail(`${name}.metrics.trades does not match trades.length`);
283
+ }
284
+ if (
285
+ curve.renderStatus !== 'unavailable' &&
286
+ Math.abs(expectedPnl - curve.pnl) > 0.01
287
+ ) {
288
+ fail(`${name}.metrics.pnl does not match final cumulative PnL`);
289
+ }
290
+ }
291
+ return {
292
+ id,
293
+ label: textValue(entry.label, `${name}.label`),
294
+ role,
295
+ color: resolveColor(entry.color, index),
296
+ source: entry.trades === undefined ? 'equity' : 'trades',
297
+ ...curve,
298
+ };
299
+ });
300
+ if (series.filter(({ role }) => role === 'baseline').length !== 1) {
301
+ fail('series must contain exactly one explicit baseline');
302
+ }
303
+ return {
304
+ schema: SCHEMA,
305
+ title: textValue(input.title, 'title'),
306
+ subtitle: textValue(input.subtitle, 'subtitle'),
307
+ universeLabel: textValue(input.universeLabel, 'universeLabel'),
308
+ pnlUnit: textValue(input.pnlUnit, 'pnlUnit'),
309
+ window,
310
+ series,
311
+ };
312
+ };
313
+
314
+ const formatNumber = (value, digits = 2) => {
315
+ const normalized = Object.is(value, -0) ? 0 : value;
316
+ return normalized.toFixed(digits);
317
+ };
318
+
319
+ const truncate = (value, maxLength) =>
320
+ value.length <= maxLength ? value : `${value.slice(0, maxLength - 1)}…`;
321
+
322
+ const formatAxis = (value) => {
323
+ const normalized = Math.abs(value) < 1e-9 ? 0 : value;
324
+ if (Math.abs(normalized) >= 1_000_000) {
325
+ return `${formatNumber(normalized / 1_000_000, 1)}m`;
326
+ }
327
+ if (Math.abs(normalized) >= 1_000) {
328
+ return `${formatNumber(normalized / 1_000, 1)}k`;
329
+ }
330
+ if (Number.isInteger(normalized)) return String(normalized);
331
+ return formatNumber(normalized, 1);
332
+ };
333
+
334
+ const niceScale = (values, divisions = 5) => {
335
+ const low = Math.min(0, ...values);
336
+ const high = Math.max(0, ...values);
337
+ const rawStep = Math.max(1e-9, (high - low || 1) / divisions);
338
+ const magnitude = 10 ** Math.floor(Math.log10(rawStep));
339
+ const scaled = rawStep / magnitude;
340
+ const stepMultiplier =
341
+ scaled <= 1 ? 1 : scaled <= 2 ? 2 : scaled <= 5 ? 5 : 10;
342
+ const step = stepMultiplier * magnitude;
343
+ const min = Math.floor(low / step) * step;
344
+ const max = Math.max(min + step, Math.ceil(high / step) * step);
345
+ return { min, max, step };
346
+ };
347
+
348
+ const downsample = (points, maxPoints = MAX_RENDER_POINTS) => {
349
+ if (points.length <= maxPoints) return points;
350
+ const selected = new Set([0, points.length - 1]);
351
+ const buckets = Math.max(1, Math.floor((maxPoints - 2) / 6));
352
+ const bucketSize = (points.length - 2) / buckets;
353
+ for (let bucket = 0; bucket < buckets; bucket += 1) {
354
+ const start = 1 + Math.floor(bucket * bucketSize);
355
+ const end = Math.min(
356
+ points.length - 1,
357
+ 1 + Math.floor((bucket + 1) * bucketSize),
358
+ );
359
+ const indices = Array.from(
360
+ { length: Math.max(1, end - start) },
361
+ (_, offset) => Math.min(points.length - 2, start + offset),
362
+ );
363
+ for (const field of [1, 2, 3]) {
364
+ selected.add(
365
+ indices.reduce((best, index) =>
366
+ points[index][field] < points[best][field] ? index : best,
367
+ ),
368
+ );
369
+ selected.add(
370
+ indices.reduce((best, index) =>
371
+ points[index][field] > points[best][field] ? index : best,
372
+ ),
373
+ );
374
+ }
375
+ }
376
+ return [...selected]
377
+ .sort((left, right) => left - right)
378
+ .map((index) => points[index]);
379
+ };
380
+
381
+ const isoDate = (timestamp) => new Date(timestamp).toISOString().slice(0, 10);
382
+
383
+ const text = (x, y, value, attributes = '') =>
384
+ `<text x="${x}" y="${y}" ${attributes}>${escapeXml(value)}</text>`;
385
+
386
+ const renderValidatedResearchComparisonSvg = (spec) => {
387
+ const width = 1280;
388
+ const left = 92;
389
+ const right = 1228;
390
+ const plotWidth = right - left;
391
+ const legendColumns = 2;
392
+ const legendRows = Math.ceil(spec.series.length / legendColumns);
393
+ const height = 795 + Math.max(0, legendRows - 1) * 52;
394
+ const x = (timestamp) =>
395
+ left +
396
+ ((timestamp - spec.window.start) / (spec.window.end - spec.window.start)) *
397
+ plotWidth;
398
+ const renderedSeries = spec.series.map((entry) => ({
399
+ ...entry,
400
+ renderedPoints: downsample(entry.points),
401
+ }));
402
+ const drawPanel = ({ top, panelHeight, field, title: panelTitle, dates }) => {
403
+ const values = spec.series.flatMap(({ points }) =>
404
+ points.map((point) => point[field]),
405
+ );
406
+ const scale = niceScale(values);
407
+ const y = (value) =>
408
+ top +
409
+ panelHeight -
410
+ ((value - scale.min) / (scale.max - scale.min)) * panelHeight;
411
+ const nodes = [text(left, top - 12, panelTitle, 'class="heading"')];
412
+ if (spec.window.highlightStart !== undefined) {
413
+ nodes.push(
414
+ `<rect x="${x(spec.window.highlightStart)}" y="${top}" width="${right - x(spec.window.highlightStart)}" height="${panelHeight}" class="highlight"/>`,
415
+ );
416
+ }
417
+ for (
418
+ let value = scale.min, guard = 0;
419
+ value <= scale.max + scale.step / 2 && guard < 20;
420
+ value += scale.step, guard += 1
421
+ ) {
422
+ const yy = y(value);
423
+ nodes.push(
424
+ `<line x1="${left}" y1="${yy}" x2="${right}" y2="${yy}" class="grid" data-value-tick="${value}"${field === 1 ? ` data-pnl-tick="${value}"` : ''}/>`,
425
+ text(
426
+ left - 8,
427
+ yy + 4,
428
+ formatAxis(value),
429
+ 'text-anchor="end" class="axis"',
430
+ ),
431
+ );
432
+ }
433
+ for (let index = 0; index <= 6; index += 1) {
434
+ const timestamp =
435
+ spec.window.start + (index / 6) * (spec.window.end - spec.window.start);
436
+ const xx = x(timestamp);
437
+ nodes.push(
438
+ `<line x1="${xx}" y1="${top}" x2="${xx}" y2="${top + panelHeight}" class="grid"${dates ? ` data-utc-tick="${timestamp}"` : ''}/>`,
439
+ );
440
+ if (dates) {
441
+ nodes.push(
442
+ text(
443
+ xx,
444
+ top + panelHeight + 22,
445
+ isoDate(timestamp),
446
+ 'text-anchor="middle" class="axis"',
447
+ ),
448
+ );
449
+ }
450
+ }
451
+ for (const entry of renderedSeries) {
452
+ if (entry.renderStatus === 'unavailable') continue;
453
+ const points = entry.renderedPoints
454
+ .map(
455
+ (point) => `${x(point[0]).toFixed(2)},${y(point[field]).toFixed(2)}`,
456
+ )
457
+ .join(' ');
458
+ nodes.push(
459
+ entry.renderedPoints.length === 1
460
+ ? `<circle cx="${x(entry.renderedPoints[0][0]).toFixed(2)}" cy="${y(entry.renderedPoints[0][field]).toFixed(2)}" r="3" data-series="${escapeXml(entry.id)}" fill="${entry.color}"/>`
461
+ : `<polyline points="${points}" data-series="${escapeXml(entry.id)}"${entry.renderStatus === 'verified-empty' ? ` data-zero-guide="${escapeXml(entry.id)}" stroke-dasharray="8 8"` : ''} stroke="${entry.color}" stroke-width="2.7" stroke-linecap="round" stroke-linejoin="round" fill="none"/>`,
462
+ );
463
+ }
464
+ return nodes.join('');
465
+ };
466
+ const metadata = `Date (UTC): ${isoDate(spec.window.start)} — ${isoDate(spec.window.end)} · ${spec.universeLabel}${spec.window.highlightStart === undefined ? '' : ' · заливка показывает выделенный период'}`;
467
+ const legend = spec.series
468
+ .map((entry, index) => {
469
+ const column = index % legendColumns;
470
+ const row = Math.floor(index / legendColumns);
471
+ const lx = left + 570 * column;
472
+ const ly = 728 + 52 * row;
473
+ const label = `${ROLE_LABELS[entry.role]} · ${truncate(entry.label, 48)}`;
474
+ const availability =
475
+ entry.renderStatus === 'verified-empty'
476
+ ? ' · EMPTY (zero guide)'
477
+ : entry.renderStatus === 'unavailable'
478
+ ? ' · UNKNOWN (no equity)'
479
+ : '';
480
+ const availabilityDetail =
481
+ entry.renderStatus === 'verified-empty'
482
+ ? '<desc>verified empty; zero guide is not observed equity</desc>'
483
+ : entry.renderStatus === 'unavailable'
484
+ ? '<desc>equity unavailable (UNKNOWN)</desc>'
485
+ : '';
486
+ return `<g data-legend="${escapeXml(entry.id)}" data-role="${entry.role}" data-equity-legend="${escapeXml(entry.id)}" transform="translate(${lx},${ly})"><title>${escapeXml(entry.label)}</title>${availabilityDetail}<rect width="12" height="12" rx="3" fill="${entry.color}"/>${text(19, 10, label, 'class="heading"')}${text(19, 31, `N=${entry.trades} · PnL ${formatNumber(entry.pnl)} ${spec.pnlUnit}${availability}`, 'class="axis"')}</g>`;
487
+ })
488
+ .join('');
489
+ return `<svg xmlns="http://www.w3.org/2000/svg" width="${width}" height="${height}" viewBox="0 0 ${width} ${height}" role="img" aria-label="${escapeXml(spec.title)}">
490
+ <title>${escapeXml(spec.title)}</title>
491
+ <desc>${escapeXml(`${spec.subtitle}. Baseline and every comparison series are labelled by role.`)}</desc>
492
+ <style>text{font:14px Arial,sans-serif;fill:#172842}.axis{fill:#526680;font-size:12px}.heading{font-weight:700;font-size:15px}.grid{stroke:#dce6ef;stroke-width:1}.highlight{fill:#edf4f9}</style>
493
+ <rect width="100%" height="100%" fill="#fff"/>
494
+ ${text(left, 42, spec.title, 'style="font-size:28px;font-weight:700"')}
495
+ ${text(left, 69, metadata, 'class="axis"')}
496
+ ${text(left, 88, spec.subtitle, 'class="axis"')}
497
+ ${drawPanel({ top: 120, panelHeight: 232, field: 1, title: 'Накопленный net PnL после комиссий и проскальзывания', dates: false })}
498
+ ${drawPanel({ top: 395, panelHeight: 128, field: 2, title: 'Просадка от максимума net PnL', dates: false })}
499
+ ${drawPanel({ top: 566, panelHeight: 110, field: 3, title: 'Последовательные убыточные сделки / отрицательные шаги equity', dates: true })}
500
+ ${legend}
501
+ </svg>`;
502
+ };
503
+
504
+ export const renderResearchComparisonSvg = (input) =>
505
+ renderValidatedResearchComparisonSvg(validateResearchComparisonSpec(input));
506
+
507
+ const renderPng = async (svg, outputPath) => {
508
+ const { default: sharp } = await import('sharp');
509
+ await writeFile(outputPath, await sharp(Buffer.from(svg)).png().toBuffer(), {
510
+ flag: 'wx',
511
+ });
512
+ };
513
+
514
+ export const generateResearchComparisonChart = async ({
515
+ spec,
516
+ outBase,
517
+ png = true,
518
+ }) => {
519
+ const validated = validateResearchComparisonSpec(spec);
520
+ const absoluteBase = path.resolve(outBase);
521
+ await mkdir(path.dirname(absoluteBase), { recursive: true });
522
+ const svg = `${renderValidatedResearchComparisonSvg(validated)}\n`;
523
+ const svgPath = `${absoluteBase}.svg`;
524
+ const pngPath = `${absoluteBase}.png`;
525
+ const summaryPath = `${absoluteBase}.summary.json`;
526
+ await writeFile(svgPath, svg, { flag: 'wx' });
527
+ const artifacts = { [path.basename(svgPath)]: sha256(svg) };
528
+ if (png) {
529
+ await renderPng(svg, pngPath);
530
+ artifacts[path.basename(pngPath)] = sha256(await readFile(pngPath));
531
+ }
532
+ const summary = {
533
+ schema: SUMMARY_SCHEMA,
534
+ inputSha256: sha256(stableStringify(spec)),
535
+ window: validated.window,
536
+ pnlUnit: validated.pnlUnit,
537
+ rendering: {
538
+ interpolation: 'linear-between-realized-observations',
539
+ maxRenderPointsPerSeries: MAX_RENDER_POINTS,
540
+ metricsUseFullResolution: true,
541
+ panels: ['cumulative-net-pnl', 'realized-drawdown', 'loss-streak'],
542
+ rolesAreExplicit: true,
543
+ },
544
+ series: validated.series.map((entry) => ({
545
+ id: entry.id,
546
+ label: entry.label,
547
+ role: entry.role,
548
+ source: entry.source,
549
+ trades: entry.trades,
550
+ pnl: entry.pnl,
551
+ fullResolutionPoints: entry.points.length,
552
+ streakSemantics: entry.streakSemantics,
553
+ renderStatus: entry.renderStatus,
554
+ })),
555
+ artifacts,
556
+ };
557
+ await writeFile(summaryPath, `${JSON.stringify(summary, null, 2)}\n`, {
558
+ flag: 'wx',
559
+ });
560
+ return { svgPath, ...(png ? { pngPath } : {}), summaryPath, summary };
561
+ };
562
+
563
+ const parseArgs = (args) => {
564
+ const options = { png: true };
565
+ for (let index = 0; index < args.length; index += 1) {
566
+ const key = args[index];
567
+ if (key === '--no-png') {
568
+ options.png = false;
569
+ continue;
570
+ }
571
+ const value = args[++index];
572
+ if (!value || value.startsWith('--')) fail(`Value required: ${key}`);
573
+ if (key === '--spec') options.specPath = value;
574
+ else if (key === '--out') options.outBase = value;
575
+ else fail(`Unknown option: ${key}`);
576
+ }
577
+ if (!options.specPath) fail('--spec is required');
578
+ if (!options.outBase) fail('--out is required');
579
+ return options;
580
+ };
581
+
582
+ const main = async () => {
583
+ const options = parseArgs(process.argv.slice(2));
584
+ const spec = JSON.parse(
585
+ await readFile(path.resolve(options.specPath), 'utf8'),
586
+ );
587
+ process.stdout.write(
588
+ `${JSON.stringify(await generateResearchComparisonChart({ spec, outBase: options.outBase, png: options.png }), null, 2)}\n`,
589
+ );
590
+ };
591
+
592
+ if (
593
+ process.argv[1] &&
594
+ import.meta.url === pathToFileURL(path.resolve(process.argv[1])).href
595
+ ) {
596
+ await main();
597
+ }