create-tradejs 3.1.29-beta.270 → 3.1.29-beta.272

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.
@@ -57,6 +57,13 @@ For calendar-duration stability diagnostics from frozen realized equity, use
57
57
  time under water and recovery duration without rebuilding approvals. Keep
58
58
  full-history diagnostics separate from development-only candidate selection.
59
59
 
60
+ For explanatory market-regime attribution, use `--regimeStudy` on the permanent
61
+ ablation tool. It slices already frozen approvals, preserves capacity identities,
62
+ keeps missing context explicit, and reports directional/monthly market mix,
63
+ exit reasons, costs and mix-versus-within-regime expectancy changes. Read the
64
+ fixed market-regime diagnosis contract in the ablation reference. This is
65
+ retrospective explanation, not a new gate search or an untouched validation.
66
+
60
67
  For frozen historical-coverage symbol groups, use `--symbolCohorts` with
61
68
  `--realizedMetrics`. It reports complete group economics without moving the
62
69
  common partitions, repeating capacity selection, or exposing membership as a
@@ -113,6 +113,43 @@ merge id.
113
113
 
114
114
  ## Variants
115
115
 
116
+ ### Fixed market-regime diagnosis
117
+
118
+ `--regimeStudy <json>` adds retrospective explanatory cohorts **after** the
119
+ named streams have frozen their approvals and capacity. It never reranks a
120
+ regime slice or searches thresholds. Use the existing `--spec` for raw-core
121
+ pass-through and the exact frozen gate. The study JSON specifies `streams`,
122
+ `periods` (`id`, epoch-ms `start`/`end`), and `dimensions` (`id`, causal feature
123
+ `path`, `scope`, `units`, plus sorted numeric `edges` or explicit `categories`).
124
+ Optional `comparePeriods` pairs decompose expectancy change into market-mix
125
+ and within-regime changes. These are descriptive associations, not causal proof.
126
+ Numeric bins are half-open; missing/null/invalid inputs get an explicit missing
127
+ bucket. Period membership uses decision time; economic cohorts sort completed
128
+ outcomes by actual exit. Monthly direction/mix and exit-reason/cost summaries
129
+ are included. Gross PnL already contains modeled slippage: fees are subtracted
130
+ once and slippage is reported separately. No live fill or prospective claim.
131
+ Run `node --test scripts/market-regime-diagnostics.test.mjs` for this contour.
132
+
133
+ Optional `snapshotAudits` (`id`, original payload `path`) diagnoses saved
134
+ numeric setup values separately as missing/null/zero/positive/negative/invalid.
135
+ These data-quality cells never enter regime predicates or gate approvals.
136
+
137
+ Use `scripts/symbol-mix-diagnostics.mjs <frozen-report.json> <regime-spec.json>
138
+ <output.json>` for a common-symbol panel from the already saved approval trace.
139
+ It retains all common symbols and a separate count-only five-trades-per-period
140
+ sensitivity panel, separates later symbols absent from the earlier trace, and
141
+ decomposes mean-PnL change into symbol mix and within-symbol effects. Absence
142
+ from a trace is not a listing date. Output binds the input/spec SHA256. It
143
+ reports economic summaries only, without pretending decision traces establish
144
+ exit-ordered risk. Run its adjacent `symbol-mix-diagnostics.test.mjs` tests.
145
+
146
+ For a formatted completed-trade contract, pass `economicBasis: 'realized'` to
147
+ `formatGateComparisonContract`. It uses realized outcome/risk/partitions and
148
+ directional economics while preserving decision-time cadence/events/capacity.
149
+ Partially overlapping positive q(N+1)+ subsets require their own realized
150
+ evidence and fail closed instead of borrowing qN+ risk. Default decision basis
151
+ is preserved for existing callers.
152
+
116
153
  Pass each hypothesis as:
117
154
 
