File size: 26,349 Bytes
643c6c8
 
 
 
 
8f12e15
 
 
 
 
193ef12
 
 
 
 
8f12e15
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
062c7cc
193ef12
8f12e15
 
 
 
193ef12
 
8f12e15
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
643c6c8
 
 
 
 
a213ac9
 
 
 
643c6c8
 
 
a213ac9
 
193ef12
8f12e15
 
a213ac9
8f12e15
643c6c8
a213ac9
643c6c8
 
 
 
 
 
 
 
 
 
a213ac9
643c6c8
 
 
a213ac9
 
 
643c6c8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a213ac9
 
 
643c6c8
 
 
a213ac9
 
 
643c6c8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a213ac9
 
 
643c6c8
 
 
a213ac9
 
 
643c6c8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a213ac9
 
 
643c6c8
 
 
a213ac9
 
 
643c6c8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a213ac9
 
38619e7
a213ac9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3f1f433
a213ac9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fc8f0bd
 
 
306ddaa
fc8f0bd
306ddaa
 
 
 
 
45ba8c9
306ddaa
 
 
816b291
 
306ddaa
fc8f0bd
45ba8c9
a213ac9
fc8f0bd
a213ac9
fc8f0bd
 
a213ac9
 
45ba8c9
a213ac9
 
 
062c7cc
a213ac9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f0d37cf
a213ac9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3f1f433
a213ac9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
306ddaa
8f12e15
 
 
c4ef28b
34666ca
 
 
a213ac9
816b291
a213ac9
193ef12
816b291
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
193ef12
a213ac9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
643c6c8
 
 
 
 
 
 
bed31fe
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
import streamlit as st
import pandas as pd
import numpy as np
from sklearn.metrics import roc_auc_score, precision_score, recall_score
from pandas.tseries.offsets import BDay
import streamlit as st
from datetime import datetime, time, timedelta
import pytz
import holidays

st.set_page_config(
    page_title="Gameday $SPX",
    page_icon="๐ŸŽฎ"
)

# Function to convert UTC to PST
def convert_to_pst(utc_time):
    utc_timezone = pytz.timezone('UTC')
    pst_timezone = pytz.timezone('America/Los_Angeles')
    utc_time = utc_timezone.localize(utc_time)
    pst_time = utc_time.astimezone(pst_timezone)
    return pst_time

# Get the current UTC time
utc_now = datetime.utcnow()

# Convert UTC to PST
pst_now = convert_to_pst(utc_now)

# Function to check if a date is a business day (Monday to Friday)
def is_business_day(date):
    return date.weekday() < 5  # Monday = 0, Friday = 4

# Function to get the list of holidays in the US for the current year
def get_us_holidays():
    return holidays.US(years=datetime.now().year)

# Function to convert the time string to a datetime object
def convert_to_datetime(time_str, pst_now):
    time_obj = datetime.strptime(time_str, "%H:%M")
    # Combine the time with the current date to get the full datetime in PST
    return datetime.combine(pst_now.date(), time_obj.time())

# Function to determine the emoji for each time
@st.cache_data
def get_time_emojis(_times, _pst_now):
    pst_now_time = pst_now.time()
    us_holidays = get_us_holidays()
    emojis = []
    
    for t in _times:
        time_obj = convert_to_datetime(t, _pst_now)
        
        # Check if the time is less than or equal to the current time in PST
        if time_obj.time() <= pst_now_time:
            emoji = "โœ…"
        else:
            # Check if it's a business day or a holiday
            if is_business_day(time_obj) or time_obj.date() in us_holidays:
                emoji = "โ›”"
            else:
                emoji = "โœ…"
        
        emojis.append(emoji)
    
    return emojis

# Example usage:
times_list = ['06:30', '07:00', '07:30', '08:00']
emojis_list = get_time_emojis(times_list, pst_now)


