-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathapp.js
More file actions
1979 lines (1824 loc) · 81.1 KB
/
Copy pathapp.js
File metadata and controls
1979 lines (1824 loc) · 81.1 KB
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
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"use strict";
/* =========================================================================
SentimentTradingView — Monte Carlo dashboard
=========================================================================
All data is mocked for the demo. Integration seams:
- fetchPrices() -> Polygon / Alpaca / Finnhub REST + WS
- fetchStarredList() -> TradingView watchlist API
- fetchSentiment() -> X API v2 + VADER/FinBERT
========================================================================= */
// ========== Starred TradingView watchlist ==========
// mu = annualized drift (decimal), sigma = annualized volatility (decimal)
const STARRED = [
{ ticker: "AAPL", name: "Apple Inc.", sector: "Technology", price: 184.32, mu: 0.14, sigma: 0.26 },
{ ticker: "MSFT", name: "Microsoft Corp.", sector: "Technology", price: 418.75, mu: 0.17, sigma: 0.23 },
{ ticker: "NVDA", name: "NVIDIA Corp.", sector: "Semiconductors", price: 892.14, mu: 0.38, sigma: 0.52 },
{ ticker: "TSLA", name: "Tesla Inc.", sector: "Auto / EV", price: 241.58, mu: 0.09, sigma: 0.58 },
{ ticker: "GOOGL", name: "Alphabet Inc. (Class A)", sector: "Internet / Ads", price: 168.90, mu: 0.15, sigma: 0.28 },
{ ticker: "AMZN", name: "Amazon.com Inc.", sector: "E-commerce / Cloud", price: 186.43, mu: 0.16, sigma: 0.31 },
{ ticker: "META", name: "Meta Platforms Inc.", sector: "Social / Ads", price: 506.21, mu: 0.22, sigma: 0.36 },
{ ticker: "JPM", name: "JPMorgan Chase & Co.", sector: "Financials", price: 215.47, mu: 0.08, sigma: 0.22 },
{ ticker: "V", name: "Visa Inc.", sector: "Payments", price: 276.84, mu: 0.11, sigma: 0.20 },
{ ticker: "SPY", name: "SPDR S&P 500 ETF Trust", sector: "Broad-market ETF", price: 528.15, mu: 0.08, sigma: 0.16 },
];
// Pre-compute a synthetic 60-day price history per ticker (for RSI / MAs).
function generateHistory(stock, seed) {
const rng = makeRng(seed + hashString(stock.ticker));
const days = 60;
const dt = 1 / 252;
const history = new Array(days);
let S = stock.price / Math.exp((stock.mu - 0.5 * stock.sigma ** 2) * (days * dt));
for (let i = 0; i < days; i++) {
const z = gaussian(rng);
S = S * Math.exp((stock.mu - 0.5 * stock.sigma ** 2) * dt + stock.sigma * Math.sqrt(dt) * z);
history[i] = S;
}
// Anchor end to current price
const scale = stock.price / history[days - 1];
for (let i = 0; i < days; i++) history[i] *= scale;
return history;
}
function hashString(s) {
let h = 0;
for (let i = 0; i < s.length; i++) h = (h * 31 + s.charCodeAt(i)) | 0;
return h;
}
// ========== Seeded RNG (Mulberry32) ==========
function makeRng(seed) {
let a = (seed | 0) || 1;
return function () {
a = (a + 0x6D2B79F5) | 0;
let t = a;
t = Math.imul(t ^ (t >>> 15), t | 1);
t ^= t + Math.imul(t ^ (t >>> 7), t | 61);
return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
};
}
// Box–Muller standard normal
function gaussian(rng) {
let u = 0, v = 0;
while (u === 0) u = rng();
while (v === 0) v = rng();
return Math.sqrt(-2 * Math.log(u)) * Math.cos(2 * Math.PI * v);
}
// ========== Technical indicators ==========
function sma(arr, period) {
if (arr.length < period) return null;
let s = 0;
for (let i = arr.length - period; i < arr.length; i++) s += arr[i];
return s / period;
}
function rsi(arr, period = 14) {
if (arr.length < period + 1) return 50;
let gains = 0, losses = 0;
for (let i = arr.length - period; i < arr.length; i++) {
const d = arr[i] - arr[i - 1];
if (d > 0) gains += d; else losses -= d;
}
const avgG = gains / period;
const avgL = losses / period;
if (avgL === 0) return 100;
const rs = avgG / avgL;
return 100 - 100 / (1 + rs);
}
// ========== Monte Carlo ==========
function monteCarlo({ S0, mu, sigma, days, nPaths, seed }) {
const rng = makeRng(seed);
const dt = 1 / 252;
const sampleN = Math.min(40, nPaths); // only return 40 sample paths for drawing
const samplePaths = [];
const finalPrices = new Float64Array(nPaths);
// For median + percentile bands, track all paths as column-major arrays
const pxByDay = new Array(days + 1);
for (let d = 0; d <= days; d++) pxByDay[d] = new Float64Array(nPaths);
for (let d = 0; d <= days; d++) pxByDay[d][0] = S0; // placeholder
const drift = (mu - 0.5 * sigma * sigma) * dt;
const diff = sigma * Math.sqrt(dt);
for (let p = 0; p < nPaths; p++) {
let s = S0;
pxByDay[0][p] = s;
const path = p < sampleN ? new Array(days + 1) : null;
if (path) path[0] = s;
for (let d = 1; d <= days; d++) {
const z = gaussian(rng);
s = s * Math.exp(drift + diff * z);
pxByDay[d][p] = s;
if (path) path[d] = s;
}
finalPrices[p] = s;
if (path) samplePaths.push(path);
}
// Percentile bands per day
const percentiles = computeBands(pxByDay, days);
const summary = summarizeFinals(finalPrices, S0);
return { samplePaths, percentiles, summary, days, S0, nPaths };
}
function computeBands(pxByDay, days) {
const p05 = new Array(days + 1);
const p50 = new Array(days + 1);
const p95 = new Array(days + 1);
for (let d = 0; d <= days; d++) {
const arr = Array.from(pxByDay[d]).sort((a, b) => a - b);
const n = arr.length;
p05[d] = arr[Math.floor(0.05 * (n - 1))];
p50[d] = arr[Math.floor(0.50 * (n - 1))];
p95[d] = arr[Math.floor(0.95 * (n - 1))];
}
return { p05, p50, p95 };
}
function summarizeFinals(finals, S0) {
const sorted = Array.from(finals).sort((a, b) => a - b);
const n = sorted.length;
const q = (x) => sorted[Math.max(0, Math.min(n - 1, Math.floor(x * (n - 1))))];
const mean = sorted.reduce((a, b) => a + b, 0) / n;
const median = q(0.5);
const p05 = q(0.05);
const p95 = q(0.95);
return {
expectedReturn: (mean - S0) / S0,
medianReturn: (median - S0) / S0,
ci95Low: (p05 - S0) / S0,
ci95High: (p95 - S0) / S0,
meanPrice: mean,
medianPrice: median,
probUp: sorted.filter((x) => x > S0).length / n,
};
}
// ========== Sentiment (mock X API) ==========
const SENTIMENT_POSTS = {
AAPL: [
{ sent: "pos", author: "@techinvestor", handle: "6h", text: "Apple's services revenue growth is flying under the radar. Long $AAPL through earnings." },
{ sent: "pos", author: "@fundmanager_jk", handle: "1d", text: "Buyback pace is unreal. $AAPL still my largest position." },
{ sent: "neu", author: "@mkt_watch", handle: "2h", text: "$AAPL iPhone China shipments flat YoY. Waiting for Vision Pro data." },
{ sent: "neg", author: "@shortstories", handle: "9h", text: "Multiple compression coming for $AAPL. No growth justifies 29x fwd." },
],
MSFT: [
{ sent: "pos", author: "@ai_thesis", handle: "3h", text: "$MSFT + OpenAI datacenter buildout is the most durable AI trade." },
{ sent: "pos", author: "@cloud_analyst", handle: "8h", text: "Azure growth reaccelerating. Copilot monetization underpriced in $MSFT." },
{ sent: "neu", author: "@longvolpete", handle: "1d", text: "$MSFT expensive vs rest of megacap. Fairly priced at best." },
],
NVDA: [
{ sent: "pos", author: "@chip_bull", handle: "1h", text: "Blackwell ramp is happening faster than consensus. $NVDA to new highs." },
{ sent: "pos", author: "@datacenter_pm", handle: "4h", text: "Hyperscaler capex up across the board. $NVDA is the shovel." },
{ sent: "neg", author: "@contrarian_f", handle: "7h", text: "$NVDA pricing peak. Custom ASICs taking share in 18 months." },
{ sent: "neu", author: "@quantdaily", handle: "12h", text: "$NVDA options vol is insane. Skew flat — market agnostic short-term." },
],
TSLA: [
{ sent: "neg", author: "@ev_skeptic", handle: "2h", text: "$TSLA margins compressing again. FSD thesis keeps getting delayed." },
{ sent: "neu", author: "@auto_news", handle: "5h", text: "$TSLA China registrations mixed. Discount wars continue." },
{ sent: "pos", author: "@musk_follower", handle: "1d", text: "Robotaxi day will reprice $TSLA. Long and strong." },
{ sent: "neg", author: "@valuationvic", handle: "10h", text: "$TSLA still priced as an AI company, delivers like an automaker." },
],
GOOGL: [
{ sent: "pos", author: "@search_analyst", handle: "3h", text: "Gemini ramp stabilizing Search share. $GOOGL cheap vs MSFT." },
{ sent: "neu", author: "@adtech_vc", handle: "6h", text: "$GOOGL YouTube shorts monetization improving. DoJ overhang still there." },
{ sent: "pos", author: "@cloud_watcher", handle: "11h", text: "GCP growing fastest of the three. $GOOGL re-rate incoming." },
],
AMZN: [
{ sent: "pos", author: "@retail_pm", handle: "2h", text: "$AMZN operating margins nowhere near peak. AWS reaccelerating." },
{ sent: "pos", author: "@logistics_nerd", handle: "7h", text: "$AMZN fulfillment regionalization paying off. Cost per unit down 8% YoY." },
{ sent: "neu", author: "@cloud_watcher", handle: "1d", text: "$AMZN AWS gaining share but Azure narrowing gap. Close call." },
],
META: [
{ sent: "pos", author: "@ads_quant", handle: "4h", text: "$META ad platform AI gains still ramping. CPM + click volume both up." },
{ sent: "neu", author: "@metaverse_sceptic", handle: "9h", text: "Reality Labs burn still huge. $META ex-RL is a 20x PE story." },
{ sent: "pos", author: "@fundmanager_jk", handle: "1d", text: "$META buyback + growth combo hard to beat in megacap." },
],
JPM: [
{ sent: "neu", author: "@bank_credit", handle: "3h", text: "$JPM deposit costs stabilizing. NII flat into next quarter." },
{ sent: "pos", author: "@ib_analyst", handle: "7h", text: "Investment banking pipeline strongest since 2021. $JPM to benefit." },
{ sent: "neg", author: "@macro_bear", handle: "1d", text: "Credit losses still bottoming. $JPM reserves look thin." },
],
V: [
{ sent: "pos", author: "@payments_vc", handle: "5h", text: "$V cross-border volume +16% YoY. Travel recovery persists." },
{ sent: "pos", author: "@compounders", handle: "12h", text: "$V is the quintessential toll road. Adding on any weakness." },
{ sent: "neu", author: "@reg_watch", handle: "1d", text: "$V interchange regulatory risk always present but priced in." },
],
SPY: [
{ sent: "pos", author: "@macro_daily", handle: "2h", text: "Breadth finally improving. $SPY supported through 5,200." },
{ sent: "neu", author: "@vol_pm", handle: "6h", text: "$SPY realized vol low, VIX calm. Insurance cheap if hedging." },
{ sent: "neg", author: "@contrarian_f", handle: "10h", text: "$SPY top-5 concentration at records. Mean revert eventually." },
],
};
function getSentiment(ticker) {
const posts = SENTIMENT_POSTS[ticker] || [];
const pos = posts.filter((p) => p.sent === "pos").length;
const neu = posts.filter((p) => p.sent === "neu").length;
const neg = posts.filter((p) => p.sent === "neg").length;
const total = posts.length || 1;
// boost with some deterministic jitter so tickers without posts still differ
const h = hashString(ticker);
const jitter = ((h % 11) - 5) * 0.01;
const posPct = Math.max(0, Math.min(1, pos / total + 0.1 + jitter));
const negPct = Math.max(0, Math.min(1, neg / total + 0.05 - jitter));
let neuPct = Math.max(0, 1 - posPct - negPct);
// Re-normalize to ensure sum to 1
const sum = posPct + neuPct + negPct;
return {
positive: posPct / sum,
neutral: neuPct / sum,
negative: negPct / sum,
posts,
score: posPct / sum - negPct / sum, // net in [-1, +1]
};
}
// ========== Strategies ==========
const STRATEGIES = [
{
id: "ma_cross",
name: "MA Cross",
desc: "20/50-day",
apply: (ctx) => {
const s20 = sma(ctx.history, 20);
const s50 = sma(ctx.history, 50);
if (s20 == null || s50 == null) return { signal: "UNSURE", detail: "Not enough history for 50-day MA." };
if (s20 > s50 * 1.005) return { signal: "BUY", detail: `20-day (${s20.toFixed(2)}) above 50-day (${s50.toFixed(2)}) — bullish trend.` };
if (s20 < s50 * 0.995) return { signal: "SELL", detail: `20-day (${s20.toFixed(2)}) below 50-day (${s50.toFixed(2)}) — bearish trend.` };
return { signal: "UNSURE", detail: `20-day ≈ 50-day — consolidation.` };
},
},
{
id: "rsi_mr",
name: "RSI Mean Reversion",
desc: "14-period",
apply: (ctx) => {
const r = rsi(ctx.history, 14);
if (r < 30) return { signal: "BUY", detail: `RSI ${r.toFixed(1)} — oversold, mean-revert up.` };
if (r > 70) return { signal: "SELL", detail: `RSI ${r.toFixed(1)} — overbought, mean-revert down.` };
return { signal: "UNSURE", detail: `RSI ${r.toFixed(1)} — mid-range, no edge.` };
},
},
{
id: "momentum",
name: "Momentum",
desc: "20-day return",
apply: (ctx) => {
const h = ctx.history;
if (h.length < 21) return { signal: "UNSURE", detail: "Not enough data." };
const r20 = (h[h.length - 1] - h[h.length - 21]) / h[h.length - 21];
if (r20 > 0.05) return { signal: "BUY", detail: `+${(r20 * 100).toFixed(1)}% past 20d — ride the trend.` };
if (r20 < -0.05) return { signal: "SELL", detail: `${(r20 * 100).toFixed(1)}% past 20d — negative momo.` };
return { signal: "UNSURE", detail: `${(r20 * 100).toFixed(1)}% past 20d — flat.` };
},
},
{
id: "mc_asymmetry",
name: "MC Asymmetry",
desc: "MC up/down skew",
apply: (ctx) => {
if (!ctx.mcSummary) return { signal: "UNSURE", detail: "Run a simulation." };
const { ci95High, ci95Low, expectedReturn, probUp } = ctx.mcSummary;
const upside = ci95High;
const downside = -ci95Low;
const ratio = upside / Math.max(downside, 0.0001);
if (ratio > 1.3 && expectedReturn > 0.01) return { signal: "BUY", detail: `Up/down ratio ${ratio.toFixed(2)}x, E[R] ${(expectedReturn * 100).toFixed(1)}%, Pr(up) ${(probUp * 100).toFixed(0)}%.` };
if (ratio < 0.8 && expectedReturn < -0.01) return { signal: "SELL", detail: `Up/down ratio ${ratio.toFixed(2)}x, E[R] ${(expectedReturn * 100).toFixed(1)}%, Pr(up) ${(probUp * 100).toFixed(0)}%.` };
return { signal: "UNSURE", detail: `Up/down ratio ${ratio.toFixed(2)}x — no clear edge.` };
},
},
{
id: "x_sentiment",
name: "X Sentiment",
desc: "net score",
apply: (ctx) => {
const s = ctx.sentiment;
if (s.score > 0.25) return { signal: "BUY", detail: `Net +${(s.score * 100).toFixed(0)} — crowd bullish.` };
if (s.score < -0.15) return { signal: "SELL", detail: `Net ${(s.score * 100).toFixed(0)} — crowd bearish.` };
return { signal: "UNSURE", detail: `Net ${(s.score * 100).toFixed(0)} — mixed crowd.` };
},
},
];
function signalScore(signal) { return signal === "BUY" ? 1 : signal === "SELL" ? -1 : 0; }
function combineSignals(results) {
if (!results.length) return { signal: "UNSURE", detail: "Select at least one strategy." };
const avg = results.reduce((a, r) => a + signalScore(r.signal), 0) / results.length;
if (avg > 0.35) return { signal: "BUY", detail: "Majority bullish." };
if (avg < -0.35) return { signal: "SELL", detail: "Majority bearish." };
return { signal: "UNSURE", detail: "Mixed strategy signals." };
}
// ========== State ==========
const state = {
selectedTicker: "AAPL",
selectedStrategies: new Set(["ma_cross", "mc_asymmetry", "x_sentiment"]),
sims: 1000,
horizon: 30,
seed: 42,
tableSort: { key: "ticker", dir: "asc" },
stocks: null, // enriched runtime stocks
portfolio: null,
mcResult: null,
prevPrices: {},
prevKpi: {},
prevSignals: {},
prevAggregateSignal: null,
};
// =======================================================================
// ===== REAL-TIME DATA SOURCE (Yahoo Finance via CORS proxy) ============
// =======================================================================
const dataSource = {
// mode: initializing | live | delayed | offline
mode: "initializing",
source: "—",
lastFetch: 0,
lastLatencyMs: null,
consecutiveErrors: 0,
disabled: false, // permanently offline for this session after N failures
hasAnnouncedFallback: false,
realHistories: {}, // ticker -> [closes]
realCalibrations: {}, // ticker -> { mu, sigma }
staticSnapshotAt: null, // ISO timestamp from data/quotes.json when same-origin path used
proxies: [
(url) => "https://corsproxy.io/?" + encodeURIComponent(url),
(url) => "https://api.allorigins.win/raw?url=" + encodeURIComponent(url),
],
proxyIdx: 0,
// Same-origin static snapshot, refreshed by a GitHub Action on a cron.
// No CORS, no third-party proxy, no rate limit. Works on plain GitHub Pages.
async loadSameOriginSnapshot() {
try {
const start = performance.now();
const res = await fetch("./data/quotes.json", { cache: "no-cache" });
if (!res.ok) throw new Error("HTTP " + res.status);
const data = await res.json();
if (!data || !data.tickers) throw new Error("malformed snapshot");
this.staticSnapshotAt = data.generatedAt || null;
return { data, latencyMs: performance.now() - start };
} catch (e) {
return null;
}
},
async fetchJson(url, timeoutMs = 5000) {
const proxied = this.proxies[this.proxyIdx](url);
const ctrl = new AbortController();
const t = setTimeout(() => ctrl.abort(), timeoutMs);
const start = performance.now();
try {
const res = await fetch(proxied, { cache: "no-store", signal: ctrl.signal });
if (!res.ok) throw new Error("HTTP " + res.status);
const data = await res.json();
return { data, latencyMs: performance.now() - start };
} finally {
clearTimeout(t);
}
},
async fetchChart(ticker, range = "3mo", interval = "1d") {
const url = `https://query1.finance.yahoo.com/v8/finance/chart/${encodeURIComponent(ticker)}?interval=${interval}&range=${range}&includePrePost=false`;
return this.fetchJson(url);
},
parseChart(json, ticker) {
const r = json?.chart?.result?.[0];
if (!r) return null;
const meta = r.meta || {};
const closes = ((r.indicators?.quote?.[0]?.close) || []).filter((v) => v != null);
return {
ticker,
price: meta.regularMarketPrice ?? closes[closes.length - 1],
prevClose: meta.chartPreviousClose ?? meta.previousClose,
ts: (meta.regularMarketTime || 0) * 1000,
closes,
};
},
calibrate(closes) {
if (!closes || closes.length < 20) return null;
const rets = [];
for (let i = 1; i < closes.length; i++) {
const r = Math.log(closes[i] / closes[i - 1]);
if (isFinite(r)) rets.push(r);
}
if (rets.length < 15) return null;
const mean = rets.reduce((a, b) => a + b, 0) / rets.length;
const varc = rets.reduce((a, b) => a + (b - mean) ** 2, 0) / rets.length;
return { mu: mean * 252, sigma: Math.sqrt(varc * 252) };
},
async bootstrap(tickers) {
if (this.disabled) return { ok: false };
// Step 1: same-origin static snapshot. Refreshed every 20 min during US
// trading hours by .github/workflows/refresh-data.yml. No CORS, no proxy,
// no rate limit. This is the path that makes the deployed site work.
const snap = await this.loadSameOriginSnapshot();
if (snap && snap.data && snap.data.tickers) {
let ok = 0;
for (const t of tickers) {
const r = snap.data.tickers[t];
if (r && r.price && Array.isArray(r.closes) && r.closes.length >= 20) {
this.realHistories[t] = r.closes.slice(-60);
this.realCalibrations[t] = this.calibrate(r.closes);
ok++;
}
}
if (ok > 0) {
const ageMs = this.staticSnapshotAt ? (Date.now() - Date.parse(this.staticSnapshotAt)) : null;
const fresh = ageMs != null && ageMs < 30 * 60 * 1000;
this.lastLatencyMs = Math.round(snap.latencyMs);
this.lastFetch = Date.now();
this.consecutiveErrors = 0;
this.source = `STATIC ${ok}/${tickers.length}`;
this.setMode(fresh ? "live" : "delayed", "STATIC");
return { ok: true, count: ok, source: "static" };
}
}
// Step 2: try the legacy CORS proxy chain. Mostly broken in production
// (corsproxy.io requires a paid plan, allorigins.win is flaky), but kept
// for local development and as a defense-in-depth fallback.
const settled = await Promise.allSettled(
tickers.map((t) => this.fetchChart(t, "3mo", "1d"))
);
let ok = 0;
let latSum = 0, latN = 0;
settled.forEach((res, i) => {
const t = tickers[i];
if (res.status === "fulfilled") {
const parsed = this.parseChart(res.value.data, t);
if (parsed && parsed.price && parsed.closes.length >= 20) {
this.realHistories[t] = parsed.closes.slice(-60);
this.realCalibrations[t] = this.calibrate(parsed.closes);
ok++;
latSum += res.value.latencyMs; latN++;
}
}
});
if (ok === 0) {
this.consecutiveErrors++;
if (this.consecutiveErrors >= 2) this.disabled = true;
this.setMode("offline", "MOCK");
return { ok: false };
}
this.lastLatencyMs = Math.round(latSum / Math.max(latN, 1));
this.lastFetch = Date.now();
this.consecutiveErrors = 0;
this.source = `YF ${ok}/${tickers.length}`;
this.setMode("live", "YF");
return { ok: true, count: ok, source: "proxy" };
},
async pollQuotes(tickers) {
if (this.disabled) return false;
// If we are running on the same-origin snapshot, just re-read it. The cron
// refreshes it every 20 minutes during the trading day, so this is the
// correct cadence and it costs one same-origin GET.
if (this.source && this.source.startsWith("STATIC")) {
const snap = await this.loadSameOriginSnapshot();
if (!snap || !snap.data || !snap.data.tickers) {
this.setMode("delayed", "STATIC");
return false;
}
const updates = {};
let ok = 0;
for (const t of tickers) {
const r = snap.data.tickers[t];
if (r && r.price) {
updates[t] = { price: r.price, prevClose: r.prevClose, ts: r.ts };
ok++;
}
}
if (state.stocks) {
for (const s of state.stocks) {
const u = updates[s.ticker];
if (!u) continue;
s.price = u.price;
if (u.prevClose) s.prevClose = u.prevClose;
s.change = (s.price - s.prevClose) / s.prevClose;
s.history[s.history.length - 1] = s.price;
}
}
this.lastLatencyMs = Math.round(snap.latencyMs);
this.lastFetch = Date.now();
const ageMs = this.staticSnapshotAt ? (Date.now() - Date.parse(this.staticSnapshotAt)) : null;
const fresh = ageMs != null && ageMs < 30 * 60 * 1000;
this.setMode(fresh ? "live" : "delayed", this.source);
return ok > 0;
}
const settled = await Promise.allSettled(
tickers.map((t) => this.fetchChart(t, "1d", "1m"))
);
let ok = 0;
let latSum = 0, latN = 0;
const updates = {};
settled.forEach((res, i) => {
const t = tickers[i];
if (res.status === "fulfilled") {
const parsed = this.parseChart(res.value.data, t);
if (parsed && parsed.price) {
updates[t] = { price: parsed.price, prevClose: parsed.prevClose, ts: parsed.ts };
ok++;
latSum += res.value.latencyMs; latN++;
}
}
});
if (ok === 0) {
this.consecutiveErrors++;
if (this.consecutiveErrors >= 3) {
this.disabled = true;
this.setMode("offline", "MOCK");
} else {
this.setMode("delayed", this.source || "YF");
}
return false;
}
this.consecutiveErrors = 0;
this.lastLatencyMs = Math.round(latSum / Math.max(latN, 1));
this.lastFetch = Date.now();
// Apply updates into state.stocks
if (state.stocks) {
for (const s of state.stocks) {
const u = updates[s.ticker];
if (!u) continue;
s.price = u.price;
if (u.prevClose) s.prevClose = u.prevClose;
s.change = (s.price - s.prevClose) / s.prevClose;
s.history[s.history.length - 1] = s.price;
}
}
// Freshness gate: if latest ts is stale, mark delayed
const staleAge = Date.now() - this.lastFetch;
this.setMode(staleAge > 15000 ? "delayed" : "live", this.source);
return true;
},
setMode(newMode, src) {
const changed = this.mode !== newMode;
this.mode = newMode;
if (src) this.source = src;
if (changed) onConnModeChange(newMode, this.source);
else updateConnStripOnly();
},
};
// ---- Market hours (US Eastern) --------------------------------------
function nyTimeParts() {
const fmt = new Intl.DateTimeFormat("en-US", {
timeZone: "America/New_York",
weekday: "short", hour: "2-digit", minute: "2-digit", hour12: false,
});
const parts = fmt.formatToParts(new Date());
const weekday = parts.find((p) => p.type === "weekday")?.value || "Mon";
const hour = +parts.find((p) => p.type === "hour").value;
const minute = +parts.find((p) => p.type === "minute").value;
return { weekday, mins: (hour % 24) * 60 + minute };
}
function marketStatus() {
const { weekday, mins } = nyTimeParts();
if (weekday === "Sat" || weekday === "Sun") return "WEEKEND";
if (mins < 4 * 60) return "CLOSED";
if (mins < 9 * 60 + 30) return "PRE";
if (mins < 16 * 60) return "OPEN";
if (mins < 20 * 60) return "AFTER";
return "CLOSED";
}
// ---- Connection-mode handlers ---------------------------------------
function updateConnStripOnly() {
const el = $("#term-conn");
if (!el) return;
el.classList.remove("initializing", "live", "delayed", "offline");
el.classList.add(dataSource.mode);
setText("#term-conn-label", (
dataSource.mode === "live" ? "LIVE" :
dataSource.mode === "delayed" ? "DELAYED" :
dataSource.mode === "offline" ? "OFFLINE" : "INIT"
));
setText("#term-conn-src", dataSource.source || "—");
if (dataSource.lastLatencyMs != null) {
setText("#term-latency", `${Math.round(dataSource.lastLatencyMs)}MS`);
}
}
function onConnModeChange(newMode, source) {
updateConnStripOnly();
const sess = $("#session-status");
const banner = $("#feed-banner");
if (newMode === "offline") {
if (banner && !banner.dataset.dismissed) {
banner.hidden = false;
setText("#feed-banner-text", "Live feed unavailable — showing simulated data.");
}
if (!dataSource.hasAnnouncedFallback && sess) {
sess.textContent = "Live data feed unavailable. Dashboard is using simulated prices.";
dataSource.hasAnnouncedFallback = true;
}
} else if (newMode === "delayed") {
if (sess) sess.textContent = `Live feed delayed. Source: ${source || ""}.`;
} else if (newMode === "live") {
if (banner && !banner.dataset.dismissed) banner.hidden = true;
if (sess) sess.textContent = `Live feed active. Source: ${source || "YF"}.`;
}
}
let lastMarketStatus = null;
function updateMarketStatus() {
const s = marketStatus();
const el = $("#term-market");
if (!el) return;
el.textContent = s === "PRE" ? "PRE-MKT" : s === "AFTER" ? "AFT-HRS" : s;
el.classList.remove("open", "pre", "after", "closed", "weekend");
el.classList.add(s === "PRE" ? "pre" : s === "AFTER" ? "after" : s.toLowerCase());
if (lastMarketStatus && lastMarketStatus !== s) {
const sess = $("#session-status");
if (sess) sess.textContent = `US market status changed to ${s}.`;
}
lastMarketStatus = s;
return s;
}
// ========== Enrichment ==========
function buildStocksRuntime() {
const stocks = STARRED.map((s) => {
// Prefer real Yahoo history + calibrated mu/sigma when available
const realHist = dataSource.realHistories[s.ticker];
const cal = dataSource.realCalibrations[s.ticker];
let history, mu, sigma, price, prevClose;
if (realHist && realHist.length >= 20) {
history = realHist.slice(-60);
price = history[history.length - 1];
prevClose = history[history.length - 2] || price;
mu = cal?.mu ?? s.mu;
sigma = cal?.sigma ?? s.sigma;
} else {
history = generateHistory(s, state.seed);
prevClose = history[history.length - 2];
price = history[history.length - 1];
mu = s.mu;
sigma = s.sigma;
}
const change = (price - prevClose) / prevClose;
const sentiment = getSentiment(s.ticker);
const mc = monteCarlo({ S0: price, mu, sigma, days: 30, nPaths: 500, seed: state.seed + hashString(s.ticker) });
return {
ticker: s.ticker, name: s.name, sector: s.sector,
mu, sigma, price, prevClose, change, history, sentiment,
mcSummary: mc.summary,
};
});
return stocks;
}
function computePortfolioKpis(stocks) {
const w = 1 / stocks.length;
const pv = stocks.reduce((a, s) => a + s.price * 10, 0); // pretend 10 shares each
const prevPv = stocks.reduce((a, s) => a + s.prevClose * 10, 0);
const pnl = pv - prevPv;
const pnlPct = pnl / prevPv;
const expReturn = stocks.reduce((a, s) => a + w * s.mcSummary.expectedReturn, 0);
const var95 = stocks.reduce((a, s) => a + w * s.mcSummary.ci95Low, 0); // weighted downside
const avgSigma = stocks.reduce((a, s) => a + w * s.sigma, 0);
const avgMu = stocks.reduce((a, s) => a + w * s.mu, 0);
const sharpe = (avgMu - 0.045) / Math.max(avgSigma, 0.01); // rf=4.5%
// weighted sentiment
const sentScore = stocks.reduce((a, s) => a + w * s.sentiment.score, 0);
return {
value: pv,
pnl,
pnlPct,
expectedReturn: expReturn,
var95,
sharpe,
sentimentScore: sentScore,
};
}
// ========== Rendering ==========
const $ = (sel) => document.querySelector(sel);
const $$ = (sel) => Array.from(document.querySelectorAll(sel));
const prefersReducedMotion = () => window.matchMedia && window.matchMedia("(prefers-reduced-motion: reduce)").matches;
// Count-up animation: interpolates numeric value through a formatter
function animateNumber(el, from, to, formatter, duration = 600) {
if (!el) return;
if (from === to || !isFinite(from) || !isFinite(to) || prefersReducedMotion()) {
el.textContent = formatter(to);
return;
}
const start = performance.now();
const ease = (t) => 1 - Math.pow(1 - t, 4); // easeOutQuart
function frame(now) {
const t = Math.min(1, (now - start) / duration);
const v = from + (to - from) * ease(t);
el.textContent = formatter(v);
if (t < 1) requestAnimationFrame(frame);
else {
el.classList.remove("landing");
void el.offsetWidth;
el.classList.add("landing");
}
}
requestAnimationFrame(frame);
}
function renderStrategyOptions() {
const el = $("#strategy-options");
el.innerHTML = STRATEGIES.map((s) => `
<label class="strategy-chip">
<input type="checkbox" value="${s.id}" ${state.selectedStrategies.has(s.id) ? "checked" : ""} />
<span>${s.name}</span>
<span class="desc">${s.desc}</span>
</label>
`).join("");
el.querySelectorAll("input[type=checkbox]").forEach((input) => {
input.addEventListener("change", (e) => {
const id = e.target.value;
if (e.target.checked) state.selectedStrategies.add(id);
else state.selectedStrategies.delete(id);
renderAll();
announce(`Strategy ${id} ${e.target.checked ? "enabled" : "disabled"}.`);
});
});
}
function renderTickerSelect() {
const el = $("#ticker-select");
el.innerHTML = state.stocks.map((s) =>
`<option value="${s.ticker}" ${state.selectedTicker === s.ticker ? "selected" : ""}>${s.ticker} — ${s.name}</option>`
).join("");
el.addEventListener("change", (e) => {
state.selectedTicker = e.target.value;
renderDetail();
renderStocksTable();
announce(`Selected ${state.selectedTicker}.`);
});
}
function pctFmt(x, digits = 2) {
if (x == null || !isFinite(x)) return "—";
const sign = x > 0 ? "+" : "";
return sign + (x * 100).toFixed(digits) + "%";
}
function priceFmt(x) {
if (x == null || !isFinite(x)) return "—";
return "$" + x.toFixed(2);
}
function dollarFmt(x) {
if (x == null || !isFinite(x)) return "—";
return "$" + x.toLocaleString(undefined, { maximumFractionDigits: 0 });
}
function signalBadge(signal, opts = {}) {
const cls = signal === "BUY" ? "badge-buy" : signal === "SELL" ? "badge-sell" : "badge-unsure";
const icon = signal === "BUY" ? "▲" : signal === "SELL" ? "▼" : "◆";
const label = `Signal: ${signal}`;
return `<span class="badge ${cls}" aria-label="${label}${opts.context ? ". " + opts.context : ""}"><span class="icon" aria-hidden="true">${icon}</span>${signal}</span>`;
}
function deltaLabel(x) {
const cls = x > 0 ? "delta-up" : x < 0 ? "delta-down" : "delta-flat";
const arrow = x > 0 ? "▲" : x < 0 ? "▼" : "—";
return `<span class="${cls}"><span aria-hidden="true">${arrow}</span> ${pctFmt(x)}</span>`;
}
let kpisBuilt = false;
const kpiDefs = () => {
const k = state.portfolio;
return [
{ id: "kpi-value", label: "Portfolio value", value: k.value, fmt: (v) => dollarFmt(v), mod: "accent", sub: `${state.stocks.length} starred · equal weight` },
{ id: "kpi-pnl", label: "Today P&L", value: k.pnl, fmt: (v) => dollarFmt(v), mod: k.pnl >= 0 ? "positive" : "negative", valueMod: k.pnl >= 0 ? "up" : "down", subHtml: deltaLabel(k.pnlPct) },
{ id: "kpi-er", label: "Expected return", value: k.expectedReturn, fmt: (v) => pctFmt(v), mod: k.expectedReturn >= 0 ? "positive" : "negative", valueMod: k.expectedReturn >= 0 ? "up" : "down", sub: `${state.horizon}-day · MC` },
{ id: "kpi-var", label: "95% VaR", value: k.var95, fmt: (v) => pctFmt(v), mod: "negative", valueMod: "down", sub: "5th percentile" },
{ id: "kpi-sharpe", label: "Sharpe", value: k.sharpe, fmt: (v) => v.toFixed(2), mod: "accent", sub: "Ex-ante · rf 4.5%" },
{ id: "kpi-sent", label: "Crowd score", value: k.sentimentScore, fmt: (v) => pctFmt(v, 0), mod: k.sentimentScore >= 0 ? "positive" : "negative", valueMod: k.sentimentScore >= 0 ? "up" : "down", sub: "X net · pos − neg" },
];
};
function renderKPIs() {
const defs = kpiDefs();
if (!kpisBuilt) {
$("#kpi-strip").innerHTML = defs.map((d) => `
<div class="kpi ${d.mod}" id="${d.id}">
<p class="kpi-label">${d.label}</p>
<p class="kpi-value ${d.valueMod || ""}" data-val>${d.fmt(d.value)}</p>
<p class="kpi-sub" data-sub></p>
</div>
`).join("");
kpisBuilt = true;
state.prevKpi = {};
}
defs.forEach((d) => {
const wrap = $(`#${d.id}`);
if (!wrap) return;
wrap.className = `kpi ${d.mod}`;
const val = wrap.querySelector("[data-val]");
val.className = `kpi-value ${d.valueMod || ""}`;
const sub = wrap.querySelector("[data-sub]");
const prev = state.prevKpi[d.id] ?? d.value;
animateNumber(val, prev, d.value, d.fmt, 520);
state.prevKpi[d.id] = d.value;
if (d.subHtml) sub.innerHTML = d.subHtml;
else sub.textContent = d.sub || "";
});
// Right rail
const buys = state.stocks.filter((x) => getCombinedSignalForStock(x).signal === "BUY").length;
const sells = state.stocks.filter((x) => getCombinedSignalForStock(x).signal === "SELL").length;
const avgProbUp = state.stocks.reduce((a, x) => a + x.mcSummary.probUp, 0) / state.stocks.length;
const k = state.portfolio;
const railUpdates = [
{ sel: "#rail-winrate-val", value: avgProbUp * 100, fmt: (v) => v.toFixed(1) + "%", up: avgProbUp >= 0.5 },
{ sel: "#rail-sharpe-val", value: k.sharpe, fmt: (v) => v.toFixed(2), up: null },
{ sel: "#rail-er-val", value: k.expectedReturn, fmt: (v) => pctFmt(v), up: k.expectedReturn >= 0 },
{ sel: "#rail-var-val", value: k.var95, fmt: (v) => pctFmt(v), up: false },
{ sel: "#rail-sent-val", value: k.sentimentScore, fmt: (v) => pctFmt(v, 0), up: k.sentimentScore >= 0 },
];
railUpdates.forEach((r) => {
const el = $(r.sel);
if (!el) return;
if (r.up !== null) el.className = "rail-box-value " + (r.up ? "up" : "down");
const prev = state.prevKpi[r.sel] ?? r.value;
animateNumber(el, prev, r.value, r.fmt, 520);
state.prevKpi[r.sel] = r.value;
});
setText("#rail-er-sub", `Portfolio · ${state.horizon}d`);
setText("#rail-buys-val", `${buys} / ${sells}`);
setText("#rail-buys-sub", `${state.stocks.length} starred total`);
// Terminal strip
setText("#term-horizon", state.horizon + "D");
setText("#term-paths", state.sims >= 1000 ? (state.sims / 1000) + "K" : String(state.sims));
setText("#term-seed", String(state.seed));
setText("#term-watch", String(state.stocks.length));
}
function setText(sel, txt) {
const el = $(sel);
if (el) el.textContent = txt;
}
function renderStocksTable() {
const body = $("#stocks-body");
// Compute per-ticker price deltas, signal changes, conviction changes before re-rendering
const priceChanges = {};
const signalChanges = {};
const convictionChanges = {};
if (!state.prevConviction) state.prevConviction = {};
for (const s of state.stocks) {
const prev = state.prevPrices[s.ticker];
if (prev != null && Math.abs(prev - s.price) > 1e-6) {
priceChanges[s.ticker] = s.price > prev ? "up" : "down";
}
state.prevPrices[s.ticker] = s.price;
const combined = getCombinedSignalForStock(s).signal;
if (state.prevSignals[s.ticker] && state.prevSignals[s.ticker] !== combined) {
signalChanges[s.ticker] = true;
}
state.prevSignals[s.ticker] = combined;
const conv = convictionFromStock(s);
const convKey = `${conv.score}:${conv.neg ? 1 : 0}`;
const prevConv = state.prevConviction[s.ticker];
if (prevConv !== convKey) convictionChanges[s.ticker] = true;
state.prevConviction[s.ticker] = convKey;
}
let rows = state.stocks.map((s) => {
const sig = getCombinedSignalForStock(s);
return { ...s, combinedSignal: sig };
});
// Sort
const { key, dir } = state.tableSort;
rows.sort((a, b) => {
let av, bv;
switch (key) {
case "ticker": av = a.ticker; bv = b.ticker; break;
case "price": av = a.price; bv = b.price; break;
case "change": av = a.change; bv = b.change; break;
case "expRet": av = a.mcSummary.expectedReturn; bv = b.mcSummary.expectedReturn; break;
case "sentiment": av = a.sentiment.score; bv = b.sentiment.score; break;
default: av = a.ticker; bv = b.ticker;
}
const cmp = typeof av === "string" ? av.localeCompare(bv) : av - bv;
return dir === "asc" ? cmp : -cmp;
});
body.innerHTML = rows.map((s) => {
const selected = s.ticker === state.selectedTicker;
const ciLabel = `${pctFmt(s.mcSummary.ci95Low, 1)} / ${pctFmt(s.mcSummary.ci95High, 1)}`;
const sentDom = s.sentiment.positive > s.sentiment.negative ? "Pos" : s.sentiment.negative > s.sentiment.positive ? "Neg" : "Mix";
const sentScore = pctFmt(s.sentiment.score, 0);
const dotCls = s.combinedSignal.signal === "BUY" ? "buy" : s.combinedSignal.signal === "SELL" ? "sell" : "unsure";
const conviction = convictionFromStock(s);
const convAnim = convictionChanges[s.ticker] ? " animate" : "";
const spark = sparklineSvg(s.history, s.change >= 0);
const spark60 = pctFmt((s.history[s.history.length - 1] - s.history[0]) / s.history[0]);
const press = pressureFromStock(s);
return `
<tr tabindex="0" role="button" aria-pressed="${selected}" aria-selected="${selected}" data-ticker="${s.ticker}" aria-label="${s.ticker}, ${s.name}. Price ${priceFmt(s.price)}, change ${pctFmt(s.change)}. 60-day trend ${spark60}. Buy pressure ${press.buyPct}%, sell pressure ${press.sellPct}%. Action ${s.combinedSignal.signal}, conviction ${conviction.score} of 8.">
<td class="ticker"><span class="status-dot ${dotCls}" aria-hidden="true"></span><span class="ticker-text" data-text="${s.ticker}">${s.ticker}</span></td>
<td class="name">${s.name}</td>
<td class="spark-cell">${spark}</td>
<td class="num">${priceFmt(s.price)}</td>
<td class="num">${deltaLabel(s.change)}</td>
<td class="num ${s.mcSummary.expectedReturn >= 0 ? "delta-up" : "delta-down"}">${pctFmt(s.mcSummary.expectedReturn)}</td>
<td class="num">${ciLabel}</td>
<td class="num">${sentDom} ${sentScore}</td>
<td class="pressure-cell">${pressureBar(press)}</td>
<td>${convictionBar(conviction, convAnim)}</td>
<td>${signalBadge(s.combinedSignal.signal, { context: s.combinedSignal.detail })}</td>
</tr>
`;
}).join("");
// Update sort indicators
$$("thead th[aria-sort]").forEach((th) => th.setAttribute("aria-sort", "none"));
const activeBtn = $(`thead th button[data-sort="${key}"]`);
if (activeBtn) {
activeBtn.closest("th").setAttribute("aria-sort", dir === "asc" ? "ascending" : "descending");
}
// Tick-flash on price cells for any ticker whose price moved
if (!prefersReducedMotion()) {
Object.entries(priceChanges).forEach(([ticker, dir]) => {
const row = body.querySelector(`tr[data-ticker="${ticker}"]`);
if (!row) return;
const priceCell = row.children[3];
if (!priceCell) return;
const color = dir === "up" ? "rgba(0,255,136,0.28)" : "rgba(255,51,102,0.28)";
const text = dir === "up" ? "#00ff88" : "#ff3366";
priceCell.animate(
[
{ backgroundColor: color, color: text, boxShadow: `inset 0 0 0 1px ${text}` },
{ backgroundColor: "transparent", color: "", boxShadow: "inset 0 0 0 0 transparent" },
],
{ duration: 720, easing: "cubic-bezier(0.22,1,0.36,1)", fill: "none" }
);
});
// Pop action-badge + glitch ticker + particle burst when signal flips
Object.keys(signalChanges).forEach((ticker) => {
const row = body.querySelector(`tr[data-ticker="${ticker}"]`);
if (!row) return;
const badge = row.querySelector(".badge");
if (badge) {
badge.animate(
[{ transform: "scale(0.94)" }, { transform: "scale(1.06)" }, { transform: "scale(1)" }],
{ duration: 320, easing: "cubic-bezier(0.25,1,0.5,1)" }
);
}
triggerGlitch(row);
const newSignal = state.prevSignals[ticker];
particlesForSignalFlip(row, newSignal);
});