File size: 51,843 Bytes
ac9a5f3
2805ddf
 
 
 
ac9a5f3
 
2805ddf
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ac9a5f3
 
 
 
 
 
 
 
 
2805ddf
ac9a5f3
 
5345f4f
ac9a5f3
 
2805ddf
ac9a5f3
 
 
 
 
 
 
2532b19
a4b28d5
2805ddf
 
 
 
 
 
 
a4b28d5
2805ddf
 
 
 
 
 
 
a4b28d5
2805ddf
6446a66
 
 
 
 
 
a4b28d5
6446a66
 
 
 
 
 
 
a4b28d5
 
 
 
 
 
 
 
 
6446a66
a4b28d5
 
 
 
 
 
 
6446a66
5345f4f
 
 
8c3c2bd
5a77151
5345f4f
 
 
 
 
a6b4e2c
5a77151
5345f4f
 
a4b28d5
5345f4f
a4b28d5
2805ddf
ac9a5f3
 
 
373e2da
ac9a5f3
2805ddf
 
ac9a5f3
 
2805ddf
ac9a5f3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
373e2da
2805ddf
ac9a5f3
 
 
 
 
1ef4e2b
ac9a5f3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
274eae9
 
 
ac9a5f3
 
 
 
 
 
 
 
 
 
 
 
274eae9
ac9a5f3
 
 
 
 
 
2805ddf
 
 
ac9a5f3
ffa148f
 
1ef4e2b
ac9a5f3
2805ddf
 
ac9a5f3
f275819
2805ddf
f275819
 
a4b28d5
 
2805ddf
 
ac9a5f3
2805ddf
f275819
ac9a5f3
 
f275819
ac9a5f3
 
a4b28d5
ac9a5f3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
274eae9
ac9a5f3
 
 
 
 
 
 
 
2805ddf
ac9a5f3
 
 
2805ddf
ac9a5f3
 
 
 
 
 
 
 
 
 
 
 
 
 
2805ddf
ac9a5f3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2805ddf
ac9a5f3
 
 
 
 
 
 
 
 
 
 
 
0cf815a
ac9a5f3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5345f4f
ac9a5f3
 
 
 
 
 
 
 
5345f4f
ac9a5f3
 
373e2da
ac9a5f3
d0ce248
ac9a5f3
 
 
 
 
 
 
 
 
 
 
 
 
d0ce248
ac9a5f3
 
 
 
 
 
5345f4f
ac9a5f3
 
 
 
 
 
 
 
 
d0ce248
ac9a5f3
3285510
ac9a5f3
d0ce248
ac9a5f3
 
 
 
 
 
 
 
 
 
 
d0ce248
ac9a5f3
 
 
 
 
5345f4f
ac9a5f3
 
 
 
 
 
 
 
3285510
ac9a5f3
 
 
 
 
 
 
d6075ef
ac9a5f3
 
 
d6075ef
ac9a5f3
 
 
d6075ef
ac9a5f3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1ef4e2b
 
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
import pulp
import numpy as np
import pandas as pd
import streamlit as st
import gspread
from itertools import combinations
import time

@st.cache_resource
def init_conn():
          scope = ['https://www.googleapis.com/auth/spreadsheets',
                    "https://www.googleapis.com/auth/drive"]
          
          credentials = {
            "type": "service_account",
            "project_id": "sheets-api-connect-378620",
            "private_key_id": "1005124050c80d085e2c5b344345715978dd9cc9",
            "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"
          }

          gc = gspread.service_account_from_dict(credentials)
          return gc

st.set_page_config(layout="wide")

gc = init_conn()

wrong_acro = ['WSH', 'AZ']
right_acro = ['WAS', 'ARI']

game_format = {'Win Percentage': '{:.2%}','First Inning Lead Percentage': '{:.2%}',
              'Fifth Inning Lead Percentage': '{:.2%}', '8+ runs': '{:.2%}', 'DK LevX': '{:.2%}', 'FD LevX': '{:.2%}'}

team_roo_format = {'Top Score%': '{:.2%}','0 Runs': '{:.2%}', '1 Run': '{:.2%}', '2 Runs': '{:.2%}', '3 Runs': '{:.2%}', '4 Runs': '{:.2%}',
                   '5 Runs': '{:.2%}','6 Runs': '{:.2%}', '7 Runs': '{:.2%}', '8 Runs': '{:.2%}', '9 Runs': '{:.2%}', '10 Runs': '{:.2%}'}

player_roo_format = {'Top_finish': '{:.2%}','Top_5_finish': '{:.2%}', 'Top_10_finish': '{:.2%}', '20+%': '{:.2%}', '2x%': '{:.2%}', '3x%': '{:.2%}',
                   '4x%': '{:.2%}','GPP%': '{:.2%}'}

expose_format = {'Proj Own': '{:.2%}','Exposure': '{:.2%}'}

all_dk_player_projections = 'https://docs.google.com/spreadsheets/d/1I_1Ve3F4tftgfLQQoRKOJ351XfEG48s36OxXUKxmgS8/edit#gid=1391856348'

