File size: 56,371 Bytes
45a439d
b86285f
9594423
b86285f
 
26751b8
9594423
a0bee85
94c1a57
b86285f
5a713b7
 
25ce10e
b86285f
25ce10e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b86285f
a0bee85
 
02caa74
 
a0bee85
25ce10e
 
 
02caa74
25ce10e
02caa74
b86285f
 
 
 
9594423
 
 
 
 
 
 
239be9c
2718b31
02caa74
 
 
 
2718b31
02caa74
 
 
 
2718b31
02caa74
 
 
 
 
0f3cb17
02caa74
 
 
 
 
 
 
 
2718b31
02caa74
 
 
 
 
5ce7b63
192168c
02caa74
 
 
 
053d8b5
02caa74
a0bee85
 
 
5cf9a04
6dad1e9
 
 
 
a0bee85
 
053d8b5
9012c48
 
 
 
 
 
 
6dad1e9
 
 
9012c48
 
 
 
 
 
 
 
 
a0bee85
4c34346
9594423
4c34346
9594423
38ab091
3932661
b86285f
33e229f
 
0f3cb17
 
33e229f
 
83b0a3d
3963b80
38ab091
39e0137
b86285f
 
 
 
 
 
 
 
a0bee85
4c34346
9594423
4c34346
9594423
2718b31
 
b86285f
 
 
14f075f
aa7c8a8
55c314c
 
 
 
b86285f
14f075f
aa7c8a8
19fe2eb
b86285f
 
 
 
 
 
 
 
 
 
39e0137
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
76f06f3
39e0137
6bba819
39e0137
 
 
 
 
 
 
 
b86285f
 
 
a0bee85
4c34346
f32fab3
4c34346
f32fab3
2718b31
 
b86285f
 
 
 
 
 
 
 
19fe2eb
b86285f
 
 
 
 
9db2e5e
b86285f
 
39e0137
b86285f
 
 
a0bee85
4c34346
9594423
4c34346
9594423
2718b31
 
b86285f
 
 
 
 
 
 
 
19fe2eb
b86285f
 
 
 
 
9db2e5e
b86285f
a0bee85
 
 
 
 
 
4c34346
9594423
4c34346
9594423
0f3cb17
 
 
 
 
 
 
 
6781ccf
0f3cb17
1ccb87a
0f3cb17
4dcd40c
0f3cb17
350c781
0f3cb17
 
 
 
 
 
 
a0bee85
0f3cb17
a0bee85
0f3cb17
a0bee85
4c34346
9594423
4c34346
9594423
2718b31
 
b86285f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4c34346
b86285f
ecffc8d
b86285f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f175319
 
b86285f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9594423
 
b86285f
 
 
9594423
b86285f
9594423
b86285f
 
 
 
 
 
 
4c34346
 
b86285f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a0bee85
b86285f
 
a0bee85
b86285f
a0bee85
4c34346
9594423
4c34346
9594423
2718b31
 
3963b80
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e066741
3963b80
 
 
 
 
 
 
 
 
 
662b921
3963b80
e066741
3963b80
 
e066741
3963b80
b86285f
3963b80
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b86285f
3963b80
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import streamlit as st
import numpy as np
from numpy import where as np_where
import pandas as pd
import gspread
import plotly.express as px
import scipy.stats as stats
from pymongo import MongoClient
st.set_page_config(layout="wide")

