File size: 54,639 Bytes
545350e
 
 
 
 
 
 
5d6c0bc
 
 
545350e
 
 
 
 
92e6a09
545350e
43474bd
 
919f9f3
 
 
 
 
 
 
 
 
 
545350e
 
 
92e6a09
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
545350e
92e6a09
 
 
 
 
 
 
43474bd
92e6a09
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
43474bd
92e6a09
 
 
 
 
 
 
 
 
 
 
43474bd
92e6a09
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
43474bd
92e6a09
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
545350e
92e6a09
545350e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
acfed57
 
545350e
 
 
 
acfed57
545350e
acfed57
545350e
 
 
 
 
 
 
 
 
 
 
 
 
c40ca3c
545350e
2457f50
545350e
 
 
 
 
 
 
 
 
 
 
 
 
 
2457f50
545350e
2457f50
545350e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
92e6a09
 
 
 
 
 
 
 
 
 
edd8da4
545350e
 
 
 
92e6a09
545350e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
85cdf44
 
 
 
 
 
 
545350e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
edd8da4
545350e
 
 
 
92e6a09
545350e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
85cdf44
 
 
 
 
 
 
545350e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2457f50
545350e
2457f50
545350e
 
 
 
 
 
 
 
 
 
 
 
 
2457f50
545350e
2457f50
545350e
 
 
 
 
 
 
 
edd8da4
545350e
 
 
 
92e6a09
545350e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
85cdf44
 
 
 
 
 
 
545350e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
edd8da4
545350e
 
 
 
919f9f3
545350e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
919f9f3
85cdf44
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
545350e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5d6c0bc
545350e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
import streamlit as st
st.set_page_config(layout="wide")

for name in dir():
    if not name.startswith('_'):
        del globals()[name]
        
import numpy as np
import pandas as pd
import streamlit as st
import plotly.express as px
import plotly.graph_objects as go
import plotly.io as pio
import certifi
ca = certifi.where()
from database import db

basic_cols = ['Player', 'Pos', 'Team', 'Opp', 'Season', 'Date', 'Matchup', 'Min']
basic_season_cols = ['Pos', 'Team', 'Min']
data_cols = ['team_score', 'opp_score', 'spread', 'Touches', 'Pts', 'FGM', 'FGA', 'FG%', 'FG3M',
            'FG3A', 'FG3%', 'FTM', 'FTA', 'FT%', 'OREB Chance', 'OREB', 'DREB Chance', 'DREB', 'REB Chance', 'REB',
            'Passes', 'Alt Assists', 'FT Assists', 'Assists', 'Stl', 'Blk', 'Tov', 'PF', 'DD', 'TD', 'Fantasy', 'FD_Fantasy',
            'FPPM', 'Rebound%', 'Assists/Pass', 'Touch_per_min', 'Fantasy/Touch', 'FD Fantasy/Touch']
season_data_cols = ['Touches', 'Touch/Min', 'Pts', 'FGM', 'FGA', 'FG%', 'FG3M', 'FG3A',
                    'FG3%', 'FTM', 'FTA', 'FT%', 'OREB Chance', 'OREB', 'DREB Chance', 'DREB', 'REB Chance', 'REB',
                    'Passes', 'Alt Assists', 'FT Assists', 'Assists', 'Stl', 'Blk', 'Tov', 'PF', 'DD', 'TD', 'Fantasy', 'FD_Fantasy',
                    'FPPM', 'Rebound%', 'Assists/Pass', 'Fantasy/Touch', 'FD Fantasy/Touch']
game_rot_cols = ['PLAYER_NAME', 'backlog_lookup', 'spread', 'MIN', 'PTS', 'FGM', 'FGA', 'FG3M', 'FG3A', 'FTM', 'FTA', 'REB', 'AST', 'STL', 'BLK', 'TOV', 'PF',
                'Fantasy', 'FD_Fantasy']

percentages_format = {'PG': '{:.2%}', 'SG': '{:.2%}', 'SF': '{:.2%}', 'PF': '{:.2%}', 'C': '{:.2%}'}

st.markdown("""
<style>
    /* Tab styling */
    .stElementContainer [data-baseweb="button-group"] {
        gap: 2.000rem;
        padding: 4px;
    }
    .stElementContainer [kind="segmented_control"] {
        height: 2.000rem;
        white-space: pre-wrap;
        background-color: #DAA520;
        color: white;
        border-radius: 20px;
        gap: 1px;
        padding: 10px 20px;
        font-weight: bold;
        transition: all 0.3s ease;
    }
    .stElementContainer [kind="segmented_controlActive"] {
        height: 3.000rem;
        background-color: #DAA520;
        border: 3px solid #FFD700;
        border-radius: 10px;
        color: black;
    }
    .stElementContainer [kind="segmented_control"]:hover {
        background-color: #FFD700;
        cursor: pointer;
    }

    div[data-baseweb="select"] > div {
        background-color: #DAA520;
        color: white;
    }

</style>""", unsafe_allow_html=True)

