File size: 57,172 Bytes
8378e52
 
 
 
 
074b8e3
a64edcf
074b8e3
 
 
8378e52
 
074b8e3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a64edcf
 
 
 
 
074b8e3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b71e2fd
 
 
 
 
 
 
 
 
 
074b8e3
 
 
 
 
 
 
b71e2fd
 
074b8e3
8378e52
 
 
074b8e3
 
 
 
 
 
 
 
c788d9a
074b8e3
8378e52
074b8e3
 
a64edcf
 
074b8e3
 
 
 
b71e2fd
074b8e3
8378e52
 
074b8e3
 
 
 
 
 
 
 
 
 
8378e52
074b8e3
 
 
 
 
 
 
 
 
 
 
 
 
37f39a7
074b8e3
8378e52
074b8e3
 
 
 
 
 
 
a64edcf
 
 
 
 
 
 
 
8378e52
 
b71e2fd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
074b8e3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8378e52
 
074b8e3
8378e52
074b8e3
 
8378e52
 
074b8e3
8378e52
074b8e3
 
 
 
 
 
 
 
8378e52
074b8e3
8378e52
074b8e3
 
8378e52
074b8e3
 
 
 
8378e52
074b8e3
b71e2fd
 
 
 
074b8e3
b71e2fd
074b8e3
 
b71e2fd
074b8e3
b71e2fd
 
8378e52
b71e2fd
8378e52
074b8e3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8378e52
 
074b8e3
37f39a7
 
 
 
074b8e3
 
 
 
 
 
 
37f39a7
 
 
 
 
 
074b8e3
37f39a7
074b8e3
37f39a7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
074b8e3
 
 
 
 
37f39a7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
00a864f
 
 
 
 
 
 
 
 
074b8e3
b71e2fd
37f39a7
8378e52
074b8e3
 
37f39a7
 
074b8e3
a64edcf
074b8e3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a64edcf
 
ae54610
 
 
 
 
 
 
a64edcf
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
074b8e3
8378e52
b71e2fd
074b8e3
 
8378e52
 
 
b71e2fd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
074b8e3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8378e52
074b8e3
 
 
 
 
 
 
 
 
 
 
8378e52
074b8e3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
37f39a7
8378e52
074b8e3
a64edcf
 
b71e2fd
8378e52
 
 
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
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Updraft β€” live quality-trend fund</title>
<meta name="description" content="Updraft holds the three quality US stocks with the strongest trends and rebalances itself on the first trading day of every month. An Alpaca live paper trade simulation, with the strategy and its backtest.">
<link rel="icon" href="data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 32 32'%3E%3Crect width='32' height='32' rx='8' fill='%230e2348'/%3E%3Cpath d='M6 25c6-1 11-6 15-14' stroke='%23ea6435' stroke-width='3' fill='none' stroke-linecap='round'/%3E%3Cpath d='M18.5 9.5 27 6l-3.6 8.4-1.9-3.3z' fill='%23fff'/%3E%3C/svg%3E">
<link rel="preconnect" href="https://fonts.googleapis.com"><link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Sora:wght@600;700&display=swap" rel="stylesheet">
<script src="https://cdn.jsdelivr.net/npm/chart.js@4.4.4/dist/chart.umd.min.js"></script>
<style>
:root{color-scheme:light;
  --page:#f2f5fa;--surface:#fbfcfe;--ink:#0b1a2e;--ink-2:#46566c;--muted:#76849a;--grid:#e3e8f0;--axis:#c6cfdc;
  --border:rgba(11,26,46,.10);--updraft:#e4572e;--plan:#2f6fd0;--spy:#8b867a;--up:#0f7a37;--down:#c2362f;
  --track:#f6dfd6;--chip:#eaf0f8;--shadow:0 1px 2px rgba(11,26,46,.06),0 8px 24px rgba(11,26,46,.06);
  --sans:system-ui,-apple-system,"Segoe UI",Roboto,sans-serif;--brandfont:"Sora",var(--sans)}