@st.cache_resource
def init_conn():
        scope = ['https://spreadsheets.google.com/feeds', 'https://www.googleapis.com/auth/drive']

        credentials = {
          "type": "service_account",
          "project_id": "model-sheets-connect",
          "private_key_id": st.secrets['model_sheets_connect_pk'],
          "private_key": "-----BEGIN PRIVATE KEY-----\nMIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQDiu1v/e6KBKOcK\ncx0KQ23nZK3ZVvADYy8u/RUn/EDI82QKxTd/DizRLIV81JiNQxDJXSzgkbwKYEDm\n48E8zGvupU8+Nk76xNPakrQKy2Y8+VJlq5psBtGchJTuUSHcXU5Mg2JhQsB376PJ\nsCw552K6Pw8fpeMDJDZuxpKSkaJR6k9G5Dhf5q8HDXnC5Rh/PRFuKJ2GGRpX7n+2\nhT/sCax0J8jfdTy/MDGiDfJqfQrOPrMKELtsGHR9Iv6F4vKiDqXpKfqH+02E9ptz\nBk+MNcbZ3m90M8ShfRu28ebebsASfarNMzc3dk7tb3utHOGXKCf4tF8yYKo7x8BZ\noO9X4gSfAgMBAAECggEAU8ByyMpSKlTCF32TJhXnVJi/kS+IhC/Qn5JUDMuk4LXr\naAEWsWO6kV/ZRVXArjmuSzuUVrXumISapM9Ps5Ytbl95CJmGDiLDwRL815nvv6k3\nUyAS8EGKjz74RpoIoH6E7EWCAzxlnUgTn+5oP9Flije97epYk3H+e2f1f5e1Nn1d\nYNe8U+1HqJgILcxA1TAUsARBfoD7+K3z/8DVPHI8IpzAh6kTHqhqC23Rram4XoQ6\nzj/ZdVBjvnKuazETfsD+Vl3jGLQA8cKQVV70xdz3xwLcNeHsbPbpGBpZUoF73c65\nkAXOrjYl0JD5yAk+hmYhXr6H9c6z5AieuZGDrhmlFQKBgQDzV6LRXmjn4854DP/J\nI82oX2GcI4eioDZPRukhiQLzYerMQBmyqZIRC+/LTCAhYQSjNgMa+ZKyvLqv48M0\n/x398op/+n3xTs+8L49SPI48/iV+mnH7k0WI/ycd4OOKh8rrmhl/0EWb9iitwJYe\nMjTV/QxNEpPBEXfR1/mvrN/lVQKBgQDuhomOxUhWVRVH6x03slmyRBn0Oiw4MW+r\nrt1hlNgtVmTc5Mu+4G0USMZwYuOB7F8xG4Foc7rIlwS7Ic83jMJxemtqAelwOLdV\nXRLrLWJfX8+O1z/UE15l2q3SUEnQ4esPHbQnZowHLm0mdL14qSVMl1mu1XfsoZ3z\nJZTQb48CIwKBgEWbzQRtKD8lKDupJEYqSrseRbK/ax43DDITS77/DWwHl33D3FYC\nMblUm8ygwxQpR4VUfwDpYXBlklWcJovzamXpSnsfcYVkkQH47NuOXPXPkXQsw+w+\nDYcJzeu7F/vZqk9I7oBkWHUrrik9zPNoUzrfPvSRGtkAoTDSwibhoc5dAoGBAMHE\nK0T/ANeZQLNuzQps6S7G4eqjwz5W8qeeYxsdZkvWThOgDd/ewt3ijMnJm5X05hOn\ni4XF1euTuvUl7wbqYx76Wv3/1ZojiNNgy7ie4rYlyB/6vlBS97F4ZxJdxMlabbCW\n6b3EMWa4EVVXKoA1sCY7IVDE+yoQ1JYsZmq45YzPAoGBANWWHuVueFGZRDZlkNlK\nh5OmySmA0NdNug3G1upaTthyaTZ+CxGliwBqMHAwpkIRPwxUJpUwBTSEGztGTAxs\nWsUOVWlD2/1JaKSmHE8JbNg6sxLilcG6WEDzxjC5dLL1OrGOXj9WhC9KX3sq6qb6\nF/j9eUXfXjAlb042MphoF3ZC\n-----END PRIVATE KEY-----\n",
          "client_email": "[email protected]",
          "client_id": "100369174533302798535",
          "auth_uri": "https://accounts.google.com/o/oauth2/auth",
          "token_uri": "https://oauth2.googleapis.com/token",
          "auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs",
          "client_x509_cert_url": "https://www.googleapis.com/robot/v1/metadata/x509/gspread-connection%40model-sheets-connect.iam.gserviceaccount.com"
        }
        
        credentials2 = {
          "type": "service_account",
          "project_id": "sheets-api-connect-378620",
          "private_key_id": st.secrets['sheets_api_connect_pk'],
          "private_key": "-----BEGIN PRIVATE KEY-----\nMIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQCtKa01beXwc88R\nnPZVQTNPVQuBnbwoOfc66gW3547ja/UEyIGAF112dt/VqHprRafkKGmlg55jqJNt\na4zceLKV+wTm7vBu7lDISTJfGzCf2TrxQYNqwMKE2LOjI69dBM8u4Dcb4k0wcp9v\ntW1ZzLVVuwTvmrg7JBHjiSaB+x5wxm/r3FOiJDXdlAgFlytzqgcyeZMJVKKBQHyJ\njEGg/1720A0numuOCt71w/2G0bDmijuj1e6tH32MwRWcvRNZ19K9ssyDz2S9p68s\nYDhIxX69OWxwScTIHLY6J2t8txf/XMivL/636fPlDADvBEVTdlT606n8CcKUVQeq\npUVdG+lfAgMBAAECggEAP38SUA7B69eTfRpo658ycOs3Amr0JW4H/bb1rNeAul0K\nZhwd/HnU4E07y81xQmey5kN5ZeNrD5EvqkZvSyMJHV0EEahZStwhjCfnDB/cxyix\nZ+kFhv4y9eK+kFpUAhBy5nX6T0O+2T6WvzAwbmbVsZ+X8kJyPuF9m8ldcPlD0sce\ntj8NwVq1ys52eosqs7zi2vjt+eMcaY393l4ls+vNq8Yf27cfyFw45W45CH/97/Nu\n5AmuzlCOAfFF+z4OC5g4rei4E/Qgpxa7/uom+BVfv9G0DIGW/tU6Sne0+37uoGKt\nW6DzhgtebUtoYkG7ZJ05BTXGp2lwgVcNRoPwnKJDxQKBgQDT5wYPUBDW+FHbvZSp\nd1m1UQuXyerqOTA9smFaM8sr/UraeH85DJPEIEk8qsntMBVMhvD3Pw8uIUeFNMYj\naLmZFObsL+WctepXrVo5NB6RtLB/jZYxiKMatMLUJIYtcKIp+2z/YtKiWcLnwotB\nWdCjVnPTxpkurmF2fWP/eewZ+wKBgQDRMtJg7etjvKyjYNQ5fARnCc+XsI3gkBe1\nX9oeXfhyfZFeBXWnZzN1ITgFHplDznmBdxAyYGiQdbbkdKQSghviUQ0igBvoDMYy\n1rWcy+a17Mj98uyNEfmb3X2cC6WpvOZaGHwg9+GY67BThwI3FqHIbyk6Ko09WlTX\nQpRQjMzU7QKBgAfi1iflu+q0LR+3a3vvFCiaToskmZiD7latd9AKk2ocsBd3Woy9\n+hXXecJHPOKV4oUJlJgvAZqe5HGBqEoTEK0wyPNLSQlO/9ypd+0fEnArwFHO7CMF\nycQprAKHJXM1eOOFFuZeQCaInqdPZy1UcV5Szla4UmUZWkk1m24blHzXAoGBAMcA\nyH4qdbxX9AYrC1dvsSRvgcnzytMvX05LU0uF6tzGtG0zVlub4ahvpEHCfNuy44UT\nxRWW/oFFaWjjyFxO5sWggpUqNuHEnRopg3QXx22SRRTGbN45li/+QAocTkgsiRh1\nqEcYZsO4mPCsQqAy6E2p6RcK+Xa+omxvSnVhq0x1AoGAKr8GdkCl4CF6rieLMAQ7\nLNBuuoYGaHoh8l5E2uOQpzwxVy/nMBcAv+2+KqHEzHryUv1owOi6pMLv7A9mTFoS\n18B0QRLuz5fSOsVnmldfC9fpUc6H8cH1SINZpzajqQA74bPwELJjnzrCnH79TnHG\nJuElxA33rFEjbgbzdyrE768=\n-----END PRIVATE KEY-----\n",
          "client_email": "gspread-connection@sheets-api-connect-378620.iam.gserviceaccount.com",
          "client_id": "106625872877651920064",
          "auth_uri": "https://accounts.google.com/o/oauth2/auth",
          "token_uri": "https://oauth2.googleapis.com/token",
          "auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs",
          "client_x509_cert_url": "https://www.googleapis.com/robot/v1/metadata/x509/gspread-connection%40sheets-api-connect-378620.iam.gserviceaccount.com"
        }
     
        NFL_Data = st.secrets['NFL_Data']

        uri = st.secrets['mongo_uri']
        client = MongoClient(uri, retryWrites=True, serverSelectionTimeoutMS=100000)
        dfs_db = client["NFL_Database"]
        props_db = client["Props_DB"]

        gc = gspread.service_account_from_dict(credentials)
        gc2 = gspread.service_account_from_dict(credentials2)

        return gc, gc2, NFL_Data, props_db, dfs_db
    
gcservice_account, gcservice_account2, NFL_Data, props_db, dfs_db = init_conn()

game_format = {'Win%': '{:.2%}', 'Vegas': '{:.2%}', 'Win% Diff': '{:.2%}'}
american_format = {'First Inning Lead Percentage': '{:.2%}', 'Fifth Inning Lead Percentage': '{:.2%}'}

def calculate_poisson(row):
    mean_val = row['Mean_Outcome']
    threshold = row['Prop']
    cdf_value = stats.poisson.cdf(threshold, mean_val)
    probability = 1 - cdf_value
    return probability

@st.cache_resource(ttl=600)
def init_baselines():
    collection = dfs_db["Game_Betting_Model"] 
    cursor = collection.find()
    raw_display = pd.DataFrame(list(cursor))
    game_model = raw_display[['Team', 'Opp', 'Win%', 'Vegas', 'Win% Diff', 'Win Line', 'Vegas Line', 'Line Diff', 'PD Spread', 'Vegas Spread', 'Spread Diff']]
    
    collection = dfs_db["Player_Stats"] 
    cursor = collection.find()
    raw_display = pd.DataFrame(list(cursor))
    overall_stats = raw_display[['Player', 'Position', 'Team', 'Opp', 'rush_att', 'rec', 'dropbacks', 'rush_yards', 'rush_tds', 'rec_yards', 'rec_tds', 'pass_att', 'pass_yards', 'pass_tds', 'PPR', 'Half_PPR']]
    
    collection = dfs_db["Prop_Trends"] 
    cursor = collection.find()
    raw_display = pd.DataFrame(list(cursor))
    prop_trends = raw_display[['Player', 'over_prop', 'over_line', 'under_prop', 'under_line', 'book', 'prop_type', 'No Vig', 'Team', 'L3 Success', 'L6_Success', 'L10_success', 'L6 Avg', 'Projection',
                               'Proj Diff', 'Implied Over', 'Trending Over', 'Over Edge', 'Implied Under', 'Trending Under', 'Under Edge']]
    
    collection = dfs_db["DK_NFL_ROO"] 
    cursor = collection.find()

    raw_display = pd.DataFrame(list(cursor))
    raw_display = raw_display[['Player', 'Position', 'Team', 'Opp', 'Salary', 'Floor', 'Median', 'Ceiling', 'Top_finish', 'Top_5_finish', 'Top_10_finish', '20+%', '2x%', '3x%', '4x%',
                               'Own', 'Small_Field_Own', 'Large_Field_Own', 'Cash_Field_Own', 'CPT_Own', 'LevX', 'version', 'slate', 'timestamp', 'player_id', 'site']]
    load_display = raw_display[raw_display['Position'] != 'K']
    timestamp = load_display['timestamp'][0]
    
    collection = dfs_db["Prop_Trends"] 
    cursor = collection.find()
    raw_display = pd.DataFrame(list(cursor))
    prop_frame = raw_display[['Player', 'over_prop', 'over_line', 'under_prop', 'under_line', 'book', 'prop_type', 'No Vig', 'Team', 'L3 Success', 'L6_Success', 'L10_success', 'L6 Avg', 'Projection',
                               'Proj Diff', 'Implied Over', 'Trending Over', 'Over Edge', 'Implied Under', 'Trending Under', 'Under Edge']]
    
    collection = dfs_db['Pick6_Trends']
    cursor = collection.find()
    raw_display = pd.DataFrame(list(cursor))
    pick_frame = raw_display[['Player', 'over_prop', 'over_line', 'under_prop', 'under_line', 'book', 'prop_type', 'No Vig', 'Team', 'L3 Success', 'L6_Success', 'L10_success', 'L6 Avg', 'Projection',
                               'Proj Diff', 'Implied Over', 'Trending Over', 'Over Edge', 'Implied Under', 'Trending Under', 'Under Edge', 'last_name', 'P6_name', 'Full_name']]

    collection = props_db["NFL_Props"] 
    cursor = collection.find()

    raw_display = pd.DataFrame(list(cursor))
    market_props = raw_display[['Name', 'Position', 'Projection', 'PropType', 'OddsType', 'over_pay', 'under_pay']]
    market_props['over_prop'] = market_props['Projection']
    market_props['over_line'] = market_props['over_pay'].apply(lambda x: (x - 1) * 100 if x >= 2.0 else -100 / (x - 1))
    market_props['under_prop'] = market_props['Projection']
    market_props['under_line'] = market_props['under_pay'].apply(lambda x: (x - 1) * 100 if x >= 2.0 else -100 / (x - 1))

    return game_model, overall_stats, timestamp, prop_frame, prop_trends, pick_frame, market_props