@st.cache_resource(ttl = 599)
def init_baselines(data_req: str):
    if data_req == 'gamelogs':
        collection = db["gamelog"] 
        cursor = collection.find()  # Finds all documents in the collection
        
        raw_display = pd.DataFrame(list(cursor))
        gamelog_table = raw_display[raw_display['PLAYER_NAME'] != ""]
        gamelog_table = gamelog_table[['PLAYER_NAME', 'POS', 'GAME_ID', 'TEAM_NAME', 'OPP_NAME', 'SEASON_ID', 'GAME_DATE', 'MATCHUP', 'MIN', 'touches', 'PTS', 'FGM', 'FGA', 'FG_PCT', 'FG3M', 'FG3A',
                                    'FG3_PCT', 'FTM', 'FTA', 'FT_PCT', 'reboundChancesOffensive', 'OREB', 'reboundChancesDefensive', 'DREB', 'reboundChancesTotal', 'REB',
                                    'passes', 'secondaryAssists', 'freeThrowAssists', 'assists', 'STL', 'BLK', 'TOV', 'PF', 'DD', 'TD', 'Fantasy', 'FD_Fantasy', 'FPPM']]
        gamelog_table['assists'].replace("", 0, inplace=True)
        gamelog_table['reboundChancesTotal'].replace("", 0, inplace=True)
        gamelog_table['passes'].replace("", 0, inplace=True)
        gamelog_table['touches'].replace("", 0, inplace=True)
        gamelog_table['MIN'].replace("", 0, inplace=True)
        gamelog_table['Fantasy'].replace("", 0, inplace=True)
        gamelog_table['FD_Fantasy'].replace("", 0, inplace=True)
        gamelog_table['FPPM'].replace("", 0, inplace=True)
        gamelog_table['REB'] = gamelog_table['REB'].astype(int)
        gamelog_table['assists'] = gamelog_table['assists'].astype(int)
        gamelog_table['reboundChancesTotal'] = gamelog_table['reboundChancesTotal'].astype(int)
        gamelog_table['passes'] = gamelog_table['passes'].astype(int)
        gamelog_table['touches'] = gamelog_table['touches'].astype(int)
        gamelog_table['MIN'] = gamelog_table['MIN'].astype(int)
        gamelog_table['Fantasy'] = gamelog_table['Fantasy'].astype(float)
        gamelog_table['FD_Fantasy'] = gamelog_table['FD_Fantasy'].astype(float)
        gamelog_table['FPPM'] = gamelog_table['FPPM'].astype(float)
        gamelog_table['rebound%'] = gamelog_table['REB'] / gamelog_table['reboundChancesTotal']
        gamelog_table['assists_per_pass'] = gamelog_table['assists'] / gamelog_table['passes']
        gamelog_table['Touch_per_min'] = gamelog_table['touches'] / gamelog_table['MIN']
        gamelog_table['Fantasy_per_touch'] = gamelog_table['Fantasy'] / gamelog_table['touches']
        gamelog_table['FD_Fantasy_per_touch'] = gamelog_table['FD_Fantasy'] / gamelog_table['touches']
        data_cols = gamelog_table.columns.drop(['PLAYER_NAME', 'POS', 'TEAM_NAME', 'OPP_NAME', 'SEASON_ID', 'GAME_DATE', 'MATCHUP'])
        gamelog_table[data_cols] = gamelog_table[data_cols].apply(pd.to_numeric, errors='coerce')
        gamelog_table['team_score'] = gamelog_table.groupby(['TEAM_NAME', 'GAME_ID'], sort=False)['PTS'].transform('sum')
        gamelog_table['opp_score'] = gamelog_table.groupby(['GAME_ID'], sort=False)['PTS'].transform('sum') - gamelog_table['team_score']
        gamelog_table['spread'] = (gamelog_table['opp_score'] - gamelog_table['team_score']).abs()
        gamelog_table['GAME_DATE'] = pd.to_datetime(gamelog_table['GAME_DATE']).dt.date
        
        spread_dict = dict(zip(gamelog_table['GAME_ID'], gamelog_table['spread']))
        
        gamelog_table = gamelog_table.set_axis(['Player', 'Pos', 'game_id', 'Team', 'Opp', 'Season', 'Date', 'Matchup', 'Min', 'Touches', 'Pts', 'FGM', 'FGA', 'FG%', 'FG3M',
                                                'FG3A', 'FG3%', 'FTM', 'FTA', 'FT%', 'OREB Chance', 'OREB', 'DREB Chance', 'DREB', 'REB Chance', 'REB',
                                                'Passes', 'Alt Assists', 'FT Assists', 'Assists', 'Stl', 'Blk', 'Tov', 'PF', 'DD', 'TD', 'Fantasy', 'FD_Fantasy', 'FPPM',
                                                'Rebound%', 'Assists/Pass', 'Touch_per_min', 'Fantasy/Touch', 'FD Fantasy/Touch', 'team_score', 'opp_score', 'spread'], axis=1)
        game_rot = None
        timestamp = gamelog_table['Date'].max()
    elif data_req == 'all':
        collection = db["gamelog"] 
        cursor = collection.find()  # Finds all documents in the collection
        
        raw_display = pd.DataFrame(list(cursor))
        gamelog_table = raw_display[raw_display['PLAYER_NAME'] != ""]
        gamelog_table = gamelog_table[['PLAYER_NAME', 'POS', 'GAME_ID', 'TEAM_NAME', 'OPP_NAME', 'SEASON_ID', 'GAME_DATE', 'MATCHUP', 'MIN', 'touches', 'PTS', 'FGM', 'FGA', 'FG_PCT', 'FG3M', 'FG3A',
                                    'FG3_PCT', 'FTM', 'FTA', 'FT_PCT', 'reboundChancesOffensive', 'OREB', 'reboundChancesDefensive', 'DREB', 'reboundChancesTotal', 'REB',
                                    'passes', 'secondaryAssists', 'freeThrowAssists', 'assists', 'STL', 'BLK', 'TOV', 'PF', 'DD', 'TD', 'Fantasy', 'FD_Fantasy', 'FPPM']]
        gamelog_table['assists'].replace("", 0, inplace=True)
        gamelog_table['reboundChancesTotal'].replace("", 0, inplace=True)
        gamelog_table['passes'].replace("", 0, inplace=True)
        gamelog_table['touches'].replace("", 0, inplace=True)
        gamelog_table['MIN'].replace("", 0, inplace=True)
        gamelog_table['Fantasy'].replace("", 0, inplace=True)
        gamelog_table['FD_Fantasy'].replace("", 0, inplace=True)
        gamelog_table['FPPM'].replace("", 0, inplace=True)
        gamelog_table['REB'] = gamelog_table['REB'].astype(int)
        gamelog_table['assists'] = gamelog_table['assists'].astype(int)
        gamelog_table['reboundChancesTotal'] = gamelog_table['reboundChancesTotal'].astype(int)
        gamelog_table['passes'] = gamelog_table['passes'].astype(int)
        gamelog_table['touches'] = gamelog_table['touches'].astype(int)
        gamelog_table['MIN'] = gamelog_table['MIN'].astype(int)
        gamelog_table['Fantasy'] = gamelog_table['Fantasy'].astype(float)
        gamelog_table['FD_Fantasy'] = gamelog_table['FD_Fantasy'].astype(float)
        gamelog_table['FPPM'] = gamelog_table['FPPM'].astype(float)
        gamelog_table['rebound%'] = gamelog_table['REB'] / gamelog_table['reboundChancesTotal']
        gamelog_table['assists_per_pass'] = gamelog_table['assists'] / gamelog_table['passes']
        gamelog_table['Touch_per_min'] = gamelog_table['touches'] / gamelog_table['MIN']
        gamelog_table['Fantasy_per_touch'] = gamelog_table['Fantasy'] / gamelog_table['touches']
        gamelog_table['FD_Fantasy_per_touch'] = gamelog_table['FD_Fantasy'] / gamelog_table['touches']
        data_cols = gamelog_table.columns.drop(['PLAYER_NAME', 'POS', 'TEAM_NAME', 'OPP_NAME', 'SEASON_ID', 'GAME_DATE', 'MATCHUP'])
        gamelog_table[data_cols] = gamelog_table[data_cols].apply(pd.to_numeric, errors='coerce')
        gamelog_table['team_score'] = gamelog_table.groupby(['TEAM_NAME', 'GAME_ID'], sort=False)['PTS'].transform('sum')
        gamelog_table['opp_score'] = gamelog_table.groupby(['GAME_ID'], sort=False)['PTS'].transform('sum') - gamelog_table['team_score']
        gamelog_table['spread'] = (gamelog_table['opp_score'] - gamelog_table['team_score']).abs()
        gamelog_table['GAME_DATE'] = pd.to_datetime(gamelog_table['GAME_DATE']).dt.date
        
        spread_dict = dict(zip(gamelog_table['GAME_ID'], gamelog_table['spread']))
        
        gamelog_table = gamelog_table.set_axis(['Player', 'Pos', 'game_id', 'Team', 'Opp', 'Season', 'Date', 'Matchup', 'Min', 'Touches', 'Pts', 'FGM', 'FGA', 'FG%', 'FG3M',
                                                'FG3A', 'FG3%', 'FTM', 'FTA', 'FT%', 'OREB Chance', 'OREB', 'DREB Chance', 'DREB', 'REB Chance', 'REB',
                                                'Passes', 'Alt Assists', 'FT Assists', 'Assists', 'Stl', 'Blk', 'Tov', 'PF', 'DD', 'TD', 'Fantasy', 'FD_Fantasy', 'FPPM',
                                                'Rebound%', 'Assists/Pass', 'Touch_per_min', 'Fantasy/Touch', 'FD Fantasy/Touch', 'team_score', 'opp_score', 'spread'], axis=1)

        timestamp = gamelog_table['Date'].max()

        collection = db["rotations"] 
        cursor = collection.find()  # Finds all documents in the collection
        
        raw_display = pd.DataFrame(list(cursor))
        game_rot = raw_display[raw_display['PLAYER_NAME'] != ""]
        data_cols = game_rot.columns.drop(['PLAYER_NAME', 'POS', 'TEAM_ABBREVIATION', 'OPP_ABBREVIATION', 'TEAM_NAME', 'OPP_NAME', 'GAME_DATE',
                                        'MATCHUP', 'WL', 'backlog_lookup', 'Task', 'game_players'])
        game_rot[data_cols] = game_rot[data_cols].apply(pd.to_numeric, errors='coerce')
        game_rot['spread'] = game_rot['GAME_ID'].map(spread_dict)
        game_rot['GAME_DATE'] = pd.to_datetime(game_rot['GAME_DATE']).dt.date
    
    return gamelog_table, game_rot, timestamp