@media (prefers-color-scheme: dark){:root:where(:not([data-theme="light"])){color-scheme:dark;
  --page:#0a1322;--surface:#111c2e;--ink:#f2f6fc;--ink-2:#b8c4d6;--muted:#8a97ab;--grid:#22304a;--axis:#34445f;
  --border:rgba(255,255,255,.10);--updraft:#ea6435;--plan:#3e84e0;--spy:#9a968a;--up:#3fbf6b;--down:#f07068;
  --track:#3a2620;--chip:#1a2a44;--shadow:0 1px 2px rgba(0,0,0,.3),0 8px 24px rgba(0,0,0,.25)}}
:root[data-theme="dark"]{color-scheme:dark;
  --page:#0a1322;--surface:#111c2e;--ink:#f2f6fc;--ink-2:#b8c4d6;--muted:#8a97ab;--grid:#22304a;--axis:#34445f;
  --border:rgba(255,255,255,.10);--updraft:#ea6435;--plan:#3e84e0;--spy:#9a968a;--up:#3fbf6b;--down:#f07068;
  --track:#3a2620;--chip:#1a2a44;--shadow:0 1px 2px rgba(0,0,0,.3),0 8px 24px rgba(0,0,0,.25)}
*{box-sizing:border-box}
body{margin:0;background:var(--page);color:var(--ink);font-family:var(--sans);line-height:1.5}
.wrap{max-width:1120px;margin:0 auto;padding:0 20px}
/* masthead β€” the brand band stays night-sky in both themes */
.masthead{background:radial-gradient(900px 340px at 82% 120%,rgba(234,100,53,.38),transparent 60%),
  radial-gradient(700px 300px at 10% -40%,rgba(62,132,224,.35),transparent 60%),linear-gradient(160deg,#0b1a3a 0%,#11295a 55%,#173a74 100%);
  color:#f2f6fc;padding:18px 0 0}
.mast{display:flex;align-items:center;gap:14px;flex-wrap:wrap}
.brand{display:flex;align-items:center;gap:10px;color:inherit;text-decoration:none}
.word{font-family:var(--brandfont);font-weight:700;font-size:24px;letter-spacing:-.02em}
.mast-right{margin-left:auto;display:flex;align-items:center;gap:12px;font-size:12px;color:#b9c8e2}
.dot{width:8px;height:8px;border-radius:50%;background:#3fbf6b;box-shadow:0 0 0 3px rgba(63,191,107,.2)}
.theme{background:rgba(255,255,255,.1);border:1px solid rgba(255,255,255,.2);color:#fff;border-radius:8px;padding:4px 9px;cursor:pointer;font-size:13px}
.hero-copy h1{font-family:var(--brandfont);font-weight:700;font-size:clamp(24px,3.4vw,38px);line-height:1.15;letter-spacing:-.02em;margin:26px 0 8px;max-width:760px}
.hero-copy p{margin:0;color:#c6d3ea;max-width:680px;font-size:16px}
.tabs{display:flex;gap:6px;margin-top:26px}
.tabs button{appearance:none;border:0;background:transparent;color:#c6d3ea;font:600 14px var(--sans);padding:11px 16px;border-radius:10px 10px 0 0;cursor:pointer}
.tabs button[aria-selected="true"]{background:var(--page);color:var(--ink)}
main{padding:22px 0 40px}
.card{background:var(--surface);border:1px solid var(--border);border-radius:16px;padding:20px;box-shadow:var(--shadow)}
.card+.card,.grid2+.card,.card+.grid2{margin-top:16px}
h2{font-family:var(--brandfont);font-size:19px;letter-spacing:-.01em;margin:0 0 4px}
h3{font-size:15px;margin:0 0 4px}
.sub{color:var(--ink-2);font-size:14px;margin:0}
.muted{color:var(--muted);font-size:12px}
.kpis{display:grid;grid-template-columns:1.3fr 1fr 1fr 1fr 1fr;gap:12px;margin-bottom:16px}
.tile{background:var(--surface);border:1px solid var(--border);border-radius:14px;padding:14px 16px;box-shadow:var(--shadow)}
.tile .l{font-size:12px;color:var(--muted)}
.tile .v{font-size:24px;font-weight:650;margin-top:2px}
.tile .s{font-size:12px;color:var(--ink-2);margin-top:2px}
.tile.hero .v{font-size:44px;line-height:1.1;letter-spacing:-.02em}
.pos{color:var(--up)}.neg{color:var(--down)}
.chart-head{display:flex;align-items:flex-start;justify-content:space-between;gap:12px;flex-wrap:wrap;margin-bottom:12px}
.legend{display:flex;gap:16px;flex-wrap:wrap;font-size:13px;color:var(--ink-2)}
.legend i{display:inline-block;width:16px;height:2px;border-radius:2px;vertical-align:middle;margin-right:6px}
.legend i.band{height:10px;border-radius:3px;opacity:.35}
.seg{display:inline-flex;background:var(--chip);border-radius:10px;padding:3px;gap:2px}
.seg button{appearance:none;border:0;background:transparent;color:var(--ink-2);font:600 12px var(--sans);padding:6px 11px;border-radius:8px;cursor:pointer}
.seg button[aria-pressed="true"]{background:var(--surface);color:var(--ink);box-shadow:0 1px 2px rgba(0,0,0,.08)}
.filters{display:flex;align-items:center;gap:12px;flex-wrap:wrap;margin:0 0 10px}
.period-read{font-size:13px;color:var(--ink-2)}
.chartbox{position:relative;height:340px}
.chartbox.sm{height:260px}
.hold{width:100%;border-collapse:collapse;font-size:14px}
.hold th{text-align:left;font-size:12px;font-weight:600;color:var(--muted);padding:8px;border-bottom:1px solid var(--grid)}
.hold td{padding:12px 8px;border-bottom:1px solid var(--grid);vertical-align:middle}
.hold td.r,.hold th.r{text-align:right;font-variant-numeric:tabular-nums}
.tick{font-weight:700;font-size:15px}.co{color:var(--muted);font-size:12px}
.wbar{display:flex;align-items:center;gap:8px;min-width:120px}
.wbar span{flex:1;height:6px;border-radius:4px;background:var(--track);overflow:hidden}
.wbar b{display:block;height:100%;border-radius:4px;background:var(--updraft)}
.rank{display:inline-block;min-width:34px;text-align:center;font-size:12px;font-weight:600;padding:2px 8px;border-radius:999px;background:var(--chip);color:var(--ink-2)}
.note{font-size:13px;color:var(--ink-2);margin:10px 0 0}
.empty{color:var(--muted);padding:12px 0}
.tag{display:inline-block;font-size:12px;font-weight:600;padding:2px 9px;border-radius:999px;white-space:nowrap;color:var(--ink)}
.tag.held{background:color-mix(in srgb,var(--updraft) 18%,transparent)}
.tag.buy{background:color-mix(in srgb,var(--plan) 18%,transparent)}
.tag.sell{background:var(--chip);color:var(--ink-2)}
.hold tr.is-held td:first-child{box-shadow:inset 3px 0 0 var(--updraft)}
.steps{display:grid;grid-template-columns:repeat(4,1fr);gap:12px;margin-top:14px}
.step{border:1px solid var(--border);border-radius:14px;padding:14px;position:relative;background:var(--surface)}
.step .n{font-family:var(--brandfont);font-size:28px;font-weight:700;color:var(--updraft);line-height:1}
.step .t{font-weight:650;margin-top:6px}.step p{font-size:13px;color:var(--ink-2);margin:6px 0 0}
.grid2{display:grid;grid-template-columns:1fr 1fr;gap:16px;margin-top:16px}
.stat6{display:grid;grid-template-columns:repeat(6,1fr);gap:10px;margin:14px 0 4px}
.stat6 .tile{box-shadow:none}
.calc{display:flex;gap:14px;flex-wrap:wrap;align-items:flex-end;margin:12px 0 4px}
.calc label{display:flex;flex-direction:column;font-size:12px;color:var(--muted);gap:4px}
.calc input{font:600 15px var(--sans);color:var(--ink);background:var(--surface);border:1px solid var(--border);border-radius:10px;padding:8px 10px;width:150px}
table.proj{width:100%;border-collapse:collapse;font-size:13px;margin-top:10px}
table.proj th{text-align:right;font-weight:600;color:var(--muted);font-size:12px;padding:6px;border-bottom:1px solid var(--grid)}
table.proj th:first-child,table.proj td:first-child{text-align:left}
table.proj td{text-align:right;padding:8px 6px;border-bottom:1px solid var(--grid);font-variant-numeric:tabular-nums}
table.proj td.big{font-weight:700;font-size:15px}
.stat4{display:grid;grid-template-columns:repeat(4,1fr);gap:12px;margin-bottom:16px}
.ev{display:grid;grid-template-columns:150px 1fr;gap:16px;padding:16px 0;border-top:1px solid var(--grid)}
.ev:first-child{border-top:0;padding-top:6px}
.ev-date b{display:block;font-family:var(--brandfont);font-size:16px}
.ev-date span{font-size:12px;color:var(--muted)}
.ev-date .now{display:inline-block;width:8px;height:8px;border-radius:50%;background:var(--updraft);margin-right:6px;vertical-align:middle}
.ev-perf{font-size:13px;color:var(--ink-2)}
.ev-row{display:flex;gap:8px;flex-wrap:wrap;align-items:center;margin-top:8px;font-size:13px}
.ev-k{width:58px;font-size:12px;color:var(--muted);font-weight:600}
.ev-small{font-size:12px;color:var(--muted);margin-top:8px}
.callout{border-left:3px solid var(--plan);background:var(--chip);border-radius:0 12px 12px 0;padding:12px 14px;font-size:13px;color:var(--ink-2);margin-top:14px}
details{margin-top:10px}details summary{cursor:pointer;font-size:13px;color:var(--ink-2)}
details table{width:100%;border-collapse:collapse;font-size:12px;margin-top:8px;font-variant-numeric:tabular-nums}
details td,details th{padding:4px 6px;border-bottom:1px solid var(--grid);text-align:right}
details td:first-child,details th:first-child{text-align:left}
footer{color:var(--muted);font-size:12px;padding:0 0 36px}
@media (max-width:900px){.kpis{grid-template-columns:1fr 1fr}.tile.hero{grid-column:1/-1}.steps{grid-template-columns:1fr 1fr}
  .grid2{grid-template-columns:1fr}.stat6{grid-template-columns:repeat(2,1fr)}.stat4{grid-template-columns:repeat(2,1fr)}
  .ev{grid-template-columns:1fr;gap:6px}}
@media (max-width:560px){.hold .hide-s{display:none}.chartbox{height:280px}}
</style>
</head>
<body>
<header class="masthead">
  <div class="wrap mast">
    <a class="brand" href="/" aria-label="Updraft home">
      <svg width="34" height="34" viewBox="0 0 32 32" aria-hidden="true"><rect width="32" height="32" rx="8" fill="#0e2348" stroke="rgba(255,255,255,.18)"/>
        <path d="M6 25c6-1 11-6 15-14" stroke="#ea6435" stroke-width="3" fill="none" stroke-linecap="round"/>
        <path d="M18.5 9.5 27 6l-3.6 8.4-1.9-3.3z" fill="#fff"/></svg>
      <span class="word">Updraft</span>
    </a>
    <div class="mast-right"><span class="dot" id="dot"></span><span id="updated">connecting…</span>
      <button class="theme" id="themeBtn" aria-label="Toggle light or dark">◐</button></div>
  </div>
  <div class="wrap hero-copy">
    <h1>Three quality stocks with the strongest trends β€” rebalanced automatically every month.</h1>
    <p id="lede">An Alpaca live paper trade simulation, run by rules, not opinions. Below: what it is worth right now, how it
      compares with the S&amp;P 500, and what it holds.</p>
  </div>
  <nav class="wrap tabs" role="tablist" aria-label="Sections">
    <button role="tab" id="t-live" aria-selected="true" aria-controls="p-live">Live fund</button>
    <button role="tab" id="t-strategy" aria-selected="false" aria-controls="p-strategy">The strategy</button>
    <button role="tab" id="t-history" aria-selected="false" aria-controls="p-history">History</button>
  </nav>
</header>

<main class="wrap">
<!-- ===================================================== LIVE FUND -->
<section id="p-live" role="tabpanel" aria-labelledby="t-live">
  <div class="kpis">
    <div class="tile hero"><div class="l">Portfolio value</div><div class="v" id="k-eq">β€”</div><div class="s" id="k-today"></div></div>
    <div class="tile"><div class="l">Since start</div><div class="v" id="k-ret">β€”</div><div class="s" id="k-ret-s"></div></div>
    <div class="tile"><div class="l">S&amp;P 500, same money</div><div class="v" id="k-spy">β€”</div><div class="s" id="k-spy-s"></div></div>
    <div class="tile"><div class="l">Worst fall</div><div class="v" id="k-dd">β€”</div><div class="s">peak to trough, since start</div></div>
    <div class="tile"><div class="l">Next rebalance</div><div class="v" id="k-next">β€”</div><div class="s" id="k-next-s"></div></div>
  </div>

  <div class="filters" aria-label="Chart period">
    <div class="seg" id="range">
      <button data-r="1M" aria-pressed="false">1M</button><button data-r="3M" aria-pressed="false">3M</button>
      <button data-r="YTD" aria-pressed="false">YTD</button><button data-r="1Y" aria-pressed="false">1Y</button>
      <button data-r="ALL" aria-pressed="true">All</button></div>
    <span class="period-read" id="period-read"></span>
  </div>
  <div class="card">
    <div class="chart-head">
      <div><h2>Portfolio value</h2><p class="sub">The Alpaca paper account, against the same money invested in the S&amp;P 500 (same start, same deposits).</p></div>
      <div class="legend"><span><i style="background:var(--updraft)"></i>Updraft</span><span><i style="background:var(--spy)"></i>S&amp;P 500</span></div>
    </div>
    <div class="chartbox"><canvas id="c-live" role="img" aria-label="Portfolio value versus the S&P 500"></canvas></div>
    <p class="note" id="live-note">Daily closes from the Alpaca account, plus the live value now (updates every 30 seconds).</p>
  </div>

  <div class="card">
    <div class="chart-head"><div><h2>Current holdings</h2><p class="sub" id="hold-sub">A third each, re-split monthly. A stock stays while it ranks in the top 6.</p></div></div>
    <div style="overflow-x:auto"><table class="hold" id="holdings"><thead><tr>
      <th>Stock</th><th class="hide-s">Weight</th><th class="r">Value</th><th class="r">Gain</th><th class="r hide-s">Today</th><th class="r">Rank now</th>
    </tr></thead><tbody><tr><td colspan="6" class="empty">Loading…</td></tr></tbody></table></div>
    <p class="note" id="cash-note"></p>
  </div>

  <div class="card">
    <div class="chart-head"><div><h2>Today's top 10</h2><p class="sub" id="short-sub">The quality pool ranked by trend β€” the list the three holdings are picked from.</p></div></div>
    <div style="overflow-x:auto"><table class="hold" id="shortlist"><thead><tr>
      <th class="r">#</th><th>Stock</th><th class="r">6 months</th><th class="r hide-s">1 month</th><th class="r hide-s">Quality</th><th>Status</th>
    </tr></thead><tbody><tr><td colspan="6" class="empty">Loading…</td></tr></tbody></table></div>
    <p class="note" id="short-note"></p>
  </div>
</section>

<!-- ===================================================== HISTORY -->
<section id="p-history" role="tabpanel" aria-labelledby="t-history" hidden>
  <div class="stat4" id="h-stats"></div>
  <div class="card">
    <h2>Rebalance by rebalance</h2>
    <p class="sub">Read from Alpaca's own orders, newest first. A holding is sold only once it drops out of the top 6; its slot
      goes to the highest-ranked stock not held, and the stocks that stay are re-split to a third each.</p>
    <div id="h-events" style="margin-top:10px"><p class="empty">Loading…</p></div>
  </div>
  <div class="card">
    <h2>Every position</h2>
    <p class="sub">Result = money taken out (sales, plus today's value while still held) minus money put in, so the monthly
      top-ups and trims are counted.</p>
    <div style="overflow-x:auto"><table class="hold" id="h-positions"><thead><tr>
      <th>Stock</th><th class="hide-s">Bought</th><th>Sold</th><th class="r hide-s">Held for</th><th class="r hide-s">Put in</th><th class="r">Result</th><th class="r">Return</th>
    </tr></thead><tbody><tr><td colspan="7" class="empty">Loading…</td></tr></tbody></table></div>
    <p class="note" id="h-note"></p>
  </div>
</section>

<!-- ===================================================== THE STRATEGY -->
<section id="p-strategy" role="tabpanel" aria-labelledby="t-strategy" hidden>
  <div class="card">
    <h2>How Updraft picks its three stocks</h2>
    <p class="sub">Two filters that each worked in 27 years of data β€” quality first, then trend β€” and a simple monthly routine.</p>
    <div class="steps">
      <div class="step"><div class="n">1,000</div><div class="t">Large US companies</div><p>The 1,000 largest by market value, price β‰₯ $5, at least $5M traded a day, US-dollar accounts.</p></div>
      <div class="step"><div class="n">~250</div><div class="t">Quality pool</div><p>The top 30% on capital discipline: buybacks, no new share issuance, low dilution, free-cash-flow yield, ROE, margins.</p></div>
      <div class="step"><div class="n">Rank</div><div class="t">Strongest trends</div><p>The pool ranked by its 50- vs 200-day average and its 6-month return (skipping the latest month).</p></div>
      <div class="step"><div class="n">3</div><div class="t">Held, a third each</div><p>On the first trading day of each month: keep a stock while it's still in the top 6, replace the rest from the top.</p></div>
    </div>
    <div class="callout">Why both filters: trend alone picks big winners and big blow-ups; the quality pool kept most of the winners and cut the
      blow-ups by about two-thirds. Holding only three concentrates the money in the strongest trends β€” fewer names earned more in every
      period tested, at the cost of bigger single-stock swings.</div>
  </div>

  <div class="card">
    <h2>27 years of backtest</h2>
    <p class="sub" id="bt-sub">Monthly, after trading costs, with companies that later went bust or were delisted included.</p>
    <div class="stat6" id="bt-stats"></div>
    <div class="chart-head" style="margin-top:14px">
      <div><h3>Growth of $10,000</h3><p class="sub">Log scale β€” equal distances mean equal percentage gains.</p></div>
      <div class="legend"><span><i style="background:var(--updraft)"></i>Updraft</span><span><i style="background:var(--spy)"></i>S&amp;P 500</span></div>
    </div>
    <div class="chartbox"><canvas id="c-growth" role="img" aria-label="Growth of ten thousand dollars, Updraft versus S&P 500"></canvas></div>
    <details><summary>View as table</summary><table id="t-growth"></table></details>
  </div>

  <div class="grid2">
    <div class="card">
      <div class="chart-head"><div><h3>Every calendar year</h3><p class="sub">First and last years are partial.</p></div>
        <div class="legend"><span><i class="band" style="background:var(--updraft);opacity:1"></i>Updraft</span><span><i class="band" style="background:var(--spy);opacity:1"></i>S&amp;P 500</span></div></div>
      <div class="chartbox sm"><canvas id="c-years" role="img" aria-label="Calendar-year returns"></canvas></div>
      <details><summary>View as table</summary><table id="t-years"></table></details>
    </div>
    <div class="card">
      <div class="chart-head"><div><h3>The falls along the way</h3><p class="sub">Distance below the previous peak at each month-end.</p></div>
        <div class="legend"><span><i style="background:var(--updraft)"></i>Updraft</span><span><i style="background:var(--spy)"></i>S&amp;P 500</span></div></div>
      <div class="chartbox sm"><canvas id="c-dd" role="img" aria-label="Drawdowns"></canvas></div>
    </div>
  </div>
  <div class="card">
    <div class="chart-head"><div><h3>What any 12 months looked like</h3><p class="sub" id="dist-sub">Share of all 12-month periods by return.</p></div>
      <div class="legend"><span><i class="band" style="background:var(--updraft);opacity:1"></i>Updraft</span><span><i class="band" style="background:var(--spy);opacity:1"></i>S&amp;P 500</span></div></div>
    <div class="chartbox sm"><canvas id="c-dist" role="img" aria-label="Distribution of 12-month returns"></canvas></div>
  </div>

  <div class="card">
    <h2>What it could grow to</h2>
    <p class="sub">20,000 simulated futures built from the real monthly returns (in 12-month blocks, so crashes and rallies stay clustered).
      Enter your amounts; the ranges scale exactly. Charts shade the middle half of outcomes; tables show the wider 10th–90th range.</p>
    <div class="calc">
      <div><div class="muted" style="margin-bottom:4px">Scenario</div><div class="seg" id="scen">
        <button data-s="planning" aria-pressed="true">Planning case</button><button data-s="history" aria-pressed="false">History repeats</button></div></div>
      <label>Lump sum ($)<input id="in-lump" type="number" min="0" step="1000" value="10000"></label>
      <label>Monthly SIP ($)<input id="in-sip" type="number" min="0" step="100" value="1000"></label>
    </div>
    <p class="muted" id="scen-note"></p>
    <div class="grid2" style="margin-top:6px">
      <div>
        <div class="chart-head" style="margin-bottom:6px"><div><h3>Lump sum</h3><p class="sub" id="lump-sub"></p></div></div>
        <div class="legend" style="margin-bottom:6px" id="leg-lump"></div>
        <div class="chartbox sm"><canvas id="c-lump" role="img" aria-label="Lump-sum projection"></canvas></div>
        <table class="proj" id="tb-lump"></table>
      </div>
      <div>
        <div class="chart-head" style="margin-bottom:6px"><div><h3>Monthly SIP</h3><p class="sub" id="sip-sub"></p></div></div>
        <div class="legend" style="margin-bottom:6px" id="leg-sip"></div>
        <div class="chartbox sm"><canvas id="c-sip" role="img" aria-label="Monthly investment projection"></canvas></div>
        <table class="proj" id="tb-sip"></table>
      </div>
    </div>
    <div class="callout">Read this honestly: the backtest's last few years were exceptionally strong (the 2024–26 AI rally). The
      <b>planning case</b> removes half of Updraft's historical edge over the S&amp;P and is the number to plan with; "history repeats" is the
      optimistic end. Single stocks are a third of the money each, so falls of 30–35% will happen along the way.</div>
  </div>
</section>
</main>

<footer class="wrap">Educational paper-trading demonstration β€” not investment advice. Live prices and positions from Alpaca (paper account,
IEX feed); rankings built daily from Sharadar fundamentals and prices; backtest 1999–2026 with point-in-time stock lists.</footer>

<script>
"use strict";
const $ = id => document.getElementById(id);
const css = n => getComputedStyle(document.documentElement).getPropertyValue(n).trim();
const pct = (x, d = 1) => x == null || !isFinite(x) ? "β€”" : (x >= 0 ? "+" : "βˆ’") + Math.abs(x * 100).toFixed(d) + "%";
const usd = x => x == null || !isFinite(x) ? "β€”" : (Math.abs(x) >= 1e6 ? "$" + (x / 1e6).toFixed(2) + "M" : "$" + Math.round(x).toLocaleString());
const usdShort = x => Math.abs(x) >= 1e6 ? "$" + (x / 1e6).toFixed(x >= 1e7 ? 0 : 1) + "M" : Math.abs(x) >= 1e3 ? "$" + Math.round(x / 1e3) + "K" : "$" + Math.round(x);
const signCls = (el, x) => { el.classList.remove("pos", "neg"); if (x != null && isFinite(x) && x !== 0) el.classList.add(x > 0 ? "pos" : "neg"); };
const alpha = (hex, a) => { const h = hex.replace("#", ""); const n = parseInt(h, 16); return `rgba(${n >> 16 & 255},${n >> 8 & 255},${n & 255},${a})`; };
async function get(u) { const r = await fetch(u); if (!r.ok) throw new Error((await r.json().catch(() => ({}))).detail || r.status); return r.json(); }
function setText(el, t) { el.textContent = t; }

/* ---------- theme */
try { const t = localStorage.getItem("updraft-theme"); if (t) document.documentElement.dataset.theme = t; } catch (e) {}
$("themeBtn").onclick = () => {
  const cur = document.documentElement.dataset.theme || (matchMedia("(prefers-color-scheme: dark)").matches ? "dark" : "light");
  const nxt = cur === "dark" ? "light" : "dark"; document.documentElement.dataset.theme = nxt;
  try { localStorage.setItem("updraft-theme", nxt); } catch (e) {}
  redrawAll();
};
matchMedia("(prefers-color-scheme: dark)").addEventListener?.("change", () => redrawAll());

/* ---------- tabs */
const LEDE = {
  live: "what it is worth right now, how it compares with the S&P 500, and what it holds.",
  strategy: "how it picks its stocks, 27 years of backtest, and what a lump sum or a monthly SIP could grow to.",
  history: "every monthly rebalance β€” what was bought, sold and kept β€” and how each position has done." };
function showTab(name) {
  for (const t of ["live", "strategy", "history"]) {
    $("t-" + t).setAttribute("aria-selected", String(t === name)); $("p-" + t).hidden = t !== name;
  }
  setText($("lede"), "An Alpaca live paper trade simulation, run by rules, not opinions. Below: " + LEDE[name]);
  if (name === "strategy") loadStrategy();
  if (name === "history") loadHistory();
  try { history.replaceState(null, "", name === "live" ? "#" : "#" + name); } catch (e) {}
}
for (const t of ["live", "strategy", "history"]) $("t-" + t).onclick = () => showTab(t);

/* ---------- chart plumbing */
const charts = {};
const crosshair = { id: "crosshair", afterDatasetsDraw(ch) {
  const a = ch.tooltip && ch.tooltip.getActiveElements && ch.tooltip.getActiveElements();
  if (!a || !a.length || ch.config.type !== "line") return;
  const x = a[0].element.x, { top, bottom } = ch.chartArea, c = ch.ctx;
  c.save(); c.strokeStyle = css("--axis"); c.lineWidth = 1; c.beginPath(); c.moveTo(x, top); c.lineTo(x, bottom); c.stroke(); c.restore();
}};
const endLabels = { id: "endLabels", afterDatasetsDraw(ch, _a, o) {
  if (!o || !o.enabled) return;
  const pts = [];
  ch.data.datasets.forEach((ds, i) => {
    if (ds.endLabel === false || ch.getDatasetMeta(i).hidden) return;
    const els = ch.getDatasetMeta(i).data; let j = ds.data.length - 1;
    while (j >= 0 && (ds.data[j] == null || !els[j])) j--;
    if (j < 0) return;
    pts.push({ x: els[j].x, y: els[j].y, color: ds.borderColor, text: o.format(ds, ds.data[j]) });
  });
  const c = ch.ctx, collide = pts.length === 2 && Math.abs(pts[0].y - pts[1].y) < 18;
  c.save();
  for (const p of pts) {
    c.beginPath(); c.arc(p.x, p.y, 6, 0, 2 * Math.PI); c.fillStyle = css("--surface"); c.fill();
    c.beginPath(); c.arc(p.x, p.y, 4, 0, 2 * Math.PI); c.fillStyle = p.color; c.fill();
    if (!collide) { c.font = "600 12px " + css("--sans"); c.fillStyle = css("--ink"); c.textAlign = "right"; c.fillText(p.text, p.x - 10, p.y - 10); }
  }
  c.restore();
}};
Chart.register(crosshair, endLabels);
function baseOpts(extra = {}) {
  const ink2 = css("--ink-2"), muted = css("--muted"), grid = css("--grid");
  return Object.assign({
    responsive: true, maintainAspectRatio: false, animation: { duration: 250 },
    interaction: { mode: "index", intersect: false },
    layout: { padding: { top: 18, right: 6 } },
    plugins: { legend: { display: false },
      tooltip: { backgroundColor: css("--surface"), borderColor: css("--border"), borderWidth: 1, titleColor: ink2, bodyColor: css("--ink"),
        padding: 10, usePointStyle: true, boxWidth: 14, boxHeight: 2, titleFont: { weight: "600" }, bodyFont: { weight: "600" } } },
    scales: {
      x: { grid: { display: false }, border: { color: css("--axis") }, ticks: { color: muted, maxTicksLimit: 8, maxRotation: 0 } },
      y: { grid: { color: grid }, border: { display: false }, ticks: { color: muted } } }
  }, extra);
}
function mk(id, cfg) { if (charts[id]) charts[id].destroy(); charts[id] = new Chart($(id), cfg); return charts[id]; }
function line(label, data, color, extra = {}) {
  return Object.assign({ label, data, borderColor: color, backgroundColor: color, borderWidth: 2, pointRadius: 0, pointHoverRadius: 4,
    pointStyle: "line", tension: 0.15, borderJoinStyle: "round", borderCapStyle: "round", spanGaps: true }, extra);
}

/* ---------- LIVE FUND */
let perf = null, port = null, range = "ALL", liveOff = 0;
const usdTick = (v, span) => span < 5e3 ? "$" + Math.round(v).toLocaleString()
  : span < 5e4 && Math.abs(v) < 1e6 ? "$" + (v / 1e3).toFixed(v % 1e3 ? 1 : 0) + "K" : usdShort(v);
function maxDD(g) { let pk = 0, w = 0; for (const x of g) { if (x == null) continue; pk = Math.max(pk, x); w = Math.min(w, x / pk - 1); } return w; }
function cut(dates) {
  if (range === "ALL" || !dates.length) return 0;
  const last = new Date(dates[dates.length - 1] + "T12:00:00"); const d = new Date(last);
  if (range === "1M") d.setMonth(d.getMonth() - 1); else if (range === "3M") d.setMonth(d.getMonth() - 3);
  else if (range === "1Y") d.setFullYear(d.getFullYear() - 1); else if (range === "YTD") d.setMonth(0, 1);
  const iso = d.toISOString().slice(0, 10); const i = dates.findIndex(x => x >= iso); return Math.max(0, i - (range === "YTD" ? 0 : 1));
}
function syncLive() {            // the chart's live point follows the 30-second account value shown above it
  if (!perf || !port || !perf.src || perf.src[perf.src.length - 1] !== "live") return;
  const n = perf.value.length - 1; perf.value[n] = port.equity;
  if (n > 0) perf.strategy[n] = perf.strategy[n - 1] * (port.equity - (perf.flows_today || 0)) / perf.value[n - 1];
}
function drawLive(fresh) {
  if (!perf || !perf.dates || !perf.dates.length) return;
  const i0 = cut(perf.dates); liveOff = i0;
  const D = perf.dates.slice(i0), V = perf.value.slice(i0), B = perf.bench_value.slice(i0);
  const all = V.concat(B).filter(x => x != null), lo = Math.min(...all), hi = Math.max(...all);
  const pad = Math.max(0, (0.06 * (lo + hi) / 2 - (hi - lo)) / 2);     // at least a 6% window: small moves look small
  const yMin = lo - pad, yMax = hi + pad, span = yMax - yMin, tick = v => usdTick(v, span);
  const ch = charts["c-live"];
  if (ch && !fresh) {
    ch.data.labels = D; ch.data.datasets[0].data = V; ch.data.datasets[1].data = B;
    Object.assign(ch.options.scales.y, { suggestedMin: yMin, suggestedMax: yMax }); ch.options.scales.y.ticks.callback = tick;
    ch.update("none");
  } else {
    const u = css("--updraft"), s = css("--spy");
    mk("c-live", { type: "line", data: { labels: D, datasets: [
        line("Updraft", V, u, { fill: "start", backgroundColor: alpha(u, 0.10) }),
        line("S&P 500, same money", B, s)] },
      options: baseOpts({ plugins: Object.assign(baseOpts().plugins, { endLabels: { enabled: true, format: (ds, v) => usd(v) },
          tooltip: Object.assign(baseOpts().plugins.tooltip, { callbacks: {
            title: c => { const src = (perf.src || [])[liveOff + c[0].dataIndex]; return c[0].label + (src === "live" ? " Β· live" : src === "rebuilt" ? " Β· rebuilt close" : ""); },
            label: c => `${usd(c.parsed.y)}   ${c.dataset.label}` } }) }),
        scales: Object.assign(baseOpts().scales, { y: Object.assign(baseOpts().scales.y, { suggestedMin: yMin, suggestedMax: yMax,
          ticks: { color: css("--muted"), maxTicksLimit: 7, callback: tick } }) }) }) });
  }
  const S = perf.strategy.slice(i0), P = perf.spy.slice(i0);
  const ru = S.length > 1 ? S[S.length - 1] / S[0] - 1 : null, rb = P.length > 1 && P[0] && P[P.length - 1] ? P[P.length - 1] / P[0] - 1 : null;
  setText($("period-read"), ru == null ? "" : `This period: Updraft ${pct(ru)} Β· S&P 500 ${pct(rb)}`);
}
document.querySelectorAll("#range button").forEach(b => b.onclick = () => {
  range = b.dataset.r; document.querySelectorAll("#range button").forEach(x => x.setAttribute("aria-pressed", String(x === b))); drawLive();
});
function showPerf() {
  if (!perf || !perf.dates || !perf.dates.length) return;
  const S = perf.strategy, P = perf.spy, n = S.length - 1, s = perf.stats || {};
  const ret = S[n] - 1, spyRet = P[n] != null ? P[n] - 1 : null, dd = maxDD(S);
  setText($("k-ret"), pct(ret)); signCls($("k-ret"), ret);
  setText($("k-ret-s"), perf.start ? `since the first trade, ${perf.start}` + (s.annualised != null ? ` Β· ${pct(s.annualised)} a year` : "") : "starts with the first trade");
  setText($("k-spy"), pct(spyRet)); signCls($("k-spy"), spyRet);
  setText($("k-spy-s"), spyRet != null ? `Updraft ${ret >= spyRet ? "ahead" : "behind"} by ${pct(Math.abs(ret - spyRet)).replace("+", "")}` : "");
  setText($("k-dd"), pct(dd)); signCls($("k-dd"), dd < 0 ? -1 : null);
  drawLive();
  const rebuilt = (perf.src || []).filter(x => x === "rebuilt").length;
  let note = "Daily closes from the Alpaca account, plus the live value now (updates every 30 seconds).";
  if (rebuilt) note += ` ${rebuilt === 1 ? "One recent close is" : rebuilt + " recent closes are"} rebuilt from the account's fills and closing prices until Alpaca's own history posts it.`;
  if (perf.dates.length < 6) note = `The fund started on ${perf.start || "its first trade"} β€” the chart fills in day by day. ` + note;
  setText($("live-note"), note);
}
function showToday() {         // against the last close on the chart: Alpaca's own last_equity can lag a day on paper
  if (!port) return;
  let ch = port.today_change, pc = port.today_pct;
  if (perf && perf.src && perf.src[perf.src.length - 1] === "live" && perf.value.length > 1) {
    const prev = perf.value[perf.value.length - 2]; ch = port.equity - (perf.flows_today || 0) - prev; pc = ch / prev;
  }
  setText($("k-today"), pc == null ? "" : `today ${pct(pc, 2)} (${ch >= 0 ? "+" : "βˆ’"}${usd(Math.abs(ch))})`);
  signCls($("k-today"), pc);
}
async function loadPerformance() {
  try { perf = await get("/api/performance"); syncLive(); showPerf(); showToday(); if (hist) renderHistory(); }
  catch (e) { setText($("live-note"), "Performance unavailable right now: " + e.message); }
}
async function loadPortfolio() {
  try {
    const p = await get("/api/portfolio"); port = p;
    if (perf) { syncLive(); showPerf(); }
    setText($("k-eq"), usd(p.equity));
    showToday(); showShortlist();
    const tb = $("holdings").querySelector("tbody"); tb.textContent = "";
    if (!p.positions.length) { const tr = tb.insertRow(); const td = tr.insertCell(); td.colSpan = 6; td.className = "empty"; td.textContent = "No positions yet β€” the first rebalance buys the top 3."; }
    for (const r of p.positions) {
      const tr = tb.insertRow();
      const a = tr.insertCell(); const t = document.createElement("div"); t.className = "tick"; t.textContent = r.symbol;
      const co = document.createElement("div"); co.className = "co"; co.textContent = [r.name, r.sector].filter(Boolean).join(" Β· "); a.append(t, co);
      const w = tr.insertCell(); w.className = "hide-s"; const wb = document.createElement("div"); wb.className = "wbar";
      const tr2 = document.createElement("span"); const fill = document.createElement("b"); fill.style.width = Math.min(100, (r.weight || 0) * 100 / 0.5) + "%"; tr2.append(fill);
      const wl = document.createElement("small"); wl.textContent = pct(r.weight, 0).replace("+", ""); wb.append(tr2, wl); w.append(wb);
      const v = tr.insertCell(); v.className = "r"; v.textContent = usd(r.value);
      const g = tr.insertCell(); g.className = "r"; g.textContent = pct(r.pl_pct); signCls(g, r.pl_pct);
      const d = tr.insertCell(); d.className = "r hide-s"; d.textContent = pct(r.today); signCls(d, r.today);
      const k = tr.insertCell(); k.className = "r"; const rk = document.createElement("span"); rk.className = "rank"; rk.textContent = r.rank_now ? "#" + r.rank_now : "β€”"; k.append(rk);
    }
    setText($("cash-note"), `Cash ${usd(p.cash)} (about 1% is kept back for fills). Prices update every 30 seconds while this page is open.`);
    setText($("updated"), "Live Β· " + new Date().toLocaleTimeString([], { hour: "2-digit", minute: "2-digit" })); $("dot").style.background = "#3fbf6b";
  } catch (e) { setText($("updated"), "Live data unavailable"); $("dot").style.background = "#f07068"; }
}
let rk = null;
async function loadRanking() {
  try {
    rk = await get("/api/ranking");
    if (!rk.ranked || !rk.ranked.length) {          // the Space rebuilds the ranking for about a minute after a restart
      setText($("short-note"), "Today's ranking is being rebuilt β€” it appears here in about a minute."); setTimeout(loadRanking, 20000); return;
    }
    showShortlist();
  }
  catch (e) { setText($("short-note"), "The ranking is unavailable right now."); }
}
function showShortlist() {
  if (!rk || !rk.ranked || !rk.ranked.length) return;
  const N = (rk.rule && rk.rule.names) || 3, K = (rk.rule && rk.rule.keep_within) || 6;
  const order = rk.ranked.map(r => r.ticker), rank = Object.fromEntries(order.map((t, i) => [t, i + 1]));
  const held = port ? port.positions.map(p => p.symbol) : null;
  let target = null;                    // the same rule as the rebalance: keep holdings in the top K, refill from the top
  if (held) {
    const kept = held.filter(t => (rank[t] || 1e9) <= K).sort((a, b) => rank[a] - rank[b]).slice(0, N);
    target = kept.concat(order.filter(t => !kept.includes(t)).slice(0, N - kept.length));
  }
  const tb = $("shortlist").querySelector("tbody"); tb.textContent = "";
  for (const r of rk.ranked.slice(0, 10)) {
    const isHeld = !!held && held.includes(r.ticker), tr = tb.insertRow();
    if (isHeld) tr.className = "is-held";
    const n = tr.insertCell(); n.className = "r"; const rc = document.createElement("span"); rc.className = "rank"; rc.textContent = "#" + r.rank; n.append(rc);
    const a = tr.insertCell(); const t = document.createElement("div"); t.className = "tick"; t.textContent = r.ticker;
    const co = document.createElement("div"); co.className = "co"; co.textContent = [r.name, r.sector].filter(Boolean).join(" Β· "); a.append(t, co);
    const m6 = tr.insertCell(); m6.className = "r"; m6.textContent = pct(r.ret_6m, 0); signCls(m6, r.ret_6m);
    const m1 = tr.insertCell(); m1.className = "r hide-s"; m1.textContent = pct(r.ret_1m, 0); signCls(m1, r.ret_1m);
    const q = tr.insertCell(); q.className = "r hide-s"; q.textContent = r.qcd_pct == null ? "β€”" : "top " + Math.max(1, Math.round((1 - r.qcd_pct) * 100)) + "%";
    const st = tr.insertCell();
    if (target) {
      const tag = document.createElement("span");
      if (isHeld && target.includes(r.ticker)) { tag.className = "tag held"; tag.textContent = "Held"; }
      else if (isHeld) { tag.className = "tag sell"; tag.textContent = "Held Β· would sell"; }
      else if (target.includes(r.ticker)) { tag.className = "tag buy"; tag.textContent = "Would buy"; }
      if (tag.className) st.append(tag);
    }
  }
  const asOf = rk.prices_as_of ? new Date(rk.prices_as_of + "T12:00:00").toLocaleDateString([], { day: "numeric", month: "short" }) : null;
  setText($("short-sub"), `The ${rk.pool || "~250"} stocks in the quality pool, ranked by trend${asOf ? " on closes of " + asOf : ""} and rebuilt every night. The three holdings are picked from this list at each monthly rebalance.`);
  let note = "";
  if (held && target) {
    const sells = held.filter(x => !target.includes(x)), buys = target.filter(x => !held.includes(x));
    if (!held.length) note = `The first rebalance would buy ${buys.join(", ")}.`;
    else if (!sells.length) note = `If the rebalance ran today: no change β€” ${held.join(", ")} ${held.length > 1 ? "are all" : "is"} still in the top ${K}.`;
    else note = `If the rebalance ran today: sell ${sells.map(x => x + (rank[x] ? ` (now #${rank[x]})` : " (left the pool)")).join(", ")}; buy ${buys.join(", ")}.`;
    const ahead = order.slice(0, N).filter(x => !held.includes(x) && !buys.includes(x));
    if (ahead.length) note += ` ${ahead.join(", ")} ${ahead.length > 1 ? "rank" : "ranks"} in today's top ${N} but ${ahead.length > 1 ? "are" : "is"} bought only when a holding drops out of the top ${K} β€” the buffer avoids trading on small rank changes.`;
  }
  setText($("short-note"), (note + ` Quality = percentile on capital discipline among the ${rk.liquid_usd || ""} tradable stocks of the 1,000 largest; the top 30% form the pool.`).replace("among the  ", "among the ").trim());
}
async function loadStatus() {
  try {
    const s = await get("/api/status"); stat = s;
    setText($("k-next"), s.next_rebalance ? new Date(s.next_rebalance + "T12:00:00").toLocaleDateString([], { day: "numeric", month: "short" }) : "β€”");
    setText($("k-next-s"), s.done_this_month ? "this month's rebalance is done" : (s.market_open ? "market open" : "first trading day of the month"));
  } catch (e) {}
}

/* ---------- HISTORY */
let hist = null, stat = null, histAt = 0;
const fmtDay = d => new Date(d + "T12:00:00").toLocaleDateString([], { day: "numeric", month: "short", year: "numeric" });
const fmtHeld = d => d == null ? "β€”" : d < 60 ? `${d} day${d === 1 ? "" : "s"}` : `${(d / 30.44).toFixed(1)} months`;
const usdSigned = x => x == null ? "β€”" : (x >= 0 ? "+" : "βˆ’") + usd(Math.abs(x));
function el(tag, cls, text) { const e = document.createElement(tag); if (cls) e.className = cls; if (text != null) e.textContent = text; return e; }
function tile(label, value, sub, cls) {
  const t = el("div", "tile"); t.append(el("div", "l", label)); const v = el("div", "v", value); if (cls) v.classList.add(cls);
  t.append(v, el("div", "s", sub)); return t;
}
function periodRet(d0, d1) {        // fund and S&P from the last close before d0 to the last close before d1 (or now)
  if (!perf || !perf.dates || perf.dates.length < 2) return null;
  const D = perf.dates; let a = -1, b = D.length - 1;
  for (let i = 0; i < D.length; i++) { if (D[i] < d0) a = i; if (d1 && D[i] < d1) b = i; }
  a = Math.max(a, 0); if (b <= a) return null;
  return [perf.strategy[b] / perf.strategy[a] - 1, perf.spy[a] && perf.spy[b] ? perf.spy[b] / perf.spy[a] - 1 : null];
}
async function loadHistory() {
  if (hist && Date.now() - histAt < 120000) return;
  try { hist = await get("/api/history"); histAt = Date.now(); renderHistory(); }
  catch (e) { $("h-events").textContent = ""; $("h-events").append(el("p", "empty", "History unavailable right now: " + e.message)); }
}
function renderHistory() {
  const h = hist, S = h.summary, nameOf = r => [r.name, r.symbol].filter(Boolean)[0];
  const next = stat && stat.next_rebalance ? new Date(stat.next_rebalance + "T12:00:00").toLocaleDateString([], { day: "numeric", month: "short" }) : "the next rebalance";
  const st = $("h-stats"); st.textContent = "";
  st.append(
    tile("Rebalances", String(S.rebalances), S.first ? "since " + fmtDay(S.first) : "none yet"),
    tile("Stocks replaced", S.swaps_per_rebalance == null ? "β€”" : S.swaps_per_rebalance.toFixed(1) + " of 3",
      S.swaps_per_rebalance == null ? `none yet β€” the first possible change is ${next}` : "per rebalance, on average"),
    tile("Sold at a profit", S.win_rate == null ? "β€”" : pct(S.win_rate, 0).replace("+", ""),
      S.win_rate == null ? "no position has been sold yet" : `${S.closed} sold Β· average ${pct(S.avg_return)}`),
    tile("Average holding", S.avg_days == null ? "β€”" : fmtHeld(Math.round(S.avg_days)),
      S.best ? `best ${S.best.symbol} ${pct(S.best.return, 0)} Β· worst ${S.worst.symbol} ${pct(S.worst.return, 0)}` : "of the positions sold so far"));
  const box = $("h-events"); box.textContent = "";
  if (!h.events.length) box.append(el("p", "empty", "No rebalance yet β€” the first one buys the top 3."));
  h.events.forEach((e, i) => {
    const ev = el("div", "ev"), left = el("div", "ev-date"), body = el("div", "ev-body");
    const b = el("b"); if (i === 0) b.append(el("i", "now")); b.append(document.createTextNode(fmtDay(e.date)));
    left.append(b, el("span", null, e.first ? "Fund started" : i === 0 ? "Current portfolio" : "Monthly rebalance"));
    const r = periodRet(e.date, i > 0 ? h.events[i - 1].date : null);
    if (r) {
      const pp = el("div", "ev-perf"); pp.append(document.createTextNode((i === 0 ? "Held since: " : "While held: ") + "Updraft "));
      const u = el("b", null, pct(r[0])); signCls(u, r[0]); pp.append(u, document.createTextNode(" Β· S&P 500 " + pct(r[1]) + (i === 0 ? " so far" : "")));
      body.append(pp);
    }
    const row = (k, items) => { if (!items.length) return; const rw = el("div", "ev-row"); rw.append(el("span", "ev-k", k), ...items); body.append(rw); };
    const chip = (sym, cls, title) => { const c = el("span", "tag " + cls, sym); if (title) c.title = title; return c; };
    const names = {}; for (const p of h.open.concat(h.closed)) names[p.symbol] = p.name;
    row("Bought", e.bought.map(x => chip(x, "buy", names[x])));
    row("Sold", e.sold.flatMap(x => { const g = el("span", null, pct(x.return)); signCls(g, x.return);
      return [chip(x.symbol, "sell", x.name), g, el("span", "muted", `after ${fmtHeld(x.days)} Β· ${usdSigned(x.pnl)}`)]; }));
    row("Kept", e.kept.map(x => chip(x, "held", names[x])));
    const notes = [];
    if (e.sold.length) notes.push(`${e.sold.map(x => x.symbol).join(", ")} dropped out of the top 6`);
    if (e.resplit.length) notes.push("re-split: " + e.resplit.map(x => `${x.value > 0 ? "topped up" : "trimmed"} ${x.symbol} ${usd(Math.abs(x.value))}`).join(", "));
    if (e.added) notes.push(`${usd(e.added)} added since the previous rebalance`);
    notes.push(`${usd(e.traded)} traded`);
    body.append(el("div", "ev-small", notes.join(" Β· ")));
    ev.append(left, body); box.append(ev);
  });
  const tb = $("h-positions").querySelector("tbody"); tb.textContent = "";
  const rows = h.open.map(x => ({ ...x, held: true })).concat(h.closed);
  if (!rows.length) { const tr = tb.insertRow(); const td = tr.insertCell(); td.colSpan = 7; td.className = "empty"; td.textContent = "No positions yet."; }
  for (const x of rows) {
    const tr = tb.insertRow(); if (x.held) tr.className = "is-held";
    const a = tr.insertCell(); a.append(el("div", "tick", x.symbol), el("div", "co", x.name || ""));
    const bd = tr.insertCell(); bd.className = "hide-s"; bd.textContent = fmtDay(x.entered);
    const sc = tr.insertCell(); if (x.held) sc.append(el("span", "tag held", "Still held")); else sc.textContent = fmtDay(x.exited);
    const hd = tr.insertCell(); hd.className = "r hide-s"; hd.textContent = fmtHeld(x.days);
    const pi = tr.insertCell(); pi.className = "r hide-s"; pi.textContent = usd(x.put_in);
    const pl = tr.insertCell(); pl.className = "r"; pl.textContent = usdSigned(x.pnl); signCls(pl, x.pnl);
    const rt = tr.insertCell(); rt.className = "r"; rt.textContent = pct(x.return); signCls(rt, x.return);
  }
  setText($("h-note"), (h.pending_deposits > 0 ? `${usd(h.pending_deposits)} added since the last rebalance β€” it is invested at the next one. ` : "") +
    "Positions still held are valued at today's price. Updates every few minutes.");
}

/* ---------- THE STRATEGY */
let strat = null, scen = "planning";
async function loadStrategy() {
  if (strat) return;
  try { strat = await get("/static/data/strategy.json"); } catch (e) { setText($("bt-sub"), "Backtest data unavailable."); return; }
  const k = strat.stats, sp = strat.spy, y = strat.rolling_12m, box = $("bt-stats"); box.textContent = "";
  const tiles = [["Return per year", pct(k.cagr), `S&P 500 ${pct(sp.cagr)}`], ["Worst fall", pct(k.max_dd, 0), `S&P 500 ${pct(sp.max_dd, 0)}`],
    ["Sharpe ratio", k.sharpe.toFixed(2), `S&P 500 ${sp.sharpe.toFixed(2)}`], ["Median 12 months", pct(y.median, 0), `S&P 500 ${pct(y.spy_median, 0)}`],
    ["12 months in profit", Math.round(y.share_positive * 100) + "%", `S&P 500 ${Math.round(y.spy_share_positive * 100)}%`],
    ["Beat the S&P over 12 months", Math.round(y.share_beat_spy * 100) + "%", "of all start months"]];
  for (const [l, v, s] of tiles) { const t = document.createElement("div"); t.className = "tile";
    for (const [c, x] of [["l", l], ["v", v], ["s", s]]) { const d = document.createElement("div"); d.className = c; d.textContent = x; t.append(d); } box.append(t); }
  setText($("bt-sub"), `${strat.period}, monthly, after trading costs; companies that later went bust or were delisted are included. Before the 2024–26 AI rally (2013–2023): ${pct(k.cagr_2013_2023)} a year vs S&P ${pct(sp.cagr_2013_2023)}.`);
  setText($("dist-sub"), `Share of all ${y.n} rolling 12-month periods by return. Updraft's middle 80% ran from ${pct(y.p10, 0)} to ${pct(y.p90, 0)}.`);
  fillTables(); drawStrategy();
}
function fillTables() {
  const g = strat.growth, tg = $("t-growth"); tg.textContent = "";
  const h = tg.createTHead().insertRow(); for (const x of ["Year-end", "Updraft", "S&P 500"]) { const th = document.createElement("th"); th.textContent = x; h.append(th); }
  const b = tg.createTBody();
  g.dates.forEach((d, i) => { if (d.endsWith("-12") || i === g.dates.length - 1) { const r = b.insertRow(); for (const x of [d, usd(g.updraft[i]), usd(g.spy[i])]) r.insertCell().textContent = x; } });
  const ty = $("t-years"); ty.textContent = ""; const h2 = ty.createTHead().insertRow();
  for (const x of ["Year", "Updraft", "S&P 500"]) { const th = document.createElement("th"); th.textContent = x; h2.append(th); }
  const b2 = ty.createTBody(); strat.years.labels.forEach((yr, i) => { const r = b2.insertRow(); for (const x of [yr, pct(strat.years.updraft[i]), pct(strat.years.spy[i])]) r.insertCell().textContent = x; });
}
function bars(label, data, color) {
  return { label, data, backgroundColor: color, borderRadius: 4, borderSkipped: "start", maxBarThickness: 24, categoryPercentage: 0.72, barPercentage: 0.88, pointStyle: "rect" };
}
function drawStrategy() {
  if (!strat) return;
  const u = css("--updraft"), s = css("--spy"), g = strat.growth;
  mk("c-growth", { type: "line", data: { labels: g.dates, datasets: [line("Updraft", g.updraft, u), line("S&P 500", g.spy, s)] },
    options: baseOpts({ plugins: Object.assign(baseOpts().plugins, { endLabels: { enabled: true, format: (ds, v) => usd(v) },
      tooltip: Object.assign(baseOpts().plugins.tooltip, { callbacks: { label: c => `${usd(c.parsed.y)}   ${c.dataset.label}` } }) }),
      scales: { x: Object.assign(baseOpts().scales.x, { ticks: { color: css("--muted"), maxTicksLimit: 10, maxRotation: 0, callback: function (v) { return this.getLabelForValue(v).slice(0, 4); } } }),
        y: Object.assign(baseOpts().scales.y, { type: "logarithmic", ticks: { color: css("--muted"), callback: v => [1e4, 3e4, 1e5, 3e5, 1e6, 3e6, 1e7, 3e7].includes(v) ? usdShort(v) : null } }) } }) });
  const Y = strat.years;
  mk("c-years", { type: "bar", data: { labels: Y.labels.map(x => "’" + x.slice(2)), datasets: [bars("Updraft", Y.updraft, u), bars("S&P 500", Y.spy, s)] },
    options: baseOpts({ interaction: { mode: "index", intersect: false }, plugins: Object.assign(baseOpts().plugins, {
      tooltip: Object.assign(baseOpts().plugins.tooltip, { callbacks: { title: c => "20" + c[0].label.slice(1), label: c => `${pct(c.parsed.y)}   ${c.dataset.label}` } }) }),
      scales: { x: Object.assign(baseOpts().scales.x, { ticks: { color: css("--muted"), maxTicksLimit: 14, maxRotation: 0 } }),
        y: Object.assign(baseOpts().scales.y, { ticks: { color: css("--muted"), callback: v => pct(v, 0) } }) } }) });
  const DD = strat.drawdown;
  mk("c-dd", { type: "line", data: { labels: DD.dates, datasets: [line("Updraft", DD.updraft, u, { fill: "origin", backgroundColor: alpha(u, 0.10) }), line("S&P 500", DD.spy, s)] },
    options: baseOpts({ plugins: Object.assign(baseOpts().plugins, { tooltip: Object.assign(baseOpts().plugins.tooltip, { callbacks: { label: c => `${pct(c.parsed.y, 0)}   ${c.dataset.label}` } }) }),
      scales: { x: Object.assign(baseOpts().scales.x, { ticks: { color: css("--muted"), maxTicksLimit: 7, maxRotation: 0, callback: function (v) { return this.getLabelForValue(v).slice(0, 4); } } }),
        y: Object.assign(baseOpts().scales.y, { max: 0, ticks: { color: css("--muted"), callback: v => pct(v, 0) } }) } }) });
  const E = strat.dist12.edges, lab = E.slice(0, -1).map((e, i) => i === E.length - 2 ? `β‰₯ ${pct(e, 0)}` : (i === 0 ? `≀ ${pct(E[1], 0)}` : pct(e, 0)));
  mk("c-dist", { type: "bar", data: { labels: lab, datasets: [bars("Updraft", strat.dist12.updraft, u), bars("S&P 500", strat.dist12.spy, s)] },
    options: baseOpts({ plugins: Object.assign(baseOpts().plugins, { tooltip: Object.assign(baseOpts().plugins.tooltip, {
      callbacks: { title: c => { const i = c[0].dataIndex; return i === 0 ? `12-month return ≀ ${pct(E[1], 0)}` : i === E.length - 2 ? `12-month return β‰₯ ${pct(E[i], 0)}` : `12-month return ${pct(E[i], 0)} to ${pct(E[i + 1], 0)}`; },
        label: c => `${Math.round(c.parsed.y * 100)}% of periods   ${c.dataset.label}` } }) }),
      scales: { x: Object.assign(baseOpts().scales.x, { ticks: { color: css("--muted"), maxTicksLimit: 9, maxRotation: 0 } }),
        y: Object.assign(baseOpts().scales.y, { ticks: { color: css("--muted"), callback: v => Math.round(v * 100) + "%" } }) } }) });
  drawProjections();
}
function num(id, def) { const v = parseFloat($(id).value); return isFinite(v) && v >= 0 ? v : def; }
function legendRow(el, items) {
  el.textContent = "";
  for (const [color, text, band] of items) { const s = document.createElement("span"); const i = document.createElement("i"); i.style.background = color;
    if (band) i.className = "band"; s.append(i, document.createTextNode(text)); el.append(s); }
}
function drawProjections() {
  if (!strat) return;
  const P = strat.projections, S = P[scen], B = P.spy, yrs = P.years;
  const col = scen === "planning" ? css("--plan") : css("--updraft"), spyc = css("--spy"), muted = css("--muted");
  const name = scen === "planning" ? "Updraft, planning case" : "Updraft, history repeats";
  setText($("scen-note"), scen === "planning"
    ? `Planning case: the same months with ${pct(P.planning_edge_removed, 1).replace("+", "")} a year of Updraft's edge removed β€” half of its historical lead over the S&P.`
    : "History repeats: Updraft's 1999–2026 monthly returns as they were β€” the optimistic end, flattered by the 2024–26 rally.");
  for (const kind of ["lump", "sip"]) {
    const amt = kind === "lump" ? num("in-lump", 10000) : num("in-sip", 1000), d = S[kind], b = B[kind];
    const scale = a => a.map(x => x * amt);
    const ds = [
      line("75th percentile", scale(d.p75), "transparent", { fill: "+1", backgroundColor: alpha(col, 0.16), endLabel: false, pointHoverRadius: 0 }),
      line("25th percentile", scale(d.p25), "transparent", { endLabel: false, pointHoverRadius: 0 }),
      line(name + " (median)", scale(d.p50), col),
      line("S&P 500 (median)", scale(b.p50), spyc)];
    if (kind === "sip") ds.push(line("Paid in", d.paid.map(x => x * amt), muted, { borderWidth: 1, endLabel: false }));
    legendRow($("leg-" + kind), [[col, "Median", false], [col, "Middle half of outcomes", true], [spyc, "S&P 500 median", false]].concat(kind === "sip" ? [[muted, "Paid in", false]] : []));
    mk("c-" + kind, { type: "line", data: { labels: yrs.map(y => y === 0 ? "Start" : y + "y"), datasets: ds },
      options: baseOpts({ plugins: Object.assign(baseOpts().plugins, { endLabels: { enabled: true, format: (x, v) => usdShort(v) },
        tooltip: Object.assign(baseOpts().plugins.tooltip, { filter: it => it.datasetIndex > 1 || it.datasetIndex === 0,
          callbacks: { title: c => c[0].label === "Start" ? "Start" : "After " + c[0].label.replace("y", " years"),
            label: c => c.datasetIndex === 0 ? `${usdShort(scale(d.p25)[c.dataIndex])} – ${usdShort(c.parsed.y)}   middle half` : `${usd(c.parsed.y)}   ${c.dataset.label}` } }) }),
        scales: { x: baseOpts().scales.x, y: Object.assign(baseOpts().scales.y, { ticks: { color: css("--muted"), callback: v => usdShort(v) } }) } }) });
    const tb = $("tb-" + kind); tb.textContent = "";
    const hr = tb.createTHead().insertRow();
    for (const h of ["After", "Paid in", "Updraft median", "Range (10th–90th)", "S&P median", "Below paid in"]) { const th = document.createElement("th"); th.textContent = h; hr.append(th); }
    const body = tb.createTBody();
    for (const yr of [5, 10, 15]) {
      const r = body.insertRow(), paid = (kind === "lump" ? amt : amt * 12 * yr);
      const cells = [`${yr} years`, usd(paid), usd(d.p50[yr] * amt), `${usdShort(d.p10[yr] * amt)} – ${usdShort(d.p90[yr] * amt)}`, usd(b.p50[yr] * amt),
        Math.round(d.below_paid[yr] * 100) + "%"];
      cells.forEach((c, i) => { const td = r.insertCell(); td.textContent = c; if (i === 2) td.className = "big"; });
    }
    const m15 = d.p50[15] / (kind === "lump" ? 1 : 180), s15 = b.p50[15] / (kind === "lump" ? 1 : 180);
    setText($(kind + "-sub"), kind === "lump" ? `${usd(amt)} once. Median after 15 years: ${m15.toFixed(1)}Γ— the money (S&P ${s15.toFixed(1)}Γ—).`
      : `${usd(amt)} every month. Median after 15 years: ${m15.toFixed(1)}Γ— what you paid in (S&P ${s15.toFixed(1)}Γ—).`);
  }
}
document.querySelectorAll("#scen button").forEach(b => b.onclick = () => { scen = b.dataset.s;
  document.querySelectorAll("#scen button").forEach(x => x.setAttribute("aria-pressed", String(x === b))); drawProjections(); });
["in-lump", "in-sip"].forEach(id => $(id).addEventListener("input", () => drawProjections()));

function redrawAll() { drawLive(true); if (strat) drawStrategy(); }

/* ---------- start */
loadPortfolio(); loadPerformance(); loadStatus(); loadRanking();
setInterval(loadPortfolio, 30000); setInterval(loadStatus, 60000); setInterval(loadRanking, 600000); setInterval(loadPerformance, 60000);
if (location.hash === "#strategy" || location.hash === "#history") showTab(location.hash.slice(1));
</script>
</body>
</html>