def calculate_no_vig(row):
    def implied_probability(american_odds):
        if american_odds < 0:
            return (-american_odds) / ((-american_odds) + 100)
        else:
            return 100 / (american_odds + 100)

    over_line = row['over_line']
    under_line = row['under_line']
    over_prop = row['over_prop']
    
    over_prob = implied_probability(over_line)
    under_prob = implied_probability(under_line)
    
    total_prob = over_prob + under_prob
    no_vig_prob = (over_prob / total_prob + 0.5) * over_prop
    
    return no_vig_prob

game_model, overall_stats, timestamp, prop_frame, prop_trends, pick_frame, market_props = init_baselines()
qb_stats = overall_stats[overall_stats['Position'] == 'QB']
qb_stats = qb_stats.drop_duplicates(subset=['Player', 'Position'])
non_qb_stats = overall_stats[overall_stats['Position'] != 'QB']
non_qb_stats = non_qb_stats.drop_duplicates(subset=['Player', 'Position'])
team_dict = dict(zip(prop_frame['Player'], prop_frame['Team']))
t_stamp = f"Last Update: " + str(timestamp) + f" CST"

prop_table_options = ['NFL_GAME_PLAYER_PASSING_YARDS', 'NFL_GAME_PLAYER_RUSHING_YARDS', 'NFL_GAME_PLAYER_PASSING_ATTEMPTS', 'NFL_GAME_PLAYER_PASSING_TOUCHDOWNS', 'NFL_GAME_PLAYER_PASSING_COMPLETIONS', 'NFL_GAME_PLAYER_RUSHING_ATTEMPTS',
                      'NFL_GAME_PLAYER_RECEIVING_RECEPTIONS', 'NFL_GAME_PLAYER_RECEIVING_YARDS', 'NFL_GAME_PLAYER_RECEIVING_TOUCHDOWNS']
prop_format = {'L3 Success': '{:.2%}', 'L6_Success': '{:.2%}', 'L10_success': '{:.2%}', 'Trending Over': '{:.2%}', 'Trending Under': '{:.2%}',
               'Implied Over': '{:.2%}', 'Implied Under': '{:.2%}', 'Over Edge': '{:.2%}', 'Under Edge': '{:.2%}'}
all_sim_vars = ['NFL_GAME_PLAYER_PASSING_YARDS', 'NFL_GAME_PLAYER_RUSHING_YARDS', 'NFL_GAME_PLAYER_PASSING_ATTEMPTS', 'NFL_GAME_PLAYER_PASSING_TOUCHDOWNS', 'NFL_GAME_PLAYER_PASSING_COMPLETIONS', 'NFL_GAME_PLAYER_RUSHING_ATTEMPTS',
                      'NFL_GAME_PLAYER_RECEIVING_RECEPTIONS', 'NFL_GAME_PLAYER_RECEIVING_YARDS', 'NFL_GAME_PLAYER_RECEIVING_TOUCHDOWNS']
pick6_sim_vars = ['Rush + Rec Yards', 'Rush + Rec TDs', 'Passing Yards', 'Passing Attempts', 'Passing TDs', 'Completions', 'Rushing Yards', 'Receptions', 'Receiving Yards']
sim_all_hold = pd.DataFrame(columns=['Player', 'Team', 'Book', 'Prop Type', 'Prop', 'Mean_Outcome', 'Imp Over', 'Trending Over', 'Over%', 'Imp Under', 'Trending Under', 'Under%', 'Bet?', 'Edge'])

tab1, tab2, tab3, tab4, tab5, tab6, tab7 = st.tabs(["Game Betting Model", 'Prop Market', "QB Projections", "RB/WR/TE Projections", "Player Prop Trends", "Player Prop Simulations", "Stat Specific Simulations"])

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

with tab1:
    st.info(t_stamp)
    if st.button("Reset Data", key='reset1'):
              st.cache_data.clear()
              game_model, overall_stats, timestamp, prop_frame, prop_trends, pick_frame, market_props = init_baselines()
              qb_stats = overall_stats[overall_stats['Position'] == 'QB']
              qb_stats = qb_stats.drop_duplicates(subset=['Player', 'Position'])
              non_qb_stats = overall_stats[overall_stats['Position'] != 'QB']
              non_qb_stats = non_qb_stats.drop_duplicates(subset=['Player', 'Position'])
              team_dict = dict(zip(prop_frame['Player'], prop_frame['Team']))
              t_stamp = f"Last Update: " + str(timestamp) + f" CST"
    line_var1 = st.radio('How would you like to display odds?', options = ['Percentage', 'American'], key='line_var1')
    team_frame = game_model
    if line_var1 == 'Percentage':
        team_frame = team_frame[['Team', 'Opp', 'Win%', 'Vegas', 'Win% Diff', 'PD Spread', 'Vegas Spread', 'Spread Diff']]
        team_frame = team_frame.set_index('Team')
        try:
            st.dataframe(team_frame.style.background_gradient(axis=0).background_gradient(cmap='RdYlGn').format(game_format, precision=2), use_container_width = True)
        except:
            st.dataframe(team_frame.style.background_gradient(axis=0).background_gradient(cmap='RdYlGn').format(precision=2), use_container_width = True)
    if line_var1 == 'American':
        team_frame = team_frame[['Team', 'Opp', 'Win Line', 'Vegas Line', 'Line Diff', 'PD Spread', 'Vegas Spread', 'Spread Diff']]
        team_frame = team_frame.set_index('Team')
        st.dataframe(team_frame.style.background_gradient(axis=0).background_gradient(cmap='RdYlGn').format(precision=2), height = 1000, use_container_width = True)
    
    st.download_button(
        label="Export Team Model",
        data=convert_df_to_csv(team_frame),
        file_name='NFL_team_betting_export.csv',
        mime='text/csv',
        key='team_export',
    )