@st.cache_data(show_spinner=False)
def seasonlong_build(data_sample):
    season_long_table = data_sample[['Player', 'Pos', 'Team']]
    season_long_table['Min'] = data_sample.groupby(['Player', 'Season'], sort=False)['Min'].transform('mean').astype(float)
    season_long_table['Touches'] = data_sample.groupby(['Player', 'Season'], sort=False)['Touches'].transform('mean').astype(float)
    season_long_table['Touch/Min'] = (data_sample.groupby(['Player', 'Season'], sort=False)['Touches'].transform('sum').astype(int) /
                                      data_sample.groupby(['Player', 'Season'], sort=False)['Min'].transform('sum').astype(int))
    season_long_table['Pts'] = data_sample.groupby(['Player', 'Season'], sort=False)['Pts'].transform('mean').astype(float)
    season_long_table['FGM'] = data_sample.groupby(['Player', 'Season'], sort=False)['FGM'].transform('mean').astype(float)
    season_long_table['FGA'] = data_sample.groupby(['Player', 'Season'], sort=False)['FGA'].transform('mean').astype(float)
    season_long_table['FG%'] = (data_sample.groupby(['Player', 'Season'], sort=False)['FGM'].transform('sum').astype(int) /
                                   data_sample.groupby(['Player', 'Season'], sort=False)['FGA'].transform('sum').astype(int))
    season_long_table['FG3M'] = data_sample.groupby(['Player', 'Season'], sort=False)['FG3M'].transform('mean').astype(float)
    season_long_table['FG3A'] = data_sample.groupby(['Player', 'Season'], sort=False)['FG3A'].transform('mean').astype(float)
    season_long_table['FG3%'] = (data_sample.groupby(['Player', 'Season'], sort=False)['FG3M'].transform('sum').astype(int) /
                                   data_sample.groupby(['Player', 'Season'], sort=False)['FG3A'].transform('sum').astype(int))
    season_long_table['FTM'] = data_sample.groupby(['Player', 'Season'], sort=False)['FTM'].transform('mean').astype(float)
    season_long_table['FTA'] = data_sample.groupby(['Player', 'Season'], sort=False)['FTA'].transform('mean').astype(float)
    season_long_table['FT%'] = (data_sample.groupby(['Player', 'Season'], sort=False)['FTM'].transform('sum').astype(int) /
                                   data_sample.groupby(['Player', 'Season'], sort=False)['FTA'].transform('sum').astype(int))
    season_long_table['OREB Chance'] = data_sample.groupby(['Player', 'Season'], sort=False)['OREB Chance'].transform('mean').astype(float)
    season_long_table['OREB'] = data_sample.groupby(['Player', 'Season'], sort=False)['OREB'].transform('mean').astype(float)
    season_long_table['DREB Chance'] = data_sample.groupby(['Player', 'Season'], sort=False)['DREB Chance'].transform('mean').astype(float)
    season_long_table['DREB'] = data_sample.groupby(['Player', 'Season'], sort=False)['DREB'].transform('mean').astype(float)
    season_long_table['REB Chance'] = data_sample.groupby(['Player', 'Season'], sort=False)['REB Chance'].transform('mean').astype(float)
    season_long_table['REB'] = data_sample.groupby(['Player', 'Season'], sort=False)['REB'].transform('mean').astype(float)
    season_long_table['Passes'] = data_sample.groupby(['Player', 'Season'], sort=False)['Passes'].transform('mean').astype(float)
    season_long_table['Alt Assists'] = data_sample.groupby(['Player', 'Season'], sort=False)['Alt Assists'].transform('mean').astype(float)
    season_long_table['FT Assists'] = data_sample.groupby(['Player', 'Season'], sort=False)['FT Assists'].transform('mean').astype(float)
    season_long_table['Assists'] = data_sample.groupby(['Player', 'Season'], sort=False)['Assists'].transform('mean').astype(float)
    season_long_table['Stl'] = data_sample.groupby(['Player', 'Season'], sort=False)['Stl'].transform('mean').astype(float)
    season_long_table['Blk'] = data_sample.groupby(['Player', 'Season'], sort=False)['Blk'].transform('mean').astype(float)
    season_long_table['Tov'] = data_sample.groupby(['Player', 'Season'], sort=False)['Tov'].transform('mean').astype(float)
    season_long_table['PF'] = data_sample.groupby(['Player', 'Season'], sort=False)['PF'].transform('mean').astype(float)
    season_long_table['DD'] = data_sample.groupby(['Player', 'Season'], sort=False)['DD'].transform('mean').astype(float)
    season_long_table['TD'] = data_sample.groupby(['Player', 'Season'], sort=False)['TD'].transform('mean').astype(float)
    season_long_table['Fantasy'] = data_sample.groupby(['Player', 'Season'], sort=False)['Fantasy'].transform('mean').astype(float)
    season_long_table['FD_Fantasy'] = data_sample.groupby(['Player', 'Season'], sort=False)['FD_Fantasy'].transform('mean').astype(float)
    season_long_table['FPPM'] = (data_sample.groupby(['Player', 'Season'], sort=False)['Fantasy'].transform('sum').astype(float) /
                                 data_sample.groupby(['Player', 'Season'], sort=False)['Min'].transform('sum').astype(int))
    season_long_table['Rebound%'] = (data_sample.groupby(['Player', 'Season'], sort=False)['REB'].transform('sum').astype(int) /
                                     data_sample.groupby(['Player', 'Season'], sort=False)['REB Chance'].transform('sum').astype(int))
    season_long_table['Assists/Pass'] = (data_sample.groupby(['Player', 'Season'], sort=False)['Assists'].transform('sum').astype(int) /
                                             data_sample.groupby(['Player', 'Season'], sort=False)['Passes'].transform('sum').astype(int))
    season_long_table['Fantasy/Touch'] = (data_sample.groupby(['Player', 'Season'], sort=False)['Fantasy'].transform('sum').astype(float) /
                                              data_sample.groupby(['Player', 'Season'], sort=False)['Touches'].transform('sum').astype(int))
    season_long_table['FD Fantasy/Touch'] = (data_sample.groupby(['Player', 'Season'], sort=False)['FD_Fantasy'].transform('sum').astype(float) /
                                                 data_sample.groupby(['Player', 'Season'], sort=False)['Touches'].transform('sum').astype(int))
    season_long_table = season_long_table.drop_duplicates(subset='Player')

    season_long_table = season_long_table.sort_values(by='Fantasy', ascending=False)
    
    season_long_table = season_long_table.set_axis(['Player', 'Pos', 'Team', 'Min', 'Touches', 'Touch/Min', 'Pts', 'FGM', 'FGA', 'FG%', 'FG3M', 'FG3A',
                                                    'FG3%', 'FTM', 'FTA', 'FT%', 'OREB Chance', 'OREB', 'DREB Chance', 'DREB', 'REB Chance', 'REB',
                                                    'Passes', 'Alt Assists', 'FT Assists', 'Assists', 'Stl', 'Blk', 'Tov', 'PF', 'DD', 'TD', 'Fantasy', 'FD_Fantasy',
                                                    'FPPM', 'Rebound%', 'Assists/Pass', 'Fantasy/Touch', 'FD Fantasy/Touch'], axis=1)

    return season_long_table

