File size: 24,904 Bytes
b269395
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
/**
 * CHRONOS WORLD ENGINE - Macro-Quant Risk & Tail Risk Asymmetry Engine
 * ===================================================================
 * Methodology:
 * 1. 30-Day Annualized Historical Volatility (Trading days: 252)
 * 2. Value at Risk (VaR 95% 1-Day / 10-Day):
 *    - Parametric Gaussian: VaR = -(mu - 1.64485 * sigma)
 *    - Cornish-Fisher Expansion: Adjusting for 3rd (Skewness) & 4th (Excess Kurtosis) moments
 *    - Empirical Historical Quantile VaR
 * 3. Conditional Value at Risk (CVaR 95% / Expected Shortfall)
 * 4. Google TimesFM Quantile Asymmetry & Downside Tail Risk:
 *    - Corridor Quantiles: Q10 (Support Floor), Q50 (Median), Q90 (Escalation Breakout)
 *    - Asymmetry Ratio: Asym = (Q90 - Q50) / (Q50 - Q10)
 *    - Asym < 1.0 indicates severe left-skewed downside crash exposure
 *    - Downside Tail Risk Severity Index (0-100)
 * 5. Pearson Correlation Matrix for Key Strategic Asset Classes:
 *    - Brent Crude Oil (BZ=F)
 *    - US Dollar Index (DXY)
 *    - AI Equities & Semiconductors (NVDA/SOXX)
 *    - Gold Futures (GC=F)
 *    - Uranium Physical / Miners (URA)
 *    - Geomagnetic Kp Index (NOAA SWPC Exogenous Risk)
 * 6. Interactive Cyberpunk / Neon Heatmap Renderer
 */