with tab2:
    st.info(t_stamp)
    if st.button("Reset Data", key='reset4'):
              st.cache_data.clear()
              game_model, overall_stats, timestamp, prop_frame, prop_trends, pick_frame, market_props = init_baselines()
              qb_stats = overall_stats[overall_stats['Position'] == 'QB']
              qb_stats = qb_stats.drop_duplicates(subset=['Player', 'Position'])
              non_qb_stats = overall_stats[overall_stats['Position'] != 'QB']
              non_qb_stats = non_qb_stats.drop_duplicates(subset=['Player', 'Position'])
              team_dict = dict(zip(prop_frame['Player'], prop_frame['Team']))
              t_stamp = f"Last Update: " + str(timestamp) + f" CST"
    market_type = st.selectbox('Select type of prop are you wanting to view', options = prop_table_options, key = 'market_type_key')
    disp_market = market_props.copy()
    disp_market = disp_market[disp_market['PropType'] == market_type]
    disp_market['No_Vig_Prop'] = disp_market.apply(calculate_no_vig, axis=1)
    fanduel_frame = disp_market[disp_market['OddsType'] == 'FANDUEL']
    fanduel_dict = dict(zip(fanduel_frame['Name'], fanduel_frame['No_Vig_Prop']))
    draftkings_frame = disp_market[disp_market['OddsType'] == 'DRAFTKINGS']
    draftkings_dict = dict(zip(draftkings_frame['Name'], draftkings_frame['No_Vig_Prop']))
    mgm_frame = disp_market[disp_market['OddsType'] == 'MGM']
    mgm_dict = dict(zip(mgm_frame['Name'], mgm_frame['No_Vig_Prop']))
    bet365_frame = disp_market[disp_market['OddsType'] == 'BET_365']
    bet365_dict = dict(zip(bet365_frame['Name'], bet365_frame['No_Vig_Prop']))

    disp_market['FANDUEL'] = disp_market['Name'].map(fanduel_dict)
    disp_market['DRAFTKINGS'] = disp_market['Name'].map(draftkings_dict)
    disp_market['MGM'] = disp_market['Name'].map(mgm_dict)
    disp_market['BET365'] = disp_market['Name'].map(bet365_dict)

    disp_market = disp_market[['Name', 'Position','FANDUEL', 'DRAFTKINGS', 'MGM', 'BET365']]
    disp_market = disp_market.drop_duplicates(subset=['Name'], keep='first', ignore_index=True)

    st.dataframe(disp_market.style.background_gradient(axis=1, subset=['FANDUEL', 'DRAFTKINGS', 'MGM', 'BET365'], cmap='RdYlGn').format(prop_format, precision=2), height = 1000, use_container_width = True)
    st.download_button(
        label="Export Market Props",
        data=convert_df_to_csv(disp_market),
        file_name='NFL_market_props_export.csv',
        mime='text/csv',
    )

with tab3:
    st.info(t_stamp)
    if st.button("Reset Data", key='reset2'):
              st.cache_data.clear()
              game_model, overall_stats, timestamp, prop_frame, prop_trends, pick_frame, market_props = init_baselines()
              qb_stats = overall_stats[overall_stats['Position'] == 'QB']
              qb_stats = qb_stats.drop_duplicates(subset=['Player', 'Position'])
              non_qb_stats = overall_stats[overall_stats['Position'] != 'QB']
              non_qb_stats = non_qb_stats.drop_duplicates(subset=['Player', 'Position'])
              team_dict = dict(zip(prop_frame['Player'], prop_frame['Team']))
              t_stamp = f"Last Update: " + str(timestamp) + f" CST"
    split_var1 = st.radio("Would you like to view all teams or specific ones?", ('All', 'Specific Teams'), key='split_var1')
    if split_var1 == 'Specific Teams':
        team_var1 = st.multiselect('Which teams would you like to include in the tables?', options = qb_stats['Team'].unique(), key='team_var1')
    elif split_var1 == 'All':
        team_var1 = qb_stats.Team.values.tolist()
    qb_stats = qb_stats[qb_stats['Team'].isin(team_var1)]
    qb_stats_disp = qb_stats.set_index('Player')
    qb_stats_disp = qb_stats_disp.sort_values(by='PPR', ascending=False)
    st.dataframe(qb_stats_disp.style.background_gradient(axis=0).background_gradient(cmap='RdYlGn').format(precision=2), height = 1000, use_container_width = True)
    st.download_button(
        label="Export Prop Model",
        data=convert_df_to_csv(qb_stats_disp),
        file_name='NFL_qb_stats_export.csv',
        mime='text/csv',
        key='NFL_qb_stats_export',
    )

with tab4:
    st.info(t_stamp)
    if st.button("Reset Data", key='reset3'):
              st.cache_data.clear()
              game_model, overall_stats, timestamp, prop_frame, prop_trends, pick_frame, market_props = init_baselines()
              qb_stats = overall_stats[overall_stats['Position'] == 'QB']
              qb_stats = qb_stats.drop_duplicates(subset=['Player', 'Position'])
              non_qb_stats = overall_stats[overall_stats['Position'] != 'QB']
              non_qb_stats = non_qb_stats.drop_duplicates(subset=['Player', 'Position'])
              team_dict = dict(zip(prop_frame['Player'], prop_frame['Team']))
              t_stamp = f"Last Update: " + str(timestamp) + f" CST"
    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_var2 = st.multiselect('Which teams would you like to include in the tables?', options = non_qb_stats['Team'].unique(), key='team_var2')
    elif split_var2 == 'All':
        team_var2 = non_qb_stats.Team.values.tolist()
    non_qb_stats = non_qb_stats[non_qb_stats['Team'].isin(team_var2)]
    non_qb_stats_disp = non_qb_stats.set_index('Player')
    non_qb_stats_disp = non_qb_stats_disp.sort_values(by='PPR', ascending=False)
    st.dataframe(non_qb_stats_disp.style.background_gradient(axis=0).background_gradient(cmap='RdYlGn').format(precision=2), height = 1000, use_container_width = True)
    st.download_button(
        label="Export Prop Model",
        data=convert_df_to_csv(non_qb_stats_disp),
        file_name='NFL_nonqb_stats_export.csv',
        mime='text/csv',
        key='NFL_nonqb_stats_export',
    )

with tab5:
    st.info(t_stamp)
    if st.button("Reset Data", key='reset5'):
              st.cache_data.clear()
              game_model, overall_stats, timestamp, prop_frame, prop_trends, pick_frame, market_props = init_baselines()
              qb_stats = overall_stats[overall_stats['Position'] == 'QB']
              qb_stats = qb_stats.drop_duplicates(subset=['Player', 'Position'])
              non_qb_stats = overall_stats[overall_stats['Position'] != 'QB']
              non_qb_stats = non_qb_stats.drop_duplicates(subset=['Player', 'Position'])
              team_dict = dict(zip(prop_frame['Player'], prop_frame['Team']))
              t_stamp = f"Last Update: " + str(timestamp) + f" CST"
    split_var5 = st.radio("Would you like to view all teams or specific ones?", ('All', 'Specific Teams'), key='split_var5')
    if split_var5 == 'Specific Teams':
        team_var5 = st.multiselect('Which teams would you like to include in the tables?', options = prop_trends['Team'].unique(), key='team_var5')
    elif split_var5 == 'All':
        team_var5 = prop_trends.Team.values.tolist()
    prop_type_var2 = st.selectbox('Select type of prop are you wanting to view', options = prop_table_options)
    book_var2 = st.selectbox('Select type of book do you want to view?', options = ['FANDUEL', 'BET365', 'DRAFTKINGS', 'CONSENSUS'])
    prop_frame_disp = prop_trends[prop_trends['Team'].isin(team_var5)]
    prop_frame_disp = prop_frame_disp[prop_frame_disp['book'] == book_var2]
    prop_frame_disp = prop_frame_disp[prop_frame_disp['prop_type'] == prop_type_var2]
    #prop_frame_disp = prop_frame_disp.set_index('Player')
    prop_frame_disp = prop_frame_disp.sort_values(by='Trending Over', ascending=False)
    st.dataframe(prop_frame_disp.style.background_gradient(axis=0).background_gradient(cmap='RdYlGn').format(prop_format, precision=2), height = 1000, use_container_width = True)
    st.download_button(
        label="Export Prop Trends Model",
        data=convert_df_to_csv(prop_frame_disp),
        file_name='NFL_prop_trends_export.csv',
        mime='text/csv',
    )