@st.cache_data(show_spinner=False)
def run_fantasy_corr(data_sample, season):
    cor_testing = data_sample
    cor_testing = cor_testing[cor_testing['Season'] == season]
    date_list = cor_testing['Date'].unique().tolist()
    player_list = cor_testing['Player'].unique().tolist()
    corr_frame = pd.DataFrame()
    corr_frame['DATE'] = date_list
    for player in player_list:
        player_testing = cor_testing[cor_testing['Player'] == player]
        fantasy_map = dict(zip(player_testing['Date'], player_testing['Fantasy']))
        corr_frame[player] = corr_frame['DATE'].map(fantasy_map)
    players_fantasy = corr_frame.drop('DATE', axis=1)
    corrM = players_fantasy.corr()
    
    return corrM

@st.cache_data(show_spinner=False)
def run_min_corr(data_sample, season):
    cor_testing = data_sample
    cor_testing = cor_testing[cor_testing['Season'] == season]
    date_list = cor_testing['Date'].unique().tolist()
    player_list = cor_testing['Player'].unique().tolist()
    corr_frame = pd.DataFrame()
    corr_frame['DATE'] = date_list
    for player in player_list:
        player_testing = cor_testing[cor_testing['Player'] == player]
        fantasy_map = dict(zip(player_testing['Date'], player_testing['Min']))
        corr_frame[player] = corr_frame['DATE'].map(fantasy_map)
    players_fantasy = corr_frame.drop('DATE', axis=1)
    corrM = players_fantasy.corr()
    
    return corrM

@st.cache_data(show_spinner=False)
def split_frame(input_df, rows):
    df = [input_df.loc[i : i + rows - 1, :] for i in range(0, len(input_df), rows)]
    return df

def convert_df_to_csv(df):
    return df.to_csv().encode('utf-8')

selected_tab = st.segmented_control(
    "Select Tab",
    options=['Gamelogs', 'Correlation Matrix', 'Position vs. Opp', 'Game Rotations'],
    selection_mode='single',
    default='Gamelogs',
    width='stretch',
    label_visibility='collapsed',
    key='tab_selector'
)

if selected_tab == 'Gamelogs':
    col1, col2 = st.columns([1, 9])
    with col1:
        if st.button("Reset Data", key='reset1'):
                  st.cache_data.clear()
                  gamelog_table, game_rot, timestamp = init_baselines('gamelogs')
                  basic_cols = ['Player', 'Pos', 'Team', 'Opp', 'Season', 'Date', 'Matchup', 'Min']
                  basic_season_cols = ['Pos', 'Team', 'Min']
                  data_cols = ['team_score', 'opp_score', 'spread', 'Touches', 'Pts', 'FGM', 'FGA', 'FG%', 'FG3M',
                               'FG3A', 'FG3%', 'FTM', 'FTA', 'FT%', 'OREB Chance', 'OREB', 'DREB Chance', 'DREB', 'REB Chance', 'REB',
                               'Passes', 'Alt Assists', 'FT Assists', 'Assists', 'Stl', 'Blk', 'Tov', 'PF', 'DD', 'TD', 'Fantasy', 'FD_Fantasy',
                               'FPPM', 'Rebound%', 'Assists/Pass', 'Touch_per_min', 'Fantasy/Touch', 'FD Fantasy/Touch']
                  season_data_cols = ['Touches', 'Touch/Min', 'Pts', 'FGM', 'FGA', 'FG%', 'FG3M', 'FG3A',
                                      'FG3%', 'FTM', 'FTA', 'FT%', 'OREB Chance', 'OREB', 'DREB Chance', 'DREB', 'REB Chance', 'REB',
                                      'Passes', 'Alt Assists', 'FT Assists', 'Assists', 'Stl', 'Blk', 'Tov', 'PF', 'DD', 'TD', 'Fantasy', 'FD_Fantasy',
                                      'FPPM', 'Rebound%', 'Assists/Pass', 'Fantasy/Touch', 'FD Fantasy/Touch']
                  game_rot_cols = ['PLAYER_NAME', 'backlog_lookup', 'spread', 'MIN', 'PTS', 'FGM', 'FGA', 'FG3M', 'FG3A', 'FTM', 'FTA', 'REB', 'AST', 'STL', 'BLK', 'TOV', 'PF',
                                   'Fantasy', 'FD_Fantasy']
                  indv_teams = gamelog_table.drop_duplicates(subset='Team')
                  total_teams = indv_teams.Team.values.tolist()
                  indv_players = gamelog_table.drop_duplicates(subset='Player')
                  total_players = indv_players.Player.values.tolist()
                  total_dates = gamelog_table.Date.values.tolist()
        
        gamelog_table, game_rot, timestamp = init_baselines('gamelogs')
        indv_teams = gamelog_table.drop_duplicates(subset='Team')
        total_teams = indv_teams.Team.values.tolist()
        indv_players = gamelog_table.drop_duplicates(subset='Player')
        total_players = indv_players.Player.values.tolist()
        total_dates = gamelog_table.Date.values.tolist()
        
        split_var1 = st.radio("What table would you like to view?", ('Season Logs', 'Gamelogs'), key='split_var1')
        split_var2 = st.radio("Would you like to view all teams or specific ones?", ('All', 'Specific Teams'), key='split_var2')
        
        if split_var2 == 'Specific Teams':
            team_var1 = st.multiselect('Which teams would you like to include in the tables?', options = total_teams, key='team_var1')
        elif split_var2 == 'All':
            team_var1 = total_teams
            
        split_var3 = st.radio("Would you like to view all dates or specific ones?", ('All', 'Specific Dates'), key='split_var3')
        
        if split_var3 == 'Specific Dates':
            low_date = st.date_input('Min Date:', value=None, format="YYYY-MM-DD", key='low_date')
            if low_date is not None:
                low_date = pd.to_datetime(low_date).date()
            high_date = st.date_input('Max Date:', value=None, format="YYYY-MM-DD", key='high_date')
            if high_date is not None:
                high_date = pd.to_datetime(high_date).date()
        elif split_var3 == 'All':
            low_date = gamelog_table['Date'].min()
            high_date = gamelog_table['Date'].max()
        
        split_var4 = st.radio("Would you like to view all players or specific ones?", ('All', 'Specific Players'), key='split_var4')
        
        if split_var4 == 'Specific Players':
            player_var1 = st.multiselect('Which players would you like to include in the tables?', options = total_players, key='player_var1')
        elif split_var4 == 'All':
            player_var1 = total_players
            
        spread_var1 = st.slider("Is there a certain spread range you want to view?", 0, 100, (0, 100), key='spread_var1')
        
        min_var1 = st.slider("Is there a certain minutes range you want to view?", 0, 60, (0, 60), key='min_var1')
    
    with col2:
        working_data = gamelog_table
        if split_var1 == 'Season Logs':
            choose_cols = st.container()
            with choose_cols:
                choose_disp = st.multiselect('Which stats would you like to view?', options = season_data_cols, default = season_data_cols, key='col_display')
            disp_stats = basic_season_cols + choose_disp
            display = st.container()
            working_data = working_data[working_data['Date'] >= low_date]
            working_data = working_data[working_data['Date'] <= high_date]
            working_data = working_data[working_data['Min'] >= min_var1[0]]
            working_data = working_data[working_data['Min'] <= min_var1[1]]
            working_data = working_data[working_data['spread'] >= spread_var1[0]]
            working_data = working_data[working_data['spread'] <= spread_var1[1]]
            working_data = working_data[working_data['Team'].isin(team_var1)]
            working_data = working_data[working_data['Player'].isin(player_var1)]
            season_long_table = seasonlong_build(working_data)
            season_long_table = season_long_table.set_index('Player')
            season_long_table_disp = season_long_table.reindex(disp_stats,axis="columns")
            display.dataframe(season_long_table_disp.style.format(precision=2), height=750, use_container_width = True)  
            st.download_button(
                    label="Export seasonlogs Model",
                    data=convert_df_to_csv(season_long_table),
                    file_name='Seasonlogs_NBA_View.csv',
                    mime='text/csv',
            )
            
        elif split_var1 == 'Gamelogs':
            choose_cols = st.container()
            with choose_cols:
                choose_disp_gamelog = st.multiselect('Which stats would you like to view?', options = data_cols, default = data_cols, key='choose_disp_gamelog')
            gamelog_disp_stats = basic_cols + choose_disp_gamelog
            working_data = working_data[working_data['Date'] >= low_date]
            working_data = working_data[working_data['Date'] <= high_date]
            working_data = working_data[working_data['Min'] >= min_var1[0]]
            working_data = working_data[working_data['Min'] <= min_var1[1]]
            working_data = working_data[working_data['spread'] >= spread_var1[0]]
            working_data = working_data[working_data['spread'] <= spread_var1[1]]
            working_data = working_data[working_data['Team'].isin(team_var1)]
            working_data = working_data[working_data['Player'].isin(player_var1)]
            working_data = working_data.reset_index(drop=True)
            gamelog_data = working_data.reindex(gamelog_disp_stats,axis="columns")
            display = st.container()
        
            bottom_menu = st.columns((4, 1, 1))
            with bottom_menu[2]:
                batch_size = st.selectbox("Page Size", options=[25, 50, 100])
            with bottom_menu[1]:
                total_pages = (
                    int(len(gamelog_data) / batch_size) if int(len(gamelog_data) / batch_size) > 0 else 1
                )
                current_page = st.number_input(
                    "Page", min_value=1, max_value=total_pages, step=1
                )
            with bottom_menu[0]:
                st.markdown(f"Page **{current_page}** of **{total_pages}** ")
            
            
            pages = split_frame(gamelog_data, batch_size)
            # pages = pages.set_index('Player')
            display.dataframe(data=pages[current_page - 1].style.format(precision=2), height=500, use_container_width=True)
            st.download_button(
                    label="Export gamelogs Model",
                    data=convert_df_to_csv(gamelog_data),
                    file_name='Gamelogs_NBA_View.csv',
                    mime='text/csv',
            )
            