@st.cache_resource(ttl=299)
def init_baselines():
    sh = gc.open_by_url(all_dk_player_projections)
    worksheet = sh.worksheet('SD_Projections')
    load_display = pd.DataFrame(worksheet.get_all_records())
    load_display.replace('', np.nan, inplace=True)
    raw_display = load_display.dropna(subset=['PPR'])
    raw_display.rename(columns={"name": "Player", "PPR": "Median"}, inplace = True)
    raw_display = raw_display[['Player', 'Salary', 'Position', 'Team', 'Opp', 'Median', 'Own', 'rush_yards', 'rec']]
    dk_roo_raw = raw_display.loc[raw_display['Median'] > 0]

    worksheet = sh.worksheet('FD_SD_Projections')
    load_display = pd.DataFrame(worksheet.get_all_records())
    load_display.replace('', np.nan, inplace=True)
    raw_display = load_display.dropna(subset=['Half_PPR'])
    raw_display.rename(columns={"name": "Player", "Half_PPR": "Median"}, inplace = True)
    raw_display = raw_display[['Player', 'Salary', 'Position', 'Team', 'Opp', 'Median', 'Own', 'rush_yards', 'rec']]
    fd_roo_raw = raw_display.loc[raw_display['Median'] > 0]

    worksheet = sh.worksheet('SD_Projections_2')
    load_display = pd.DataFrame(worksheet.get_all_records())
    load_display.replace('', np.nan, inplace=True)
    raw_display = load_display.dropna(subset=['PPR'])
    raw_display.rename(columns={"name": "Player", "PPR": "Median"}, inplace = True)
    raw_display = raw_display[['Player', 'Salary', 'Position', 'Team', 'Opp', 'Median', 'Own', 'rush_yards', 'rec']]
    dk_roo_raw_2 = raw_display.loc[raw_display['Median'] > 0]

    worksheet = sh.worksheet('FD_SD_Projections_2')
    load_display = pd.DataFrame(worksheet.get_all_records())
    load_display.replace('', np.nan, inplace=True)
    raw_display = load_display.dropna(subset=['Half_PPR'])
    raw_display.rename(columns={"name": "Player", "Half_PPR": "Median"}, inplace = True)
    raw_display = raw_display[['Player', 'Salary', 'Position', 'Team', 'Opp', 'Median', 'Own', 'rush_yards', 'rec']]
    fd_roo_raw_2 = raw_display.loc[raw_display['Median'] > 0]
    
    worksheet = sh.worksheet('SD_Projections_3')
    load_display = pd.DataFrame(worksheet.get_all_records())
    load_display.replace('', np.nan, inplace=True)
    raw_display = load_display.dropna(subset=['PPR'])
    raw_display.rename(columns={"name": "Player", "PPR": "Median"}, inplace = True)
    raw_display = raw_display[['Player', 'Salary', 'Position', 'Team', 'Opp', 'Median', 'Own', 'rush_yards', 'rec']]
    dk_roo_raw_3 = raw_display.loc[raw_display['Median'] > 0]

    worksheet = sh.worksheet('FD_SD_Projections_3')
    load_display = pd.DataFrame(worksheet.get_all_records())
    load_display.replace('', np.nan, inplace=True)
    raw_display = load_display.dropna(subset=['Half_PPR'])
    raw_display.rename(columns={"name": "Player", "Half_PPR": "Median"}, inplace = True)
    raw_display = raw_display[['Player', 'Salary', 'Position', 'Team', 'Opp', 'Median', 'Own', 'rush_yards', 'rec']]
    fd_roo_raw_3 = raw_display.loc[raw_display['Median'] > 0]

    worksheet = sh.worksheet('SD_Projections')
    load_display = pd.DataFrame(worksheet.get_all_records())
    load_display.replace('', np.nan, inplace=True)
    load_display.rename(columns={"PPR": "Median", "name": "Player"}, inplace = True)
    raw_display = load_display.dropna(subset=['Median'])
    dk_ids = dict(zip(raw_display['Player'], raw_display['player_id']))
    
    worksheet = sh.worksheet('FD_SD_Projections')
    load_display = pd.DataFrame(worksheet.get_all_records())
    load_display.replace('', np.nan, inplace=True)
    load_display.rename(columns={"Half_PPR": "Median", "name": "Player"}, inplace = True)
    raw_display = load_display.dropna(subset=['Median'])
    fd_ids = dict(zip(raw_display['Player'], raw_display['player_id']))

    return dk_roo_raw, dk_roo_raw_2, dk_roo_raw_3, fd_roo_raw, fd_roo_raw_2, fd_roo_raw_3, dk_ids, fd_ids

dk_roo_raw, dk_roo_raw_2, dk_roo_raw_3, fd_roo_raw, fd_roo_raw_2, fd_roo_raw_3, dkid_dict, fdid_dict = init_baselines()

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

tab1, tab2, tab3 = st.tabs(['Uploads and Info', 'Range of Outcomes', 'Optimizer'])

with tab1:
    st.info("The Projections file can have any columns in any order, but must contain columns explicitly named: 'Player', 'Salary', 'Position', 'Team', 'Opp', 'rush_yards', 'rec', 'Median', and 'Own'. For the purposes of this showdown optimizer, only include FLEX positions, salaries, and medians. The optimizer logic will handle the rest!")
    col1, col2 = st.columns([1, 5])

    with col1:
        proj_file = st.file_uploader("Upload Projections File", key = 'proj_uploader')
    
        if proj_file is not None:
                  try:
                            proj_dataframe = pd.read_csv(proj_file)
                            proj_dataframe = proj_dataframe.loc[proj_dataframe['Median'] > 0]
                            try: 
                                  proj_dataframe['Own'] = proj_dataframe['Own'].str.replace('%', '').astype(float)
                            except:
                                  pass
                  except:
                            proj_dataframe = pd.read_excel(proj_file)
                            proj_dataframe = proj_dataframe.loc[proj_dataframe['Median'] > 0]
                            try: 
                                  proj_dataframe['Own'] = proj_dataframe['Own'].str.replace('%', '').astype(float)
                            except:
                                  pass
    with col2:
        if proj_file is not None:  
                  st.dataframe(proj_dataframe.style.background_gradient(axis=0).background_gradient(cmap='RdYlGn').format(precision=2), use_container_width = True)