with tab6:
    st.info(t_stamp)
    if st.button("Reset Data", key='reset6'):
              st.cache_data.clear()
              game_model, overall_stats, timestamp, prop_frame, prop_trends, pick_frame, market_props = init_baselines()
              qb_stats = overall_stats[overall_stats['Position'] == 'QB']
              qb_stats = qb_stats.drop_duplicates(subset=['Player', 'Position'])
              non_qb_stats = overall_stats[overall_stats['Position'] != 'QB']
              non_qb_stats = non_qb_stats.drop_duplicates(subset=['Player', 'Position'])
              team_dict = dict(zip(prop_frame['Player'], prop_frame['Team']))
              t_stamp = f"Last Update: " + str(timestamp) + f" CST"
    col1, col2 = st.columns([1, 5])
    
    with col2:
        df_hold_container = st.empty()
        info_hold_container = st.empty()
        plot_hold_container = st.empty()
    
    with col1:
        player_check = st.selectbox('Select player to simulate props', options = overall_stats['Player'].unique())
        prop_type_var = st.selectbox('Select type of prop to simulate', options = ['Pass Yards', 'Pass TDs', 'Rush Yards', 'Rush TDs', 'Receptions', 'Rec Yards', 'Rec TDs', 'Fantasy', 'FD Fantasy', 'PrizePicks'])

        ou_var = st.selectbox('Select wether it is an over or under', options = ['Over', 'Under'])
        if prop_type_var == 'Pass Yards':
            prop_var = st.number_input('Type in the prop offered (i.e 5.5)', min_value = 100.0, max_value = 400.5, value = 250.5, step = .5)
        elif prop_type_var == 'Pass TDs':
            prop_var = st.number_input('Type in the prop offered (i.e 5.5)', min_value = 0.0, max_value = 5.5, value = 1.5, step = .5)
        elif prop_type_var == 'Rush Yards':
            prop_var = st.number_input('Type in the prop offered (i.e 5.5)', min_value = 0.0, max_value = 155.5, value = 25.5, step = .5)
        elif prop_type_var == 'Rush TDs':
            prop_var = st.number_input('Type in the prop offered (i.e 5.5)', min_value = 0.0, max_value = 5.5, value = 1.5, step = .5)
        elif prop_type_var == 'Receptions':
            prop_var = st.number_input('Type in the prop offered (i.e 5.5)', min_value = 0.0, max_value = 15.5, value = 5.5, step = .5)
        elif prop_type_var == 'Rec Yards':
            prop_var = st.number_input('Type in the prop offered (i.e 5.5)', min_value = 0.0, max_value = 155.5, value = 25.5, step = .5)
        elif prop_type_var == 'Rec TDs':
            prop_var = st.number_input('Type in the prop offered (i.e 5.5)', min_value = 0.0, max_value = 5.5, value = 1.5, step = .5)
        elif prop_type_var == 'Fantasy':
            prop_var = st.number_input('Type in the prop offered (i.e 5.5)', min_value = 0.0, max_value = 50.5, value = 10.5, step = .5)
        elif prop_type_var == 'FD Fantasy':
            prop_var = st.number_input('Type in the prop offered (i.e 5.5)', min_value = 0.0, max_value = 50.5, value = 10.5, step = .5)
        elif prop_type_var == 'PrizePicks':
            prop_var = st.number_input('Type in the prop offered (i.e 5.5)', min_value = 0.0, max_value = 50.5, value = 10.5, step = .5)
        line_var = st.number_input('Type in the line on the prop (i.e. -120)', min_value = -1000, max_value = 1000, value = -150, step = 1)
        line_var = line_var + 1

        if st.button('Simulate Prop'):
            with col2:
                   
                    with df_hold_container.container():

                        df = overall_stats

                        total_sims = 5000

                        df.replace("", 0, inplace=True)

                        player_var = df[df['Player'] == player_check]
                        player_var = player_var.reset_index()
                        
                        if prop_type_var == 'Pass Yards':
                            df['Median'] = df['pass_yards']
                        elif prop_type_var == 'Pass TDs':
                            df['Median'] = df['pass_tds']
                        elif prop_type_var == 'Rush Yards':
                            df['Median'] = df['rush_yards']
                        elif prop_type_var == 'Rush TDs':
                            df['Median'] = df['rush_tds']
                        elif prop_type_var == 'Receptions':
                            df['Median'] = df['rec']
                        elif prop_type_var == 'Rec Yards':
                            df['Median'] = df['rec_yards']
                        elif prop_type_var == 'Rec TDs':
                            df['Median'] = df['rec_tds']
                        elif prop_type_var == 'Fantasy':
                            df['Median'] = df['PPR']
                        elif prop_type_var == 'FD Fantasy':
                            df['Median'] = df['Half_PPF']
                        elif prop_type_var == 'PrizePicks':
                            df['Median'] = df['Half_PPF']

                        flex_file = df
                        flex_file['Floor'] = flex_file['Median'] * .25
                        flex_file['Ceiling'] = flex_file['Median'] + (flex_file['Median'] * 1.75)
                        flex_file['STD'] = flex_file['Median'] / 4
                        flex_file = flex_file[['Player', 'Floor', 'Median', 'Ceiling', 'STD']]

                        hold_file = flex_file
                        overall_file = flex_file
                        salary_file = flex_file

                        overall_players = overall_file[['Player']]

                        for x in range(0,total_sims):
                            overall_file[x] = np.random.normal(overall_file['Median'],overall_file['STD'])

                        overall_file=overall_file.drop(['Player', 'Floor', 'Median', 'Ceiling', 'STD'], axis=1)
                        overall_file.astype('int').dtypes

                        players_only = hold_file[['Player']]

                        player_outcomes = pd.merge(players_only, overall_file, left_index=True, right_index=True)

                        players_only['Mean_Outcome'] = overall_file.mean(axis=1)
                        players_only['Prop'] = prop_var
                        players_only['poisson_var'] = players_only.apply(calculate_poisson, axis=1)
                        players_only['10%'] = overall_file.quantile(0.1, axis=1)
                        players_only['90%'] = overall_file.quantile(0.9, axis=1)
                        if ou_var == 'Over':
                            players_only['beat_prop'] = np.where(players_only['Prop'] <= 3, players_only['poisson_var'], overall_file[overall_file > prop_var].count(axis=1)/float(total_sims))
                        elif ou_var == 'Under':
                            players_only['beat_prop'] = np.where(players_only['Prop'] <= 3, 1 - players_only['poisson_var'], (overall_file[overall_file < prop_var].count(axis=1)/float(total_sims)))

                        players_only['implied_odds'] = np.where(line_var <= 0, (-(line_var)/((-(line_var))+100)), 100/(line_var+100))

                        players_only['Player'] = hold_file[['Player']]

                        final_outcomes = players_only[['Player', '10%', 'Mean_Outcome', '90%', 'implied_odds', 'beat_prop']]
                        final_outcomes['Bet?'] = np.where(final_outcomes['beat_prop'] - final_outcomes['implied_odds'] >= .10, "Bet", "No Bet")
                        final_outcomes = final_outcomes[final_outcomes['Player'] == player_check]
                        player_outcomes = player_outcomes[player_outcomes['Player'] == player_check]
                        player_outcomes = player_outcomes.drop(columns=['Player']).transpose()
                        player_outcomes = player_outcomes.reset_index()
                        player_outcomes.columns = ['Instance', 'Outcome']

                        x1 = player_outcomes.Outcome.to_numpy()

                        print(x1)

                        hist_data = [x1]

                        group_labels = ['player outcomes']

                        fig = px.histogram(
                                player_outcomes, x='Outcome')
                        fig.add_vline(x=prop_var, line_dash="dash", line_color="green")

                        with df_hold_container:
                            df_hold_container = st.empty()
                            format_dict = {'10%': '{:.2f}', 'Mean_Outcome': '{:.2f}','90%': '{:.2f}', 'beat_prop': '{:.2%}','implied_odds': '{:.2%}'}
                            st.dataframe(final_outcomes.style.format(format_dict), use_container_width = True)

                        with info_hold_container:
                            st.info('The Y-axis is the percent of times in simulations that the player reaches certain thresholds, while the X-axis is the threshold to be met. The Green dotted line is the prop you entered. You can hover over any spot and see the percent to reach that mark.')

                        with plot_hold_container:
                            st.dataframe(player_outcomes, use_container_width = True)
                            plot_hold_container = st.empty()
                            st.plotly_chart(fig, use_container_width=True)