if selected_tab == 'Correlation Matrix':
    col1, col2 = st.columns([1, 9])
    with col1:
        if st.button("Reset Data", key='reset2'):
                  st.cache_data.clear()
                  gamelog_table, game_rot, timestamp = init_baselines('gamelogs')
                  basic_cols = ['Player', 'Pos', 'Team', 'Opp', 'Season', 'Date', 'Matchup', 'Min']
                  basic_season_cols = ['Pos', 'Team', 'Min']
                  data_cols = ['team_score', 'opp_score', 'spread', 'Touches', 'Pts', 'FGM', 'FGA', 'FG%', 'FG3M',
                               'FG3A', 'FG3%', 'FTM', 'FTA', 'FT%', 'OREB Chance', 'OREB', 'DREB Chance', 'DREB', 'REB Chance', 'REB',
                               'Passes', 'Alt Assists', 'FT Assists', 'Assists', 'Stl', 'Blk', 'Tov', 'PF', 'DD', 'TD', 'Fantasy', 'FD_Fantasy',
                               'FPPM', 'Rebound%', 'Assists/Pass', 'Touch_per_min', 'Fantasy/Touch', 'FD Fantasy/Touch']
                  season_data_cols = ['Touches', 'Touch/Min', 'Pts', 'FGM', 'FGA', 'FG%', 'FG3M', 'FG3A',
                                      'FG3%', 'FTM', 'FTA', 'FT%', 'OREB Chance', 'OREB', 'DREB Chance', 'DREB', 'REB Chance', 'REB',
                                      'Passes', 'Alt Assists', 'FT Assists', 'Assists', 'Stl', 'Blk', 'Tov', 'PF', 'DD', 'TD', 'Fantasy', 'FD_Fantasy',
                                      'FPPM', 'Rebound%', 'Assists/Pass', 'Fantasy/Touch', 'FD Fantasy/Touch']
                  game_rot_cols = ['PLAYER_NAME', 'backlog_lookup', 'spread', 'MIN', 'PTS', 'FGM', 'FGA', 'FG3M', 'FG3A', 'FTM', 'FTA', 'REB', 'AST', 'STL', 'BLK', 'TOV', 'PF',
                                   'Fantasy', 'FD_Fantasy']
                  indv_teams = gamelog_table.drop_duplicates(subset='Team')
                  total_teams = indv_teams.Team.values.tolist()
                  indv_players = gamelog_table.drop_duplicates(subset='Player')
                  total_players = indv_players.Player.values.tolist()
                  total_dates = gamelog_table.Date.values.tolist()
        
        gamelog_table, game_rot, timestamp = init_baselines('gamelogs')
        indv_teams = gamelog_table.drop_duplicates(subset='Team')
        total_teams = indv_teams.Team.values.tolist()
        indv_players = gamelog_table.drop_duplicates(subset='Player')
        total_players = indv_players.Player.values.tolist()
        total_dates = gamelog_table.Date.values.tolist()
        
        corr_var = st.radio("Are you correlating fantasy or minutes?", ('Fantasy', 'Minutes'), key='corr_var')
        
        split_var1_t2 = st.radio("Would you like to view specific teams or specific players?", ('Specific Teams', 'Specific Players'), key='split_var1_t2')
        
        if split_var1_t2 == 'Specific Teams':
            corr_var1_t2 = st.multiselect('Which teams would you like to include in the correlation?', options = total_teams, key='corr_var1_t2')
        elif split_var1_t2 == 'Specific Players':
            corr_var1_t2 = st.multiselect('Which players would you like to include in the correlation?', options = total_players, key='corr_var1_t2')
            
        split_var2_t2 = st.radio("Would you like to view all dates or specific ones?", ('All', 'Specific Dates'), key='split_var3_t2')
        
        if split_var2_t2 == 'Specific Dates':
            low_date_t2 = st.date_input('Min Date:', value=None, format="YYYY-MM-DD", key='low_date_t2')
            if low_date_t2 is not None:
                low_date_t2 = pd.to_datetime(low_date_t2).date()
            high_date_t2 = st.date_input('Max Date:', value=None, format="YYYY-MM-DD", key='high_date_t2')
            if high_date_t2 is not None:
                high_date_t2 = pd.to_datetime(high_date_t2).date()
        elif split_var2_t2 == 'All':
            low_date_t2 = gamelog_table['Date'].min()
            high_date_t2 = gamelog_table['Date'].max()
            
        spread_var1_t2 = st.slider("Is there a certain spread range you want to view?", 0, 100, (0, 100), key='spread_var1_t2')
        
        min_var1_t2 = st.slider("Is there a certain minutes range you want to view?", 0, 60, (0, 60), key='min_var1_t2')
    
    with col2:
        working_data = gamelog_table
        if split_var1_t2 == 'Specific Teams':
            display = st.container()
            working_data = working_data.sort_values(by='Fantasy', ascending=False)
            working_data = working_data[working_data['Date'] >= low_date_t2]
            working_data = working_data[working_data['Date'] <= high_date_t2]
            working_data = working_data[working_data['Min'] >= min_var1_t2[0]]
            working_data = working_data[working_data['Min'] <= min_var1_t2[1]]
            working_data = working_data[working_data['spread'] >= spread_var1_t2[0]]
            working_data = working_data[working_data['spread'] <= spread_var1_t2[1]]
            working_data = working_data[working_data['Team'].isin(corr_var1_t2)]
            if corr_var == 'Fantasy':
                corr_display = run_fantasy_corr(working_data, '22025')
            elif corr_var == 'Minutes':
                corr_display = run_min_corr(working_data, '22025')
            display.dataframe(corr_display.style.background_gradient(axis=0).background_gradient(cmap='RdYlGn').format(precision=2), height=1000, use_container_width = True)
            
        elif split_var1_t2 == 'Specific Players':
            display = st.container()
            working_data = working_data.sort_values(by='Fantasy', ascending=False)
            working_data = working_data[working_data['Date'] >= low_date_t2]
            working_data = working_data[working_data['Date'] <= high_date_t2]
            working_data = working_data[working_data['Min'] >= min_var1_t2[0]]
            working_data = working_data[working_data['Min'] <= min_var1_t2[1]]
            working_data = working_data[working_data['spread'] >= spread_var1_t2[0]]
            working_data = working_data[working_data['spread'] <= spread_var1_t2[1]]
            working_data = working_data[working_data['Player'].isin(corr_var1_t2)]
            if corr_var == 'Fantasy':
                corr_display = run_fantasy_corr(working_data, '22025')
            elif corr_var == 'Minutes':
                corr_display = run_min_corr(working_data, '22025')
            display.dataframe(corr_display.style.background_gradient(axis=0).background_gradient(cmap='RdYlGn').format(precision=2), use_container_width = True)
        st.download_button(
                label="Export Correlations Model",
                data=convert_df_to_csv(corr_display),
                file_name='Correlations_NBA_View.csv',
                mime='text/csv',
        )