with tab2:
    col1, col2 = st.columns([1, 5])
    with col1:
        if st.button("Load/Reset Data", key='reset2'):
              st.cache_data.clear()
              dk_roo_raw, dk_roo_raw_2, dk_roo_raw_3, fd_roo_raw, fd_roo_raw_2, fd_roo_raw_3, dkid_dict, fdid_dict = init_baselines()
        slate_var2 = st.radio("Which data are you loading?", ('Paydirt (Main)', 'Paydirt (Secondary)', 'Paydirt (Third)', 'User'), key='slate_var2')
        site_var2 = st.radio("What table would you like to display?", ('Draftkings', 'Fanduel'), key='site_var2')
        if slate_var2 == 'User':
            raw_baselines = proj_dataframe
        elif slate_var2 != 'User':
            if site_var2 == 'Draftkings':
                if slate_var2 == 'Paydirt (Main)':
                    raw_baselines = dk_roo_raw
                elif slate_var2 == 'Paydirt (Secondary)':
                    raw_baselines = dk_roo_raw_2
                elif slate_var2 == 'Paydirt (Third)':
                    raw_baselines = dk_roo_raw_3
            elif site_var2 == 'Fanduel':
                if slate_var2 == 'Paydirt (Main)':
                    raw_baselines = fd_roo_raw
                elif slate_var2 == 'Paydirt (Secondary)':
                    raw_baselines = fd_roo_raw_2
                elif slate_var2 == 'Paydirt (Third)':
                    raw_baselines = fd_roo_raw_3
    
    with col2:
        hold_container = st.empty()
        if st.button('Create Range of Outcomes for Slate'):
            with hold_container:
                working_roo = raw_baselines
                working_roo = working_roo.loc[working_roo['Median'] > 0]
                if site_var2 == 'Draftkings':
                    working_roo.rename(columns={"name": "Player", "rush_yards": "Rush Yards", "rec": "Receptions", "Median": "Fantasy"}, inplace = True)
                elif site_var2 == 'Fanduel':
                    working_roo.rename(columns={"name": "Player", "rush_yards": "Rush Yards", "rec": "Receptions", "Median": "Fantasy"}, inplace = True)
                working_roo.replace('', 0, inplace=True)
                own_dict = dict(zip(working_roo.Player, working_roo.Own))
                team_dict = dict(zip(working_roo.Player, working_roo.Team))
                opp_dict = dict(zip(working_roo.Player, working_roo.Opp))
                total_sims = 1000
  
                flex_file = working_roo[['Player', 'Position', 'Salary', 'Fantasy', 'Rush Yards', 'Receptions']]
                flex_file.rename(columns={"Fantasy": "Median", "Pos": "Position"}, inplace = True)
                flex_file['Floor'] = np.where(flex_file['Position'] == 'QB',(flex_file['Median']*.25) + (flex_file['Rush Yards']*.01),flex_file['Median']*.25)
                flex_file['Ceiling'] = np.where(flex_file['Position'] == 'QB',(flex_file['Median'] + flex_file['Floor']) + (flex_file['Rush Yards']*.01), flex_file['Median'] + flex_file['Floor'] + flex_file['Receptions'])
                flex_file['Ceiling'] = flex_file['Ceiling'].fillna(15)
                flex_file['STD'] = np.where(flex_file['Position'] != 'QB', (flex_file['Median']/4) + flex_file['Receptions'], (flex_file['Median']/4))
                flex_file['STD'] = flex_file['Ceiling'].fillna(5)
                flex_file = flex_file[['Player', 'Position', 'Salary', '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):    
                    salary_file[x] = salary_file['Salary']
  
                salary_file=salary_file.drop(['Player', 'Position', 'Salary', 'Floor', 'Median', 'Ceiling', 'STD'], axis=1)
                salary_file.astype('int').dtypes
  
                salary_file = salary_file.div(1000)
  
                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', 'Position', 'Salary', 'Floor', 'Median', 'Ceiling', 'STD'], axis=1)
                overall_file.astype('int').dtypes
  
                players_only = hold_file[['Player']]
                raw_lineups_file = players_only
  
                for x in range(0,total_sims):
                    maps_dict = {'proj_map':dict(zip(hold_file.Player,hold_file[x]))}
                    raw_lineups_file[x] = sum([raw_lineups_file['Player'].map(maps_dict['proj_map'])])
                    players_only[x] = raw_lineups_file[x].rank(ascending=False)
  
                players_only=players_only.drop(['Player'], axis=1)
                players_only.astype('int').dtypes
  
                salary_2x_check = (overall_file - (salary_file*2))
                salary_3x_check = (overall_file - (salary_file*3))
                salary_4x_check = (overall_file - (salary_file*4))
  
                players_only['Average_Rank'] = players_only.mean(axis=1)
                players_only['Top_finish'] = players_only[players_only == 1].count(axis=1)/total_sims
                players_only['Top_5_finish'] = players_only[players_only <= 5].count(axis=1)/total_sims
                players_only['Top_10_finish'] = players_only[players_only <= 10].count(axis=1)/total_sims
                players_only['20+%'] = overall_file[overall_file >= 20].count(axis=1)/float(total_sims)
                players_only['2x%'] = salary_2x_check[salary_2x_check >= 1].count(axis=1)/float(total_sims)
                players_only['3x%'] = salary_3x_check[salary_3x_check >= 1].count(axis=1)/float(total_sims)
                players_only['4x%'] = salary_4x_check[salary_4x_check >= 1].count(axis=1)/float(total_sims)
  
                players_only['Player'] = hold_file[['Player']]
  
                final_outcomes = players_only[['Player', 'Top_finish', 'Top_5_finish', 'Top_10_finish', '20+%', '2x%', '3x%', '4x%']]
  
                final_Proj = pd.merge(hold_file, final_outcomes, on="Player")
                final_Proj = final_Proj[['Player', 'Position', 'Salary', 'Floor', 'Median', 'Ceiling', 'Top_finish', 'Top_5_finish', 'Top_10_finish', '20+%', '2x%', '3x%', '4x%']]
                final_Proj['Own'] = final_Proj['Player'].map(own_dict)
                final_Proj['Team'] = final_Proj['Player'].map(team_dict)
                final_Proj['Opp'] = final_Proj['Player'].map(opp_dict)
                final_Proj = final_Proj[['Player', 'Position', 'Team', 'Opp', 'Salary', 'Floor', 'Median', 'Ceiling', 'Top_finish', 'Top_5_finish', 'Top_10_finish', '20+%', '2x%', '3x%', '4x%', 'Own']]
                final_Proj['Projection Rank'] = final_Proj.Median.rank(pct = True)
                final_Proj['Own Rank'] = final_Proj.Own.rank(pct = True)
                final_Proj['LevX'] = 0
                final_Proj['LevX'] = final_Proj[['Projection Rank', 'Top_5_finish']].mean(axis=1) + final_Proj['4x%'] - final_Proj['Own Rank']
                final_Proj['CPT_Own'] = final_Proj['Own'] / 4
                final_Proj['CPT_Proj'] = final_Proj['Median'] * 1.5 
                final_Proj['CPT_Salary'] = final_Proj['Salary'] * 1.5       

                export_final_proj = final_Proj
                export_final_proj['ID'] = export_final_proj['Player'].map(dkid_dict)
  
                display_Proj = final_Proj[['Player', 'Position', 'Team', 'Opp', 'Salary', 'Floor', 'Median', 'Ceiling', 'Top_finish', 'Top_5_finish', 'Top_10_finish', '20+%', '2x%', '3x%', '4x%', 'Own', 'CPT_Own', 'LevX']]
                display_Proj = display_Proj.set_index('Player')
                display_Proj = display_Proj.sort_values(by='Median', ascending=False)
  
            with hold_container:
                hold_container = st.empty()
                display_Proj = display_Proj
                st.dataframe(display_Proj.style.background_gradient(axis=0).background_gradient(cmap='RdYlGn').format(player_roo_format, precision=2), use_container_width = True)
  
            st.download_button(
                    label="Export Tables",
                    data=convert_df_to_csv(export_final_proj),
                    file_name='Custom_NFL_overall_export.csv',
                    mime='text/csv',
            )

with tab3:
    col1, col2 = st.columns([1, 5])
    with col1:
        if st.button("Load/Reset Data", key='reset1'):
              st.cache_data.clear()
              dk_roo_raw, dk_roo_raw_2, dk_roo_raw_3, fd_roo_raw, fd_roo_raw_2, fd_roo_raw_3, dkid_dict, fdid_dict = init_baselines()
              for key in st.session_state.keys():
                  del st.session_state[key]
        slate_var1 = st.radio("Which data are you loading?", ('Paydirt (Main)', 'Paydirt (Secondary)', 'Paydirt (Third)', 'User'), key='slate_var1')
        site_var1 = st.selectbox("What site is the showdown on?", ('Draftkings', 'Fanduel'), key='site_var1')
        if site_var1 == 'Draftkings':
              if slate_var1 == 'User':
                  raw_baselines = proj_dataframe
              elif slate_var1 == 'Paydirt (Main)':
                  raw_baselines = dk_roo_raw
              elif slate_var1 == 'Paydirt (Secondary)':
                  raw_baselines = dk_roo_raw_2
              elif slate_var1 == 'Paydirt (Third)':
                  raw_baselines = dk_roo_raw_3
        elif site_var1 == 'Fanduel':
              if slate_var1 == 'User':
                  st.info("Showdown on Fanduel sucks, you should not do that, but I understand degen's gotta degen")
                  raw_baselines = proj_dataframe
              elif slate_var1 == 'Paydirt (Main)':
                  st.info("Showdown on Fanduel sucks, you should not do that, but I understand degen's gotta degen")
                  raw_baselines = fd_roo_raw
              elif slate_var1 == 'Paydirt (Secondary)':
                  st.info("Showdown on Fanduel sucks, you should not do that, but I understand degen's gotta degen")
                  raw_baselines = fd_roo_raw_2
              elif slate_var1 == 'Paydirt (Third)':
                  st.info("Showdown on Fanduel sucks, you should not do that, but I understand degen's gotta degen")
                  raw_baselines = fd_roo_raw_3
        contest_var1 = st.selectbox("What contest type are you optimizing for?", ('Cash', 'Small Field GPP', 'Large Field GPP'), key='contest_var1')
        lock_var1 = st.multiselect("Are there any players you want to use in all lineups in the CAPTAIN (Lock Button)?", options = raw_baselines['Player'].unique(), key='lock_var1')
        lock_var2 = st.multiselect("Are there any players you want to use in all lineups in the FLEX (Lock Button)?", options = raw_baselines['Player'].unique(), key='lock_var2')
        avoid_var1 = st.multiselect("Are there any players you want to remove from the pool (Drop Button)?", options = raw_baselines['Player'].unique(), key='avoid_var1')
        trim_choice1 = st.selectbox("Allow overowned lineups?", options = ['Yes', 'No'])
        linenum_var1 = st.number_input("How many lineups would you like to produce?", min_value = 1, max_value = 300, value = 20, step = 1, key='linenum_var1')
        if trim_choice1 == 'Yes':
            trim_var1 = 0
        elif trim_choice1 == 'No':
            trim_var1 = 1
        if site_var1 == 'Draftkings':
            min_sal1 = st.number_input('Min Salary', min_value = 35000, max_value = 49900, value = 49000, step = 100, key='min_sal1')
            max_sal1 = st.number_input('Max Salary', min_value = 35000, max_value = 50000, value = 50000, step = 100, key='max_sal1')
        elif site_var1 == 'Fanduel':
            min_sal1 = st.number_input('Min Salary', min_value = 45000, max_value = 59900, value = 59000, step = 100, key='min_sal1')
            max_sal1 = st.number_input('Max Salary', min_value = 45000, max_value = 60000, value = 60000, step = 100, key='max_sal1')
    
        if contest_var1 == 'Small Field GPP':
            if site_var1 == 'Draftkings':
                ownframe = raw_baselines.copy()
                ownframe['Own%'] = np.where((ownframe['Position'] == 'QB') & (ownframe['Own'] - ownframe.loc[ownframe['Position'] == 'QB', 'Own'].mean() >= 0), ownframe['Own'] * (5 * (ownframe['Own'] - ownframe.loc[ownframe['Position'] == 'QB', 'Own'].mean())/100) + ownframe.loc[ownframe['Position'] == 'QB', 'Own'].mean(), ownframe['Own'])
                ownframe['Own%'] = np.where((ownframe['Position'] != 'QB') & (ownframe['Own'] - ownframe.loc[ownframe['Position'] != 'QB', 'Own'].mean() >= 0), ownframe['Own'] * (5 * (ownframe['Own'] - ownframe.loc[ownframe['Position'] != 'QB', 'Own'].mean())/100) + ownframe.loc[ownframe['Position'] != 'QB', 'Own'].mean(), ownframe['Own%'])
                ownframe['Own%'] = np.where(ownframe['Own%'] > 85, 85, ownframe['Own%'])
                ownframe['Own'] = ownframe['Own%'] * (500 / ownframe['Own%'].sum())
            elif site_var1 == 'Fanduel':
                ownframe = raw_baselines.copy()
                ownframe['Own%'] = np.where((ownframe['Position'] == 'QB') & (ownframe['Own'] - ownframe.loc[ownframe['Position'] == 'QB', 'Own'].mean() >= 0), ownframe['Own'] * (5 * (ownframe['Own'] - ownframe.loc[ownframe['Position'] == 'QB', 'Own'].mean())/50) + ownframe.loc[ownframe['Position'] == 'QB', 'Own'].mean(), ownframe['Own'])
                ownframe['Own%'] = np.where((ownframe['Position'] != 'QB') & (ownframe['Own'] - ownframe.loc[ownframe['Position'] != 'QB', 'Own'].mean() >= 0), ownframe['Own'] * (5 * (ownframe['Own'] - ownframe.loc[ownframe['Position'] != 'QB', 'Own'].mean())/150) + ownframe.loc[ownframe['Position'] != 'QB', 'Own'].mean(), ownframe['Own%'])
                ownframe['Own%'] = np.where(ownframe['Own%'] > 75, 75, ownframe['Own%'])
                ownframe['Own'] = ownframe['Own%'] * (400 / ownframe['Own%'].sum())
        elif contest_var1 == 'Large Field GPP':
            if site_var1 == 'Draftkings':
                ownframe = raw_baselines.copy()
                ownframe['Own%'] = np.where((ownframe['Position'] == 'QB') & (ownframe['Own'] - ownframe.loc[ownframe['Position'] == 'QB', 'Own'].mean() >= 0), ownframe['Own'] * (2.5 * (ownframe['Own'] - ownframe.loc[ownframe['Position'] == 'QB', 'Own'].mean())/100) + ownframe.loc[ownframe['Position'] == 'QB', 'Own'].mean(), ownframe['Own'])
                ownframe['Own%'] = np.where((ownframe['Position'] != 'QB') & (ownframe['Own'] - ownframe.loc[ownframe['Position'] != 'QB', 'Own'].mean() >= 0), ownframe['Own'] * (2.5 * (ownframe['Own'] - ownframe.loc[ownframe['Position'] != 'QB', 'Own'].mean())/100) + ownframe.loc[ownframe['Position'] != 'QB', 'Own'].mean(), ownframe['Own%'])
                ownframe['Own%'] = np.where(ownframe['Own%'] > 75, 75, ownframe['Own%'])
                ownframe['Own'] = ownframe['Own%'] * (500 / ownframe['Own%'].sum())
            elif site_var1 == 'Fanduel':
                ownframe = raw_baselines.copy()
                ownframe['Own%'] = np.where((ownframe['Position'] == 'QB') & (ownframe['Own'] - ownframe.loc[ownframe['Position'] == 'QB', 'Own'].mean() >= 0), ownframe['Own'] * (2.5 * (ownframe['Own'] - ownframe.loc[ownframe['Position'] == 'QB', 'Own'].mean())/50) + ownframe.loc[ownframe['Position'] == 'QB', 'Own'].mean(), ownframe['Own'])
                ownframe['Own%'] = np.where((ownframe['Position'] != 'QB') & (ownframe['Own'] - ownframe.loc[ownframe['Position'] != 'QB', 'Own'].mean() >= 0), ownframe['Own'] * (2.5 * (ownframe['Own'] - ownframe.loc[ownframe['Position'] != 'QB', 'Own'].mean())/150) + ownframe.loc[ownframe['Position'] != 'QB', 'Own'].mean(), ownframe['Own%'])
                ownframe['Own%'] = np.where(ownframe['Own%'] > 75, 75, ownframe['Own%'])
                ownframe['Own'] = ownframe['Own%'] * (400 / ownframe['Own%'].sum())
        elif contest_var1 == 'Cash':
            if site_var1 == 'Draftkings':
                ownframe = raw_baselines.copy()
                ownframe['Own%'] = np.where((ownframe['Position'] == 'QB') & (ownframe['Own'] - ownframe.loc[ownframe['Position'] == 'QB', 'Own'].mean() >= 0), ownframe['Own'] * (6 * (ownframe['Own'] - ownframe.loc[ownframe['Position'] == 'QB', 'Own'].mean())/100) + ownframe.loc[ownframe['Position'] == 'QB', 'Own'].mean(), ownframe['Own'])
                ownframe['Own%'] = np.where((ownframe['Position'] != 'QB') & (ownframe['Own'] - ownframe.loc[ownframe['Position'] != 'QB', 'Own'].mean() >= 0), ownframe['Own'] * (6 * (ownframe['Own'] - ownframe.loc[ownframe['Position'] != 'QB', 'Own'].mean())/100) + ownframe.loc[ownframe['Position'] != 'QB', 'Own'].mean(), ownframe['Own%'])
                ownframe['Own%'] = np.where(ownframe['Own%'] > 90, 90, ownframe['Own%'])
                ownframe['Own'] = ownframe['Own%'] * (500 / ownframe['Own%'].sum())
            elif site_var1 == 'Fanduel':
                ownframe = raw_baselines.copy()
                ownframe['Own%'] = np.where((ownframe['Position'] == 'QB') & (ownframe['Own'] - ownframe.loc[ownframe['Position'] == 'QB', 'Own'].mean() >= 0), ownframe['Own'] * (6 * (ownframe['Own'] - ownframe.loc[ownframe['Position'] == 'QB', 'Own'].mean())/50) + ownframe.loc[ownframe['Position'] == 'QB', 'Own'].mean(), ownframe['Own'])
                ownframe['Own%'] = np.where((ownframe['Position'] != 'QB') & (ownframe['Own'] - ownframe.loc[ownframe['Position'] != 'QB', 'Own'].mean() >= 0), ownframe['Own'] * (6 * (ownframe['Own'] - ownframe.loc[ownframe['Position'] != 'QB', 'Own'].mean())/150) + ownframe.loc[ownframe['Position'] != 'QB', 'Own'].mean(), ownframe['Own%'])
                ownframe['Own%'] = np.where(ownframe['Own%'] > 75, 75, ownframe['Own%'])
                ownframe['Own'] = ownframe['Own%'] * (400 / ownframe['Own%'].sum())
        export_baselines = ownframe[['Player', 'Salary', 'Position', 'Team', 'Opp', 'Median', 'Own']]
        export_baselines['CPT_Proj'] = export_baselines['Median'] * 1.5
        export_baselines['CPT_Salary'] = export_baselines['Salary'] * 1.5
        export_baselines['ID'] = export_baselines['Player'].map(dkid_dict)
        display_baselines = ownframe[['Player', 'Salary', 'Position', 'Team', 'Opp', 'Median', 'Own']]
        display_baselines['CPT Own'] = display_baselines['Own'] / 4
        display_baselines = display_baselines.sort_values(by='Median', ascending=False)
        display_baselines['cpt_lock'] = np.where(display_baselines['Player'].isin(lock_var1), 1, 0)
        display_baselines['lock'] = np.where(display_baselines['Player'].isin(lock_var2), 1, 0)
          
        st.session_state.display_baselines = display_baselines.copy()
        st.session_state.export_baselines = export_baselines.copy()
        
        index_check = pd.DataFrame()
        flex_proj = pd.DataFrame()
        cpt_proj = pd.DataFrame()
        
        if site_var1 == 'Draftkings':
            cpt_proj['Player'] = display_baselines['Player']
            cpt_proj['Salary'] = display_baselines['Salary'] * 1.5
            cpt_proj['Position'] = display_baselines['Position']
            cpt_proj['Team'] = display_baselines['Team']
            cpt_proj['Opp'] = display_baselines['Opp']
            cpt_proj['Median'] = display_baselines['Median'] * 1.5
            cpt_proj['Own'] = display_baselines['CPT Own']
            cpt_proj['lock'] = display_baselines['cpt_lock']
            cpt_proj['roster'] = 'CPT'
            if len(lock_var1) > 0:
                cpt_proj = cpt_proj[cpt_proj['lock'] == 1]
            if len(lock_var2) > 0:
                cpt_proj = cpt_proj[~cpt_proj['Player'].isin(lock_var2)]
            
            flex_proj['Player'] = display_baselines['Player']
            flex_proj['Salary'] = display_baselines['Salary']
            flex_proj['Position'] = display_baselines['Position']
            flex_proj['Team'] = display_baselines['Team']
            flex_proj['Opp'] = display_baselines['Opp']
            flex_proj['Median'] = display_baselines['Median']
            flex_proj['Own'] = display_baselines['Own']
            flex_proj['lock'] = display_baselines['lock']
            flex_proj['roster'] = 'FLEX'
        elif site_var1 == 'Fanduel':
            cpt_proj['Player'] = display_baselines['Player']
            cpt_proj['Salary'] = display_baselines['Salary']
            cpt_proj['Position'] = display_baselines['Position']
            cpt_proj['Team'] = display_baselines['Team']
            cpt_proj['Opp'] = display_baselines['Opp']
            cpt_proj['Median'] = display_baselines['Median'] * 1.5
            cpt_proj['Own'] = display_baselines['CPT Own'] *.75
            cpt_proj['lock'] = display_baselines['cpt_lock']
            cpt_proj['roster'] = 'CPT'
            
            flex_proj['Player'] = display_baselines['Player']
            flex_proj['Salary'] = display_baselines['Salary']
            flex_proj['Position'] = display_baselines['Position']
            flex_proj['Team'] = display_baselines['Team']
            flex_proj['Opp'] = display_baselines['Opp']
            flex_proj['Median'] = display_baselines['Median']
            flex_proj['Own'] = display_baselines['Own']
            flex_proj['lock'] = display_baselines['lock']
            flex_proj['roster'] = 'FLEX'
        
        combo_file = pd.concat([cpt_proj, flex_proj], ignore_index=True)
    
    with col2:
        display_container = st.empty()
        display_dl_container = st.empty()
        optimize_container = st.empty()
        download_container = st.empty()
        freq_container = st.empty()
        if st.button('Optimize'):
            for key in st.session_state.keys():
                del st.session_state[key]
            max_proj = 1000
            max_own = 1000
            total_proj = 0
            total_own = 0
            display_container = st.empty()
            display_dl_container = st.empty()
            optimize_container = st.empty()
            download_container = st.empty()
            freq_container = st.empty()
            lineup_display = []
            check_list = []
            lineups = []
            portfolio = pd.DataFrame()
            x = 1
    
            with st.spinner('Wait for it...'):
                with optimize_container:
    
                        while x <= linenum_var1:
                            sorted_lineup = []
                            p_used = []
                            
                            raw_proj_file = combo_file
                            raw_flex_file = raw_proj_file.dropna(how='all')
                            raw_flex_file = raw_flex_file.loc[raw_flex_file['Median'] > 0]
                            flex_file = raw_flex_file
                            flex_file.rename(columns={"Own": "Proj DK Own%"}, inplace = True)
                            flex_file['name_var'] = flex_file['Player']
                            flex_file['lock'] = np.where(flex_file['Player'].isin(lock_var2), 1, 0)
                            flex_file = flex_file[~flex_file['Player'].isin(avoid_var1)]
                            flex_file['Player'] = np.where(flex_file['roster'] == 'CPT', flex_file['Player'] + ' - CPT', flex_file['Player'] + ' - FLEX')
                            player_ids = flex_file.index
    
                            overall_players = flex_file[['Player']]
                            overall_players['player_var_add'] = flex_file.index
                            overall_players['player_var'] = 'player_vars_' + overall_players['player_var_add'].astype(str)
    
                            player_vars = pulp.LpVariable.dicts("player_vars", flex_file.index, 0, 1, pulp.LpInteger)
                            total_score = pulp.LpProblem("Fantasy_Points_Problem", pulp.LpMaximize)
                            player_match = dict(zip(overall_players['player_var'], overall_players['Player']))
                            player_index_match = dict(zip(overall_players['player_var'], overall_players['player_var_add']))
    
                            player_own = dict(zip(flex_file['Player'], flex_file['Proj DK Own%']))
                            player_team = dict(zip(flex_file['Player'], flex_file['Team']))
                            player_pos = dict(zip(flex_file['Player'], flex_file['Position']))
                            player_sal = dict(zip(flex_file['Player'], flex_file['Salary']))
                            player_proj = dict(zip(flex_file['Player'], flex_file['Median']))
    
                            obj_points = {idx: (flex_file['Median'][idx]) for idx in flex_file.index}
                            total_score += sum([player_vars[idx]*obj_points[idx] for idx in flex_file.index])
    
                            obj_points_max = {idx: (flex_file['Median'][idx]) for idx in flex_file.index}
                            obj_own_max = {idx: (flex_file['Proj DK Own%'][idx]) for idx in flex_file.index}
    
                            obj_salary = {idx: (flex_file['Salary'][idx]) for idx in flex_file.index}
                            total_score += pulp.lpSum([player_vars[idx]*obj_salary[idx] for idx in flex_file.index]) <= max_sal1
                            total_score += pulp.lpSum([player_vars[idx]*obj_salary[idx] for idx in flex_file.index]) >= min_sal1
    
                            if site_var1 == 'Draftkings':
                                
                                for flex in flex_file['lock'].unique():
                                    sub_idx = flex_file[flex_file['lock'] == 1].index
                                    total_score += pulp.lpSum([player_vars[idx] for idx in sub_idx]) == len(lock_var2)
                                
                                for flex in flex_file['roster'].unique():
                                    sub_idx = flex_file[flex_file['roster'] == "CPT"].index
                                    total_score += pulp.lpSum([player_vars[idx] for idx in sub_idx]) == 1
                                
                                for flex in flex_file['roster'].unique():
                                    sub_idx = flex_file[flex_file['roster'] == "FLEX"].index
                                    total_score += pulp.lpSum([player_vars[idx] for idx in sub_idx]) == 5
                                    
                                for playerid in player_ids:
                                    total_score += pulp.lpSum([player_vars[i] for i in player_ids if 
                                                       (flex_file['name_var'][i] == flex_file['name_var'][playerid])]) <= 1
    
                            elif site_var1 == 'Fanduel':
                                
                                for flex in flex_file['lock'].unique():
                                    sub_idx = flex_file[flex_file['lock'] == 1].index
                                    total_score += pulp.lpSum([player_vars[idx] for idx in sub_idx]) == len(lock_var2)
                                
                                for flex in flex_file['Position'].unique():
                                    sub_idx = flex_file[flex_file['Position'] != "Var"].index
                                    total_score += pulp.lpSum([player_vars[idx] for idx in sub_idx]) == 5
                                
                                for flex in flex_file['roster'].unique():
                                    sub_idx = flex_file[flex_file['roster'] == "CPT"].index
                                    total_score += pulp.lpSum([player_vars[idx] for idx in sub_idx]) == 1
                                
                                for playerid in player_ids:
                                    total_score += pulp.lpSum([player_vars[i] for i in player_ids if 
                                                       (flex_file['name_var'][i] == flex_file['name_var'][playerid])]) <= 1
    
                            player_count = []
                            player_trim = []
                            lineup_list = []
                            
                            if contest_var1 == 'Cash':
                                obj_points = {idx: (flex_file['Proj DK Own%'][idx]) for idx in flex_file.index}
                                total_score += sum([player_vars[idx]*obj_points[idx] for idx in flex_file.index])
                                total_score += pulp.lpSum([player_vars[idx]*obj_points[idx] for idx in flex_file.index]) <= max_own - .001
                            elif contest_var1 != 'Cash':
                                obj_points = {idx: (flex_file['Median'][idx]) for idx in flex_file.index}
                                total_score += sum([player_vars[idx]*obj_points[idx] for idx in flex_file.index])
                                total_score += pulp.lpSum([player_vars[idx]*obj_points[idx] for idx in flex_file.index]) <= max_proj - .01
                            if trim_var1 == 1:
                                total_score += pulp.lpSum([player_vars[idx]*obj_own_max[idx] for idx in flex_file.index]) <= max_own - .001
                            
                            total_score.solve()
                            for v in total_score.variables():
                                if v.varValue > 0:
                                    lineup_list.append(v.name)
                            df = pd.DataFrame(lineup_list)
                            df['Names'] = df[0].map(player_match)
                            df['Cost'] = df['Names'].map(player_sal)
                            df['Proj'] = df['Names'].map(player_proj)
                            df['Own'] = df['Names'].map(player_own)
                            total_cost = sum(df['Cost'])
                            total_own = sum(df['Own'])
                            total_proj = sum(df['Proj'])
                            lineup_raw = pd.DataFrame(lineup_list)
                            lineup_raw['Names'] = lineup_raw[0].map(player_match)
                            lineup_raw['value'] = lineup_raw[0].map(player_index_match)
                            lineup_final = lineup_raw.sort_values(by=['value'])
                            del lineup_final[lineup_final.columns[0]]
                            del lineup_final[lineup_final.columns[1]]
                            lineup_final['Team'] = lineup_final['Names'].map(player_team)
                            lineup_final['Position'] = lineup_final['Names'].map(player_pos)
                            lineup_final['Salary'] = lineup_final['Names'].map(player_sal)
                            lineup_final['Proj'] = lineup_final['Names'].map(player_proj)
                            lineup_final['Own'] = lineup_final['Names'].map(player_own)
                            lineup_final.loc['Column_Total'] = lineup_final.sum(numeric_only=True, axis=0)
                            lineup_final = lineup_final.reset_index(drop=True)
    
                            max_proj = total_proj
                            max_own = total_own
                            
                            if site_var1 == 'Draftkings':
                                if len(lineup_final) == 7:
                                    port_display = pd.DataFrame(lineup_final['Names'][:-1].values.reshape(1, -1))
                                    
                                    port_display['Cost'] = total_cost
                                    port_display['Proj'] = total_proj
                                    port_display['Own'] = total_own
                                    st.table(port_display)
        
                                    portfolio = pd.concat([portfolio, port_display], ignore_index = True)
                            elif site_var1 == 'Fanduel':
                                if len(lineup_final) == 6:
                                    port_display = pd.DataFrame(lineup_final['Names'][:-1].values.reshape(1, -1))
                                    
                                    port_display['Cost'] = total_cost
                                    port_display['Proj'] = total_proj
                                    port_display['Own'] = total_own
                                    st.table(port_display)
        
                                    portfolio = pd.concat([portfolio, port_display], ignore_index = True)
    
                            x += 1
    
                        if site_var1 == 'Draftkings':
                            portfolio.rename(columns={0: "CPT", 1: "FLEX1", 2: "FLEX2", 3: "FLEX3", 4: "FLEX4", 5: "FLEX5"}, inplace = True)
                        elif site_var1 == 'Fanduel':
                            portfolio.rename(columns={0: "MVP", 1: "FLEX1", 2: "FLEX2", 3: "FLEX3", 4: "FLEX4"}, inplace = True)
                        portfolio = portfolio.dropna()
                        portfolio = portfolio.reset_index()
                        portfolio['Lineup_num'] = portfolio['index'] + 1
                        portfolio.rename(columns={'Lineup_num': "Lineup"}, inplace = True)
                        portfolio = portfolio.set_index('Lineup')
                        portfolio = portfolio.drop(columns=['index'])
                        st.session_state.portfolio = portfolio.drop_duplicates()
    
                        final_outcomes = portfolio
                        st.session_state.final_outcomes = portfolio
                        
                        player_freq = pd.DataFrame(np.column_stack(np.unique(st.session_state.portfolio.iloc[:,0:5].values, return_counts=True)),
                                            columns=['Player','Freq']).sort_values('Freq', ascending=False).reset_index(drop=True)
                        player_freq['Freq'] = player_freq['Freq'].astype(int)
                        player_freq['Position'] = player_freq['Player'].map(player_pos)
                        player_freq['Salary'] = player_freq['Player'].map(player_sal)
                        player_freq['Proj Own'] = player_freq['Player'].map(player_own) / 100
                        player_freq['Exposure'] = player_freq['Freq']/(linenum_var1)
                        player_freq['Team'] = player_freq['Player'].map(player_team)
                        
                        final_outcomes_export = pd.DataFrame()
                        split_portfolio = pd.DataFrame()
                        
                        if site_var1 == 'Draftkings':
                            
                            split_portfolio[['CPT', 'CPT_ID']] = final_outcomes.CPT.str.split("-", n=1, expand = True)
                            split_portfolio[['FLEX1', 'FLEX1_ID']] = final_outcomes.FLEX1.str.split("-", n=1, expand = True)
                            split_portfolio[['FLEX2', 'FLEX2_ID']] = final_outcomes.FLEX2.str.split("-", n=1, expand = True)
                            split_portfolio[['FLEX3', 'FLEX3_ID']] = final_outcomes.FLEX3.str.split("-", n=1, expand = True)
                            split_portfolio[['FLEX4', 'FLEX4_ID']] = final_outcomes.FLEX4.str.split("-", n=1, expand = True)
                            split_portfolio[['FLEX5', 'FLEX5_ID']] = final_outcomes.FLEX5.str.split("-", n=1, expand = True)
  
                            split_portfolio['CPT'] = split_portfolio['CPT'].str.strip()
                            split_portfolio['FLEX1'] = split_portfolio['FLEX1'].str.strip()
                            split_portfolio['FLEX2'] = split_portfolio['FLEX2'].str.strip()
                            split_portfolio['FLEX3'] = split_portfolio['FLEX3'].str.strip()
                            split_portfolio['FLEX4'] = split_portfolio['FLEX4'].str.strip()
                            split_portfolio['FLEX5'] = split_portfolio['FLEX5'].str.strip()
                            
                            final_outcomes_export['CPT'] = split_portfolio['CPT']
                            final_outcomes_export['FLEX1'] = split_portfolio['FLEX1']
                            final_outcomes_export['FLEX2'] = split_portfolio['FLEX2']
                            final_outcomes_export['FLEX3'] = split_portfolio['FLEX3']
                            final_outcomes_export['FLEX4'] = split_portfolio['FLEX4']
                            final_outcomes_export['FLEX5'] = split_portfolio['FLEX5']
                            
                            final_outcomes_export['CPT'].replace(dkid_dict, inplace=True)
                            final_outcomes_export['FLEX1'].replace(dkid_dict, inplace=True)
                            final_outcomes_export['FLEX2'].replace(dkid_dict, inplace=True)
                            final_outcomes_export['FLEX3'].replace(dkid_dict, inplace=True)
                            final_outcomes_export['FLEX4'].replace(dkid_dict, inplace=True)
                            final_outcomes_export['FLEX5'].replace(dkid_dict, inplace=True)
                            final_outcomes_export['Salary'] = final_outcomes['Cost']
                            final_outcomes_export['Own'] = final_outcomes['Own']
                            final_outcomes_export['Proj'] = final_outcomes['Proj']
                            
                            st.session_state.final_outcomes_export = final_outcomes_export.copy()
                            
                        elif site_var1 == 'Fanduel':
                            
                            split_portfolio[['MVP', 'CPT_ID']] = final_outcomes.MVP.str.split("-", n=1, expand = True)
                            split_portfolio[['FLEX1', 'FLEX1_ID']] = final_outcomes.FLEX1.str.split("-", n=1, expand = True)
                            split_portfolio[['FLEX2', 'FLEX2_ID']] = final_outcomes.FLEX2.str.split("-", n=1, expand = True)
                            split_portfolio[['FLEX3', 'FLEX3_ID']] = final_outcomes.FLEX3.str.split("-", n=1, expand = True)
                            split_portfolio[['FLEX4', 'FLEX4_ID']] = final_outcomes.FLEX4.str.split("-", n=1, expand = True)
  
                            split_portfolio['MVP'] = split_portfolio['MVP'].str.strip()
                            split_portfolio['FLEX1'] = split_portfolio['FLEX1'].str.strip()
                            split_portfolio['FLEX2'] = split_portfolio['FLEX2'].str.strip()
                            split_portfolio['FLEX3'] = split_portfolio['FLEX3'].str.strip()
                            split_portfolio['FLEX4'] = split_portfolio['FLEX4'].str.strip()
                            
                            final_outcomes_export['MVP'] = split_portfolio['MVP']
                            final_outcomes_export['FLEX1'] = split_portfolio['FLEX1']
                            final_outcomes_export['FLEX2'] = split_portfolio['FLEX2']
                            final_outcomes_export['FLEX3'] = split_portfolio['FLEX3']
                            final_outcomes_export['FLEX4'] = split_portfolio['FLEX4']
                            
                            final_outcomes_export['MVP'].replace(fdid_dict, inplace=True)
                            final_outcomes_export['FLEX1'].replace(fdid_dict, inplace=True)
                            final_outcomes_export['FLEX2'].replace(fdid_dict, inplace=True)
                            final_outcomes_export['FLEX3'].replace(fdid_dict, inplace=True)
                            final_outcomes_export['FLEX4'].replace(fdid_dict, inplace=True)
                            final_outcomes_export['Salary'] = final_outcomes['Cost']
                            final_outcomes_export['Own'] = final_outcomes['Own']
                            final_outcomes_export['Proj'] = final_outcomes['Proj']
                            
                            st.session_state.FD_final_outcomes_export = final_outcomes_export.copy()
          
                        st.session_state.player_freq = player_freq[['Player', 'Position', 'Team', 'Salary', 'Proj Own', 'Exposure']]
        with display_container:
                    display_container = st.empty()
                    if 'display_baselines' in st.session_state:
                        st.dataframe(st.session_state.display_baselines.style.background_gradient(axis=0).background_gradient(cmap='RdYlGn').format(precision=2), use_container_width = True)
        
        with display_dl_container:
                    display_dl_container = st.empty()
                    if 'export_baselines' in st.session_state:
                        st.download_button(
                            label="Export Projections",
                            data=convert_df_to_csv(st.session_state.export_baselines),
                            file_name='showdown_proj_export.csv',
                            mime='text/csv',
                        )        
                
        with optimize_container:
                    optimize_container = st.empty()
                    if 'final_outcomes' in st.session_state:
                        st.dataframe(st.session_state.final_outcomes.style.background_gradient(axis=0).background_gradient(cmap='RdYlGn').format(precision=2), use_container_width = True)
        
        with download_container:
            download_container = st.empty()
            if site_var1 == 'Draftkings':
                if 'final_outcomes_export' in st.session_state:
                    st.download_button(
                        label="Export Optimals",
                        data=convert_df_to_csv(st.session_state.final_outcomes_export),
                        file_name='NFL_optimals_export.csv',
                        mime='text/csv',
                    )
            elif site_var1 == 'Fanduel':
                if 'FD_final_outcomes_export' in st.session_state:
                    st.download_button(
                        label="Export Optimals",
                        data=convert_df_to_csv(st.session_state.FD_final_outcomes_export),
                        file_name='FD_NFL_optimals_export.csv',
                        mime='text/csv',
                    )
        
        with freq_container:
            freq_container = st.empty()
            if 'player_freq' in st.session_state:
                st.dataframe(st.session_state.player_freq.style.background_gradient(axis=0).background_gradient(cmap='RdYlGn').format(expose_format, precision=2), use_container_width = True)