st.title('๐ŸŽฎ Gameday Model for $SPX')
st.markdown('**PLEASE NOTE:** Model should be run at or after market open. Documentation on the model and its features [can be found here.](https://huggingface.co/spaces/boomsss/gamedayspx/blob/main/README.md)')
with st.form("choose_model"):
    # option = st.selectbox(
    #     'Select a model, then run.',
    #     ('', '๐ŸŒž At Open', 'โŒš 30 Mins', 'โณ 60 Mins', '๐Ÿ•ฐ 90 Mins'))


    col1, col2 = st.columns(2)
        
    with col1:
        option = st.select_slider(
            f"""Slide the scale based on PST, then run.""",
            times_list,
            format_func=lambda x: f"{emojis_list[times_list.index(x)]} {x}"
        )

    with col2:
        submitted = st.form_submit_button('๐Ÿƒ๐Ÿฝโ€โ™‚๏ธ Run',use_container_width=True)
        cleared = st.form_submit_button('๐Ÿงน Clear All',use_container_width=True)

    if cleared:
        st.cache_data.clear()

    if option == '':
        st.write('No model selected.')

    if submitted:

        if option == '06:30':
        # runday = st.button('๐Ÿƒ๐Ÿฝโ€โ™‚๏ธ Run')
        # if runday:
            from model_day import *

            fname='performance_for_open_model.csv'

            with st.spinner('Loading data...'):
                data, df_final, final_row = get_data()
            # st.success("โœ… Historical data")

            with st.spinner("Training models..."):
                def train_models():
                    res1, xgbr, seq2 = walk_forward_validation_seq(df_final.dropna(), 'Target_clf', 'Target', 100, 1)
                    return res1, xgbr, seq2
                res1, xgbr, seq2 = train_models()
            # st.success("โœ… Models trained")

            with st.spinner("Getting new prediction..."):

                # Get last row
                new_pred = data.loc[final_row, ['BigNewsDay',
                    'Quarter',
                    'Perf5Day',
                    'Perf5Day_n1',    
                    'DaysGreen',    
                    'DaysRed',    
                    'CurrentGap',
                    'RangePct',
                    'RangePct_n1',
                    'RangePct_n2',
                    'OHLC4_VIX',
                    'OHLC4_VIX_n1',
                    'OHLC4_VIX_n2']]

                new_pred = pd.DataFrame(new_pred).T
                # new_pred_show = pd.DataFrame(index=[new_pred.columns], columns=[new_pred.index], data=[[v] for v in new_pred.values])
                # last_date = datetime.datetime.strptime(data.loc[final_row], '%Y-%m-%d')
                curr_date = final_row + BDay(1)
                curr_date = curr_date.strftime('%Y-%m-%d')

                new_pred['BigNewsDay'] = new_pred['BigNewsDay'].astype(float)
                new_pred['Quarter'] = new_pred['Quarter'].astype(int)
                new_pred['Perf5Day'] = new_pred['Perf5Day'].astype(bool)
                new_pred['Perf5Day_n1'] = new_pred['Perf5Day_n1'].astype(bool)
                new_pred['DaysGreen'] = new_pred['DaysGreen'].astype(float)
                new_pred['DaysRed'] = new_pred['DaysRed'].astype(float)
                new_pred['CurrentGap'] = new_pred['CurrentGap'].astype(float)
                new_pred['RangePct'] = new_pred['RangePct'].astype(float)
                new_pred['RangePct_n1'] = new_pred['RangePct_n1'].astype(float)
                new_pred['RangePct_n2'] = new_pred['RangePct_n2'].astype(float)
                new_pred['OHLC4_VIX'] = new_pred['OHLC4_VIX'].astype(float)
                new_pred['OHLC4_VIX_n1'] = new_pred['OHLC4_VIX_n1'].astype(float)
                new_pred['OHLC4_VIX_n2'] = new_pred['OHLC4_VIX_n2'].astype(float)

                seq_proba = seq_predict_proba(new_pred, xgbr, seq2)

        elif option == '07:00':
        # run30 = st.button('๐Ÿƒ๐Ÿฝโ€โ™‚๏ธ Run')
        # if run30:
            from model_30m import *

            fname='performance_for_30m_model.csv'

            with st.spinner('Loading data...'):
                data, df_final, final_row = get_data()
            # st.success("โœ… Historical data")

            with st.spinner("Training models..."):
                def train_models():
                    res1, xgbr, seq2 = walk_forward_validation_seq(df_final.dropna(), 'Target_clf', 'Target', 100, 1)
                    return res1, xgbr, seq2
                res1, xgbr, seq2 = train_models()
            # st.success("โœ… Models trained")

            with st.spinner("Getting new prediction..."):

                # Get last row
                new_pred = data.loc[final_row, ['BigNewsDay',
                    'Quarter',
                    'Perf5Day',
                    'Perf5Day_n1',    
                    'DaysGreen',    
                    'DaysRed',
                    'CurrentHigh30toClose',
                    'CurrentLow30toClose',
                    'CurrentClose30toClose',
                    'CurrentRange30',
                    'GapFill30',    
                    'CurrentGap',
                    'RangePct',
                    'RangePct_n1',
                    'RangePct_n2',
                    'OHLC4_VIX',
                    'OHLC4_VIX_n1',
                    'OHLC4_VIX_n2']]

                new_pred = pd.DataFrame(new_pred).T
                # new_pred_show = pd.DataFrame(index=[new_pred.columns], columns=[new_pred.index], data=[[v] for v in new_pred.values])
                # last_date = datetime.datetime.strptime(data.loc[final_row], '%Y-%m-%d')
                curr_date = final_row + BDay(1)
                curr_date = curr_date.strftime('%Y-%m-%d')

                new_pred['BigNewsDay'] = new_pred['BigNewsDay'].astype(float)
                new_pred['Quarter'] = new_pred['Quarter'].astype(int)
                new_pred['Perf5Day'] = new_pred['Perf5Day'].astype(bool)
                new_pred['Perf5Day_n1'] = new_pred['Perf5Day_n1'].astype(bool)
                new_pred['DaysGreen'] = new_pred['DaysGreen'].astype(float)
                new_pred['DaysRed'] = new_pred['DaysRed'].astype(float)
                new_pred['CurrentHigh30toClose'] = new_pred['CurrentHigh30toClose'].astype(float)
                new_pred['CurrentLow30toClose'] = new_pred['CurrentLow30toClose'].astype(float)
                new_pred['CurrentClose30toClose'] = new_pred['CurrentClose30toClose'].astype(float)
                new_pred['CurrentRange30'] = new_pred['CurrentRange30'].astype(float)
                new_pred['GapFill30'] = new_pred['GapFill30'].astype(float)  
                new_pred['CurrentGap'] = new_pred['CurrentGap'].astype(float)
                new_pred['RangePct'] = new_pred['RangePct'].astype(float)
                new_pred['RangePct_n1'] = new_pred['RangePct_n1'].astype(float)
                new_pred['RangePct_n2'] = new_pred['RangePct_n2'].astype(float)
                new_pred['OHLC4_VIX'] = new_pred['OHLC4_VIX'].astype(float)
                new_pred['OHLC4_VIX_n1'] = new_pred['OHLC4_VIX_n1'].astype(float)
                new_pred['OHLC4_VIX_n2'] = new_pred['OHLC4_VIX_n2'].astype(float)

                seq_proba = seq_predict_proba(new_pred, xgbr, seq2)
        
        elif option == '07:30':
        # run60 = st.button('๐Ÿƒ๐Ÿฝโ€โ™‚๏ธ Run')
        # if run60:
            from model_1h import *
            
            fname='performance_for_1h_model.csv'

            with st.spinner('Loading data...'):
                data, df_final, final_row = get_data()
            # st.success("โœ… Historical data")

            with st.spinner("Training models..."):
                def train_models():
                    res1, xgbr, seq2 = walk_forward_validation_seq(df_final.dropna(), 'Target_clf', 'Target', 100, 1)
                    return res1, xgbr, seq2
                res1, xgbr, seq2 = train_models()
            # st.success("โœ… Models trained")

            with st.spinner("Getting new prediction..."):

                # Get last row
                new_pred = data.loc[final_row, ['BigNewsDay',
                    'Quarter',
                    'Perf5Day',
                    'Perf5Day_n1',    
                    'DaysGreen',    
                    'DaysRed',
                    'CurrentHigh30toClose',
                    'CurrentLow30toClose',
                    'CurrentClose30toClose',
                    'CurrentRange30',
                    'GapFill30',    
                    'CurrentGap',
                    'RangePct',
                    'RangePct_n1',
                    'RangePct_n2',
                    'OHLC4_VIX',
                    'OHLC4_VIX_n1',
                    'OHLC4_VIX_n2']]

                new_pred = pd.DataFrame(new_pred).T
                # new_pred_show = pd.DataFrame(index=[new_pred.columns], columns=[new_pred.index], data=[[v] for v in new_pred.values])
                # last_date = datetime.datetime.strptime(data.loc[final_row], '%Y-%m-%d')
                curr_date = final_row + BDay(1)
                curr_date = curr_date.strftime('%Y-%m-%d')

                new_pred['BigNewsDay'] = new_pred['BigNewsDay'].astype(float)
                new_pred['Quarter'] = new_pred['Quarter'].astype(int)
                new_pred['Perf5Day'] = new_pred['Perf5Day'].astype(bool)
                new_pred['Perf5Day_n1'] = new_pred['Perf5Day_n1'].astype(bool)
                new_pred['DaysGreen'] = new_pred['DaysGreen'].astype(float)
                new_pred['DaysRed'] = new_pred['DaysRed'].astype(float)
                new_pred['CurrentHigh30toClose'] = new_pred['CurrentHigh30toClose'].astype(float)
                new_pred['CurrentLow30toClose'] = new_pred['CurrentLow30toClose'].astype(float)
                new_pred['CurrentClose30toClose'] = new_pred['CurrentClose30toClose'].astype(float)
                new_pred['CurrentRange30'] = new_pred['CurrentRange30'].astype(float)
                new_pred['GapFill30'] = new_pred['GapFill30'].astype(float)  
                new_pred['CurrentGap'] = new_pred['CurrentGap'].astype(float)
                new_pred['RangePct'] = new_pred['RangePct'].astype(float)
                new_pred['RangePct_n1'] = new_pred['RangePct_n1'].astype(float)
                new_pred['RangePct_n2'] = new_pred['RangePct_n2'].astype(float)
                new_pred['OHLC4_VIX'] = new_pred['OHLC4_VIX'].astype(float)
                new_pred['OHLC4_VIX_n1'] = new_pred['OHLC4_VIX_n1'].astype(float)
                new_pred['OHLC4_VIX_n2'] = new_pred['OHLC4_VIX_n2'].astype(float)

                seq_proba = seq_predict_proba(new_pred, xgbr, seq2)
        
        elif option == '08:00':
        # run60 = st.button('๐Ÿƒ๐Ÿฝโ€โ™‚๏ธ Run')
        # if run60:
            from model_90m import *

            fname='performance_for_90m_model.csv'

            with st.spinner('Loading data...'):
                data, df_final, final_row = get_data()
            # st.success("โœ… Historical data")

            with st.spinner("Training models..."):
                def train_models():
                    res1, xgbr, seq2 = walk_forward_validation_seq(df_final.dropna(), 'Target_clf', 'Target', 100, 1)
                    return res1, xgbr, seq2
                res1, xgbr, seq2 = train_models()
            # st.success("โœ… Models trained")

            with st.spinner("Getting new prediction..."):

                # Get last row
                new_pred = data.loc[final_row, ['BigNewsDay',
                    'Quarter',
                    'Perf5Day',
                    'Perf5Day_n1',    
                    'DaysGreen',    
                    'DaysRed',
                    'CurrentHigh30toClose',
                    'CurrentLow30toClose',
                    'CurrentClose30toClose',
                    'CurrentRange30',
                    'GapFill30',    
                    'CurrentGap',
                    'RangePct',
                    'RangePct_n1',
                    'RangePct_n2',
                    'OHLC4_VIX',
                    'OHLC4_VIX_n1',
                    'OHLC4_VIX_n2']]

                new_pred = pd.DataFrame(new_pred).T
                # new_pred_show = pd.DataFrame(index=[new_pred.columns], columns=[new_pred.index], data=[[v] for v in new_pred.values])
                # last_date = datetime.datetime.strptime(data.loc[final_row], '%Y-%m-%d')
                curr_date = final_row + BDay(1)
                curr_date = curr_date.strftime('%Y-%m-%d')

                new_pred['BigNewsDay'] = new_pred['BigNewsDay'].astype(float)
                new_pred['Quarter'] = new_pred['Quarter'].astype(int)
                new_pred['Perf5Day'] = new_pred['Perf5Day'].astype(bool)
                new_pred['Perf5Day_n1'] = new_pred['Perf5Day_n1'].astype(bool)
                new_pred['DaysGreen'] = new_pred['DaysGreen'].astype(float)
                new_pred['DaysRed'] = new_pred['DaysRed'].astype(float)
                new_pred['CurrentHigh30toClose'] = new_pred['CurrentHigh30toClose'].astype(float)
                new_pred['CurrentLow30toClose'] = new_pred['CurrentLow30toClose'].astype(float)
                new_pred['CurrentClose30toClose'] = new_pred['CurrentClose30toClose'].astype(float)
                new_pred['CurrentRange30'] = new_pred['CurrentRange30'].astype(float)
                new_pred['GapFill30'] = new_pred['GapFill30'].astype(float)  
                new_pred['CurrentGap'] = new_pred['CurrentGap'].astype(float)
                new_pred['RangePct'] = new_pred['RangePct'].astype(float)
                new_pred['RangePct_n1'] = new_pred['RangePct_n1'].astype(float)
                new_pred['RangePct_n2'] = new_pred['RangePct_n2'].astype(float)
                new_pred['OHLC4_VIX'] = new_pred['OHLC4_VIX'].astype(float)
                new_pred['OHLC4_VIX_n1'] = new_pred['OHLC4_VIX_n1'].astype(float)
                new_pred['OHLC4_VIX_n2'] = new_pred['OHLC4_VIX_n2'].astype(float)

                seq_proba = seq_predict_proba(new_pred, xgbr, seq2)

        st.info(f'as of {option} on {curr_date} ๐Ÿ‘‡๐Ÿฝ', icon="๐Ÿ”ฎ")

        green_proba = seq_proba[0]
        red_proba = 1 - green_proba
        do_not_play = (seq_proba[0] > 0.4) and (seq_proba[0] <= 0.6) 
        stdev = 0.01
        score = None
        num_obs = None
        cond = None
        historical_proba = None
        text_cond = None
        operator = None

        if do_not_play:
            text_cond = '๐ŸŸจ'
            operator = ''
            score = seq_proba[0]
            cond = (res1['Predicted'] > 0.4) & (res1['Predicted'] <= 0.6)
            num_obs = len(res1.loc[cond])
            historical_proba = res1.loc[cond, 'True'].mean()

            
        elif green_proba > red_proba:
            # If the day is predicted to be green, say so
            text_cond = '๐ŸŸฉ'
            operator = '>='
            score = green_proba
            # How many with this score?
            cond = (res1['Predicted'] >= green_proba)
            num_obs = len(res1.loc[cond])
            # How often green?
            historical_proba = res1.loc[cond, 'True'].mean()
            # print(cond)

        elif green_proba <= red_proba:
            # If the day is predicted to be green, say so
            text_cond = '๐ŸŸฅ'
            operator = '<='
            score = red_proba
            # How many with this score?
            cond = (res1['Predicted'] <= seq_proba[0])
            num_obs = len(res1.loc[cond])
            # How often green?
            historical_proba = 1 - res1.loc[cond, 'True'].mean()
            # print(cond)

        score_fmt = f'{score:.1%}'

        prev_close = data.loc[final_row,'Close']
        curr_close = data['Close'].iloc[-1]

        # confidence, success, nn = st.columns(3)

        # confidence.metric('Confidence',value=f'{text_cond} {score:.1%}')
        # success.metric('SuccessRate',value=f'{historical_proba:.1%}')
        # nn.metric(f'N{operator}{"" if do_not_play else score_fmt}',value=num_obs)

        top_of_fold = pd.DataFrame(
            index=['Results'], 
            data = {
                'Confidence':[f'{text_cond} {score:.1%}'],
                'Success':[f'{historical_proba:.1%}'],
                f'N{operator}{score:.1%}':[f'{num_obs} / {len(data)}'],
                'Prev / Curr':[f'{prev_close:.2f} / {curr_close:.2f}']
            })

        prices = pd.DataFrame(index=[
            'PrevClose',
            'CurrClose'
        ], data = [
            f"{prev_close:.2f}",
            f"{curr_close:.2f}"
            ])

        prices.columns = ['']

        # st.subheader('New Prediction')

        int_labels = ['(0, .20]', '(.20, .40]', '(.40, .60]', '(.60, .80]', '(.80, .1]']
        # df_probas = res1.groupby(pd.qcut(res1['Predicted'],5)).agg({'True':[np.mean,len,np.sum]})

        data['ClosePct'] = (data['Close'] / data['PrevClose']) - 1
        data['ClosePct'] = data['ClosePct'].shift(-1)
        res1 = res1.merge(data['ClosePct'], left_index=True,right_index=True)
        df_probas = res1.groupby(pd.cut(res1['Predicted'], bins = [-np.inf, 0.2, 0.4, 0.6, 0.8, np.inf], labels = int_labels)).agg({'True':[np.mean,len,np.sum],'ClosePct':[np.mean]})
        df_probas.columns = ['PctGreen','NumObs','NumGreen','AvgPerf']
        df_probas['AvgPerf'] = df_probas['AvgPerf'].apply(lambda x: f'{x:.2%}')

        roc_auc_score_all = roc_auc_score(res1['True'].astype(int), res1['Predicted'].values)
        precision_score_all = precision_score(res1['True'].astype(int), res1['Predicted'] > 0.5)
        recall_score_all = recall_score(res1['True'].astype(int), res1['Predicted'] > 0.5)
        len_all = len(res1)

        res2_filtered = res1.loc[(res1['Predicted'] > 0.6) | (res1['Predicted'] <= 0.4)]

        roc_auc_score_hi = roc_auc_score(res2_filtered['True'].astype(int), res2_filtered['Predicted'].values)
        precision_score_hi = precision_score(res2_filtered['True'].astype(int), res2_filtered['Predicted'] > 0.5)
        recall_score_hi = recall_score(res2_filtered['True'].astype(int), res2_filtered['Predicted'] > 0.5)
        len_hi = len(res2_filtered)

        df_performance = pd.DataFrame(
            index=[
                'N',
                'ROC AUC',
                'Precision',
                'Recall'
            ],
            columns = [
                'All',
                'High Confidence'
            ],
            data = [
                [len_all, len_hi],
                [roc_auc_score_all, roc_auc_score_hi],
                [precision_score_all, precision_score_hi],
                [recall_score_all, recall_score_hi]
            ]
        ).round(2)

        def get_acc(t, p):
            if t == False and p <= 0.4:
                return 'โœ…'
            elif t == True and p > 0.6:
                return 'โœ…'
            elif t == False and p > 0.6:
                return 'โŒ'
            elif t == True and p <= 0.4:
                return 'โŒ'
            else:
                return '๐ŸŸจ'
            
        def get_acc_text(t, p):
            if t == False and p <= 0.4:
                return 'Correct'
            elif t == True and p > 0.6:
                return 'Correct'
            elif t == False and p > 0.6:
                return 'Incorrect'
            elif t == True and p <= 0.4:
                return 'Incorrect'
            else:
                return 'No Action'

        perf_daily = res1.copy()
        perf_daily['TargetDate'] = perf_daily.index + BDay(1)
        perf_daily['Accuracy'] = [get_acc(t, p) for t, p in zip(perf_daily['True'], perf_daily['Predicted'])]
        perf_daily['AccuracyText'] = [get_acc_text(t, p) for t, p in zip(perf_daily['True'], perf_daily['Predicted'])]
        perf_daily['ConfidenceScore'] = [x if x > 0.6 else 1-x if x <= 0.4 else x for x in perf_daily['Predicted']]
        perf_daily = perf_daily[['TargetDate','Predicted','True','Accuracy','AccuracyText','ConfidenceScore']]

        def convert_df(df):
            # IMPORTANT: Cache the conversion to prevent computation on every rerun
            return df.to_csv()

        csv = convert_df(perf_daily)
            
        check = data.tail(1)

        data['VIX_EM'] = data['Close'] * (data['Close_VIX']/100) * (np.sqrt( 1 ) / np.sqrt(252))
        data['VIX_EM_High'] = data['Close'] + data['VIX_EM']
        data['VIX_EM_Low'] = data['Close'] - data['VIX_EM']

        # Tomorrrow's EM and Today's EM
        fwd_em, curr_em = data['VIX_EM'].iloc[-1], data['VIX_EM'].iloc[-2]

        data['VIX_EM_125'] = data['VIX_EM'] * 1.25
        data['VIX_EM_125_High'] = data['Close'] + data['VIX_EM_125']
        data['VIX_EM_125_Low'] = data['Close'] - data['VIX_EM_125']

        data['VIX_EM_15'] = data['VIX_EM'] * 1.5
        data['VIX_EM_15_High'] = data['Close'] + data['VIX_EM_15']
        data['VIX_EM_15_Low'] = data['Close'] - data['VIX_EM_15']

        data['VIX_EM'] = data['VIX_EM'].shift(1)
        data['VIX_EM_High'] = data['VIX_EM_High'].shift(1)
        data['VIX_EM_Low'] = data['VIX_EM_Low'].shift(1)

        data['VIX_EM_15'] = data['VIX_EM_15'].shift(1)
        data['VIX_EM_15_High'] = data['VIX_EM_15_High'].shift(1)
        data['VIX_EM_15_Low'] = data['VIX_EM_15_Low'].shift(1)

        data['VIX_EM_125'] = data['VIX_EM_125'].shift(1)
        data['VIX_EM_125_High'] = data['VIX_EM_125_High'].shift(1)
        data['VIX_EM_125_Low'] = data['VIX_EM_125_Low'].shift(1)
        
        # Cache all DFs
        all_dfs = []

        st.dataframe(top_of_fold.set_index('Confidence',drop=True), use_container_width=True)

        tab1, tab2, tab3, tab4 = st.tabs(["๐Ÿค– Stats", "โœจ New Data", "๐Ÿ“š Historical", "๐Ÿ“Š Performance"])

        with tab1:
            # st.dataframe(prices.T.set_index('PrevClose', drop=True))
            st.write(df_probas)

            for close_use, em_use, lbl in zip([prev_close, curr_close], [curr_em, fwd_em], ['Current','Forward']):

                st.write(f'๐ŸŒŠ VIX EM {lbl}: {em_use:.2f}')
                df_em = pd.DataFrame(columns=['EM','Low','High','InRange','Tested'])
                df_em.index.name = f'{close_use:.2f}'
                df_em.loc['EM 1X'] = [
                    f"{em_use:.2f} ({em_use / close_use:.1%})",
                    f"{close_use - em_use:.2f}",
                    f"{close_use + em_use:.2f}",
                    f"{len(data.query('Close <= VIX_EM_High & Close >= VIX_EM_Low')) / len(data):.1%}",
                    f"{len(data.query('High > VIX_EM_High | Low < VIX_EM_Low')) / len(data):.1%}"
                    ]
                df_em.loc['EM 1.25X'] = [
                    f"{curr_em * 1.25:.2f} ({(em_use * 1.25) / close_use:.1%})",
                    f"{close_use - (em_use * 1.25):.2f}",
                    f"{close_use + (em_use * 1.25):.2f}",
                    f"{len(data.query('Close <= VIX_EM_125_High & Close >= VIX_EM_125_Low')) / len(data):.1%}",
                    f"{len(data.query('High > VIX_EM_125_High | Low < VIX_EM_125_Low')) / len(data):.1%}"
                    ]
                df_em.loc[f"EM 1.5X"] = [
                    f"{curr_em * 1.5:.2f} ({(em_use * 1.5) / close_use:.1%})",
                    f"{close_use - (em_use * 1.5):.2f}",
                    f"{close_use + (em_use * 1.5):.2f}",
                    f"{len(data.query('Close <= VIX_EM_15_High & Close >= VIX_EM_15_Low')) / len(data):.1%}",
                    f"{len(data.query('High > VIX_EM_15_High | Low < VIX_EM_15_Low')) / len(data):.1%}"
                    ]
                st.write(df_em)

        with tab2:
            st.subheader('Latest Data for Pred')
            st.write(new_pred)
        with tab3:
            st.subheader('Historical Data')
            st.write(df_final)
        with tab4:
            st.subheader('Performance')
            st.write(df_performance)
            st.text('Performance last 10 days (download for all)')
            st.write(perf_daily[['TargetDate','Predicted','True','Accuracy']].iloc[-10:])
            # st.download_button(
            #     label="Download Historical Performance",
            #     data=csv,
            # )

if submitted:
    st.download_button(
        label="Download Historical Performance",
        data=csv,
        file_name=fname,
    )
    st.caption('โš ๏ธ Downloading the CSV will reload the page. โš ๏ธ')