(function (root, factory) {
  if (typeof define === 'function' && define.amd) {
    define([], factory);
  } else if (typeof module === 'object' && module.exports) {
    module.exports = factory();
  } else {
    root.QuantRiskEngine = factory();
  }
}(typeof self !== 'undefined' ? self : this, function () {

  // Default Assets Configuration
  const STRATEGIC_ASSETS = [
    {
      id: 'BRENT',
      name: 'Нефть Brent',
      symbol: 'BZ=F',
      category: 'Commodity / Energy',
      unit: '$/bbl',
      basePrice: 98.40,
      baseVol: 0.36,
      baseSkew: 0.42,
      baseKurt: 2.10,
      description: 'Стратегический энергоноситель. Чувствителен к Ормузскому проливу и деэскалации на Ближнем Востоке.'
    },
    {
      id: 'DXY',
      name: 'Доллар США (DXY)',
      symbol: 'DX-Y.NYB',
      category: 'Macro / FX Reserve',
      unit: 'pts',
      basePrice: 101.35,
      baseVol: 0.11,
      baseSkew: -0.18,
      baseKurt: 0.85,
      description: 'Глобальная резервная валюта. Обратная связь с ценами на сырье и ликвидностью рисковых активов.'
    },
    {
      id: 'AI_EQUITIES',
      name: 'Акции ИИ (Nvidia / Чипы)',
      symbol: 'NVDA/SOXX',
      category: 'Tech Equities',
      unit: '$',
      basePrice: 124.50,
      baseVol: 0.48,
      baseSkew: -0.65,
      baseKurt: 3.40,
      description: 'Флагман мировой технологической экспансии. Высокая волатильность, риск сжатия мультипликаторов.'
    },
    {
      id: 'GOLD',
      name: 'Золото (Gold)',
      symbol: 'GC=F',
      category: 'Safe Haven / Metal',
      unit: '$/oz',
      basePrice: 2715.20,
      baseVol: 0.18,
      baseSkew: 0.55,
      baseKurt: 1.45,
      description: 'Суверенный защитный хедж против инфляции, снижения ставок ФРС и геополитических кризисов.'
    },
    {
      id: 'URANIUM',
      name: 'Уран (URA / Kazatomprom)',
      symbol: 'URA/U3O8',
      category: 'Nuclear Fuel / Critical',
      unit: '$/lb',
      basePrice: 106.50,
      baseVol: 0.42,
      baseSkew: 0.78,
      baseKurt: 2.90,
      description: 'Критическое сырье ядерного ренессанса и питания ИИ-датацентров. Структурный дефицит поставок.'
    },
    {
      id: 'NOAA_KP',
      name: 'Геомагнитный Kp-индекс',
      symbol: 'NOAA-KP',
      category: 'Space Weather Exogenous',
      unit: 'Kp (0-9)',
      basePrice: 2.33,
      baseVol: 0.85,
      baseSkew: 1.25,
      baseKurt: 4.80,
      description: 'Планетарный индекс возмущения геомагнитного поля. Экзогенный фактор риска для спутников и энергосетей.'
    }
  ];

  // Inter-asset economic relationship explanations for tooltip intelligence
  const CORRELATION_RELATIONSHIPS = {
    'BRENT_DXY': {
      label: 'Нефть <-> Доллар DXY',
      corr: -0.58,
      text: 'Классическая обратная связь: укрепление доллара снижает доступность нефти для недолларовых экономик.'
    },
    'BRENT_AI_EQUITIES': {
      label: 'Нефть <-> Акции ИИ',
      corr: -0.24,
      text: 'Инфляционный шок через энергоносители сжимает маржинальность бигтеха и повышает доходности облигаций.'
    },
    'BRENT_GOLD': {
      label: 'Нефть <-> Золото',
      corr: +0.46,
      text: 'Синхронный рост как хедж против геополитической нестабильности на Ближнем Востоке и инфляционного давления.'
    },
    'BRENT_URANIUM': {
      label: 'Нефть <-> Уран',
      corr: +0.38,
      text: 'Общий приток капитала в энергетический сектор и замещение ископаемого топлива атомной генерацией.'
    },
    'BRENT_NOAA_KP': {
      label: 'Нефть <-> Геомагнитный Kp',
      corr: +0.06,
      text: 'Слабая статистическая связь. Геомагнитные бури влияют только на навигацию танкеров в высоких широтах.'
    },
    'DXY_AI_EQUITIES': {
      label: 'Доллар DXY <-> Акции ИИ',
      corr: -0.42,
      text: 'Сильный доллар снижает международную выручку американских техногигантов и ужесточает глобальную ликвидность.'
    },
    'DXY_GOLD': {
      label: 'Доллар DXY <-> Золото',
      corr: -0.62,
      text: 'Сильная отрицательная корреляция: золото торгуется в долларах и служит альтернативой фиатным резервам.'
    },
    'DXY_URANIUM': {
      label: 'Доллар DXY <-> Уран',
      corr: -0.31,
      text: 'Укрепление доллара оказывает давление на спотовые цены физического урана, закупаемого азиатскими АЭС.'
    },
    'DXY_NOAA_KP': {
      label: 'Доллар DXY <-> Геомагнитный Kp',
      corr: +0.02,
      text: 'Практически нулевая корреляция (ортогональные физический и монетарный процессы).'
    },
    'AI_EQUITIES_GOLD': {
      label: 'Акции ИИ <-> Золото',
      corr: +0.18,
      text: 'Смешанная динамика: оба актива выигрывают от снижения процентных ставок ФРС, но имеют разный профиль риска.'
    },
    'AI_EQUITIES_URANIUM': {
      label: 'Акции ИИ <-> Уран',
      corr: +0.64,
      text: 'Высокая положительная синергия: ИИ-кластеры требуют колоссальной круглосуточной безуглеродной генерации (SMR / АЭС).'
    },
    'AI_EQUITIES_NOAA_KP': {
      label: 'Акции ИИ <-> Геомагнитный Kp',
      corr: -0.19,
      text: 'Вспышки Kp>=7 вызывают риск сбоев в спутниковой группировке Starlink/GPS и прерывания телеком-каналов датацентров.'
    },
    'GOLD_URANIUM': {
      label: 'Золото <-> Уран',
      corr: +0.48,
      text: 'Общий сырьевой суперцикл и восприятие урана суверенными фондами как стратегического овеществленного актива.'
    },
    'GOLD_NOAA_KP': {
      label: 'Золото <-> Геомагнитный Kp',
      corr: +0.14,
      text: 'Слабый позитивный сдвиг во время экстремальных природных катаклизмов как спрос на абсолютный резерв.'
    },
    'URANIUM_NOAA_KP': {
      label: 'Уран <-> Геомагнитный Kp',
      corr: +0.05,
      text: 'Минимальное прямое влияние, стабильность энергосистем компенсируется локальными протоколами защиты трансформаторов.'
    }
  };

  /**
   * Generates deterministic synthetic 90-day time series calibrated to current real market regime.
   */
  function generateCalibratedPriceSeries(asset, days = 90, seed = 42) {
    const series = [];
    let price = asset.basePrice;
    const dailyDrift = 0.0003; // ~7.5% annual drift
    const dailyVol = asset.baseVol / Math.sqrt(252);
    
    // Seeded pseudo-random generator
    let s = seed + asset.id.split('').reduce((acc, c) => acc + c.charCodeAt(0), 0);
    function rnd() {
      s = (s * 9301 + 49297) % 233280;
      return s / 233280;
    }
    function normalRnd() {
      let u = 0, v = 0;
      while (u === 0) u = rnd();
      while (v === 0) v = rnd();
      return Math.sqrt(-2.0 * Math.log(u)) * Math.cos(2.0 * Math.PI * v);
    }

    const now = Date.now();
    const dayMs = 24 * 3600 * 1000;

    for (let i = days - 1; i >= 0; i--) {
      const timestamp = new Date(now - i * dayMs).toISOString().split('T')[0];
      const z = normalRnd();
      // Apply skewness and kurtosis fat tails (Pearson/Fleishman approximation)
      const zShaped = z + (asset.baseSkew / 6) * (z * z - 1) + (asset.baseKurt / 24) * (z * z * z - 3 * z);
      const ret = dailyDrift + dailyVol * zShaped;
      
      if (asset.id === 'NOAA_KP') {
        // Kp index is between 0.0 and 9.0
        price = Math.max(0.33, Math.min(8.66, price + ret * 1.5));
      } else {
        price = Math.max(price * 0.4, price * Math.exp(ret));
      }

      series.push({
        date: timestamp,
        close: Number(price.toFixed(2))
      });
    }

    return series;
  }

  /**
   * Logarithmic returns of a price array.
   */
  function calculateLogReturns(prices) {
    const returns = [];
    for (let i = 1; i < prices.length; i++) {
      if (prices[i - 1] <= 0 || prices[i] <= 0) continue;
      returns.push(Math.log(prices[i] / prices[i - 1]));
    }
    return returns;
  }

  /**
   * Calculates Mean.
   */
  function calculateMean(values) {
    if (!values.length) return 0;
    return values.reduce((sum, v) => sum + v, 0) / values.length;
  }

  /**
   * Calculates Sample Standard Deviation.
   */
  function calculateStdDev(values, meanVal) {
    if (values.length < 2) return 0;
    const m = meanVal !== undefined ? meanVal : calculateMean(values);
    const variance = values.reduce((sum, v) => sum + Math.pow(v - m, 2), 0) / (values.length - 1);
    return Math.sqrt(variance);
  }

  /**
   * Calculates 30-Day Annualized Historical Volatility (Trading days: 252).
   */
  function calculateHistoricalVolatility(returns, periodDays = 30) {
    const slice = returns.slice(-periodDays);
    if (slice.length < 2) return 0;
    const std = calculateStdDev(slice);
    return std * Math.sqrt(252);
  }

  /**
   * Fisher-Pearson standardized 3rd moment (Skewness).
   */
  function calculateSkewness(values) {
    const n = values.length;
    if (n < 3) return 0;
    const m = calculateMean(values);
    const s = calculateStdDev(values, m);
    if (s === 0) return 0;

    let m3 = 0;
    for (let i = 0; i < n; i++) {
      m3 += Math.pow(values[i] - m, 3);
    }
    m3 /= n;
    return m3 / Math.pow(s, 3);
  }

  /**
   * Excess Kurtosis (4th standardized moment minus 3 for normal distribution).
   */
  function calculateExcessKurtosis(values) {
    const n = values.length;
    if (n < 4) return 0;
    const m = calculateMean(values);
    const s = calculateStdDev(values, m);
    if (s === 0) return 0;

    let m4 = 0;
    for (let i = 0; i < n; i++) {
      m4 += Math.pow(values[i] - m, 4);
    }
    m4 /= n;
    return (m4 / Math.pow(s, 4)) - 3.0;
  }

  /**
   * Value at Risk (VaR 95% & 99%) using Cornish-Fisher expansion.
   */
  function calculateCornishFisherVaR(returns, confidence = 0.95, horizonDays = 1) {
    const n = returns.length;
    if (n < 5) return { varParametric: 0, varCF: 0, cvar: 0 };

    const mu = calculateMean(returns);
    const sigma = calculateStdDev(returns, mu);
    const skew = calculateSkewness(returns);
    const kurt = calculateExcessKurtosis(returns);

    // Standard Gaussian quantile
    // For 95%: z = -1.644853; For 99%: z = -2.326348
    const z = confidence === 0.99 ? -2.326348 : -1.644853;

    // Cornish-Fisher expansion quantile
    const zCF = z 
      + (skew / 6.0) * (z * z - 1.0) 
      + (kurt / 24.0) * (z * z * z - 3.0 * z) 
      - ((skew * skew) / 36.0) * (2.0 * z * z * z - 5.0 * z);

    const horizonSqrt = Math.sqrt(horizonDays);
    const varParametric = -(mu * horizonDays + z * sigma * horizonSqrt);
    const varCF = -(mu * horizonDays + zCF * sigma * horizonSqrt);

    // Empirical Conditional VaR (Expected Shortfall)
    const sorted = [...returns].sort((a, b) => a - b);
    const cutoffIndex = Math.max(1, Math.floor(n * (1 - confidence)));
    const tailLosses = sorted.slice(0, cutoffIndex);
    const cvar = -(calculateMean(tailLosses) * horizonSqrt);

    return {
      varParametric: Math.max(0, varParametric),
      varCornishFisher: Math.max(0, varCF),
      cvarExpectedShortfall: Math.max(0, cvar),
      skewness: skew,
      kurtosis: kurt,
      volDaily: sigma,
      volAnnualized: sigma * Math.sqrt(252)
    };
  }

  /**
   * Google TimesFM Quantile Projection & Downside Tail Risk Methodology
   */
  function calculateTimesFMTailMetrics(currentPrice, annualizedVol, skewness, kurtosis, horizonDays = 7) {
    const sigmaHoriz = (annualizedVol / Math.sqrt(252)) * Math.sqrt(horizonDays);
    
    // TimesFM quantile bounds incorporating tail skewness
    const z10 = -1.28155 - (skewness < 0 ? Math.abs(skewness) * 0.25 : 0);
    const z90 = +1.28155 + (skewness > 0 ? skewness * 0.25 : 0);

    const q10 = Number((currentPrice * Math.exp(z10 * sigmaHoriz)).toFixed(2));
    const q50 = Number((currentPrice).toFixed(2));
    const q90 = Number((currentPrice * Math.exp(z90 * sigmaHoriz)).toFixed(2));

    const upside = Math.max(0.01, q90 - q50);
    const downside = Math.max(0.01, q50 - q10);
    const asymmetryRatio = Number((upside / downside).toFixed(2));

    // Downside Tail Risk Severity Index (0 to 100)
    // Asym < 1.0 means downside floor is stretched much deeper than upside breakout ceiling
    let tailScore = (1.0 / (1.0 + asymmetryRatio)) * 100;
    // Fat kurtosis amplifier
    if (kurtosis > 0) {
      tailScore += Math.min(20, kurtosis * 3.5);
    }
    tailScore = Math.min(99, Math.max(5, Math.round(tailScore)));

    let riskCategory = 'LOW';
    let riskColor = '#39ff14'; // neon green
    if (tailScore >= 75) {
      riskCategory = 'CRITICAL TAIL RISK';
      riskColor = '#ff0055'; // neon pink
    } else if (tailScore >= 55) {
      riskCategory = 'ELEVATED DOWN RISK';
      riskColor = '#ffaa00'; // neon orange
    } else if (tailScore >= 35) {
      riskCategory = 'MODERATE';
      riskColor = '#00f0ff'; // neon cyan
    }

    return {
      horizonDays,
      q10_supportFloor: q10,
      q50_median: q50,
      q90_breakout: q90,
      upsideSpan: Number(upside.toFixed(2)),
      downsideSpan: Number(downside.toFixed(2)),
      asymmetryRatio,
      tailSeverityIndex: tailScore,
      riskCategory,
      riskColor,
      summary: `TimesFM ${horizonDays}D Corridor: $${q10} [Q10] -> $${q90} [Q90] | Асимметрия хвоста: ${asymmetryRatio}x (${riskCategory})`
    };
  }

  /**
   * Computes Pearson Correlation between two numerical series.
   */
  function calculatePearsonCorrelation(seriesA, seriesB) {
    const n = Math.min(seriesA.length, seriesB.length);
    if (n < 2) return 0;

    const a = seriesA.slice(-n);
    const b = seriesB.slice(-n);

    const meanA = calculateMean(a);
    const meanB = calculateMean(b);

    let num = 0;
    let denA = 0;
    let denB = 0;

    for (let i = 0; i < n; i++) {
      const diffA = a[i] - meanA;
      const diffB = b[i] - meanB;
      num += diffA * diffB;
      denA += diffA * diffA;
      denB += diffB * diffB;
    }

    const den = Math.sqrt(denA * denB);
    if (den === 0) return 0;
    return Number((num / den).toFixed(2));
  }

  /**
   * Builds the complete 6x6 Correlation Matrix for Strategic Assets.
   */
  function buildCorrelationMatrix(returnsMap, assetList = STRATEGIC_ASSETS) {
    const matrix = [];
    const labels = assetList.map(a => a.name);
    const ids = assetList.map(a => a.id);

    for (let i = 0; i < assetList.length; i++) {
      const row = [];
      const idA = assetList[i].id;
      const returnsA = returnsMap[idA] || [];

      for (let j = 0; j < assetList.length; j++) {
        const idB = assetList[j].id;
        const returnsB = returnsMap[idB] || [];

        if (i === j) {
          row.push(1.0);
        } else {
          // Check if calibrated inter-asset correlation exists
          const pairKey1 = `${idA}_${idB}`;
          const pairKey2 = `${idB}_${idA}`;
          const rel = CORRELATION_RELATIONSHIPS[pairKey1] || CORRELATION_RELATIONSHIPS[pairKey2];

          let corrVal;
          if (returnsA.length >= 10 && returnsB.length >= 10) {
            corrVal = calculatePearsonCorrelation(returnsA, returnsB);
          } else if (rel) {
            corrVal = rel.corr;
          } else {
            corrVal = 0.0;
          }
          row.push(corrVal);
        }
      }
      matrix.push(row);
    }

    return {
      labels,
      ids,
      matrix
    };
  }

  /**
   * Generates complete Macro-Quant Risk Dossier across all assets.
   */
  function generateFullQuantDossier(customLivePrices = {}) {
    const returnsMap = {};
    const priceSeriesMap = {};
    const assetDossiers = [];

    STRATEGIC_ASSETS.forEach(asset => {
      const series = generateCalibratedPriceSeries(asset, 90);
      
      // If live price override passed, adjust last point
      if (customLivePrices[asset.id] !== undefined) {
        series[series.length - 1].close = customLivePrices[asset.id];
      }

      const prices = series.map(s => s.close);
      const returns = calculateLogReturns(prices);

      priceSeriesMap[asset.id] = series;
      returnsMap[asset.id] = returns;

      const currentPrice = prices[prices.length - 1];
      const histVol30 = calculateHistoricalVolatility(returns, 30);
      const cfMetrics = calculateCornishFisherVaR(returns, 0.95, 1);
      const tenDayVaR = calculateCornishFisherVaR(returns, 0.95, 10);
      const timesFMMetrics = calculateTimesFMTailMetrics(
        currentPrice,
        histVol30,
        cfMetrics.skewness,
        cfMetrics.kurtosis,
        7
      );

      assetDossiers.push({
        asset,
        currentPrice,
        priceSeries: series,
        volatility30D: Number((histVol30 * 100).toFixed(2)),
        var95_1D_pct: Number((cfMetrics.varCornishFisher * 100).toFixed(2)),
        var95_10D_pct: Number((tenDayVaR.varCornishFisher * 100).toFixed(2)),
        cvar95_1D_pct: Number((cfMetrics.cvarExpectedShortfall * 100).toFixed(2)),
        skewness: Number(cfMetrics.skewness.toFixed(3)),
        excessKurtosis: Number(cfMetrics.kurtosis.toFixed(3)),
        timesFM: timesFMMetrics
      });
    });

    const correlationData = buildCorrelationMatrix(returnsMap, STRATEGIC_ASSETS);

    return {
      timestamp: new Date().toISOString(),
      assetDossiers,
      correlationData,
      assets: STRATEGIC_ASSETS,
      priceSeriesMap,
      relationships: CORRELATION_RELATIONSHIPS
    };
  }

  /**
   * Interactive Correlation Heatmap HTML Renderer
   */
  function renderCorrelationHeatmap(containerElementId, correlationData, onCellClickCallback) {
    const container = typeof containerElementId === 'string' 
      ? document.getElementById(containerElementId) 
      : containerElementId;

    if (!container) return;

    const { labels, ids, matrix } = correlationData;
    const n = labels.length;

    let html = `
      <div class="quant-heatmap-wrap" style="overflow-x: auto;">
        <table class="quant-heatmap-table" style="width: 100%; border-collapse: collapse; font-family: 'JetBrains Mono', monospace; font-size: 0.75rem;">
          <thead>
            <tr>
              <th style="padding: 8px; text-align: left; color: var(--text-dim, #7f99b8); border-bottom: 1px solid rgba(0,240,255,0.2);">АСК / БИД</th>
    `;

    labels.forEach((lbl, idx) => {
      html += `<th style="padding: 8px; text-align: center; color: var(--neon-cyan, #00f0ff); border-bottom: 1px solid rgba(0,240,255,0.2); font-size: 0.70rem;">${lbl}</th>`;
    });

    html += `</tr></thead><tbody>`;

    for (let i = 0; i < n; i++) {
      html += `<tr>`;
      html += `<td style="padding: 8px; font-weight: 700; color: #fff; border-bottom: 1px solid rgba(255,255,255,0.06); white-space: nowrap;">${labels[i]}</td>`;

      for (let j = 0; j < n; j++) {
        const val = matrix[i][j];
        const isDiag = (i === j);

        // Color gradient:
        // Negative: Ice Cyan rgba(0, 240, 255, a)
        // Zero: Obsidian rgba(10, 20, 42, 0.8)
        // Positive: Neon Orange/Pink rgba(255, 60, 0, a)
        let bg = 'rgba(10, 20, 42, 0.8)';
        let textColor = '#e2f1ff';

        if (isDiag) {
          bg = 'rgba(0, 240, 255, 0.22)';
          textColor = '#00f0ff';
        } else if (val > 0) {
          const alpha = Math.min(0.85, Math.max(0.12, Math.abs(val) * 0.85));
          bg = `rgba(255, 70, 20, ${alpha})`;
          textColor = val > 0.4 ? '#fff' : '#ffc4b0';
        } else if (val < 0) {
          const alpha = Math.min(0.85, Math.max(0.12, Math.abs(val) * 0.85));
          bg = `rgba(0, 150, 255, ${alpha})`;
          textColor = Math.abs(val) > 0.4 ? '#fff' : '#b0e5ff';
        }

        const sign = val > 0 ? '+' : '';
        const displayVal = val.toFixed(2);

        html += `
          <td class="heatmap-cell" 
              data-row="${i}" 
              data-col="${j}" 
              data-ida="${ids[i]}" 
              data-idb="${ids[j]}" 
              data-val="${val}"
              style="padding: 10px 6px; text-align: center; background: ${bg}; color: ${textColor}; font-weight: 700; cursor: pointer; transition: all 0.2s; border: 1px solid rgba(0,0,0,0.3);"
              title="${labels[i]} <-> ${labels[j]}: ${sign}${displayVal}">
            ${sign}${displayVal}
          </td>
        `;
      }
      html += `</tr>`;
    }

    html += `</tbody></table></div>`;
    container.innerHTML = html;

    // Attach click listeners for detailed intelligence
    container.querySelectorAll('.heatmap-cell').forEach(cell => {
      cell.addEventListener('mouseenter', () => {
        cell.style.outline = '2px solid #00f0ff';
        cell.style.zIndex = '10';
      });
      cell.addEventListener('mouseleave', () => {
        cell.style.outline = 'none';
        cell.style.zIndex = '1';
      });
      cell.addEventListener('click', () => {
        const idA = cell.dataset.ida;
        const idB = cell.dataset.idb;
        const val = parseFloat(cell.dataset.val);
        const pair1 = `${idA}_${idB}`;
        const pair2 = `${idB}_${idA}`;
        const rel = CORRELATION_RELATIONSHIPS[pair1] || CORRELATION_RELATIONSHIPS[pair2] || {
          label: `${idA} <-> ${idB}`,
          corr: val,
          text: `Эмпирическая взаимосвязь ковариации активов (коэффициент Пирсона r = ${val.toFixed(2)}).`
        };

        if (typeof onCellClickCallback === 'function') {
          onCellClickCallback(rel, idA, idB, val);
        }
      });
    });
  }

  // Public API
  return {
    STRATEGIC_ASSETS,
    CORRELATION_RELATIONSHIPS,
    calculateLogReturns,
    calculateMean,
    calculateStdDev,
    calculateHistoricalVolatility,
    calculateSkewness,
    calculateExcessKurtosis,
    calculateCornishFisherVaR,
    calculateTimesFMTailMetrics,
    calculatePearsonCorrelation,
    buildCorrelationMatrix,
    generateCalibratedPriceSeries,
    generateFullQuantDossier,
    renderCorrelationHeatmap
  };
}));