118
155
  ```text
@@ -8,6 +8,10 @@ import { execFileSync } from 'node:child_process';
8
8
  import { createRequire } from 'node:module';
9
9
  import { pathToFileURL } from 'node:url';
10
10
  import { createHash } from 'node:crypto';
11
+ import {
12
+ buildMarketRegimeDiagnostics,
13
+ validateRegimeStudy,
14
+ } from './market-regime-diagnostics.mjs';
11
15
 
12
16
  const DAY_MS = 24 * 60 * 60 * 1000;
13
17
  const MONTH_DAYS = 30.4375;
@@ -69,6 +73,7 @@ Options:
69
73
  --realizedMetrics Additional completed-trade metrics ordered by actual exit time
70
74
  --symbolCohorts <path> Disjoint frozen symbol groups, diagnostic realized metrics only
71
75
  --monthlyCohorts Calendar monthly export/gate funnel by direction and payload cohort
76
+ --regimeStudy <json> Explanatory fixed market buckets after frozen approval/capacity selection
72
77
  --compareTo <variant> Exact added/removed approval slices versus a named variant
73
78
  --includeGateContext Include current gate output fields for audits only
74
79
  --movingAverageStudy Causal SMA/EMA/WMA grid ablation from candle cache
@@ -304,6 +309,7 @@ export const parseCliArgs = (argv) => {
304
309
  'materializeDiscoveryExport',
305
310
  'timestampPartitionMetadata',
306
311
  'symbolCohorts',
312
+ 'regimeStudy',
307
313
  ].includes(name)
308
314
  ) {
309
315
  options[name] = value;
@@ -350,6 +356,18 @@ export const parseCliArgs = (argv) => {
350
356
  if (options.monthlyCohorts && !options.cohortPath) {
351
357
  throw new Error('--monthlyCohorts requires --cohortPath');
352
358
  }
359
+ if (
360
+ options.regimeStudy &&
361
+ (!options.realizedMetrics ||
362
+ options.crossStrategy ||
363
+ options.movingAverageStudy ||
364
+ options.windowStart == null ||
365
+ options.windowEnd == null)
366
+ ) {
367
+ throw new Error(
368
+ '--regimeStudy requires explicit-window single-core realizedMetrics',
369
+ );
370
+ }
353
371
  if (
354
372
  options.symbolCohorts &&
355
373
  (!options.realizedMetrics ||
@@ -3027,6 +3045,7 @@ export const loadResearchRows = async ({
3027
3045
  runtimeCheckpoint = null,
3028
3046
  strategyArtifactAuthority = null,
3029
3047
  entryNotionalAuthority = null,
3048
+ snapshotAuditPaths = [],
3030
3049
  }) => {
3031
3050
  validateResearchWindow(windowStart, windowEnd);
3032
3051
  const {
@@ -3128,6 +3147,12 @@ export const loadResearchRows = async ({
3128
3147
  quality >= minQuality,
3129
3148
  features,
3130
3149
  auditFeatures: collectDiagnosticFeatures(payload, featurePattern),
3150
+ savedSnapshotFeatures: Object.fromEntries(
3151
+ snapshotAuditPaths.map((p) => [
3152
+ p,
3153
+ readDiagnosticPath(source.payload, p),
3154
+ ]),
3155
+ ),
3131
3156
  auditCohort: cohortPath
3132
3157
  ? readDiagnosticPath(payload, cohortPath)
3133
3158
  : null,
@@ -3142,6 +3167,11 @@ export const loadResearchRows = async ({
3142
3167
  : {
3143
3168
  exitTimestamp: source.tradeResult.exitTimestamp,
3144
3169
  netProfit: source.tradeResult.netProfit,
3170
+ entryTimestamp: source.tradeResult.entryTimestamp,
3171
+ exitReason: source.tradeResult.exitReason,
3172
+ grossProfit: source.tradeResult.grossProfit,
3173
+ totalFee: source.tradeResult.totalFee,
3174
+ totalSlippageCost: source.tradeResult.totalSlippageCost,
3145
3175
  },
3146
3176
  movingAverageSource: {
3147
3177
  provider: String(source.connectorName ?? '')
@@ -6141,6 +6171,7 @@ export const buildAblationReport = ({
6141
6171
  realizedMetrics = false,
6142
6172
  symbolCohorts = null,
6143
6173
  monthlyCohorts = false,
6174
+ regimeStudy = null,
6144
6175
  compareTo = null,
6145
6176
  executionRuntime = null,
6146
6177
  strategyArtifact = null,
@@ -6524,6 +6555,17 @@ export const buildAblationReport = ({
6524
6555
  baseline,
6525
6556
  variants: variantReports,
6526
6557
  featureInventory,
6558
+ ...(regimeStudy
6559
+ ? {
6560
+ marketRegimeDiagnostics: buildMarketRegimeDiagnostics({
6561
+ rows,
6562
+ selectors,
6563
+ spec: regimeStudy,
6564
+ summarizeRows,
6565
+ summaryOptions,
6566
+ }),
6567
+ }
6568
+ : {}),
6527
6569
  ...(monthlyCohorts
6528
6570
  ? {
6529
6571
  monthlyCohortFunnel: buildMonthlyCohortFunnel({
@@ -6585,7 +6627,10 @@ export const formatGateComparisonContract = ({
6585
6627
  acceptanceChecks = [],
6586
6628
  rejectReasons = [],
6587
6629
  conclusion,
6630
+ economicBasis = 'decision',
6588
6631
  }) => {
6632
+ if (!['decision', 'realized'].includes(economicBasis))
6633
+ throw new Error('Invalid contract economicBasis');
6589
6634
  const policies = [
6590
6635
  [beforeReport, beforeVariant, 'before'],
6591
6636
  [afterReport, afterVariant, 'after'],
@@ -6625,12 +6670,17 @@ export const formatGateComparisonContract = ({
6625
6670
  for (const required of ['180d', '90d', '30d', '7d'])
6626
6671
  if (!windows.includes(required))
6627
6672
  throw new Error(`Missing contract window: ${required}`);
6628
- const periodRows = (render) =>
6673
+ const periodRows = (render, economic = true) =>
6629
6674
  windows.flatMap((window) =>
6630
6675
  policies.map(({ policy, label }) => [
6631
6676
  window,
6632
6677
  label,
6633
- ...render(policy.periods[window]),
6678
+ ...render(
6679
+ economic && economicBasis === 'realized'
6680
+ ? policy.realized.periods[window]
6681
+ : policy.periods[window],
6682
+ policy.periods[window],
6683
+ ),
6634
6684
  ]),
6635
6685
  );
6636
6686
  const outcome = (m) => [
@@ -6686,17 +6736,20 @@ export const formatGateComparisonContract = ({
6686
6736
  'Top event count',
6687
6737
  'Top event PnL',
6688
6738
  ],
6689
- periodRows((m) => [
6690
- formatNumber(m.cadencePerDay, 3),
6691
- formatNumber(m.eventsPerDay, 3),
6692
- formatPct(m.activeDayRatio),
6693
- m.events,
6694
- formatNumber(m.tradesPerEvent),
6695
- formatNumber(m.p95Batch),
6696
- m.maxBatch,
6697
- formatPct(m.topEventCountShare),
6698
- formatPct(m.topEventPnlShare),
6699
- ]),
6739
+ periodRows(
6740
+ (m) => [
6741
+ formatNumber(m.cadencePerDay, 3),
6742
+ formatNumber(m.eventsPerDay, 3),
6743
+ formatPct(m.activeDayRatio),
6744
+ m.events,
6745
+ formatNumber(m.tradesPerEvent),
6746
+ formatNumber(m.p95Batch),
6747
+ m.maxBatch,
6748
+ formatPct(m.topEventCountShare),
6749
+ formatPct(m.topEventPnlShare),
6750
+ ],
6751
+ false,
6752
+ ),
6700
6753
  ),
6701
6754
  '',
6702
6755
  '### Risk-adjusted metrics',
@@ -6714,7 +6767,7 @@ export const formatGateComparisonContract = ({
6714
6767
  'Profit/month',
6715
6768
  'Trades/week',
6716
6769
  ],
6717
- periodRows((m) => [
6770
+ periodRows((m, decision) => [
6718
6771
  formatNumber(m.sharpeRatio),
6719
6772
  formatNumber(m.sortinoRatio),
6720
6773
  formatNumber(m.calmarRatio),
@@ -6722,7 +6775,7 @@ export const formatGateComparisonContract = ({
6722
6775
  formatPct(m.maxDrawdownPctOfTotalProfit),
6723
6776
  formatNumber(m.averageProfitPerDay),
6724
6777
  formatNumber(m.averageProfitPerMonth),
6725
- formatNumber(m.cadencePerWeek, 3),
6778
+ formatNumber(decision.cadencePerWeek, 3),
6726
6779
  ]),
6727
6780
  ),
6728
6781
  '',
@@ -6732,24 +6785,43 @@ export const formatGateComparisonContract = ({
6732
6785
  ['Slice', 'Gate', 'N', 'Events', 'WR', 'PF', 'PnL', 'MaxDD', 'Max batch'],
6733
6786
  slices.flatMap((slice, index) =>
6734
6787
  policies.map(({ policy, label }) => {
6735
- const m =
6788
+ const decision =
6736
6789
  index === 0
6737
6790
  ? policy.periods.full
6738
6791
  : index === 1
6739
6792
  ? policy.qualityThresholds[slice]
6740
6793
  : policy.directions[slice];
6794
+ if (
6795
+ economicBasis === 'realized' &&
6796
+ index === 1 &&
6797
+ decision?.trades &&
6798
+ decision.trades !== policy.periods.full.trades
6799
+ )
6800
+ throw new Error(
6801
+ 'Realized contract requires separately realized quality subsets',
6802
+ );
6803
+ const m =
6804
+ economicBasis === 'realized'
6805
+ ? index === 0
6806
+ ? policy.realized.periods.full
6807
+ : index > 1
6808
+ ? policy.realized.directions[slice]
6809
+ : decision?.trades
6810
+ ? policy.realized.periods.full
6811
+ : decision
6812
+ : decision;
6741
6813
  return [
6742
6814
  index > 1 ? `${slice} q${beforeReport.run.minQuality}+` : slice,
6743
6815
  label,
6744
6816
  ...(m
6745
6817
  ? [
6746
6818
  m.trades,
6747
- m.events,
6819
+ decision.events,
6748
6820
  formatPct(m.winRate),
6749
6821
  formatNumber(m.profitFactor),
6750
6822
  formatNumber(m.totalProfit),
6751
6823
  formatNumber(m.maxDrawdown),
6752
- m.maxBatch,
6824
+ decision.maxBatch,
6753
6825
  ]
6754
6826
  : Array(7).fill('n/a')),
6755
6827
  ];
@@ -6800,21 +6872,26 @@ export const formatGateComparisonContract = ({
6800
6872
  'development 60%',
6801
6873
  report.run.trainRows,
6802
6874
  report.run.trainEvents,
6875
+ economicBasis === 'realized' ? policy.realized.train : policy.train,
6803
6876
  policy.train,
6804
6877
  ],
6805
6878
  ...policy.developmentStability.map((block, index) => [
6806
6879
  `development block ${index + 1}`,
6807
6880
  block.rows,
6808
6881
  block.events,
6882
+ economicBasis === 'realized'
6883
+ ? policy.realized.developmentStability[index].metrics
6884
+ : block.metrics,
6809
6885
  block.metrics,
6810
6886
  ]),
6811
6887
  [
6812
6888
  'outer test 40%, historical',
6813
6889
  report.run.testRows,
6814
6890
  report.run.testEvents,
6891
+ economicBasis === 'realized' ? policy.realized.test : policy.test,
6815
6892
  policy.test,
6816
6893
  ],
6817
- ].map(([partition, rows, events, m]) => [
6894
+ ].map(([partition, rows, events, m, decision]) => [
6818
6895
  partition,
6819
6896
  rows,
6820
6897
  events,
@@ -6823,7 +6900,7 @@ export const formatGateComparisonContract = ({
6823
6900
  formatNumber(m.profitFactor),
6824
6901
  formatNumber(m.totalProfit),
6825
6902
  formatNumber(m.maxDrawdown),
6826
- m.maxBatch,
6903
+ decision.maxBatch,
6827
6904
  ]),
6828
6905
  ),
6829
6906
  '',
@@ -7980,6 +8057,16 @@ export const main = async () => {
7980
8057
  return;
7981
8058
  }
7982
8059
  let variants = await loadVariants(options.variants, options.spec);
8060
+ const regimeStudy = options.regimeStudy
8061
+ ? validateRegimeStudy(
8062
+ JSON.parse(
8063
+ await fsp.readFile(
8064
+ path.resolve(projectRoot, options.regimeStudy),
8065
+ 'utf8',
8066
+ ),
8067
+ ),
8068
+ )
8069
+ : null;
7983
8070
  const symbolCohorts = options.symbolCohorts
7984
8071
  ? loadSymbolCohorts({ projectRoot, file: options.symbolCohorts })
7985
8072
  : null;
@@ -8015,6 +8102,7 @@ export const main = async () => {
8015
8102
  frameworkRepositoryRoot,
8016
8103
  filePaths,
8017
8104
  variants: options.movingAverageStudy ? [] : variants,
8105
+ snapshotAuditPaths: (regimeStudy?.snapshotAudits ?? []).map((d) => d.path),
8018
8106
  minQuality: options.minQuality,
8019
8107
  includeGateContext: options.includeGateContext,
8020
8108
  featurePattern,
@@ -8043,6 +8131,7 @@ export const main = async () => {
8043
8131
  }
8044
8132
  const report = buildAblationReport({
8045
8133
  ...loaded,
8134
+ regimeStudy,
8046
8135
  variants,
8047
8136
  minQuality: options.minQuality,
8048
8137
  qualityThresholds: options.qualityThresholds,
@@ -0,0 +1,367 @@
1
+ // Explanatory cohorts of frozen approvals. Never refits a gate or reranks capacity.
2
+ const DAY = 86400000;
3
+ const finite = (x) => typeof x === 'number' && Number.isFinite(x);
4
+
5
+ export function validateRegimeStudy(spec) {
6
+ if (!spec || !Array.isArray(spec.dimensions) || !Array.isArray(spec.periods))
7
+ throw new Error('Regime study requires dimensions and periods');
8
+ const ids = new Set();
9
+ for (const d of spec.dimensions) {
10
+ if (!d.id || ids.has(d.id) || typeof d.path !== 'string')
11
+ throw new Error('Invalid/duplicate regime dimension');
12
+ ids.add(d.id);
13
+ if (
14
+ /(?:^|\.)(?:[^.]*GateFeatures|quality|profit|timestamp|coverage|available|points|rows)(?:\.|$)/i.test(
15
+ d.path,
16
+ )
17
+ )
18
+ throw new Error('Regime dimension must be a signal-time market feature');
19
+ if (d.edges) {
20
+ if (
21
+ !d.edges.every(finite) ||
22
+ d.edges.some((v, i) => i && v <= d.edges[i - 1])
23
+ )
24
+ throw new Error('Regime edges must be finite and strictly increasing');
25
+ } else if (!Array.isArray(d.categories) || !d.categories.length)
26
+ throw new Error('Regime dimension requires edges or categories');
27
+ }
28
+ const periods = new Set();
29
+ for (const p of spec.periods) {
30
+ if (
31
+ !p.id ||
32
+ periods.has(p.id) ||
33
+ !finite(p.start) ||
34
+ !finite(p.end) ||
35
+ p.start >= p.end
36
+ )
37
+ throw new Error('Invalid/duplicate regime period');
38
+ periods.add(p.id);
39
+ }
40
+ return spec;
41
+ }
42
+
43
+ export const savedSnapshotStatus = (value) =>
44
+ value === undefined
45
+ ? 'missing'
46
+ : value === null
47
+ ? 'null'
48
+ : !finite(value)
49
+ ? 'invalid-or-nonnumeric'
50
+ : value === 0
51
+ ? 'zero'
52
+ : value > 0
53
+ ? 'positive'
54
+ : 'negative';
55
+
56
+ export function regimeBucket(value, dimension) {
57
+ if (value == null || (typeof value === 'number' && !finite(value)))
58
+ return 'missing';
59
+ if (dimension.edges) {
60
+ if (!finite(value)) return 'missing';
61
+ const i = dimension.edges.findIndex((edge) => value < edge);
62
+ const n = i === -1 ? dimension.edges.length : i;
63
+ return `[${n ? dimension.edges[n - 1] : '-inf'},${n < dimension.edges.length ? dimension.edges[n] : '+inf'})`;
64
+ }
65
+ return dimension.categories.includes(value) ? String(value) : 'other';
66
+ }
67
+
68
+ function bucketLabels(d) {
69
+ return d.edges
70
+ ? Array.from(
71
+ { length: d.edges.length + 1 },
72
+ (_, i) =>
73
+ `[${i ? d.edges[i - 1] : '-inf'},${i < d.edges.length ? d.edges[i] : '+inf'})`,
74
+ ).concat('missing')
75
+ : d.categories.map(String).concat('other', 'missing');
76
+ }
77
+
78
+ export function buildMarketRegimeDiagnostics({
79
+ rows,
80
+ selectors,
81
+ spec,
82
+ summarizeRows,
83
+ summaryOptions = {},
84
+ }) {
85
+ validateRegimeStudy(spec);
86
+ const realized = new Map();
87
+ for (const r of rows) {
88
+ const t = r.completedTrade;
89
+ if (
90
+ !finite(t?.exitTimestamp) ||
91
+ t.exitTimestamp < r.timestamp ||
92
+ !finite(t.netProfit)
93
+ )
94
+ throw new Error('Regime analysis requires complete valid trade outcomes');
95
+ realized.set(r, { ...r, timestamp: t.exitTimestamp, profit: t.netProfit });
96
+ }
97
+ const metrics = (group, start, end) => {
98
+ const days = Math.max((end - start) / DAY, 1);
99
+ const ordered = group
100
+ .map((r) => realized.get(r))
101
+ .sort((a, b) => a.timestamp - b.timestamp || a.sequence - b.sequence);
102
+ const options = {
103
+ ...summaryOptions,
104
+ denominatorDays: days,
105
+ calendarDays: Math.ceil(days),
106
+ };
107
+ const decision = summarizeRows(group, days, options);
108
+ const completed = summarizeRows(ordered, days, options);
109
+ const exits = {};
110
+ let grossBeforeFees = 0,
111
+ fees = 0,
112
+ slippageEmbeddedInGross = 0,
113
+ costMissing = 0;
114
+ const durations = { win: [], loss: [] };
115
+ for (const r of group) {
116
+ const t = r.completedTrade;
117
+ const reason = t.exitReason ?? 'missing';
118
+ const e = (exits[reason] ??= { n: 0, pnl: 0 });
119
+ e.n++;
120
+ e.pnl += t.netProfit;
121
+ if (![t.grossProfit, t.totalFee, t.totalSlippageCost].every(finite))
122
+ costMissing++;
123
+ else {
124
+ grossBeforeFees += t.grossProfit;
125
+ fees += t.totalFee;
126
+ slippageEmbeddedInGross += t.totalSlippageCost;
127
+ }
128
+ if (
129
+ finite(t.entryTimestamp) &&
130
+ t.exitTimestamp >= t.entryTimestamp &&
131
+ t.netProfit !== 0
132
+ )
133
+ durations[t.netProfit > 0 ? 'win' : 'loss'].push(
134
+ (t.exitTimestamp - t.entryTimestamp) / 3600000,
135
+ );
136
+ }
137
+ const mean = (v) =>
138
+ v.length ? v.reduce((a, b) => a + b, 0) / v.length : null;
139
+ return {
140
+ decision,
141
+ completed,
142
+ exits,
143
+ costs: {
144
+ complete: costMissing === 0,
145
+ missing: costMissing,
146
+ grossBeforeFees,
147
+ fees,
148
+ slippageEmbeddedInGross,
149
+ reconciliation: costMissing
150
+ ? null
151
+ : grossBeforeFees - fees - completed.totalProfit,
152
+ },
153
+ holdingHours: {
154
+ winners: mean(durations.win),
155
+ losers: mean(durations.loss),
156
+ },
157
+ };
158
+ };
159
+ const streams = [];
160
+ for (const name of spec.streams ?? [...selectors.keys()]) {
161
+ const selector = selectors.get(name);
162
+ if (!selector) throw new Error(`Unknown frozen regime stream ${name}`);
163
+ const selected = rows.filter(selector);
164
+ const periods = spec.periods.map((p) => {
165
+ const period = selected.filter(
166
+ (r) => r.timestamp >= p.start && r.timestamp < p.end,
167
+ );
168
+ return {
169
+ ...p,
170
+ metrics: metrics(period, p.start, p.end),
171
+ snapshotAudits: (spec.snapshotAudits ?? []).map((d) => ({
172
+ id: d.id,
173
+ path: d.path,
174
+ role: 'Original saved snapshot data-quality audit only, never market regime or approval feature',
175
+ buckets: [
176
+ 'missing',
177
+ 'null',
178
+ 'zero',
179
+ 'positive',
180
+ 'negative',
181
+ 'invalid-or-nonnumeric',
182
+ ].map((status) => {
183
+ const group = period.filter(
184
+ (r) =>
185
+ savedSnapshotStatus(r.savedSnapshotFeatures?.[d.path]) ===
186
+ status,
187
+ );
188
+ return {
189
+ status,
190
+ metrics: metrics(group, p.start, p.end),
191
+ directions: Object.fromEntries(
192
+ ['LONG', 'SHORT'].map((side) => [
193
+ side,
194
+ metrics(
195
+ group.filter((r) => r.direction === side),
196
+ p.start,
197
+ p.end,
198
+ ),
199
+ ]),
200
+ ),
201
+ };
202
+ }),
203
+ })),
204
+ directions: Object.fromEntries(
205
+ ['LONG', 'SHORT'].map((side) => [
206
+ side,
207
+ metrics(
208
+ period.filter((r) => r.direction === side),
209
+ p.start,
210
+ p.end,
211
+ ),
212
+ ]),
213
+ ),
214
+ dimensions: spec.dimensions.map((d) => {
215
+ const groups = new Map(bucketLabels(d).map((key) => [key, []]));
216
+ for (const r of period)
217
+ groups.get(regimeBucket(r.features[d.path], d)).push(r);
218
+ return {
219
+ id: d.id,
220
+ path: d.path,
221
+ scope: d.scope,
222
+ units: d.units,
223
+ buckets: [...groups].map(([bucket, group]) => ({
224
+ bucket,
225
+ share: period.length ? group.length / period.length : null,
226
+ metrics: metrics(group, p.start, p.end),
227
+ directions: Object.fromEntries(
228
+ ['LONG', 'SHORT'].map((side) => [
229
+ side,
230
+ metrics(
231
+ group.filter((r) => r.direction === side),
232
+ p.start,
233
+ p.end,
234
+ ),
235
+ ]),
236
+ ),
237
+ })),
238
+ };
239
+ }),
240
+ };
241
+ });
242
+ const monthGroups = new Map();
243
+ for (const r of selected) {
244
+ const month = new Date(r.timestamp).toISOString().slice(0, 7);
245
+ (
246
+ monthGroups.get(month) ??
247
+ (monthGroups.set(month, []), monthGroups.get(month))
248
+ ).push(r);
249
+ }
250
+ const months = [...monthGroups]
251
+ .sort(([a], [b]) => a.localeCompare(b))
252
+ .map(([month, group]) => {
253
+ const start = Date.parse(`${month}-01T00:00:00Z`);
254
+ const date = new Date(start);
255
+ date.setUTCMonth(date.getUTCMonth() + 1);
256
+ const end = date.getTime();
257
+ return {
258
+ month,
259
+ metrics: metrics(group, start, end),
260
+ directions: Object.fromEntries(
261
+ ['LONG', 'SHORT'].map((side) => [
262
+ side,
263
+ metrics(
264
+ group.filter((r) => r.direction === side),
265
+ start,
266
+ end,
267
+ ),
268
+ ]),
269
+ ),
270
+ mix: spec.dimensions.map((d) => ({
271
+ id: d.id,
272
+ counts: Object.fromEntries(
273
+ bucketLabels(d).map((b) => [
274
+ b,
275
+ group.filter((r) => regimeBucket(r.features[d.path], d) === b)
276
+ .length,
277
+ ]),
278
+ ),
279
+ })),
280
+ };
281
+ });
282
+ const decompositions = (spec.comparePeriods ?? []).map(
283
+ ([before, after]) => {
284
+ const a = periods.find((p) => p.id === before),
285
+ b = periods.find((p) => p.id === after);
286
+ if (!a || !b) throw new Error('Unknown regime comparison period');
287
+ return {
288
+ before,
289
+ after,
290
+ dimensions: spec.dimensions.map((d, i) => {
291
+ const cells = a.dimensions[i].buckets.map((x, j) => {
292
+ const y = b.dimensions[i].buckets[j];
293
+ const ma = x.metrics.completed.averageTrade,
294
+ mb = y.metrics.completed.averageTrade;
295
+ return {
296
+ bucket: x.bucket,
297
+ beforeN: x.metrics.completed.trades,
298
+ afterN: y.metrics.completed.trades,
299
+ beforeShare: x.share,
300
+ afterShare: y.share,
301
+ beforeMean: ma,
302
+ afterMean: mb,
303
+ mixEffect:
304
+ ma == null || y.share == null
305
+ ? null
306
+ : (y.share - x.share) * ma,
307
+ withinRegimeEffect:
308
+ ma == null || mb == null || y.share == null
309
+ ? null
310
+ : y.share * (mb - ma),
311
+ };
312
+ });
313
+ const complete = cells.every((c) => c.beforeN || !c.afterN);
314
+ return {
315
+ id: d.id,
316
+ complete,
317
+ totalMeanChange:
318
+ b.metrics.completed.averageTrade == null ||
319
+ a.metrics.completed.averageTrade == null
320
+ ? null
321
+ : b.metrics.completed.averageTrade -
322
+ a.metrics.completed.averageTrade,
323
+ mixEffect: complete
324
+ ? cells.reduce((n, c) => n + (c.mixEffect ?? 0), 0)
325
+ : null,
326
+ withinRegimeEffect: complete
327
+ ? cells.reduce((n, c) => n + (c.withinRegimeEffect ?? 0), 0)
328
+ : null,
329
+ cells,
330
+ };
331
+ }),
332
+ };
333
+ },
334
+ );
335
+ streams.push({
336
+ name,
337
+ selected: selected.length,
338
+ periods,
339
+ months,
340
+ decompositions,
341
+ worstTrades: [...selected]
342
+ .sort((a, b) => realized.get(a).profit - realized.get(b).profit)
343
+ .slice(0, 20)
344
+ .map((r) => ({
345
+ signalId: r.signalId,
346
+ symbol: r.symbol,
347
+ direction: r.direction,
348
+ timestamp: r.timestamp,
349
+ trade: r.completedTrade,
350
+ features: Object.fromEntries(
351
+ spec.dimensions.map((d) => [d.id, r.features[d.path] ?? null]),
352
+ ),
353
+ })),
354
+ });
355
+ }
356
+ return {
357
+ schema: 'tradejs-market-regime-diagnostics/v1',
358
+ role: 'Retrospective explanation, not candidate selection or causal proof',
359
+ periodMembership:
360
+ 'signal timestamp, completed outcomes sorted by exit inside each fixed cohort',
361
+ missingPolicy: 'Explicit missing bucket; never neutral or zero',
362
+ costs:
363
+ 'Gross already includes modeled slippage; subtract fees once, never subtract slippage twice',
364
+ spec,
365
+ streams,
366
+ };
367
+ }
@@ -0,0 +1,240 @@
1
+ import test from 'node:test';
2
+ import assert from 'node:assert/strict';
3
+ import {
4
+ summarizeRows,
5
+ buildAblationReport,
6
+ parseVariant,
7
+ formatGateComparisonContract,
8
+ } from './ai-gate-ablation.mjs';
9
+
10
+ test('realized contract presentation keeps completed risk and decision fanout separate', () => {
11
+ const variant = parseVariant('frozen::replace@4::true');
12
+ const rows = [
13
+ row(1, 1, 30, -3, 'bull'),
14
+ row(2, 2, 20, 5, 'bull'),
15
+ row(3, 3, 31, -2, 'bull'),
16
+ ];
17
+ rows.forEach((r) => {
18
+ r.variantMatches = [true];
19
+ r.quality = 4;
20
+ r.directionMatches = true;
21
+ });
22
+ const d = buildAblationReport({
23
+ rows,
24
+ variants: [variant],
25
+ minQuality: 4,
26
+ qualityThresholds: [4, 5],
27
+ terminalWindows: [180, 90, 30, 7],
28
+ validationSplit: 0,
29
+ testSplit: 0.4,
30
+ windowStart: 0,
31
+ windowEnd: 100,
32
+ realizedMetrics: true,
33
+ filePaths: ['fixture.jsonl'],
34
+ });
35
+ const text = formatGateComparisonContract({
36
+ beforeReport: d,
37
+ beforeVariant: 'frozen',
38
+ afterReport: d,
39
+ afterVariant: 'frozen',
40
+ header: 'test',
41
+ economicBasis: 'realized',
42
+ });
43
+ assert.match(
44
+ text,
45
+ /\| full \| before \| 3 \| 33.3% \| 1.00 \| 0.00 \| 0.00 \| 5.00 \| 2 \|/,
46
+ );
47
+ assert.match(text, /\| q4\+ total \| before \| 3 \| 3 \|/);
48
+ });
49
+ import {
50
+ regimeBucket,
51
+ buildMarketRegimeDiagnostics,
52
+ validateRegimeStudy,
53
+ savedSnapshotStatus,
54
+ } from './market-regime-diagnostics.mjs';
55
+
56
+ test('saved-snapshot audit separates null from zero without reconstructing the setup', () => {
57
+ assert.equal(savedSnapshotStatus(null), 'null');
58
+ assert.equal(savedSnapshotStatus(0), 'zero');
59
+ const r = row(1, 1, 2, -3, 'bull');
60
+ r.savedSnapshotFeatures = { 'setup.level': 0 };
61
+ const d = build([r], {
62
+ ...spec,
63
+ snapshotAudits: [{ id: 'level', path: 'setup.level' }],
64
+ });
65
+ const b = d.streams[0].periods[0].snapshotAudits[0].buckets;
66
+ assert.equal(b.find((x) => x.status === 'zero').metrics.completed.trades, 1);
67
+ assert.equal(b.find((x) => x.status === 'null').metrics.completed.trades, 0);
68
+ });
69
+
70
+ test('causal candleQuality is allowed; outcome and gate-output segments are rejected', () => {
71
+ const fixture = (path) => ({
72
+ streams: [],
73
+ periods: [],
74
+ dimensions: [{ id: 'x', path, edges: [0.2] }],
75
+ });
76
+ assert.doesNotThrow(() =>
77
+ validateRegimeStudy(
78
+ fixture('baseContext.structure.candleQuality.rejectionWickScore'),
79
+ ),
80
+ );
81
+ for (const path of [
82
+ 'baseContext.gateFeatures.rsi',
83
+ 'strategyGateFeatures.rsi',
84
+ 'outcome.profit',
85
+ 'quality',
86
+ 'provider.rows',
87
+ ])
88
+ assert.throws(() => validateRegimeStudy(fixture(path)), /signal-time/);
89
+ });
90
+
91
+ const row = (
92
+ sequence,
93
+ timestamp,
94
+ exitTimestamp,
95
+ netProfit,
96
+ state,
97
+ selected = true,
98
+ ) => ({
99
+ sequence,
100
+ signalId: String(sequence),
101
+ timestamp,
102
+ direction: 'SHORT',
103
+ symbol: 'X',
104
+ profit: netProfit,
105
+ features: { state },
106
+ selected,
107
+ completedTrade: {
108
+ entryTimestamp: timestamp,
109
+ exitTimestamp,
110
+ netProfit,
111
+ grossProfit: netProfit + 0.5,
112
+ totalFee: 0.5,
113
+ totalSlippageCost: 1,
114
+ exitReason: netProfit > 0 ? 'take_profit' : 'stop_loss',
115
+ },
116
+ });
117
+ const spec = {
118
+ streams: ['frozen'],
119
+ periods: [{ id: 'full', start: 0, end: 100 }],
120
+ dimensions: [{ id: 'state', path: 'state', categories: ['bull', 'bear'] }],
121
+ };
122
+ const build = (rows, study = spec) =>
123
+ buildMarketRegimeDiagnostics({
124
+ rows,
125
+ selectors: new Map([['frozen', (r) => r.selected]]),
126
+ spec: study,
127
+ summarizeRows,
128
+ });
129
+
130
+ test('CLI report integration groups only final capacity-selected stream', () => {
131
+ const variant = parseVariant('frozen::replace@4::true');
132
+ variant.selection = {
133
+ capacity: 1,
134
+ rankBy: [{ path: 'margin', order: 'desc' }],
135
+ };
136
+ const rows = [row(1, 1, 20, -3, 'bull'), row(2, 1, 21, 5, 'bear')];
137
+ rows.forEach((r, i) => {
138
+ r.variantMatches = [true];
139
+ r.features.margin = i;
140
+ r.quality = 4;
141
+ r.directionMatches = true;
142
+ });
143
+ const report = buildAblationReport({
144
+ rows,
145
+ variants: [variant],
146
+ minQuality: 4,
147
+ qualityThresholds: [4],
148
+ terminalWindows: [7],
149
+ validationSplit: 0,
150
+ testSplit: 0.4,
151
+ windowStart: 0,
152
+ windowEnd: 100,
153
+ realizedMetrics: true,
154
+ filePaths: ['fixture.jsonl'],
155
+ regimeStudy: spec,
156
+ });
157
+ assert.equal(report.variants[0].periods.full.trades, 1);
158
+ const study = report.marketRegimeDiagnostics.streams[0];
159
+ assert.equal(study.selected, 1);
160
+ assert.equal(
161
+ study.periods[0].dimensions[0].buckets.find((b) => b.bucket === 'bull')
162
+ .metrics.completed.trades,
163
+ 0,
164
+ );
165
+ assert.equal(study.periods[0].metrics.completed.totalProfit, 5);
166
+ });
167
+
168
+ test('regime cohorts preserve previously frozen capacity identities and explicit missing', () => {
169
+ const rows = [
170
+ row(1, 1, 20, 5, 'bull'),
171
+ row(2, 1, 21, -3, 'bear'),
172
+ row(3, 1, 22, 99, 'bull', false),
173
+ row(4, 2, 23, -2, null),
174
+ ];
175
+ const report = build(rows).streams[0].periods[0];
176
+ assert.equal(report.metrics.completed.trades, 3);
177
+ assert.equal(report.metrics.completed.totalProfit, 0);
178
+ const buckets = report.dimensions[0].buckets;
179
+ assert.equal(
180
+ buckets.find((b) => b.bucket === 'bull').metrics.completed.trades,
181
+ 1,
182
+ );
183
+ assert.equal(
184
+ buckets.find((b) => b.bucket === 'missing').metrics.completed.trades,
185
+ 1,
186
+ );
187
+ assert.equal(
188
+ buckets.reduce((n, b) => n + b.metrics.completed.trades, 0),
189
+ 3,
190
+ );
191
+ });
192
+
193
+ test('completed risk uses exits, fees reconcile and slippage is not subtracted twice', () => {
194
+ const rows = [
195
+ row(1, 1, 30, -3, 'bull'),
196
+ row(2, 2, 20, 5, 'bull'),
197
+ row(3, 3, 31, -2, 'bull'),
198
+ ];
199
+ const m = build(rows).streams[0].periods[0].metrics;
200
+ assert.equal(m.decision.maxLossStreak, 1);
201
+ assert.equal(m.completed.maxLossStreak, 2);
202
+ assert.equal(m.completed.maxDrawdown, 5);
203
+ assert.equal(m.costs.grossBeforeFees, 1.5);
204
+ assert.equal(m.costs.fees, 1.5);
205
+ assert.equal(m.costs.slippageEmbeddedInGross, 3);
206
+ assert.equal(m.costs.reconciliation, 0);
207
+ });
208
+
209
+ test('numeric bin boundaries are half-open and null/string never becomes zero', () => {
210
+ const d = { edges: [-2, 0, 2] };
211
+ assert.equal(regimeBucket(-2, d), '[-2,0)');
212
+ assert.equal(regimeBucket(0, d), '[0,2)');
213
+ assert.equal(regimeBucket(2, d), '[2,+inf)');
214
+ for (const v of [null, undefined, '0', NaN, Infinity])
215
+ assert.equal(regimeBucket(v, d), 'missing');
216
+ assert.throws(() => build([row(1, 20, 10, 1, 'bull')]), /valid trade/);
217
+ });
218
+
219
+ test('fixed period mean-change decomposition reconciles mix and within-regime change', () => {
220
+ const study = {
221
+ ...spec,
222
+ periods: [
223
+ { id: 'a', start: 0, end: 10 },
224
+ { id: 'b', start: 10, end: 20 },
225
+ ],
226
+ comparePeriods: [['a', 'b']],
227
+ };
228
+ const rows = [
229
+ row(1, 1, 2, 2, 'bull'),
230
+ row(2, 3, 4, -2, 'bear'),
231
+ row(3, 11, 12, 1, 'bull'),
232
+ row(4, 13, 14, 1, 'bull'),
233
+ row(5, 15, 16, -3, 'bear'),
234
+ ];
235
+ const d = build(rows, study).streams[0].decompositions[0].dimensions[0];
236
+ assert.equal(d.complete, true);
237
+ assert.ok(
238
+ Math.abs(d.totalMeanChange - d.mixEffect - d.withinRegimeEffect) < 1e-12,
239
+ );
240
+ });
@@ -0,0 +1,83 @@
1
+ """Plot existing diagnostic aggregates; no gate reconstruction or model fitting."""
2
+ import json
3
+ import sys
4
+ from datetime import datetime
5
+ from pathlib import Path
6
+ import matplotlib
7
+ matplotlib.use("Agg")
8
+ import matplotlib.pyplot as plt
9
+ import matplotlib.dates as dates
10
+
11
+ source, panel, output = map(Path, sys.argv[1:4])
12
+ report = json.loads(source.read_text())
13
+ study = report["marketRegimeDiagnostics"]
14
+ raw, frozen = study["streams"]
15
+ old, later = frozen["periods"][1:3]
16
+ symbols = json.loads(panel.read_text())["streams"][1]["comparisons"][0]["allObservedCommon"]
17
+ green, red, gray = "#007f73", "#bf4b45", "#778899"
18
+ plt.rcParams.update({"font.family": "DejaVu Sans", "font.size": 11, "axes.spines.top": False, "axes.spines.right": False})
19
+ fig = plt.figure(figsize=(15, 12), layout="constrained")
20
+ grid = fig.add_gridspec(3, 2, height_ratios=[1.1, 1, 1])
21
+ top = fig.add_subplot(grid[0, :])
22
+ for stream, color, label in [(raw, gray, "Весь core"), (frozen, green, "Прежний C")]:
23
+ months = stream["months"]
24
+ x = [datetime.fromisoformat(m["month"] + "-01") for m in months]
25
+ y = [m["metrics"]["completed"]["winRate"] * 100 for m in months]
26
+ top.plot(x, y, color=color, label=label, linewidth=1.6)
27
+ sparse = [(a, b) for a, b, m in zip(x, y, months) if m["metrics"]["completed"]["trades"] < 25]
28
+ if sparse:
29
+ top.scatter(*zip(*sparse), color=color, marker="x", s=35, alpha=.5)
30
+ top.axvspan(datetime.fromtimestamp(old["start"] / 1000), datetime.fromtimestamp(old["end"] / 1000), color=green, alpha=.08, label="Ранее удачный период")
31
+ top.axhline(42.5, linestyle="--", color=red, label="Около 42,5% — порог безубыточности C")
32
+ top.set(title="Доля прибыльных сделок по месяцу сигнала", ylabel="Прибыльные сделки, %", ylim=(0, 100))
33
+ top.xaxis.set_major_locator(dates.YearLocator())
34
+ top.xaxis.set_major_formatter(dates.DateFormatter("%Y"))
35
+ top.set_xlim(datetime.fromtimestamp(frozen["periods"][0]["start"] / 1000), datetime.fromtimestamp(frozen["periods"][0]["end"] / 1000))
36
+ top.legend(loc="upper left", ncol=2, fontsize=10)
37
+ top.grid(axis="y", alpha=.15)
38
+
39
+ def comparison(ax, dimension, labels, title):
40
+ a = next(d for d in old["dimensions"] if d["id"] == dimension)
41
+ b = next(d for d in later["dimensions"] if d["id"] == dimension)
42
+ cells = [(x, y) for x, y in zip(a["buckets"], b["buckets"]) if x["metrics"]["completed"]["trades"] and y["metrics"]["completed"]["trades"]]
43
+ indexes = list(range(len(cells)))
44
+ for offset, color, where, legend in [(-.18, green, 0, "04.09.2024–03.03.2025"), (.18, red, 1, "03.03.2025–09.10.2026")]:
45
+ heights = [c[where]["metrics"]["completed"]["winRate"] * 100 for c in cells]
46
+ bars = ax.bar([i + offset for i in indexes], heights, width=.35, color=color, label=legend)
47
+ for bar, c in zip(bars, cells):
48
+ n = c[where]["metrics"]["completed"]["trades"]
49
+ ax.text(bar.get_x() + bar.get_width()/2, bar.get_height() + .7, f"N={n}", ha="center", fontsize=9)
50
+ ax.set_xticks(indexes, labels[:len(cells)])
51
+ ax.axhline(42.5, color=gray, linestyle="--")
52
+ ax.set(title=title, ylabel="Прибыльные сделки, %", ylim=(0, 78))
53
+ ax.legend(fontsize=9)
54
+ ax.grid(axis="y", alpha=.15)
55
+
56
+ comparison(fig.add_subplot(grid[1, 0]), "btc-benchmark-trend", ["BTC: рост MA", "BTC: падение MA"], "Ухудшение есть при обоих направлениях BTC")
57
+ comparison(fig.add_subplot(grid[1, 1]), "btc-return24h", ["BTC < −2%", "−2…0%", "0…+2%", "BTC ≥ +2%"], "Дневное движение BTC не объясняет весь регресс")
58
+
59
+ ax = fig.add_subplot(grid[2, 0])
60
+ dimensions = frozen["decompositions"][0]["dimensions"]
61
+ chosen = [next(d for d in dimensions if d["id"] == name) for name in ["btc-benchmark-trend", "atr-rank100", "adx-strength", "btc-correlation20"]]
62
+ for offset, key, color, label in [(-.18, "mixEffect", gray, "Изменение долей режимов"), (.18, "withinRegimeEffect", red, "Ухудшение внутри режимов")]:
63
+ ax.barh([i + offset for i in range(4)], [d[key] for d in chosen], height=.35, color=color, label=label)
64
+ ax.set_yticks(range(4), ["Тренд BTC", "ATR rank", "ADX", "Корреляция BTC"])
65
+ ax.set(title="Разложение изменения PnL/сделку\nКаждая строка — отдельное сравнение", xlabel="USDT на сделку")
66
+ ax.axvline(0, color=gray)
67
+ ax.legend(fontsize=9, loc="lower left")
68
+ ax.grid(axis="x", alpha=.15)
69
+
70
+ ax = fig.add_subplot(grid[2, 1])
71
+ values = [symbols["before"]["averageTrade"], symbols["after"]["averageTrade"], symbols["laterAbsentBefore"]["averageTrade"]]
72
+ bars = ax.bar(range(3), values, color=[green, red, red], width=.6)
73
+ for bar, val in zip(bars, values):
74
+ ax.text(bar.get_x()+bar.get_width()/2, val + (.1 if val >= 0 else -.22), f"{val:+.2f}", ha="center")
75
+ ax.set_xticks(range(3), ["Общие символы\nраньше", "Те же символы\nпозже", "Поздние символы\nбез ранних сделок"])
76
+ ax.set(title=f"Состав сигналов тоже изменился\nОбщие символы: {symbols['symbols']}", ylabel="PnL/сделку, USDT")
77
+ ax.set_ylim(-1.15, 3.55)
78
+ ax.axhline(0, color=gray)
79
+ ax.grid(axis="y", alpha=.15)
80
+ fig.suptitle("VolatilityCompressionBreakout C: почему хороший период не повторился", fontsize=18)
81
+ fig.supxlabel("Сделки сгруппированы по времени сигнала; x — месяц с N < 25. История уже исследовалась. Связь с режимом не доказывает причинность.", fontsize=10)
82
+ fig.savefig(output, dpi=150)
83
+ fig.savefig(output.with_suffix(".svg"))
@@ -0,0 +1,149 @@
1
+ #!/usr/bin/env node
2
+ import fs from 'node:fs/promises';
3
+ import { createHash } from 'node:crypto';
4
+ import { pathToFileURL } from 'node:url';
5
+ import { summarizeRows } from './ai-gate-ablation.mjs';
6
+
7
+ // Consume only an existing frozen approval trace; never rebuild/rerank a gate.
8
+ export function compareSymbolMix(before, after, minTradesPerSymbol = 1) {
9
+ const group = (rows) => {
10
+ const map = new Map();
11
+ for (const r of rows) {
12
+ if (
13
+ !r.symbol ||
14
+ !Number.isFinite(r.profit) ||
15
+ !Number.isFinite(r.timestamp)
16
+ )
17
+ throw new Error('Invalid frozen approval trace');
18
+ if (!map.has(r.symbol)) map.set(r.symbol, []);
19
+ map.get(r.symbol).push(r);
20
+ }
21
+ return map;
22
+ };
23
+ const a = group(before),
24
+ b = group(after);
25
+ const common = [...a.keys()]
26
+ .filter(
27
+ (s) =>
28
+ a.get(s).length >= minTradesPerSymbol &&
29
+ (b.get(s)?.length ?? 0) >= minTradesPerSymbol,
30
+ )
31
+ .sort();
32
+ const selected = new Set(common);
33
+ const old = before.filter((r) => selected.has(r.symbol)),
34
+ recent = after.filter((r) => selected.has(r.symbol));
35
+ const metrics = (rows) => {
36
+ const m = summarizeRows(rows);
37
+ return Object.fromEntries(
38
+ [
39
+ 'trades',
40
+ 'events',
41
+ 'wins',
42
+ 'losses',
43
+ 'winRate',
44
+ 'totalProfit',
45
+ 'profitFactor',
46
+ 'averageTrade',
47
+ 'averageWin',
48
+ 'averageLoss',
49
+ ].map((k) => [k, m[k]]),
50
+ );
51
+ };
52
+ const symbolCells = common.map((symbol) => {
53
+ const x = metrics(a.get(symbol)),
54
+ y = metrics(b.get(symbol));
55
+ const pa = a.get(symbol).length / old.length,
56
+ pb = b.get(symbol).length / recent.length;
57
+ return {
58
+ symbol,
59
+ before: x,
60
+ after: y,
61
+ beforeShare: pa,
62
+ afterShare: pb,
63
+ mixEffect: (pb - pa) * x.averageTrade,
64
+ withinSymbolEffect: pb * (y.averageTrade - x.averageTrade),
65
+ };
66
+ });
67
+ return {
68
+ minTradesPerSymbol,
69
+ symbols: common.length,
70
+ before: metrics(old),
71
+ after: metrics(recent),
72
+ beforeDirections: Object.fromEntries(
73
+ ['LONG', 'SHORT'].map((d) => [
74
+ d,
75
+ metrics(old.filter((r) => r.direction === d)),
76
+ ]),
77
+ ),
78
+ afterDirections: Object.fromEntries(
79
+ ['LONG', 'SHORT'].map((d) => [
80
+ d,
81
+ metrics(recent.filter((r) => r.direction === d)),
82
+ ]),
83
+ ),
84
+ laterAbsentBefore: metrics(after.filter((r) => !a.has(r.symbol))),
85
+ laterAbsentBeforeSymbols: [...b.keys()].filter((s) => !a.has(s)).length,
86
+ meanChange:
87
+ old.length && recent.length
88
+ ? metrics(recent).averageTrade - metrics(old).averageTrade
89
+ : null,
90
+ mixEffect: symbolCells.length
91
+ ? symbolCells.reduce((n, c) => n + c.mixEffect, 0)
92
+ : null,
93
+ withinSymbolEffect: symbolCells.length
94
+ ? symbolCells.reduce((n, c) => n + c.withinSymbolEffect, 0)
95
+ : null,
96
+ symbolCells,
97
+ };
98
+ }
99
+
100
+ if (
101
+ process.argv[1] &&
102
+ pathToFileURL(process.argv[1]).href === import.meta.url
103
+ ) {
104
+ const [input, specFile, output] = process.argv.slice(2);
105
+ if (!output)
106
+ throw new Error(
107
+ 'Usage: symbol-mix-diagnostics.mjs <frozen-report.json> <regime-spec.json> <output.json>',
108
+ );
109
+ const bytes = await fs.readFile(input),
110
+ specBytes = await fs.readFile(specFile);
111
+ const report = JSON.parse(bytes),
112
+ spec = JSON.parse(specBytes);
113
+ const hash = (b) => createHash('sha256').update(b).digest('hex');
114
+ const streams = spec.streams.map((name) => {
115
+ const trace = report.variants.find((v) => v.name === name)?.approvedSignals;
116
+ if (!trace) throw new Error(`No frozen trace for ${name}`);
117
+ return {
118
+ name,
119
+ comparisons: spec.comparePeriods.map(([before, after]) => {
120
+ const a = spec.periods.find((p) => p.id === before),
121
+ b = spec.periods.find((p) => p.id === after);
122
+ if (!a || !b) throw new Error('Unknown fixed symbol comparison period');
123
+ const rows = (p) =>
124
+ trace.filter((r) => r.timestamp >= p.start && r.timestamp < p.end);
125
+ return {
126
+ before,
127
+ after,
128
+ allObservedCommon: compareSymbolMix(rows(a), rows(b)),
129
+ supportFiveEach: compareSymbolMix(rows(a), rows(b), 5),
130
+ };
131
+ }),
132
+ };
133
+ });
134
+ await fs.writeFile(
135
+ output,
136
+ JSON.stringify(
137
+ {
138
+ schema: 'tradejs-symbol-mix-diagnostics/v1',
139
+ role: 'Retrospective common-symbol panel; economic summaries only, no exit-ordered risk or causal claim',
140
+ input,
141
+ inputSHA256: hash(bytes),
142
+ specSHA256: hash(specBytes),
143
+ streams,
144
+ },
145
+ null,
146
+ 2,
147
+ ) + '\n',
148
+ );
149
+ }
@@ -0,0 +1,29 @@
1
+ import test from 'node:test';
2
+ import assert from 'node:assert/strict';
3
+ import { compareSymbolMix } from './symbol-mix-diagnostics.mjs';
4
+ const r = (symbol, timestamp, profit, direction = 'SHORT') => ({
5
+ symbol,
6
+ timestamp,
7
+ profit,
8
+ direction,
9
+ });
10
+ test('symbol panel separates newly observed symbols and reconciles mean attribution', () => {
11
+ const d = compareSymbolMix(
12
+ [r('A', 1, 2), r('B', 2, -2)],
13
+ [r('A', 3, 1), r('A', 4, 1), r('B', 5, -3), r('C', 5, -10)],
14
+ );
15
+ assert.equal(d.symbols, 2);
16
+ assert.equal(d.after.trades, 3);
17
+ assert.equal(d.laterAbsentBefore.trades, 1);
18
+ assert.equal(d.after.events, 3);
19
+ assert.ok(
20
+ Math.abs(d.meanChange - d.mixEffect - d.withinSymbolEffect) < 1e-12,
21
+ );
22
+ });
23
+ test('support panel uses counts only, preserves direction zeros and rejects invalid traces', () => {
24
+ const d = compareSymbolMix([r('A', 1, 2)], [r('A', 2, -3)], 5);
25
+ assert.equal(d.symbols, 0);
26
+ assert.equal(d.afterDirections.LONG.trades, 0);
27
+ assert.equal(d.meanChange, null);
28
+ assert.throws(() => compareSymbolMix([r('A', 1, NaN)], []), /Invalid/);
29
+ });
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "schema": "tradejs-skill-bundle/v1",
3
3
  "source": "TradeJS-Dev/TradeJS:.codex/skills",
4
- "bundleSha256": "5420dc3f8ed36fd7d8cf508704acd5919b508dd7972d291091b0470834e0bd2e",
4
+ "bundleSha256": "2106b5dcc9688d50d0e73902d1ee981e0c7b7d15aba3d273af6eb04ef688b532",
5
5
  "skills": [
6
6
  "ai-train-local-research",
7
7
  "backtest-config-redis",
@@ -20,10 +20,10 @@
20
20
  "strategy-release"
21
21
  ],
22
22
  "files": {
23
- ".codex/skills/ai-train-local-research/references/gate-ablation.md": "c110d0a986eeccced7ad47c0ab47da8ec1074ff6562dd3f87d85eab3606c2d11",
23
+ ".codex/skills/ai-train-local-research/references/gate-ablation.md": "0de5ad8476df2659e5c0d5a0cb9c053d3d7f424b229253bde683a7c562a2e78f",
24
24
  ".codex/skills/ai-train-local-research/references/pocket-feature-exclusion.md": "c7af65fcfcd404d5324f0222678126d5e166fb77c4c27afea96369ef427f4bb0",
25
25
  ".codex/skills/ai-train-local-research/references/reporting.md": "ae0faaab3b3dd0f4bd27142fa2c9aa889c5e7572a10e9fe1ee79ff57ebbd8653",
26
- ".codex/skills/ai-train-local-research/scripts/ai-gate-ablation.mjs": "1ae57fcebf1cb01a0a0d3222881cc5f9ae36b3e008979b3a5f2bae75e02ed653",
26
+ ".codex/skills/ai-train-local-research/scripts/ai-gate-ablation.mjs": "73d7592eb3c5f52e9739e160348b1419d642ef34044694822c5a6b6e2e26b32e",
27
27
  ".codex/skills/ai-train-local-research/scripts/ai-gate-ablation.test.mjs": "3d37e2ab217991aa083a60e77369a9f1c9afe8c5d0f99b3ea964f59be2c143f3",
28
28
  ".codex/skills/ai-train-local-research/scripts/decision-capture-join.mjs": "be10d5bec64bf102d16aa8097eb8e32701e46cbe4328a99093ab7fb256b4f815",
29
29
  ".codex/skills/ai-train-local-research/scripts/decision-capture-join.test.mjs": "017511e3d1530ab85f1c43677cddd146c7a68aab49cfce201cae0a187038e625",
@@ -31,9 +31,14 @@
31
31
  ".codex/skills/ai-train-local-research/scripts/decision-capture-storage.test.mjs": "10af1fabaa880023215239e27b7d17cdf66e6e09a4a1329a226f2a8a2606d18e",
32
32
  ".codex/skills/ai-train-local-research/scripts/equity-stability.mjs": "3f60d079f881437f275d50ca78e063ef76451b166e031ec3e8f7a29b3b5e8a8a",
33
33
  ".codex/skills/ai-train-local-research/scripts/equity-stability.test.mjs": "48e544ec259d3bbb6b8f7c3112bcf003807b5c84ecff65f43254627ea4dd3de0",
34
+ ".codex/skills/ai-train-local-research/scripts/market-regime-diagnostics.mjs": "a9f69ec62937344f5a160dce0f66d1f3251c9fcf061229dea65236cfe116c59c",
35
+ ".codex/skills/ai-train-local-research/scripts/market-regime-diagnostics.test.mjs": "d7a4f1d8c19a4506bd09cd865b9718f498e4e65a5f54b902fb0309b8eede186c",
36
+ ".codex/skills/ai-train-local-research/scripts/market-regime-plot.py": "3f1e5d93110c6c8987dd09ba16cd65968c789f548fb374905009bb12705b423d",
34
37
  ".codex/skills/ai-train-local-research/scripts/research-entry-gate-bridge.mjs": "f8c9cb7f63c7e83dcaedf6d58979a2b2a3b4730bf7159aae10ee19b875530fa7",
35
38
  ".codex/skills/ai-train-local-research/scripts/research-entry-gate-bridge.test.mjs": "439e844a08631c1af78f2c2b226bb649a2efad79d08c14d67bd2fff297f8a9fe",
36
- ".codex/skills/ai-train-local-research/SKILL.md": "43c084e7fda09470511b3ca6b8b0c571c1e601984e8a46989378504ab26fc994",
39
+ ".codex/skills/ai-train-local-research/scripts/symbol-mix-diagnostics.mjs": "ad70b73ea49060c0a350d2ca2f85788e6900bdbece46434e9a95865965329d89",
40
+ ".codex/skills/ai-train-local-research/scripts/symbol-mix-diagnostics.test.mjs": "6244c3540f708be6f2f29fa5b871a266e0ecee7a5ba4d588b0e3acb47e1ee445",
41
+ ".codex/skills/ai-train-local-research/SKILL.md": "23bd6dbae5d5e8fab46dc94a64de2ac797e47058949d19ca696b9160be67d351",
37
42
  ".codex/skills/backtest-config-redis/scripts/get_backtest_config.sh": "833e950d6348c5b7a4bd3f00d25af60f6394190bff744bd5ab64db9e43d826d5",
38
43
  ".codex/skills/backtest-config-redis/SKILL.md": "ac4f9d685c12f748a87b1882df1f731dd3ae9ec8bd7c11cb652221fe0463febc",
39
44
  ".codex/skills/runtime-parity-mismatch-analysis/SKILL.md": "f9cbc571baaba7a185550415c3ef31f0f55a9503107c8ace2314fac88ba025bd",
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "create-tradejs",
3
- "version": "3.1.29-beta.270",
3
+ "version": "3.1.29-beta.272",
4
4
  "description": "Create a ready-to-run TradeJS project with local infrastructure and the Web UI.",
5
5
  "keywords": [
6
6
  "tradejs",