if selected_tab == 'Position vs. Opp':
    col1, col2 = st.columns([1, 9])
    with col1:
        if st.button("Reset Data", key='reset3'):
                  st.cache_data.clear()
                  gamelog_table, game_rot, timestamp = init_baselines('gamelogs')
                  basic_cols = ['Player', 'Pos', 'Team', 'Opp', 'Season', 'Date', 'Matchup', 'Min']
                  basic_season_cols = ['Pos', 'Team', 'Min']
                  data_cols = ['team_score', 'opp_score', 'spread', 'Touches', 'Pts', 'FGM', 'FGA', 'FG%', 'FG3M',
                               'FG3A', 'FG3%', 'FTM', 'FTA', 'FT%', 'OREB Chance', 'OREB', 'DREB Chance', 'DREB', 'REB Chance', 'REB',
                               'Passes', 'Alt Assists', 'FT Assists', 'Assists', 'Stl', 'Blk', 'Tov', 'PF', 'DD', 'TD', 'Fantasy', 'FD_Fantasy',
                               'FPPM', 'Rebound%', 'Assists/Pass', 'Touch_per_min', 'Fantasy/Touch', 'FD Fantasy/Touch']
                  season_data_cols = ['Touches', 'Touch/Min', 'Pts', 'FGM', 'FGA', 'FG%', 'FG3M', 'FG3A',
                                      'FG3%', 'FTM', 'FTA', 'FT%', 'OREB Chance', 'OREB', 'DREB Chance', 'DREB', 'REB Chance', 'REB',
                                      'Passes', 'Alt Assists', 'FT Assists', 'Assists', 'Stl', 'Blk', 'Tov', 'PF', 'DD', 'TD', 'Fantasy', 'FD_Fantasy',
                                      'FPPM', 'Rebound%', 'Assists/Pass', 'Fantasy/Touch', 'FD Fantasy/Touch']
                  game_rot_cols = ['PLAYER_NAME', 'backlog_lookup', 'spread', 'MIN', 'PTS', 'FGM', 'FGA', 'FG3M', 'FG3A', 'FTM', 'FTA', 'REB', 'AST', 'STL', 'BLK', 'TOV', 'PF',
                                   'Fantasy', 'FD_Fantasy']
                  indv_teams = gamelog_table.drop_duplicates(subset='Team')
                  total_teams = indv_teams.Team.values.tolist()
                  indv_players = gamelog_table.drop_duplicates(subset='Player')
                  total_players = indv_players.Player.values.tolist()
                  total_dates = gamelog_table.Date.values.tolist()
        
        gamelog_table, game_rot, timestamp = init_baselines('gamelogs')
        indv_teams = gamelog_table.drop_duplicates(subset='Team')
        total_teams = indv_teams.Team.values.tolist()
        indv_players = gamelog_table.drop_duplicates(subset='Player')
        total_players = indv_players.Player.values.tolist()
        total_dates = gamelog_table.Date.values.tolist()
        
        team_var3 = st.selectbox('Which opponent would you like to view?', options = total_teams, key='team_var3')
        pos_var3 = st.selectbox('Which position would you like to view?', options = ['PG', 'SG', 'SF', 'PF', 'C'], key='pos_var3')
        disp_var3 = st.radio('Which view would you like to see?', options = ['Fantasy', 'Stats'], key='disp_var3')
        date_var3 = st.radio("Would you like to view all dates or specific ones?", ('All', 'Specific Dates'), key='date_var3')
        
        if date_var3 == 'Specific Dates':
            low_date3 = st.date_input('Min Date:', value=None, format="YYYY-MM-DD", key='low_date3')
            if low_date3 is not None:
                low_date3 = pd.to_datetime(low_date3).date()
            high_date3 = st.date_input('Max Date:', value=None, format="YYYY-MM-DD", key='high_date3')
            if high_date3 is not None:
                high_date3 = pd.to_datetime(high_date3).date()
        elif date_var3 == 'All':
            low_date3 = gamelog_table['Date'].min()
            high_date3 = gamelog_table['Date'].max()
        
        spread_var3 = st.slider("Is there a certain spread range you want to view?", 0, 100, (0, 100), key='spread_var3')
        
        min_var3 = st.slider("Is there a certain minutes range you want to view?", 0, 60, (0, 60), key='min_var3')
    
    with col2:
        if disp_var3 == 'Stats':
            choose_cols = st.container()
            with choose_cols:
                choose_disp_matchup = st.multiselect('Which stats would you like to view?', options = data_cols, default = data_cols, key='choose_disp_matchup')
            matchup_disp_stats = basic_cols + choose_disp_matchup
        working_data = gamelog_table
        working_data = working_data[gamelog_table['Date'] >= low_date3]
        working_data = working_data[gamelog_table['Date'] <= high_date3]
        season_long_table = seasonlong_build(working_data)
        fantasy_dict = dict(zip(season_long_table['Player'], season_long_table['Fantasy']))
        fd_fantasy_dict = dict(zip(season_long_table['Player'], season_long_table['FD_Fantasy']))
            
        working_data = working_data[working_data['Pos'] == pos_var3]
        working_data = working_data[working_data['Min'] >= min_var3[0]]
        working_data = working_data[working_data['Min'] <= min_var3[1]]
        working_data = working_data[working_data['spread'] >= spread_var3[0]]
        working_data = working_data[working_data['spread'] <= spread_var3[1]]
        working_data = working_data[working_data['Opp'] == team_var3]
        working_data = working_data.reset_index(drop=True)
        if disp_var3 == 'Fantasy':
            gamelog_display = working_data[['Player', 'Pos', 'Team', 'Opp', 'Date', 'Min', 'Fantasy', 'FD_Fantasy']]
        elif disp_var3 == 'Stats':
            gamelog_data = working_data.reindex(matchup_disp_stats,axis="columns")
            gamelog_display = gamelog_data
        gamelog_display['Avg_Fantasy'] = gamelog_display['Player'].map(fantasy_dict)
        gamelog_display['Avg_FD_Fantasy'] = gamelog_display['Player'].map(fd_fantasy_dict)
        display = st.container()

        # pages = pages.set_index('Player')
        display.dataframe(gamelog_display.style.format(precision=2), height=500, use_container_width=True)
        st.download_button(
                label="Export Matchups Model",
                data=convert_df_to_csv(gamelog_display),
                file_name='Matchups_NBA_View.csv',
                mime='text/csv',
        )