with tab7:
    st.info(t_stamp)
    st.info('The Over and Under percentages are a compositve percentage based on simulations, historical performance, and implied probabilities, and may be different than you would expect based purely on the median projection. Likewise, the Edge of a bet is not the only indicator of if you should make the bet or not as the suggestion is using a base acceptable threshold to determine how much edge you should have for each stat category.')
    if st.button("Reset Data/Load Data", key='reset7'):
              st.cache_data.clear()
              game_model, overall_stats, timestamp, prop_frame, prop_trends, pick_frame, market_props = init_baselines()
              qb_stats = overall_stats[overall_stats['Position'] == 'QB']
              qb_stats = qb_stats.drop_duplicates(subset=['Player', 'Position'])
              non_qb_stats = overall_stats[overall_stats['Position'] != 'QB']
              non_qb_stats = non_qb_stats.drop_duplicates(subset=['Player', 'Position'])
              team_dict = dict(zip(prop_frame['Player'], prop_frame['Team']))
              t_stamp = f"Last Update: " + str(timestamp) + f" CST"
        
    settings_container = st.empty()
    df_hold_container = st.empty()
    export_container = st.empty()

    with settings_container.container():
        col1, col2, col3, col4 = st.columns([3, 3, 3, 3])
        with col1:
            game_select_var = st.selectbox('Select prop source', options = ['Aggregate', 'Pick6'])
        with col2:
            book_select_var = st.selectbox('Select book', options = ['ALL', 'BET_365', 'DRAFTKINGS', 'FANDUEL', 'MGM', 'UNIBET', 'WILLIAM_HILL'])
            if book_select_var == 'ALL':
                book_selections = ['BET_365', 'DRAFTKINGS', 'FANDUEL', 'MGM', 'UNIBET', 'WILLIAM_HILL']
            else:
                book_selections = [book_select_var]
            if game_select_var == 'Aggregate':
                prop_df = prop_frame[['Player', 'book', 'over_prop', 'over_line', 'under_line', 'prop_type', 'Trending Over', 'Trending Under']]
            elif game_select_var == 'Pick6':
                prop_df = pick_frame[['Player', 'book', 'over_prop', 'over_line', 'under_line', 'prop_type', 'Trending Over', 'Trending Under']]
                book_selections = ['Pick6']
        with col3:
            if game_select_var == 'Aggregate':
                prop_type_var = st.selectbox('Select prop category', options = ['All Props', 'NFL_GAME_PLAYER_PASSING_YARDS', 'NFL_GAME_PLAYER_RUSHING_YARDS', 'NFL_GAME_PLAYER_PASSING_ATTEMPTS', 'NFL_GAME_PLAYER_PASSING_TOUCHDOWNS', 'NFL_GAME_PLAYER_RUSHING_ATTEMPTS',
                                                'NFL_GAME_PLAYER_RECEIVING_RECEPTIONS', 'NFL_GAME_PLAYER_RECEIVING_YARDS', 'NFL_GAME_PLAYER_RECEIVING_TOUCHDOWNS'])
            elif game_select_var == 'Pick6':
                prop_type_var = st.selectbox('Select prop category', options = ['All Props', 'Rush + Rec Yards', 'Rush + Rec TDs', 'Passing Yards', 'Passing Attempts', 'Passing TDs', 'Rushing Attempts', 'Rushing Yards', 'Receptions', 'Receiving Yards', 'Receiving TDs'])
        with col4:
            st.download_button(
                label="Download Prop Source",
                data=convert_df_to_csv(prop_df),
                file_name='NFL_prop_source.csv',
                mime='text/csv',
                key='prop_source',
            )

    if st.button('Simulate Prop Category'):
                
        with df_hold_container.container():
            if prop_type_var == 'All Props':
                if game_select_var == 'Aggregate':
                    prop_df_raw = prop_frame[['Player', 'book', 'over_prop', 'over_line', 'under_line', 'prop_type', 'Trending Over', 'Trending Under']]
                    sim_vars = ['NFL_GAME_PLAYER_PASSING_YARDS', 'NFL_GAME_PLAYER_RUSHING_YARDS', 'NFL_GAME_PLAYER_PASSING_ATTEMPTS', 'NFL_GAME_PLAYER_PASSING_TOUCHDOWNS', 'NFL_GAME_PLAYER_RUSHING_ATTEMPTS',
                                'NFL_GAME_PLAYER_RECEIVING_RECEPTIONS', 'NFL_GAME_PLAYER_RECEIVING_YARDS', 'NFL_GAME_PLAYER_RECEIVING_TOUCHDOWNS']
                elif game_select_var == 'Pick6':
                    prop_df_raw = pick_frame[['Player', 'book', 'over_prop', 'over_line', 'under_line', 'prop_type', 'Trending Over', 'Trending Under']]
                    sim_vars = ['Rush + Rec Yards', 'Rush + Rec TDs', 'Passing Yards', 'Passing Attempts', 'Passing TDs', 'Rushing Attempts', 'Rushing Yards', 'Receptions', 'Receiving Yards', 'Receiving TDs']
                
                player_df = overall_stats.copy()
                
                for prop in sim_vars:
                        
                    for books in book_selections:
                        prop_df = prop_df_raw[prop_df_raw['book'] == books]
                        prop_df = prop_df[prop_df['prop_type'] == prop]
                        prop_df = prop_df[~((prop_df['over_prop'] < 15) & (prop_df['prop_type'] == 'NFL_GAME_PLAYER_RUSHING_YARDS'))]
                        prop_df = prop_df[['Player', 'book', 'over_prop', 'over_line', 'under_line', 'prop_type', 'Trending Over', 'Trending Under']]
                        prop_df.rename(columns={"over_prop": "Prop"}, inplace = True)
                        prop_df['Over'] = 1 / prop_df['over_line']
                        prop_df['Under'] = 1 / prop_df['under_line']

                        prop_dict = dict(zip(prop_df.Player, prop_df.Prop))
                        prop_type_dict = dict(zip(prop_df.Player, prop_df.prop_type))
                        book_dict = dict(zip(prop_df.Player, prop_df.book))
                        over_dict = dict(zip(prop_df.Player, prop_df.Over))
                        under_dict = dict(zip(prop_df.Player, prop_df.Under))
                        trending_over_dict = dict(zip(prop_df.Player, prop_df['Trending Over']))
                        trending_under_dict = dict(zip(prop_df.Player, prop_df['Trending Under']))

                        player_df['book'] = player_df['Player'].map(book_dict)
                        player_df['Prop'] = player_df['Player'].map(prop_dict)
                        player_df['prop_type'] = player_df['Player'].map(prop_type_dict)
                        player_df['Trending Over'] = player_df['Player'].map(trending_over_dict)
                        player_df['Trending Under'] = player_df['Player'].map(trending_under_dict)

                        df = player_df.reset_index(drop=True)

                        team_dict = dict(zip(df.Player, df.Team))
                        
                        total_sims = 1000

                        df.replace("", 0, inplace=True)
                        
                        if prop == "NFL_GAME_PLAYER_PASSING_YARDS" or prop == "Passing Yards":
                            df['Median'] = df['pass_yards']
                        elif prop == "NFL_GAME_PLAYER_RUSHING_YARDS" or prop == "Rushing Yards":
                            df['Median'] = df['rush_yards']
                        elif prop == "NFL_GAME_PLAYER_PASSING_ATTEMPTS" or prop == "Passing Attempts":
                            df['Median'] = df['pass_att']
                        elif prop == "NFL_GAME_PLAYER_PASSING_TOUCHDOWNS" or prop == "Passing TDs":
                            df['Median'] = df['pass_tds']
                        elif prop == "NFL_GAME_PLAYER_RUSHING_ATTEMPTS" or prop == "Rushing Attempts":
                            df['Median'] = df['rush_att']
                        elif prop == "NFL_GAME_PLAYER_RECEIVING_RECEPTIONS" or prop == "Receptions":
                            df['Median'] = df['rec']
                        elif prop == "NFL_GAME_PLAYER_RECEIVING_YARDS" or prop == "Receiving Yards":
                            df['Median'] = df['rec_yards']
                        elif prop == "NFL_GAME_PLAYER_RECEIVING_TOUCHDOWNS" or prop == "Receiving TDs":
                            df['Median'] = df['rec_tds']
                        elif prop == "Rush + Rec Yards":
                            df['Median'] = df['rush_yards'] + df['rec_yards']
                        elif prop == "Rush + Rec TDs":
                            df['Median'] = df['rush_tds'] + df['rec_tds']
                            
                        flex_file = df.copy()
                        flex_file['Floor'] = flex_file['Median'] * .25
                        flex_file['Ceiling'] = flex_file['Median'] + (flex_file['Median'] * 1.75)
                        flex_file['STD'] = flex_file['Median'] / 4
                        flex_file['Prop'] = flex_file['Player'].map(prop_dict)
                        flex_file = flex_file[['Player', 'book', 'Prop', 'Floor', 'Median', 'Ceiling', 'STD']]

                        hold_file = flex_file.copy()
                        overall_file = flex_file.copy()
                        prop_file = flex_file.copy()
                                
                        overall_players = overall_file[['Player']]

                        for x in range(0,total_sims):    
                            prop_file[x] = prop_file['Prop']

                        prop_file = prop_file.drop(['Player', 'book', 'Prop', 'Floor', 'Median', 'Ceiling', 'STD'], axis=1)

                        for x in range(0,total_sims):
                            overall_file[x] = np.random.normal(overall_file['Median'],overall_file['STD'])

                        overall_file=overall_file.drop(['Player', 'book', 'Prop', 'Floor', 'Median', 'Ceiling', 'STD'], axis=1)

                        players_only = hold_file[['Player']]

                        player_outcomes = pd.merge(players_only, overall_file, left_index=True, right_index=True)

                        prop_check = (overall_file - prop_file)

                        players_only['Mean_Outcome'] = overall_file.mean(axis=1)
                        players_only['Book'] = players_only['Player'].map(book_dict)
                        players_only['Prop'] = players_only['Player'].map(prop_dict)
                        players_only['Trending Over'] = players_only['Player'].map(trending_over_dict)
                        players_only['Trending Under'] = players_only['Player'].map(trending_under_dict)
                        players_only['poisson_var'] = players_only.apply(calculate_poisson, axis=1)
                        players_only['10%'] = overall_file.quantile(0.1, axis=1)
                        players_only['90%'] = overall_file.quantile(0.9, axis=1)
                        players_only['Over'] = np_where(players_only['Prop'] <= 3, players_only['poisson_var'], prop_check[prop_check > 0].count(axis=1)/float(total_sims))
                        players_only['Imp Over'] = players_only['Player'].map(over_dict)
                        players_only['Over%'] = players_only[["Over", "Imp Over", "Trending Over"]].mean(axis=1)
                        players_only['Under'] = np_where(players_only['Prop'] <= 3, 1 - players_only['poisson_var'], prop_check[prop_check < 0].count(axis=1)/float(total_sims))
                        players_only['Imp Under'] = players_only['Player'].map(under_dict)
                        players_only['Under%'] = players_only[["Under", "Imp Under", "Trending Under"]].mean(axis=1)
                        players_only['Prop_avg'] = players_only['Prop'].mean() / 100
                        players_only['prop_threshold'] = .10
                        players_only = players_only[players_only['Mean_Outcome'] > 0]
                        players_only['Over_diff'] = players_only['Over%'] - players_only['Imp Over']
                        players_only['Under_diff'] = players_only['Under%'] - players_only['Imp Under']
                        players_only['Bet_check'] = np.where(players_only['Over_diff'] > players_only['Under_diff'], players_only['Over_diff'] , players_only['Under_diff'])
                        players_only['Bet_suggest'] = np.where(players_only['Over_diff'] > players_only['Under_diff'], "Over" , "Under")
                        players_only['Bet?'] = np.where(players_only['Bet_check'] >= players_only['prop_threshold'], players_only['Bet_suggest'], "No Bet")
                        players_only['Edge'] = players_only['Bet_check']
                        players_only['Prop Type'] = prop

                        players_only['Player'] = hold_file[['Player']]
                        players_only['Team'] = players_only['Player'].map(team_dict)

                        leg_outcomes = players_only[['Player', 'Team', 'Book', 'Prop Type', 'Prop', 'Mean_Outcome', 'Imp Over', 'Trending Over', 'Over%', 'Imp Under', 'Trending Under', 'Under%', 'Bet?', 'Edge']]
                        sim_all_hold = pd.concat([sim_all_hold, leg_outcomes], ignore_index=True)
                        
                        final_outcomes = sim_all_hold
                        st.write(f'finished {prop} for {books}')
                    
            elif prop_type_var != 'All Props':

                player_df = overall_stats.copy()

                if game_select_var == 'Aggregate':
                    prop_df_raw = prop_frame[['Player', 'book', 'over_prop', 'over_line', 'under_line', 'prop_type', 'Trending Over', 'Trending Under']]
                elif game_select_var == 'Pick6':
                    prop_df_raw = pick_frame[['Player', 'book', 'over_prop', 'over_line', 'under_line', 'prop_type', 'Trending Over', 'Trending Under']]
                    
                for books in book_selections:
                    prop_df = prop_df_raw[prop_df_raw['book'] == books]
                    
                    if prop_type_var == "NFL_GAME_PLAYER_PASSING_YARDS":
                        prop_df = prop_df[prop_df['prop_type'] == 'NFL_GAME_PLAYER_PASSING_YARDS']
                    elif prop_type_var == "Passing Yards":
                        prop_df = prop_df[prop_df['prop_type'] == 'Passing Yards']
                    elif prop_type_var == "NFL_GAME_PLAYER_RUSHING_YARDS":
                        prop_df = prop_df[prop_df['prop_type'] == 'NFL_GAME_PLAYER_RUSHING_YARDS']
                    elif prop_type_var == "Rushing Yards":
                        prop_df = prop_df[prop_df['prop_type'] == 'Rushing Yards']
                    elif prop_type_var == "NFL_GAME_PLAYER_PASSING_ATTEMPTS":
                        prop_df = prop_df[prop_df['prop_type'] == 'NFL_GAME_PLAYER_PASSING_ATTEMPTS']
                    elif prop_type_var == "Passing Attempts":
                        prop_df = prop_df[prop_df['prop_type'] == 'Passing Attempts']
                    elif prop_type_var == "NFL_GAME_PLAYER_PASSING_TOUCHDOWNS":
                        prop_df = prop_df[prop_df['prop_type'] == 'NFL_GAME_PLAYER_PASSING_TOUCHDOWNS']
                    elif prop_type_var == "Passing TDs":
                        prop_df = prop_df[prop_df['prop_type'] == 'Passing TDs']
                    elif prop_type_var == "NFL_GAME_PLAYER_RUSHING_ATTEMPTS":
                        prop_df = prop_df[prop_df['prop_type'] == 'NFL_GAME_PLAYER_RUSHING_ATTEMPTS']
                    elif prop_type_var == "Rushing Attempts":
                        prop_df = prop_df[prop_df['prop_type'] == 'Rushing Attempts']
                    elif prop_type_var == "NFL_GAME_PLAYER_RECEIVING_RECEPTIONS":
                        prop_df = prop_df[prop_df['prop_type'] == 'NFL_GAME_PLAYER_RECEIVING_RECEPTIONS']
                    elif prop_type_var == "Receptions":
                        prop_df = prop_df[prop_df['prop_type'] == 'Receptions']
                    elif prop_type_var == "NFL_GAME_PLAYER_RECEIVING_YARDS":
                        prop_df = prop_df[prop_df['prop_type'] == 'NFL_GAME_PLAYER_RECEIVING_YARDS']
                    elif prop_type_var == "Receiving Yards":
                        prop_df = prop_df[prop_df['prop_type'] == 'Receiving Yards']
                    elif prop_type_var == "NFL_GAME_PLAYER_RECEIVING_TOUCHDOWNS":
                        prop_df = prop_df[prop_df['prop_type'] == 'NFL_GAME_PLAYER_RECEIVING_TOUCHDOWNS']
                    elif prop_type_var == "Receiving TDs":
                        prop_df = prop_df[prop_df['prop_type'] == 'Receiving TDs']
                    elif prop_type_var == "Rush + Rec Yards":
                        prop_df = prop_df[prop_df['prop_type'] == 'Rush + Rec Yards']
                    elif prop_type_var == "Rush + Rec TDs":
                        prop_df = prop_df[prop_df['prop_type'] == 'Rush + Rec TDs']

                    prop_df = prop_df[['Player', 'book', 'over_prop', 'over_line', 'under_line', 'prop_type', 'Trending Over', 'Trending Under']]
                    prop_df = prop_df.rename(columns={"over_prop": "Prop"})
                    prop_df['Over'] = 1 / prop_df['over_line']
                    prop_df['Under'] = 1 / prop_df['under_line']

                    prop_dict = dict(zip(prop_df.Player, prop_df.Prop))
                    prop_type_dict = dict(zip(prop_df.Player, prop_df.prop_type))
                    book_dict = dict(zip(prop_df.Player, prop_df.book))
                    over_dict = dict(zip(prop_df.Player, prop_df.Over))
                    under_dict = dict(zip(prop_df.Player, prop_df.Under))
                    trending_over_dict = dict(zip(prop_df.Player, prop_df['Trending Over']))
                    trending_under_dict = dict(zip(prop_df.Player, prop_df['Trending Under']))

                    player_df['book'] = player_df['Player'].map(book_dict)
                    player_df['Prop'] = player_df['Player'].map(prop_dict)
                    player_df['prop_type'] = player_df['Player'].map(prop_type_dict)
                    player_df['Trending Over'] = player_df['Player'].map(trending_over_dict)
                    player_df['Trending Under'] = player_df['Player'].map(trending_under_dict)

                    df = player_df.reset_index(drop=True)

                    team_dict = dict(zip(df.Player, df.Team))
                    
                    total_sims = 1000

                    df.replace("", 0, inplace=True)
                    
                    if prop_type_var == "NFL_GAME_PLAYER_PASSING_YARDS" or prop_type_var == "Passing Yards":
                        df['Median'] = df['pass_yards']
                    elif prop_type_var == "NFL_GAME_PLAYER_RUSHING_YARDS" or prop_type_var == "Rushing Yards":
                        df['Median'] = df['rush_yards']
                    elif prop_type_var == "NFL_GAME_PLAYER_PASSING_ATTEMPTS" or prop_type_var == "Passing Attempts":
                        df['Median'] = df['pass_att']
                    elif prop_type_var == "NFL_GAME_PLAYER_PASSING_TOUCHDOWNS" or prop_type_var == "Passing TDs":
                        df['Median'] = df['pass_tds']
                    elif prop_type_var == "NFL_GAME_PLAYER_RUSHING_ATTEMPTS" or prop_type_var == "Rushing Attempts":
                        df['Median'] = df['rush_att']
                    elif prop_type_var == "NFL_GAME_PLAYER_RECEIVING_RECEPTIONS" or prop_type_var == "Receptions":
                        df['Median'] = df['rec']
                    elif prop_type_var == "NFL_GAME_PLAYER_RECEIVING_YARDS" or prop_type_var == "Receiving Yards":
                        df['Median'] = df['rec_yards']
                    elif prop_type_var == "NFL_GAME_PLAYER_RECEIVING_TOUCHDOWNS" or prop_type_var == "Receiving TDs":
                        df['Median'] = df['rec_tds']
                    elif prop_type_var == "Rush + Rec Yards":
                        df['Median'] = df['rush_yards'] + df['rec_yards']
                    elif prop_type_var == "Rush + Rec TDs":
                        df['Median'] = df['rush_tds'] + df['rec_tds']

                    flex_file = df.copy()
                    flex_file['Floor'] = flex_file['Median'] * .25
                    flex_file['Ceiling'] = flex_file['Median'] + (flex_file['Median'] * 1.75)
                    flex_file['STD'] = flex_file['Median'] / 4
                    flex_file['Prop'] = flex_file['Player'].map(prop_dict)
                    flex_file = flex_file[['Player', 'book', 'Prop', 'Floor', 'Median', 'Ceiling', 'STD']]

                    hold_file = flex_file.copy()
                    overall_file = flex_file.copy()
                    prop_file = flex_file.copy()
                            
                    overall_players = overall_file[['Player']]

                    for x in range(0,total_sims):    
                        prop_file[x] = prop_file['Prop']

                    prop_file = prop_file.drop(['Player', 'book', 'Prop', 'Floor', 'Median', 'Ceiling', 'STD'], axis=1)

                    for x in range(0,total_sims):
                        overall_file[x] = np.random.normal(overall_file['Median'],overall_file['STD'])

                    overall_file=overall_file.drop(['Player', 'book', 'Prop', 'Floor', 'Median', 'Ceiling', 'STD'], axis=1)

                    players_only = hold_file[['Player']]

                    player_outcomes = pd.merge(players_only, overall_file, left_index=True, right_index=True)

                    prop_check = (overall_file - prop_file)

                    players_only['Mean_Outcome'] = overall_file.mean(axis=1)
                    players_only['Book'] = players_only['Player'].map(book_dict)
                    players_only['Prop'] = players_only['Player'].map(prop_dict)
                    players_only['Trending Over'] = players_only['Player'].map(trending_over_dict)
                    players_only['Trending Under'] = players_only['Player'].map(trending_under_dict)
                    players_only['poisson_var'] = players_only.apply(calculate_poisson, axis=1)
                    players_only['10%'] = overall_file.quantile(0.1, axis=1)
                    players_only['90%'] = overall_file.quantile(0.9, axis=1)
                    players_only['Over'] = np_where(players_only['Prop'] <= 3, players_only['poisson_var'], prop_check[prop_check > 0].count(axis=1)/float(total_sims))
                    players_only['Imp Over'] = players_only['Player'].map(over_dict)
                    players_only['Over%'] = players_only[["Over", "Imp Over", "Trending Over"]].mean(axis=1)
                    players_only['Under'] = np_where(players_only['Prop'] <= 3, 1 - players_only['poisson_var'], prop_check[prop_check < 0].count(axis=1)/float(total_sims))
                    players_only['Imp Under'] = players_only['Player'].map(under_dict)
                    players_only['Under%'] = players_only[["Under", "Imp Under", "Trending Under"]].mean(axis=1)
                    players_only['Prop_avg'] = players_only['Prop'].mean() / 100
                    players_only['prop_threshold'] = .10
                    players_only = players_only[players_only['Mean_Outcome'] > 0]
                    players_only['Over_diff'] = players_only['Over%'] - players_only['Imp Over']
                    players_only['Under_diff'] = players_only['Under%'] - players_only['Imp Under']
                    players_only['Bet_check'] = np.where(players_only['Over_diff'] > players_only['Under_diff'], players_only['Over_diff'] , players_only['Under_diff'])
                    players_only['Bet_suggest'] = np.where(players_only['Over_diff'] > players_only['Under_diff'], "Over" , "Under")
                    players_only['Bet?'] = np.where(players_only['Bet_check'] >= players_only['prop_threshold'], players_only['Bet_suggest'], "No Bet")
                    players_only['Edge'] = players_only['Bet_check']
                    players_only['Prop Type'] = prop_type_var

                    players_only['Player'] = hold_file[['Player']]
                    players_only['Team'] = players_only['Player'].map(team_dict)

                    leg_outcomes = players_only[['Player', 'Team', 'Book', 'Prop Type', 'Prop', 'Mean_Outcome', 'Imp Over', 'Trending Over', 'Over%', 'Imp Under', 'Trending Under', 'Under%', 'Bet?', 'Edge']]
                    sim_all_hold = pd.concat([sim_all_hold, leg_outcomes], ignore_index=True)
                    
                    final_outcomes = sim_all_hold
                    st.write(f'finished {prop_type_var} for {books}')
            
            final_outcomes = final_outcomes.dropna()
            if game_select_var == 'Pick6':
                final_outcomes = final_outcomes.drop_duplicates(subset=['Player', 'Prop Type'])
            final_outcomes = final_outcomes.sort_values(by='Edge', ascending=False)

            with df_hold_container:
                df_hold_container = st.empty()
                st.dataframe(final_outcomes.style.background_gradient(axis=0).background_gradient(cmap='RdYlGn').format(precision=2), use_container_width = True)
            with export_container:
                export_container = st.empty()
                st.download_button(
                    label="Export Projections",
                    data=convert_df_to_csv(final_outcomes),
                    file_name='NFL_prop_proj.csv',
                    mime='text/csv',
                    key='prop_proj',
                )