if selected_tab == 'Game Rotations':
    col1, col2 = st.columns([1, 9])
    with col1:
        if st.button("Reset Data", key='reset5'):
                  st.cache_data.clear()
                  gamelog_table, game_rot, timestamp = init_baselines('all')
                  basic_cols = ['Player', 'Pos', 'Team', 'Opp', 'Season', 'Date', 'Matchup', 'Min']
                  basic_season_cols = ['Pos', 'Team', 'Min']
                  data_cols = ['team_score', 'opp_score', 'spread', 'Touches', 'Pts', 'FGM', 'FGA', 'FG%', 'FG3M',
                               'FG3A', 'FG3%', 'FTM', 'FTA', 'FT%', 'OREB Chance', 'OREB', 'DREB Chance', 'DREB', 'REB Chance', 'REB',
                               'Passes', 'Alt Assists', 'FT Assists', 'Assists', 'Stl', 'Blk', 'Tov', 'PF', 'DD', 'TD', 'Fantasy', 'FD_Fantasy',
                               'FPPM', 'Rebound%', 'Assists/Pass', 'Touch_per_min', 'Fantasy/Touch', 'FD Fantasy/Touch']
                  season_data_cols = ['Touches', 'Touch/Min', 'Pts', 'FGM', 'FGA', 'FG%', 'FG3M', 'FG3A',
                                      'FG3%', 'FTM', 'FTA', 'FT%', 'OREB Chance', 'OREB', 'DREB Chance', 'DREB', 'REB Chance', 'REB',
                                      'Passes', 'Alt Assists', 'FT Assists', 'Assists', 'Stl', 'Blk', 'Tov', 'PF', 'DD', 'TD', 'Fantasy', 'FD_Fantasy',
                                      'FPPM', 'Rebound%', 'Assists/Pass', 'Fantasy/Touch', 'FD Fantasy/Touch']
                  game_rot_cols = ['PLAYER_NAME', 'backlog_lookup', 'spread', 'MIN', 'PTS', 'FGM', 'FGA', 'FG3M', 'FG3A', 'FTM', 'FTA', 'REB', 'AST', 'STL', 'BLK', 'TOV', 'PF',
                                   'Fantasy', 'FD_Fantasy']
                  indv_teams = gamelog_table.drop_duplicates(subset='Team')
                  total_teams = indv_teams.Team.values.tolist()
                  indv_game_rot_teams = game_rot.drop_duplicates(subset='TEAM_ABBREVIATION')
                  total_game_rot_teams = indv_game_rot_teams.TEAM_ABBREVIATION.values.tolist()
                  indv_players = gamelog_table.drop_duplicates(subset='Player')
                  total_players = indv_players.Player.values.tolist()
                  total_dates = gamelog_table.Date.values.tolist()
        
        gamelog_table, game_rot, timestamp = init_baselines('all')
        basic_cols = ['Player', 'Pos', 'Team', 'Team Abbr', 'Opp', 'Opp Abbr', 'Season', 'Date', 'Matchup', 'Min']
        basic_season_cols = ['Pos', 'Team', 'Team Abbr', 'Min']
        data_cols = ['team_score', 'opp_score', 'spread', 'Touches', 'Pts', 'FGM', 'FGA', 'FG%', 'FG3M',
                    'FG3A', 'FG3%', 'FTM', 'FTA', 'FT%', 'OREB Chance', 'OREB', 'DREB Chance', 'DREB', 'REB Chance', 'REB',
                    'Passes', 'Alt Assists', 'FT Assists', 'Assists', 'Stl', 'Blk', 'Tov', 'PF', 'DD', 'TD', 'Fantasy', 'FD_Fantasy',
                    'FPPM', 'Rebound%', 'Assists/Pass', 'Touch_per_min', 'Fantasy/Touch', 'FD Fantasy/Touch']
        season_data_cols = ['Touches', 'Touch/Min', 'Pts', 'FGM', 'FGA', 'FG%', 'FG3M', 'FG3A',
                            'FG3%', 'FTM', 'FTA', 'FT%', 'OREB Chance', 'OREB', 'DREB Chance', 'DREB', 'REB Chance', 'REB',
                            'Passes', 'Alt Assists', 'FT Assists', 'Assists', 'Stl', 'Blk', 'Tov', 'PF', 'DD', 'TD', 'Fantasy', 'FD_Fantasy',
                            'FPPM', 'Rebound%', 'Assists/Pass', 'Fantasy/Touch', 'FD Fantasy/Touch']
        game_rot_cols = ['PLAYER_NAME', 'backlog_lookup', 'spread', 'MIN', 'PTS', 'FGM', 'FGA', 'FG3M', 'FG3A', 'FTM', 'FTA', 'REB', 'AST', 'STL', 'BLK', 'TOV', 'PF',
                        'Fantasy', 'FD_Fantasy']
        indv_teams = gamelog_table.drop_duplicates(subset='Team')
        total_teams = indv_teams.Team.values.tolist()
        indv_game_rot_teams = game_rot.drop_duplicates(subset='TEAM_ABBREVIATION')
        total_game_rot_teams = indv_game_rot_teams.TEAM_ABBREVIATION.values.tolist()
        indv_players = gamelog_table.drop_duplicates(subset='Player')
        total_players = indv_players.Player.values.tolist()
        total_dates = gamelog_table.Date.values.tolist()
        
        game_rot_view = st.radio("What set would you like to view?", ('Team Rotations', 'Player Rotations'), key='game_rot_view')
        
        if game_rot_view == 'Team Rotations':
            game_rot_team = st.selectbox("What team would you like to work with?", options = total_game_rot_teams, key='game_rot_team')
            
            game_rot_spread = st.slider("Is there a certain spread range you want to view?", 0, 100, (0, 100), key='game_rot_spread')
            
            game_rot_min = st.slider("Is there a certain minutes range you want to view?", 0, 60, (0, 60), key='game_rot_min')
            
            game_rot_dates = st.radio("Would you like to view all dates or specific ones?", ('All', 'Specific Dates'), key='game_rot_dates')
            
            if game_rot_dates == 'Specific Dates':
                game_rot_low_date = st.date_input('Min Date:', value=None, format="YYYY-MM-DD", key='game_rot_low_date')
                if game_rot_low_date is not None:
                    game_rot_low_date = pd.to_datetime(low_date).date()
                game_rot_high_date = st.date_input('Max Date:', value=None, format="YYYY-MM-DD", key='game_rot_high_date')
                if game_rot_high_date is not None:
                    game_rot_high_date = pd.to_datetime(high_date).date()
            elif game_rot_dates == 'All':
                game_rot_low_date = gamelog_table['Date'].min()
                game_rot_high_date = gamelog_table['Date'].max()
        elif game_rot_view == 'Player Rotations':
            game_rot_team = st.multiselect("What players would you like to work with?", options = total_players, key='game_rot_team')
            
            game_rot_spread = st.slider("Is there a certain spread range you want to view?", 0, 100, (0, 100), key='game_rot_spread')
            
            game_rot_min = st.slider("Is there a certain minutes range you want to view?", 0, 60, (0, 60), key='game_rot_min')
            
            game_rot_dates = st.radio("Would you like to view all dates or specific ones?", ('All', 'Specific Dates'), key='game_rot_dates')
            
            if game_rot_dates == 'Specific Dates':
                game_rot_low_date = st.date_input('Min Date:', value=None, format="YYYY-MM-DD", key='game_rot_low_date')
                if game_rot_low_date is not None:
                    game_rot_low_date = pd.to_datetime(game_rot_low_date).date()
                game_rot_high_date = st.date_input('Max Date:', value=None, format="YYYY-MM-DD", key='game_rot_high_date')
                if game_rot_high_date is not None:
                    game_rot_high_date = pd.to_datetime(game_rot_high_date).date()
            elif game_rot_dates == 'All':
                game_rot_low_date = gamelog_table['Date'].min()
                game_rot_high_date = gamelog_table['Date'].max()
                
            
    with col2:
        if game_rot_view == 'Player Rotations':
            team_backlog = game_rot[game_rot['PLAYER_NAME'].isin(game_rot_team)]
            team_backlog = team_backlog[pd.to_datetime(team_backlog['GAME_DATE']).dt.date >= game_rot_low_date]
            team_backlog = team_backlog[pd.to_datetime(team_backlog['GAME_DATE']).dt.date <= game_rot_high_date]
            team_backlog = team_backlog[team_backlog['MIN'] >= game_rot_min[0]]
            team_backlog = team_backlog[team_backlog['MIN'] <= game_rot_min[1]]
            team_backlog = team_backlog[team_backlog['spread'] >= game_rot_spread[0]]
            team_backlog = team_backlog[team_backlog['spread'] <= game_rot_spread[1]]
            working_data = game_rot
            display = st.container()
            stats_disp = st.container()
            check_rotation = team_backlog.sort_values(by=['GAME_DATE', 'Finish'], ascending=[False, True])
            
            # Ensure Start and Finish are numeric and Task is properly set
            check_rotation['Start'] = pd.to_numeric(check_rotation['Start'], errors='coerce')
            check_rotation['Finish'] = pd.to_numeric(check_rotation['Finish'], errors='coerce')
            check_rotation['delta'] = pd.to_numeric(check_rotation['delta'], errors='coerce')
            
            # Create figure
            fig = go.Figure()
            
            # Add bars for each shift
            for idx, row in check_rotation.iterrows():
                fig.add_trace(go.Bar(
                    x=[row['delta']],  # Width of bar
                    y=[row['Task']],
                    base=row['Start'],  # Start position of bar
                    orientation='h',
                    text=f"{row['delta']:.1f} Minutes",
                    textposition='inside',
                    showlegend=False,
                    marker_color=px.colors.qualitative.Plotly[hash(row['PLAYER_NAME']) % len(px.colors.qualitative.Plotly)]
                ))
            
            # Update layout
            fig.update_layout(
                barmode='overlay',
                xaxis=dict(
                    range=[0, 48],
                    title='Game Time (minutes)'
                ),
                yaxis=dict(
                    autorange='reversed'
                )
            )
            
            # Add quarter lines
            fig.add_vline(x=12, line_width=3, line_dash="dash", line_color="green")
            fig.add_vline(x=24, line_width=3, line_dash="dash", line_color="green")
            fig.add_vline(x=36, line_width=3, line_dash="dash", line_color="green")

            game_rot_stats = check_rotation.reindex(game_rot_cols,axis="columns")
            game_rot_stats = game_rot_stats.drop_duplicates(subset='backlog_lookup')

            # pages = pages.set_index('Player')
            display.plotly_chart(fig, use_container_width=True)
            stats_disp.dataframe(game_rot_stats.style.format(precision=2), hide_index=True, use_container_width = True)
            
        elif game_rot_view == 'Team Rotations':
            team_backlog = game_rot[game_rot['TEAM_ABBREVIATION'] == game_rot_team]
            team_backlog = team_backlog[pd.to_datetime(team_backlog['GAME_DATE']).dt.date >= game_rot_low_date]
            team_backlog = team_backlog[pd.to_datetime(team_backlog['GAME_DATE']).dt.date <= game_rot_high_date]
            team_backlog = team_backlog[team_backlog['MIN'] >= game_rot_min[0]]
            team_backlog = team_backlog[team_backlog['MIN'] <= game_rot_min[1]]
            team_backlog = team_backlog[team_backlog['spread'] >= game_rot_spread[0]]
            team_backlog = team_backlog[team_backlog['spread'] <= game_rot_spread[1]]
            game_id_var = st.selectbox("What game would you like to view?", options = team_backlog['backlog_lookup'].unique(), key='game_id_var')
            working_data = game_rot
            display = st.container()
            stats_disp = st.container()
            check_rotation = working_data[working_data['backlog_lookup'] == game_id_var]
            check_rotation = check_rotation.sort_values(by='Start', ascending=True)
            game_rot_stats = check_rotation.reindex(game_rot_cols,axis="columns")
            game_rot_stats = game_rot_stats.drop_duplicates(subset='PLAYER_NAME')

            # Create figure
            fig = go.Figure()

            distinct_colors = [
                '#1f77b4',  # blue
                '#ff7f0e',  # orange
                '#2ca02c',  # green
                '#d62728',  # red
                '#9467bd',  # purple
                '#8c564b',  # brown
                '#e377c2',  # pink
                '#7f7f7f',  # gray
                '#bcbd22',  # yellow-green
                '#17becf',  # cyan
                '#aec7e8',  # light blue
                '#ffbb78',  # light orange
                '#98df8a',  # light green
                '#ff9896',  # light red
                '#c5b0d5'   # light purple
            ]
            
            # Create a mapping of unique tasks to colors
            unique_tasks = check_rotation['Task'].unique()
            color_map = dict(zip(unique_tasks, distinct_colors[:len(unique_tasks)]))
            
            # Add bars for each rotation shift
            for idx, row in check_rotation.iterrows():
                fig.add_trace(go.Bar(
                    x=[row['Finish'] - row['Start']],  # Width of bar
                    y=[row['Task']],
                    base=row['Start'],  # Start position of bar
                    orientation='h',
                    text=f"{row['minutes']:.1f} Minutes",
                    textposition='inside',
                    showlegend=False,
                    marker_color=color_map[row['Task']]  # Use mapped color for task
                ))
            
            # Update layout
            fig.update_layout(
                barmode='overlay',
                xaxis=dict(
                    range=[0, 48],
                    title='Game Time (minutes)'
                ),
                yaxis=dict(
                    autorange='reversed'
                )
            )
            
            # Add quarter lines
            fig.add_vline(x=12, line_width=3, line_dash="dash", line_color="green")
            fig.add_vline(x=24, line_width=3, line_dash="dash", line_color="green")
            fig.add_vline(x=36, line_width=3, line_dash="dash", line_color="green")
            # pages = pages.set_index('Player')
            display.plotly_chart(fig, use_container_width=True)
            stats_disp.dataframe(game_rot_stats.style.format(precision=2), hide_index=True, use_container_width = True)