File size: 94,402 Bytes
368acd3
 
 
 
 
 
 
49e77f1
 
 
 
 
 
368acd3
 
6f51338
 
 
368acd3
 
6f51338
368acd3
 
 
 
 
 
 
 
6f51338
 
49e77f1
6f51338
49e77f1
6f51338
 
 
49e77f1
 
 
 
 
 
 
 
 
 
 
 
b60f1b9
6f51338
 
49e77f1
 
6f51338
 
49e77f1
 
38da73d
6f51338
 
49e77f1
 
 
 
38da73d
6f51338
 
 
49e77f1
 
 
 
38da73d
6f51338
 
 
49e77f1
 
 
 
6f51338
 
49e77f1
 
 
 
6f51338
49e77f1
6f51338
49e77f1
 
 
 
 
6f51338
49e77f1
 
 
 
6e7a3b8
49e77f1
a8bd03f
49e77f1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a8bd03f
49e77f1
 
 
 
 
6f51338
49e77f1
6f51338
 
49e77f1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4a110f1
 
 
 
 
49e77f1
32b7ae1
49e77f1
25917df
 
 
 
 
841b7c8
49e77f1
32b7ae1
49e77f1
25917df
 
 
 
 
a5e8911
49e77f1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6e7a3b8
49e77f1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e374d37
 
 
 
 
8c6ff6e
 
49e77f1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c9f3a65
49e77f1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fa65c40
49e77f1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fa65c40
49e77f1
 
0f6c775
49e77f1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3b6c847
49e77f1
 
 
 
 
 
 
 
 
 
841b7c8
 
 
 
6d1aa19
fb0e171
841b7c8
6d1aa19
fb0e171
 
 
841b7c8
 
daa71a3
841b7c8
49e77f1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
841b7c8
 
 
 
6d1aa19
fb0e171
342b4dc
6d1aa19
fb0e171
 
 
daa71a3
841b7c8
 
49e77f1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fa65c40
49e77f1
 
fa65c40
49e77f1
 
 
 
 
 
 
 
 
 
 
 
fbb1ea4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
49e77f1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
943c5f5
 
 
 
 
 
 
 
 
 
 
 
 
 
49e77f1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fa65c40
49e77f1
 
0f6c775
49e77f1
 
 
 
 
 
 
 
 
 
 
 
 
 
b03db49
 
49e77f1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
import streamlit as st
st.set_page_config(layout="wide")

for name in dir():
    if not name.startswith('_'):
        del globals()[name]

import pulp
import numpy as np
import pandas as pd
import streamlit as st
import gspread

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

        gc_con = gspread.service_account_from_dict(credentials, scope)

        return gc_con, NFL_Data
    
gc, all_dk_player_projections = 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%}'}

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

@st.cache_resource(ttl = 599)
def init_baselines():
    sh = gc.open_by_url(all_dk_player_projections)
    worksheet = sh.worksheet('Site_Info')
    raw_display = pd.DataFrame(worksheet.get_all_records())
    site_slates = raw_display
    
    worksheet = sh.worksheet('Player_Projections')
    raw_display = pd.DataFrame(worksheet.get_all_records())
    raw_display = raw_display[raw_display['Position'] != 'K']
    player_stats = raw_display
    
    worksheet = sh.worksheet('DK_ROO')
    load_display = pd.DataFrame(worksheet.get_all_records())
    load_display.replace('', np.nan, inplace=True)
    raw_display = load_display.dropna(subset=['Median'])
    raw_display = raw_display[raw_display['Position'] != 'K']
    dk_ids = dict(zip(raw_display['Player'], raw_display['player_id']))
    dk_roo_raw = raw_display
    
    worksheet = sh.worksheet('FD_ROO')
    load_display = pd.DataFrame(worksheet.get_all_records())
    load_display.replace('', np.nan, inplace=True)
    raw_display = load_display.dropna(subset=['Median'])
    raw_display = raw_display[raw_display['Position'] != 'K']
    fd_ids = dict(zip(raw_display['Player'], raw_display['player_id']))
    fd_roo_raw = raw_display
    
    worksheet = sh.worksheet('DK_Stacks')
    load_display = pd.DataFrame(worksheet.get_all_records())
    raw_display = load_display
    raw_display = raw_display.sort_values(by='Own', ascending=False)
    dk_stacks_raw = raw_display
    
    worksheet = sh.worksheet('FD_Stacks')
    load_display = pd.DataFrame(worksheet.get_all_records())
    raw_display = load_display
    raw_display = raw_display.sort_values(by='Own', ascending=False)
    fd_stacks_raw = raw_display

    return site_slates, player_stats, dk_roo_raw, fd_roo_raw, dk_stacks_raw, fd_stacks_raw, dk_ids, fd_ids

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

site_slates, player_stats, dk_roo_raw, fd_roo_raw, dk_stacks_raw, fd_stacks_raw, dkid_dict, fdid_dict  = init_baselines()
t_stamp = f"Last Update: " + str(dk_roo_raw['timestamp'][0]) + f" CST"
col1, col2 = st.columns([1, 5])
opp_dict = dict(zip(dk_roo_raw.Team, dk_roo_raw.Opp))

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

with tab2:
    st.info("The Projections file can have any columns in any order, but must contain columns explicitly named: 'Player', 'Salary', 'Position', 'Team', 'Opp', 'Median', and 'Own'.")
    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)
                  except:
                            proj_dataframe = pd.read_excel(proj_file)
    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 tab1:
    col1, col2 = st.columns([1, 5])
    with col1:
        st.info(t_stamp)
        if st.button("Load/Reset Data", key='reset1'):
              st.cache_data.clear()
              site_slates, player_stats, dk_roo_raw, fd_roo_raw, dk_stacks_raw, fd_stacks_raw, dk_ids, fd_ids = init_baselines()
              t_stamp = f"Last Update: " + str(dk_roo_raw['timestamp'][0]) + f" CST"
              col1, col2 = st.columns([1, 5])
              opp_dict = dict(zip(dk_roo_raw.Team, dk_roo_raw.Opp))
              
        slate_var1 = st.radio("Which data are you loading?", ('Main Slate', 'Secondary Slate', 'All Games', 'User'), key='slate_var1')
        site_var1 = st.radio("What site are you working with?", ('Draftkings', 'Fanduel'), key='site_var1')
        if site_var1 == 'Draftkings':
              if slate_var1 == 'User':
                  raw_baselines = proj_dataframe
              elif slate_var1 != 'User':
                  raw_baselines = dk_roo_raw[dk_roo_raw['slate'] == str(slate_var1)]
                  raw_baselines = raw_baselines[raw_baselines['version'] == 'overall']
        elif site_var1 == 'Fanduel':
              if slate_var1 == 'User':
                  raw_baselines = proj_dataframe
              elif slate_var1 != 'User':
                  raw_baselines = fd_roo_raw[fd_roo_raw['slate'] == str(slate_var1)]
                  raw_baselines = raw_baselines[raw_baselines['version'] == 'overall']
        contest_var1 = st.selectbox("What contest type are you optimizing for?", ('Cash', 'Small Field GPP', 'Large Field GPP', 'Round Robin'), key='contest_var1')
        trim_choice1 = st.selectbox("Allow overowned lineups?", options = ['Yes', 'No'])
        if trim_choice1 == 'Yes':
            trim_var1 = 0
        elif trim_choice1 == 'No':
            trim_var1 = 1
        if contest_var1 == 'Small Field GPP':
            st.info('The Pivot optimal uses backend functions to create a stack and lock in certain pieces, if you want control over QB pairing use the Manual model instead.')
            opto_var1 = st.selectbox("Pivot optimal or Manual?", ('Pivot Optimal', 'Manual'), key='opto_var1')
            if opto_var1 == "Manual":
                stack_var1 = st.selectbox('Which teams are you stacking?', options = raw_baselines['Team'].unique(), key='stack_var1')
                opp_var1 = opp_dict[stack_var1]
                qbstack_var1 = st.selectbox('How many forced WR/TE stacked with QB?', options = [1, 2], key='qbstack_var1')
                ministack_var1 = st.selectbox('How many forced bring backs?', options = [0, 1, 2], key='ministack_var1')
                
        elif contest_var1 == 'Large Field GPP':
            st.info('The Pivot optimal uses backend functions to create a stack and lock in certain pieces, if you want control over QB pairing use the Manual model instead.')
            opto_var1 = st.selectbox("Pivot optimal or Manual?", ('Pivot Optimal', 'Manual'), key='opto_var1')
            if opto_var1 == "Manual":
                stack_var1 = st.selectbox('Which team are you stacking?', options = raw_baselines['Team'].unique(), key='stack_var1')
                opp_var1 = opp_dict[stack_var1]
                qbstack_var1 = st.selectbox('How many forced WR/TE stacked with QB?', options = [1, 2], key='qbstack_var1')
                ministack_var1 = st.selectbox('How many forced bring backs?', options = [0, 1, 2], key='ministack_var1')
                
        elif contest_var1 == 'Round Robin':
            st.info('A Round Robin optimization will run a single optimal for all the teams on the slate based on your stacking inputs')
            qbstack_var1 = st.selectbox('How many forced WR/TE stacked with QB?', options = [1, 2], key='qbstack_var1')
            ministack_var1 = st.selectbox('How many forced bring backs?', options = [0, 1, 2], key='ministack_var1')
        split_var1 = st.radio("Are you running the full slate or certain games?", ('Full Slate Run', 'Specific Games'), key='split_var1')
        if split_var1 == 'Specific Games':
            team_var1 = st.multiselect('Which teams would you like to include in the optimization?', options = raw_baselines['Team'].unique(), key='team_var1')
        elif split_var1 == 'Full Slate Run':
            team_var1 = raw_baselines.Team.values.tolist()
        lock_var1 = st.multiselect("Are there any players you want to use in all lineups (Lock Button)?", options = raw_baselines['Player'].unique(), key='lock_var1')
        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')
        if contest_var1 == 'Round Robin':
            linenum_var1 = len(raw_baselines['Team'].unique())
        elif contest_var1 != 'Round Robin':
            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 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')
    with col2:
        raw_baselines = raw_baselines[raw_baselines['Team'].isin(team_var1)]
        
        raw_baselines = raw_baselines[~raw_baselines['Player'].isin(avoid_var1)]
        ownframe = raw_baselines.copy()
        if contest_var1 == 'Cash':
                ownframe['Own%'] = np.where((ownframe['Position'] == 'QB') & (ownframe['Own'] - ownframe.loc[ownframe['Position'] == 'QB', 'Own'].mean() >= 0), ownframe['Own'] * (10 * (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%'] > 75, 75, ownframe['Own%'])
                ownframe['Own'] = ownframe['Own%'] * (900 / ownframe['Own%'].sum())
        if contest_var1 == 'Small Field GPP':
                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'] * (3 * (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%'] * (900 / ownframe['Own%'].sum())
        if contest_var1 == 'Large Field GPP':
                ownframe['Own%'] = np.where((ownframe['Position'] == 'QB') & (ownframe['Own'] - ownframe.loc[ownframe['Position'] == 'QB', 'Own'].mean() >= 0), ownframe['Own'] * (3 * (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'] * (1.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%'] * (900 / ownframe['Own%'].sum())
        raw_baselines = ownframe[['Player', 'Salary', 'Position', 'Team', 'Opp', 'Median', 'Own']]
        raw_baselines = raw_baselines.sort_values(by='Median', ascending=False)
        raw_baselines['lock'] = np.where(raw_baselines['Player'].isin(lock_var1), 1, 0)
        st.dataframe(raw_baselines.style.background_gradient(axis=0).background_gradient(cmap='RdYlGn').format(precision=2), use_container_width = True)
        st.download_button(
                label="Export Projections",
                data=convert_df_to_csv(raw_baselines),
                file_name='NFL_proj_export.csv',
                mime='text/csv',
            )
        if st.button('Optimize'):
            max_proj = 1000
            max_own = 1000
            total_proj = 0
            total_own = 0
            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:
                        if contest_var1 == 'Round Robin':
                            
                            while x <= len(raw_baselines['Team'].unique()):
                                stack_var1 = raw_baselines['Team'].unique()[x-1]
                                if site_var1 == 'Draftkings':
                                    opp_var1 = opp_dict[stack_var1]
                                elif site_var1 == 'Fanduel':
                                    if stack_var1 == 'JAC':
                                        opp_var1 = opp_dict['JAX']
                                    elif stack_var1 != 'JAC':
                                        opp_var1 = opp_dict[stack_var1]
                                st.write(stack_var1)
                                sorted_lineup = []
                                p_used = []
                                cvar = 0
                                firvar = 0
                                secvar = 0
                                thirvar = 0
        
                                raw_proj_file = raw_baselines
                                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_var1), 1, 0)
                                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_salary = {idx: (flex_file['Salary'][idx]) for idx in flex_file.index}
                                obj_own_max = {idx: (flex_file['Proj DK Own%'][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':
                                    
                                    if contest_var1 == 'Cash':
                                        qbfile = flex_file[flex_file['Team'] == stack_var1]
                                        qbfile = qbfile[qbfile['Position'] == 'QB']
                                        qbfile = qbfile.reset_index()
                                        qb_var = qbfile['Player'][0]
                                    elif contest_var1 == 'Small Field GPP':
                                        qbfile = flex_file[flex_file['Team'] == stack_var1]
                                        qbfile = qbfile[qbfile['Position'] == 'QB']
                                        qbfile = qbfile.reset_index()
                                        qb_var = qbfile['Player'][0]
                                        st.table(qbfile)
                                        #st.write(stack_var1 + ' ' + qb_var)
                                        for qbid in player_ids:
                                            if flex_file['Position'][qbid] == 'QB':
                                                total_score += pulp.lpSum([player_vars[i] for i in player_ids if 
                                                                   (flex_file['Team'][i] == stack_var1 and 
                                                                    flex_file['Position'][i] in ('WR', 'TE'))] + 
                                                                   [-qbstack_var1*player_vars[qbid]]) >= 0
                                            if flex_file['Position'][qbid] == 'QB':
                                                total_score += pulp.lpSum([player_vars[i] for i in player_ids if 
                                                                   (flex_file['Team'][i] == stack_var1 and 
                                                                    flex_file['Position'][i] in ('RB'))] + 
                                                                   [0*player_vars[qbid]]) == 0
                                            if flex_file['Position'][qbid] == 'QB':
                                                total_score += pulp.lpSum([player_vars[i] for i in player_ids if 
                                                                   (flex_file['Team'][i] == opp_var1 and 
                                                                    flex_file['Position'][i] in ('WR', 'TE'))] + 
                                                                   [-ministack_var1*player_vars[qbid]]) >= 0
                                        for flex in flex_file['Player'].unique():
                                                sub_idx = flex_file[flex_file['Player'] == qb_var].index
                                                total_score += pulp.lpSum([player_vars[idx] for idx in sub_idx]) == 1
                                    elif contest_var1 == 'Round Robin':
                                        qbfile = flex_file[flex_file['Team'] == stack_var1]
                                        qbfile = qbfile[qbfile['Position'] == 'QB']
                                        qbfile = qbfile.reset_index()
                                        qb_var = qbfile['Player'][0]
                                        st.table(qbfile)
                                        #st.write(stack_var1 + ' ' + qb_var)
                                        for qbid in player_ids:
                                            if flex_file['Position'][qbid] == 'QB':
                                                total_score += pulp.lpSum([player_vars[i] for i in player_ids if 
                                                                   (flex_file['Team'][i] == stack_var1 and 
                                                                    flex_file['Position'][i] in ('WR', 'TE'))] + 
                                                                   [-qbstack_var1*player_vars[qbid]]) >= 0
                                            if flex_file['Position'][qbid] == 'QB':
                                                total_score += pulp.lpSum([player_vars[i] for i in player_ids if 
                                                                   (flex_file['Team'][i] == stack_var1 and 
                                                                    flex_file['Position'][i] in ('RB'))] + 
                                                                   [0*player_vars[qbid]]) == 0
                                            if flex_file['Position'][qbid] == 'QB':
                                                total_score += pulp.lpSum([player_vars[i] for i in player_ids if 
                                                                   (flex_file['Team'][i] == opp_var1 and 
                                                                    flex_file['Position'][i] in ('WR', 'TE'))] + 
                                                                   [-ministack_var1*player_vars[qbid]]) >= 0
                                        for flex in flex_file['Player'].unique():
                                                sub_idx = flex_file[flex_file['Player'] == qb_var].index
                                                total_score += pulp.lpSum([player_vars[idx] for idx in sub_idx]) == 1
                                    elif contest_var1 == 'Large Field GPP':
                                        qbfile = flex_file[flex_file['Team'] == stack_var1]
                                        qbfile = qbfile[qbfile['Position'] == 'QB']
                                        qbfile = qbfile.reset_index()
                                        qb_var = qbfile['Player'][0]
                                        st.table(qbfile)
                                        #st.write(stack_var1 + ' ' + qb_var)
                                        for qbid in player_ids:
                                            if flex_file['Position'][qbid] == 'QB':
                                                total_score += pulp.lpSum([player_vars[i] for i in player_ids if 
                                                                   (flex_file['Team'][i] == stack_var1 and 
                                                                    flex_file['Position'][i] in ('WR', 'TE'))] +
                                                                   [-qbstack_var1*player_vars[qbid]]) >= 0
                                            if flex_file['Position'][qbid] == 'QB':
                                                total_score += pulp.lpSum([player_vars[i] for i in player_ids if 
                                                                   (flex_file['Team'][i] == stack_var1 and 
                                                                    flex_file['Position'][i] in ('RB'))] + 
                                                                   [0*player_vars[qbid]]) == 0
                                            if flex_file['Position'][qbid] == 'QB':
                                                total_score += pulp.lpSum([player_vars[i] for i in player_ids if 
                                                                   (flex_file['Team'][i] == opp_var1 and 
                                                                    flex_file['Position'][i] in ('WR', 'TE'))] + 
                                                                   [-ministack_var1*player_vars[qbid]]) >= 0
                                        for flex in flex_file['Player'].unique():
                                                sub_idx = flex_file[flex_file['Player'] == qb_var].index
                                                total_score += pulp.lpSum([player_vars[idx] for idx in sub_idx]) == 1
                                    
                                    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_var1)
        
                                    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]) == 9
                                    
                                    for flex in flex_file['Position'].unique():
                                        sub_idx = flex_file[flex_file['Position'] == "QB"].index
                                        total_score += pulp.lpSum([player_vars[idx] for idx in sub_idx]) == 1
                                    
                                    for flex in flex_file['Position'].unique():
                                        sub_idx = flex_file[flex_file['Position'] == "RB"].index
                                        total_score += pulp.lpSum([player_vars[idx] for idx in sub_idx]) <= 3
                                        
                                    for flex in flex_file['Position'].unique():
                                        sub_idx = flex_file[flex_file['Position'] == "RB"].index
                                        total_score += pulp.lpSum([player_vars[idx] for idx in sub_idx]) >= 2
        
                                    for flex in flex_file['Position'].unique():
                                        sub_idx = flex_file[flex_file['Position'] == "WR"].index
                                        total_score += pulp.lpSum([player_vars[idx] for idx in sub_idx]) <= 4
                                    
                                    for flex in flex_file['Position'].unique():
                                        sub_idx = flex_file[flex_file['Position'] == "WR"].index
                                        total_score += pulp.lpSum([player_vars[idx] for idx in sub_idx]) >= 3
        
                                    for flex in flex_file['Position'].unique():
                                        sub_idx = flex_file[flex_file['Position'] == "TE"].index
                                        total_score += pulp.lpSum([player_vars[idx] for idx in sub_idx]) == 1
                                    
                                    for flex in flex_file['Position'].unique():
                                        sub_idx = flex_file[flex_file['Position'] == "DST"].index
                                        total_score += pulp.lpSum([player_vars[idx] for idx in sub_idx]) == 1
        
                                elif site_var1 == 'Fanduel':
        
                                    if contest_var1 == 'Cash':
                                        qbfile = flex_file[flex_file['Team'] == stack_var1]
                                        qbfile = qbfile[qbfile['Position'] == 'QB']
                                        qbfile = qbfile.reset_index()
                                        qb_var = qbfile['Player'][0]
                                    elif contest_var1 == 'Small Field GPP':
                                        qbfile = flex_file[flex_file['Team'] == stack_var1]
                                        qbfile = qbfile[qbfile['Position'] == 'QB']
                                        qbfile = qbfile.reset_index()
                                        qb_var = qbfile['Player'][0]
                                        st.table(qbfile)
                                        #st.write(stack_var1 + ' ' + qb_var)
                                        for qbid in player_ids:
                                            if flex_file['Position'][qbid] == 'QB':
                                                total_score += pulp.lpSum([player_vars[i] for i in player_ids if 
                                                                   (flex_file['Team'][i] == stack_var1 and 
                                                                    flex_file['Position'][i] in ('WR', 'TE'))] + 
                                                                   [-qbstack_var1*player_vars[qbid]]) >= 0
                                            if flex_file['Position'][qbid] == 'QB':
                                                total_score += pulp.lpSum([player_vars[i] for i in player_ids if 
                                                                   (flex_file['Team'][i] == stack_var1 and 
                                                                    flex_file['Position'][i] in ('RB'))] + 
                                                                   [0*player_vars[qbid]]) == 0
                                            if flex_file['Position'][qbid] == 'QB':
                                                total_score += pulp.lpSum([player_vars[i] for i in player_ids if 
                                                                   (flex_file['Team'][i] == opp_var1 and 
                                                                    flex_file['Position'][i] in ('WR', 'TE'))] + 
                                                                   [-ministack_var1*player_vars[qbid]]) >= 0
                                        for flex in flex_file['Player'].unique():
                                                sub_idx = flex_file[flex_file['Player'] == qb_var].index
                                                total_score += pulp.lpSum([player_vars[idx] for idx in sub_idx]) == 1
                                    elif contest_var1 == 'Round Robin':
                                        qbfile = flex_file[flex_file['Team'] == stack_var1]
                                        qbfile = qbfile[qbfile['Position'] == 'QB']
                                        qbfile = qbfile.reset_index()
                                        qb_var = qbfile['Player'][0]
                                        st.table(qbfile)
                                        #st.write(stack_var1 + ' ' + qb_var)
                                        for qbid in player_ids:
                                            if flex_file['Position'][qbid] == 'QB':
                                                total_score += pulp.lpSum([player_vars[i] for i in player_ids if 
                                                                   (flex_file['Team'][i] == stack_var1 and 
                                                                    flex_file['Position'][i] in ('WR', 'TE'))] + 
                                                                   [-qbstack_var1*player_vars[qbid]]) >= 0
                                            if flex_file['Position'][qbid] == 'QB':
                                                total_score += pulp.lpSum([player_vars[i] for i in player_ids if 
                                                                   (flex_file['Team'][i] == stack_var1 and 
                                                                    flex_file['Position'][i] in ('RB'))] + 
                                                                   [0*player_vars[qbid]]) == 0
                                            if flex_file['Position'][qbid] == 'QB':
                                                total_score += pulp.lpSum([player_vars[i] for i in player_ids if 
                                                                   (flex_file['Team'][i] == opp_var1 and 
                                                                    flex_file['Position'][i] in ('WR', 'TE'))] + 
                                                                   [-ministack_var1*player_vars[qbid]]) >= 0
                                        for flex in flex_file['Player'].unique():
                                                sub_idx = flex_file[flex_file['Player'] == qb_var].index
                                                total_score += pulp.lpSum([player_vars[idx] for idx in sub_idx]) == 1
                                    elif contest_var1 == 'Large Field GPP':
                                        qbfile = flex_file[flex_file['Team'] == stack_var1]
                                        qbfile = qbfile[qbfile['Position'] == 'QB']
                                        qbfile = qbfile.reset_index()
                                        qb_var = qbfile['Player'][0]
                                        st.table(qbfile)
                                        #st.write(stack_var1 + ' ' + qb_var)
                                        for qbid in player_ids:
                                            if flex_file['Position'][qbid] == 'QB':
                                                total_score += pulp.lpSum([player_vars[i] for i in player_ids if 
                                                                   (flex_file['Team'][i] == stack_var1 and 
                                                                    flex_file['Position'][i] in ('WR', 'TE'))] +
                                                                   [-qbstack_var1*player_vars[qbid]]) >= 0
                                            if flex_file['Position'][qbid] == 'QB':
                                                total_score += pulp.lpSum([player_vars[i] for i in player_ids if 
                                                                   (flex_file['Team'][i] == stack_var1 and 
                                                                    flex_file['Position'][i] in ('RB'))] + 
                                                                   [0*player_vars[qbid]]) == 0
                                            if flex_file['Position'][qbid] == 'QB':
                                                total_score += pulp.lpSum([player_vars[i] for i in player_ids if 
                                                                   (flex_file['Team'][i] == opp_var1 and 
                                                                    flex_file['Position'][i] in ('WR', 'TE'))] + 
                                                                   [-ministack_var1*player_vars[qbid]]) >= 0
                                        for flex in flex_file['Player'].unique():
                                                sub_idx = flex_file[flex_file['Player'] == qb_var].index
                                                total_score += pulp.lpSum([player_vars[idx] for idx in sub_idx]) == 1
                                    
                                    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_var1)
        
                                    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]) == 9
                                    
                                    for flex in flex_file['Position'].unique():
                                        sub_idx = flex_file[flex_file['Position'] == "QB"].index
                                        total_score += pulp.lpSum([player_vars[idx] for idx in sub_idx]) == 1
                                    
                                    for flex in flex_file['Position'].unique():
                                        sub_idx = flex_file[flex_file['Position'] == "RB"].index
                                        total_score += pulp.lpSum([player_vars[idx] for idx in sub_idx]) <= 3
                                        
                                    for flex in flex_file['Position'].unique():
                                        sub_idx = flex_file[flex_file['Position'] == "RB"].index
                                        total_score += pulp.lpSum([player_vars[idx] for idx in sub_idx]) >= 2
        
                                    for flex in flex_file['Position'].unique():
                                        sub_idx = flex_file[flex_file['Position'] == "WR"].index
                                        total_score += pulp.lpSum([player_vars[idx] for idx in sub_idx]) <= 4
                                    
                                    for flex in flex_file['Position'].unique():
                                        sub_idx = flex_file[flex_file['Position'] == "WR"].index
                                        total_score += pulp.lpSum([player_vars[idx] for idx in sub_idx]) >= 3
        
                                    for flex in flex_file['Position'].unique():
                                        sub_idx = flex_file[flex_file['Position'] == "TE"].index
                                        total_score += pulp.lpSum([player_vars[idx] for idx in sub_idx]) == 1
                                    
                                    for flex in flex_file['Position'].unique():
                                        sub_idx = flex_file[flex_file['Position'] == "DST"].index
                                        total_score += pulp.lpSum([player_vars[idx] for idx in sub_idx]) == 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])
                                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.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 = lineup_final.reset_index(drop=True)
                                
                                if site_var1 == 'Draftkings':
                                    line_hold = lineup_final[['Names']]
                                    line_hold['pos'] = line_hold['Names'].map(player_pos)
        
                                    for pname in range(0,len(line_hold)):
                                        if line_hold.iat[pname,1] == 'QB':
                                            if line_hold.iat[pname,0] not in p_used:
                                                sorted_lineup.append(line_hold.iat[pname,0])
                                    p_used.extend(sorted_lineup)        
                                    rbvar = 0
                                    for pname in range(0,len(line_hold)):
                                        if rbvar == 2:
                                            pname = len(line_hold)
                                        elif rbvar < 2:
                                            if line_hold.iat[pname,1] == 'RB':
                                                if line_hold.iat[pname,0] not in p_used:
                                                    sorted_lineup.append(line_hold.iat[pname,0])
                                                    rbvar = rbvar + 1
                                    p_used.extend(sorted_lineup)
                                    wrvar = 0
                                    for pname in range(0,len(line_hold)):
                                        if wrvar == 3:
                                            pname = len(line_hold)
                                        elif wrvar < 3:
                                            if line_hold.iat[pname,1] == 'WR':
                                                if line_hold.iat[pname,0] not in p_used:
                                                    sorted_lineup.append(line_hold.iat[pname,0])
                                                    wrvar = wrvar + 1
                                    p_used.extend(sorted_lineup)
                                    tevar = 0
                                    for pname in range(0,len(line_hold)):
                                        if tevar == 1:
                                            pname = len(line_hold)
                                        elif tevar < 1:
                                            if line_hold.iat[pname,1] == 'TE':
                                                if line_hold.iat[pname,0] not in p_used:
                                                    sorted_lineup.append(line_hold.iat[pname,0])
                                                    tevar = tevar + 1
                                    p_used.extend(sorted_lineup)
                                    
                                    for pname in range(0,len(line_hold)):
                                        if line_hold.iat[pname,1] != 'DST':
                                            if line_hold.iat[pname,0] not in p_used:
                                                sorted_lineup.append(line_hold.iat[pname,0])
                                    p_used.extend(sorted_lineup)
                                    
                                    for pname in range(0,len(line_hold)):
                                        if line_hold.iat[pname,1] == 'DST':
                                            if line_hold.iat[pname,0] not in p_used:
                                                sorted_lineup.append(line_hold.iat[pname,0])
                                    p_used.extend(sorted_lineup)
                                    
                                    lineup_final['sorted'] = sorted_lineup
                                    lineup_final = lineup_final.drop(columns=['Names'])
                                    lineup_final.rename(columns={"sorted": "Names"}, inplace = True)
                                      
                                elif site_var1 == 'Fanduel':
                                    line_hold = lineup_final[['Names']]
                                    line_hold['pos'] = line_hold['Names'].map(player_pos)
        
                                    for pname in range(0,len(line_hold)):
                                        if line_hold.iat[pname,1] == 'QB':
                                            if line_hold.iat[pname,0] not in p_used:
                                                sorted_lineup.append(line_hold.iat[pname,0])
                                    p_used.extend(sorted_lineup)        
                                    rbvar = 0
                                    for pname in range(0,len(line_hold)):
                                        if rbvar == 2:
                                            pname = len(line_hold)
                                        elif rbvar < 2:
                                            if line_hold.iat[pname,1] == 'RB':
                                                if line_hold.iat[pname,0] not in p_used:
                                                    sorted_lineup.append(line_hold.iat[pname,0])
                                                    rbvar = rbvar + 1
                                    p_used.extend(sorted_lineup)
                                    wrvar = 0
                                    for pname in range(0,len(line_hold)):
                                        if wrvar == 3:
                                            pname = len(line_hold)
                                        elif wrvar < 3:
                                            if line_hold.iat[pname,1] == 'WR':
                                                if line_hold.iat[pname,0] not in p_used:
                                                    sorted_lineup.append(line_hold.iat[pname,0])
                                                    wrvar = wrvar + 1
                                    p_used.extend(sorted_lineup)
                                    tevar = 0
                                    for pname in range(0,len(line_hold)):
                                        if tevar == 1:
                                            pname = len(line_hold)
                                        elif tevar < 1:
                                            if line_hold.iat[pname,1] == 'TE':
                                                if line_hold.iat[pname,0] not in p_used:
                                                    sorted_lineup.append(line_hold.iat[pname,0])
                                                    tevar = tevar + 1
                                    p_used.extend(sorted_lineup)
                                    
                                    for pname in range(0,len(line_hold)):
                                        if line_hold.iat[pname,1] != 'DST':
                                            if line_hold.iat[pname,0] not in p_used:
                                                sorted_lineup.append(line_hold.iat[pname,0])
                                    p_used.extend(sorted_lineup)
                                    
                                    for pname in range(0,len(line_hold)):
                                        if line_hold.iat[pname,1] == 'DST':
                                            if line_hold.iat[pname,0] not in p_used:
                                                sorted_lineup.append(line_hold.iat[pname,0])
                                    p_used.extend(sorted_lineup)
                                    
                                    lineup_final['sorted'] = sorted_lineup
                                    lineup_final = lineup_final.drop(columns=['Names'])
                                    lineup_final.rename(columns={"sorted": "Names"}, inplace = True)
                                      
                                lineup_test = lineup_final
                                lineup_final = lineup_final.T
                                lineup_final['Cost'] = total_cost
                                lineup_final['Proj'] = total_proj
                                lineup_final['Own'] = total_own
                            
                                lineup_test['Team'] = lineup_test['Names'].map(player_team)
                                lineup_test['Position'] = lineup_test['Names'].map(player_pos)
                                lineup_test['Salary'] = lineup_test['Names'].map(player_sal)
                                lineup_test['Proj'] = lineup_test['Names'].map(player_proj)
                                lineup_test['Own'] = lineup_test['Names'].map(player_own)
                                lineup_test = lineup_test.set_index('Names')
                                lineup_test.loc['Column_Total'] = lineup_test.sum(numeric_only=True, axis=0)
        
                                lineup_display.append(lineup_test)
        
                                with col2:
                                    with st.container():
                                        st.table(lineup_test)
        
                                max_proj = total_proj
                                max_own = total_own
        
                                check_list.append(total_proj)
        
                                portfolio = pd.concat([portfolio, lineup_final], ignore_index = True)
        
                                x += 1
                            
                        elif contest_var1 != 'Round Robin':
                            while x <= linenum_var1:
                                sorted_lineup = []
                                p_used = []
                                cvar = 0
                                firvar = 0
                                secvar = 0
                                thirvar = 0
        
                                raw_proj_file = raw_baselines
                                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_var1), 1, 0)
                                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_salary = {idx: (flex_file['Salary'][idx]) for idx in flex_file.index}
                                obj_own_max = {idx: (flex_file['Proj DK Own%'][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':
                                    
                                    if contest_var1 == 'Cash':
                                        qbfile = flex_file
                                        qbfile = qbfile[qbfile['Position'] == 'QB']
                                        qbfile = qbfile.reset_index()
                                    elif contest_var1 == 'Small Field GPP':
                                        if opto_var1 == "Pivot Optimal":
                                            qbstack_var1 = 2
                                            ministack_var1 = 0
                                            dk_stacks_raw = dk_stacks_raw[dk_stacks_raw['Team'].isin(team_var1)]
                                            dk_stacks_raw = dk_stacks_raw.sort_values(by='Own', ascending=False)
                                            dk_stacks_raw.reset_index(drop=True)
                                            fd_stacks_raw = fd_stacks_raw[fd_stacks_raw['Team'].isin(team_var1)]
                                            dk_stacks_raw = dk_stacks_raw.sort_values(by='Own', ascending=False)
                                            fd_stacks_raw.reset_index(drop=True)
                                            dk_Max_Rank = dk_stacks_raw['Team'].values[0]
                                            fd_Max_Rank = fd_stacks_raw['Team'].values[0]
                                            stack_var1 = dk_Max_Rank
                                            opp_var1 = opp_dict[stack_var1]
                                            st.table(dk_stacks_raw)
                                            
                                        qbfile = flex_file[flex_file['Team'] == stack_var1]
                                        qbfile = qbfile[qbfile['Position'] == 'QB']
                                        qbfile = qbfile.reset_index()
                                        qb_var = qbfile['Player'][0]
                                        st.table(qbfile)
                                        #st.write(stack_var1 + ' ' + qb_var)
                                        for qbid in player_ids:
                                            if flex_file['Position'][qbid] == 'QB':
                                                total_score += pulp.lpSum([player_vars[i] for i in player_ids if 
                                                                   (flex_file['Team'][i] == stack_var1 and 
                                                                    flex_file['Position'][i] in ('WR', 'TE'))] + 
                                                                   [-qbstack_var1*player_vars[qbid]]) >= 0
                                            if flex_file['Position'][qbid] == 'QB':
                                                total_score += pulp.lpSum([player_vars[i] for i in player_ids if 
                                                                   (flex_file['Team'][i] == stack_var1 and 
                                                                    flex_file['Position'][i] in ('RB'))] + 
                                                                   [0*player_vars[qbid]]) == 0
                                            if flex_file['Position'][qbid] == 'QB':
                                                total_score += pulp.lpSum([player_vars[i] for i in player_ids if 
                                                                   (flex_file['Team'][i] == opp_var1 and 
                                                                    flex_file['Position'][i] in ('WR', 'TE'))] + 
                                                                   [-ministack_var1*player_vars[qbid]]) >= 0
                                        for flex in flex_file['Player'].unique():
                                                sub_idx = flex_file[flex_file['Player'] == qb_var].index
                                                total_score += pulp.lpSum([player_vars[idx] for idx in sub_idx]) == 1
                                    elif contest_var1 == 'Large Field GPP':
                                        if opto_var1 == "Pivot Optimal":
                                            qbstack_var1 = 2
                                            ministack_var1 = 0
                                            dk_stacks_raw = dk_stacks_raw[dk_stacks_raw['Team'].isin(team_var1)]
                                            dk_stacks_raw = dk_stacks_raw.sort_values(by='Median', ascending=False)
                                            dk_stacks_raw.reset_index(drop=True)
                                            fd_stacks_raw = fd_stacks_raw[fd_stacks_raw['Team'].isin(team_var1)]
                                            dk_stacks_raw = dk_stacks_raw.sort_values(by='Median', ascending=False)
                                            fd_stacks_raw.reset_index(drop=True)
                                            dk_Max_Rank = dk_stacks_raw['Team'].values[0]
                                            fd_Max_Rank = fd_stacks_raw['Team'].values[0]
                                            stack_var1 = dk_Max_Rank
                                            opp_var1 = opp_dict[stack_var1]
                                            
                                        qbfile = flex_file[flex_file['Team'] == stack_var1]
                                        qbfile = qbfile[qbfile['Position'] == 'QB']
                                        qbfile = qbfile.reset_index()
                                        qb_var = qbfile['Player'][0]
                                        st.table(qbfile)
                                        #st.write(stack_var1 + ' ' + qb_var)
                                        for qbid in player_ids:
                                            if flex_file['Position'][qbid] == 'QB':
                                                total_score += pulp.lpSum([player_vars[i] for i in player_ids if 
                                                                   (flex_file['Team'][i] == stack_var1 and 
                                                                    flex_file['Position'][i] in ('WR', 'TE'))] +
                                                                   [-qbstack_var1*player_vars[qbid]]) >= 0
                                            if flex_file['Position'][qbid] == 'QB':
                                                total_score += pulp.lpSum([player_vars[i] for i in player_ids if 
                                                                   (flex_file['Team'][i] == stack_var1 and 
                                                                    flex_file['Position'][i] in ('RB'))] + 
                                                                   [0*player_vars[qbid]]) == 0
                                            if flex_file['Position'][qbid] == 'QB':
                                                total_score += pulp.lpSum([player_vars[i] for i in player_ids if 
                                                                   (flex_file['Team'][i] == opp_var1 and 
                                                                    flex_file['Position'][i] in ('WR', 'TE'))] + 
                                                                   [-ministack_var1*player_vars[qbid]]) >= 0
                                        for flex in flex_file['Player'].unique():
                                                sub_idx = flex_file[flex_file['Player'] == qb_var].index
                                                total_score += pulp.lpSum([player_vars[idx] for idx in sub_idx]) == 1
                                    
                                    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_var1)
        
                                    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]) == 9
                                    
                                    for flex in flex_file['Position'].unique():
                                        sub_idx = flex_file[flex_file['Position'] == "QB"].index
                                        total_score += pulp.lpSum([player_vars[idx] for idx in sub_idx]) == 1
                                    
                                    for flex in flex_file['Position'].unique():
                                        sub_idx = flex_file[flex_file['Position'] == "RB"].index
                                        total_score += pulp.lpSum([player_vars[idx] for idx in sub_idx]) <= 3
                                        
                                    for flex in flex_file['Position'].unique():
                                        sub_idx = flex_file[flex_file['Position'] == "RB"].index
                                        total_score += pulp.lpSum([player_vars[idx] for idx in sub_idx]) >= 2
        
                                    for flex in flex_file['Position'].unique():
                                        sub_idx = flex_file[flex_file['Position'] == "WR"].index
                                        total_score += pulp.lpSum([player_vars[idx] for idx in sub_idx]) <= 4
                                    
                                    for flex in flex_file['Position'].unique():
                                        sub_idx = flex_file[flex_file['Position'] == "WR"].index
                                        total_score += pulp.lpSum([player_vars[idx] for idx in sub_idx]) >= 3
                                        
                                    for flex in flex_file['Position'].unique():
                                        sub_idx = flex_file[flex_file['Position'] == "TE"].index
                                        total_score += pulp.lpSum([player_vars[idx] for idx in sub_idx]) == 1
                                    
                                    for flex in flex_file['Position'].unique():
                                        sub_idx = flex_file[flex_file['Position'] == "DST"].index
                                        total_score += pulp.lpSum([player_vars[idx] for idx in sub_idx]) == 1
        
                                elif site_var1 == 'Fanduel':
        
                                    if contest_var1 == 'Cash':
                                        qbfile = flex_file
                                        qbfile = qbfile[qbfile['Position'] == 'QB']
                                        qbfile = qbfile.reset_index()
                                    elif contest_var1 == 'Small Field GPP':
                                        if opto_var1 == "Pivot Optimal":
                                            qbstack_var1 = 2
                                            ministack_var1 = 0
                                            dk_stacks_raw = dk_stacks_raw[dk_stacks_raw['Team'].isin(team_var1)]
                                            dk_stacks_raw = dk_stacks_raw.sort_values(by='Own', ascending=False)
                                            dk_stacks_raw.reset_index(drop=True)
                                            fd_stacks_raw = fd_stacks_raw[fd_stacks_raw['Team'].isin(team_var1)]
                                            dk_stacks_raw = dk_stacks_raw.sort_values(by='Own', ascending=False)
                                            fd_stacks_raw.reset_index(drop=True)
                                            dk_Max_Rank = dk_stacks_raw['Team'].values[0]
                                            fd_Max_Rank = fd_stacks_raw['Team'].values[0]
                                            stack_var1 = dk_Max_Rank
                                            opp_var1 = opp_dict[stack_var1]
                                            st.table(fd_stacks_raw)

                                        qbfile = flex_file[flex_file['Team'] == stack_var1]
                                        qbfile = qbfile[qbfile['Position'] == 'QB']
                                        qbfile = qbfile.reset_index()
                                        qb_var = qbfile['Player'][0]
                                        st.table(qbfile)
                                        #st.write(stack_var1 + ' ' + qb_var)
                                        for qbid in player_ids:
                                            if flex_file['Position'][qbid] == 'QB':
                                                total_score += pulp.lpSum([player_vars[i] for i in player_ids if 
                                                                   (flex_file['Team'][i] == stack_var1 and 
                                                                    flex_file['Position'][i] in ('WR', 'TE'))] + 
                                                                   [-qbstack_var1*player_vars[qbid]]) >= 0
                                            if flex_file['Position'][qbid] == 'QB':
                                                total_score += pulp.lpSum([player_vars[i] for i in player_ids if 
                                                                   (flex_file['Team'][i] == stack_var1 and 
                                                                    flex_file['Position'][i] in ('RB'))] + 
                                                                   [0*player_vars[qbid]]) == 0
                                            if flex_file['Position'][qbid] == 'QB':
                                                total_score += pulp.lpSum([player_vars[i] for i in player_ids if 
                                                                   (flex_file['Team'][i] == opp_var1 and 
                                                                    flex_file['Position'][i] in ('WR', 'TE'))] + 
                                                                   [-ministack_var1*player_vars[qbid]]) >= 0
                                        for flex in flex_file['Player'].unique():
                                                sub_idx = flex_file[flex_file['Player'] == qb_var].index
                                                total_score += pulp.lpSum([player_vars[idx] for idx in sub_idx]) == 1
                                    elif contest_var1 == 'Large Field GPP':
                                        if opto_var1 == "Pivot Optimal":
                                            qbstack_var1 = 2
                                            ministack_var1 = 0
                                            dk_stacks_raw = dk_stacks_raw[dk_stacks_raw['Team'].isin(team_var1)]
                                            dk_stacks_raw = dk_stacks_raw.sort_values(by='Median', ascending=False)
                                            dk_stacks_raw.reset_index(drop=True)
                                            fd_stacks_raw = fd_stacks_raw[fd_stacks_raw['Team'].isin(team_var1)]
                                            dk_stacks_raw = dk_stacks_raw.sort_values(by='Median', ascending=False)
                                            fd_stacks_raw.reset_index(drop=True)
                                            dk_Max_Rank = dk_stacks_raw['Team'].values[0]
                                            fd_Max_Rank = fd_stacks_raw['Team'].values[0]
                                            stack_var1 = fd_Max_Rank
                                            opp_var1 = opp_dict[stack_var1]
                                            
                                        qbfile = flex_file[flex_file['Team'] == stack_var1]
                                        qbfile = qbfile[qbfile['Position'] == 'QB']
                                        qbfile = qbfile.reset_index()
                                        qb_var = qbfile['Player'][0]
                                        st.table(qbfile)
                                        #st.write(stack_var1 + ' ' + qb_var)
                                        for qbid in player_ids:
                                            if flex_file['Position'][qbid] == 'QB':
                                                total_score += pulp.lpSum([player_vars[i] for i in player_ids if 
                                                                   (flex_file['Team'][i] == stack_var1 and 
                                                                    flex_file['Position'][i] in ('WR', 'TE'))] +
                                                                   [-qbstack_var1*player_vars[qbid]]) >= 0
                                            if flex_file['Position'][qbid] == 'QB':
                                                total_score += pulp.lpSum([player_vars[i] for i in player_ids if 
                                                                   (flex_file['Team'][i] == stack_var1 and 
                                                                    flex_file['Position'][i] in ('RB'))] + 
                                                                   [0*player_vars[qbid]]) == 0
                                            if flex_file['Position'][qbid] == 'QB':
                                                total_score += pulp.lpSum([player_vars[i] for i in player_ids if 
                                                                   (flex_file['Team'][i] == opp_var1 and 
                                                                    flex_file['Position'][i] in ('WR', 'TE'))] + 
                                                                   [-ministack_var1*player_vars[qbid]]) >= 0
                                        for flex in flex_file['Player'].unique():
                                                sub_idx = flex_file[flex_file['Player'] == qb_var].index
                                                total_score += pulp.lpSum([player_vars[idx] for idx in sub_idx]) == 1
                                    
                                    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_var1)
        
                                    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]) == 9
                                    
                                    for flex in flex_file['Position'].unique():
                                        sub_idx = flex_file[flex_file['Position'] == "QB"].index
                                        total_score += pulp.lpSum([player_vars[idx] for idx in sub_idx]) == 1
                                    
                                    for flex in flex_file['Position'].unique():
                                        sub_idx = flex_file[flex_file['Position'] == "RB"].index
                                        total_score += pulp.lpSum([player_vars[idx] for idx in sub_idx]) <= 3
                                        
                                    for flex in flex_file['Position'].unique():
                                        sub_idx = flex_file[flex_file['Position'] == "RB"].index
                                        total_score += pulp.lpSum([player_vars[idx] for idx in sub_idx]) >= 2
        
                                    for flex in flex_file['Position'].unique():
                                        sub_idx = flex_file[flex_file['Position'] == "WR"].index
                                        total_score += pulp.lpSum([player_vars[idx] for idx in sub_idx]) <= 4
                                    
                                    for flex in flex_file['Position'].unique():
                                        sub_idx = flex_file[flex_file['Position'] == "WR"].index
                                        total_score += pulp.lpSum([player_vars[idx] for idx in sub_idx]) >= 3
        
                                    for flex in flex_file['Position'].unique():
                                        sub_idx = flex_file[flex_file['Position'] == "TE"].index
                                        total_score += pulp.lpSum([player_vars[idx] for idx in sub_idx]) == 1
                                    
                                    for flex in flex_file['Position'].unique():
                                        sub_idx = flex_file[flex_file['Position'] == "DST"].index
                                        total_score += pulp.lpSum([player_vars[idx] for idx in sub_idx]) == 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 = lineup_final.reset_index(drop=True)
                                
                                if site_var1 == 'Draftkings':
                                    line_hold = lineup_final[['Names']]
                                    line_hold['pos'] = line_hold['Names'].map(player_pos)
        
                                    for pname in range(0,len(line_hold)):
                                        if line_hold.iat[pname,1] == 'QB':
                                            if line_hold.iat[pname,0] not in p_used:
                                                sorted_lineup.append(line_hold.iat[pname,0])
                                    p_used.extend(sorted_lineup)        
                                    rbvar = 0
                                    for pname in range(0,len(line_hold)):
                                        if rbvar == 2:
                                            pname = len(line_hold)
                                        elif rbvar < 2:
                                            if line_hold.iat[pname,1] == 'RB':
                                                if line_hold.iat[pname,0] not in p_used:
                                                    sorted_lineup.append(line_hold.iat[pname,0])
                                                    rbvar = rbvar + 1
                                    p_used.extend(sorted_lineup)
                                    wrvar = 0
                                    for pname in range(0,len(line_hold)):
                                        if wrvar == 3:
                                            pname = len(line_hold)
                                        elif wrvar < 3:
                                            if line_hold.iat[pname,1] == 'WR':
                                                if line_hold.iat[pname,0] not in p_used:
                                                    sorted_lineup.append(line_hold.iat[pname,0])
                                                    wrvar = wrvar + 1
                                    p_used.extend(sorted_lineup)
                                    tevar = 0
                                    for pname in range(0,len(line_hold)):
                                        if tevar == 1:
                                            pname = len(line_hold)
                                        elif tevar < 1:
                                            if line_hold.iat[pname,1] == 'TE':
                                                if line_hold.iat[pname,0] not in p_used:
                                                    sorted_lineup.append(line_hold.iat[pname,0])
                                                    tevar = tevar + 1
                                    p_used.extend(sorted_lineup)
                                    
                                    for pname in range(0,len(line_hold)):
                                        if line_hold.iat[pname,1] != 'DST':
                                            if line_hold.iat[pname,0] not in p_used:
                                                sorted_lineup.append(line_hold.iat[pname,0])
                                    p_used.extend(sorted_lineup)
                                    
                                    for pname in range(0,len(line_hold)):
                                        if line_hold.iat[pname,1] == 'DST':
                                            if line_hold.iat[pname,0] not in p_used:
                                                sorted_lineup.append(line_hold.iat[pname,0])
                                    p_used.extend(sorted_lineup)
                                    
                                    lineup_final['sorted'] = sorted_lineup
                                    lineup_final = lineup_final.drop(columns=['Names'])
                                    lineup_final.rename(columns={"sorted": "Names"}, inplace = True)
                                      
                                elif site_var1 == 'Fanduel':
                                    line_hold = lineup_final[['Names']]
                                    line_hold['pos'] = line_hold['Names'].map(player_pos)
        
                                    for pname in range(0,len(line_hold)):
                                        if line_hold.iat[pname,1] == 'QB':
                                            if line_hold.iat[pname,0] not in p_used:
                                                sorted_lineup.append(line_hold.iat[pname,0])
                                    p_used.extend(sorted_lineup)        
                                    rbvar = 0
                                    for pname in range(0,len(line_hold)):
                                        if rbvar == 2:
                                            pname = len(line_hold)
                                        elif rbvar < 2:
                                            if line_hold.iat[pname,1] == 'RB':
                                                if line_hold.iat[pname,0] not in p_used:
                                                    sorted_lineup.append(line_hold.iat[pname,0])
                                                    rbvar = rbvar + 1
                                    p_used.extend(sorted_lineup)
                                    wrvar = 0
                                    for pname in range(0,len(line_hold)):
                                        if wrvar == 3:
                                            pname = len(line_hold)
                                        elif wrvar < 3:
                                            if line_hold.iat[pname,1] == 'WR':
                                                if line_hold.iat[pname,0] not in p_used:
                                                    sorted_lineup.append(line_hold.iat[pname,0])
                                                    wrvar = wrvar + 1
                                    p_used.extend(sorted_lineup)
                                    tevar = 0
                                    for pname in range(0,len(line_hold)):
                                        if tevar == 1:
                                            pname = len(line_hold)
                                        elif tevar < 1:
                                            if line_hold.iat[pname,1] == 'TE':
                                                if line_hold.iat[pname,0] not in p_used:
                                                    sorted_lineup.append(line_hold.iat[pname,0])
                                                    tevar = tevar + 1
                                    p_used.extend(sorted_lineup)
                                    
                                    for pname in range(0,len(line_hold)):
                                        if line_hold.iat[pname,1] != 'DST':
                                            if line_hold.iat[pname,0] not in p_used:
                                                sorted_lineup.append(line_hold.iat[pname,0])
                                    p_used.extend(sorted_lineup)
                                    
                                    for pname in range(0,len(line_hold)):
                                        if line_hold.iat[pname,1] == 'DST':
                                            if line_hold.iat[pname,0] not in p_used:
                                                sorted_lineup.append(line_hold.iat[pname,0])
                                    p_used.extend(sorted_lineup)
                                    
                                    lineup_final['sorted'] = sorted_lineup
                                    lineup_final = lineup_final.drop(columns=['Names'])
                                    lineup_final.rename(columns={"sorted": "Names"}, inplace = True)
                                      
                                lineup_test = lineup_final
                                lineup_final = lineup_final.T
                                lineup_final['Cost'] = total_cost
                                lineup_final['Proj'] = total_proj
                                lineup_final['Own'] = total_own
                            
                                lineup_test['Team'] = lineup_test['Names'].map(player_team)
                                lineup_test['Position'] = lineup_test['Names'].map(player_pos)
                                lineup_test['Salary'] = lineup_test['Names'].map(player_sal)
                                lineup_test['Proj'] = lineup_test['Names'].map(player_proj)
                                lineup_test['Own'] = lineup_test['Names'].map(player_own)
                                lineup_test = lineup_test.set_index('Names')
                                lineup_test.loc['Column_Total'] = lineup_test.sum(numeric_only=True, axis=0)
        
                                lineup_display.append(lineup_test)
        
                                with col2:
                                    with st.container():
                                        st.table(lineup_test)
        
                                max_proj = total_proj
                                max_own = total_own
        
                                check_list.append(total_proj)
        
                                portfolio = pd.concat([portfolio, lineup_final], ignore_index = True)
        
                                x += 1
    
                        if site_var1 == 'Draftkings':
                            portfolio.rename(columns={0: "QB", 1: "RB1", 2: "RB2", 3: "WR1", 4: "WR2", 5: "WR3", 6: "TE", 7: "UTIL", 8: "DST"}, inplace = True)
                        elif site_var1 == 'Fanduel':
                            portfolio.rename(columns={0: "QB", 1: "RB1", 2: "RB2", 3: "WR1", 4: "WR2", 5: "WR3", 6: "TE", 7: "UTIL", 8: "DST"}, 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'])
    
                        final_outcomes = portfolio[['QB', 'RB1', 'RB2', 'WR1', 'WR2', 'WR3', 'TE', 'UTIL', 'DST', 'Cost', 'Proj', 'Own']]
                        final_outcomes = final_outcomes.set_axis(['QB', 'RB1', 'RB2', 'WR1', 'WR2', 'WR3', 'TE', 'UTIL', 'DST', 'Cost', 'Proj', 'Own'], axis=1)
                        final_outcomes_export = pd.DataFrame()
                        final_outcomes_export['QB'] = final_outcomes['QB']
                        final_outcomes_export['RB1'] = final_outcomes['RB1']
                        final_outcomes_export['RB2'] = final_outcomes['RB2']
                        final_outcomes_export['WR1'] = final_outcomes['WR1']
                        final_outcomes_export['WR2'] = final_outcomes['WR2']
                        final_outcomes_export['WR3'] = final_outcomes['WR3']
                        final_outcomes_export['TE'] = final_outcomes['TE']
                        final_outcomes_export['UTIL'] = final_outcomes['UTIL']
                        final_outcomes_export['DST'] = final_outcomes['DST']
                        final_outcomes_export['Salary'] = final_outcomes['Cost']
                        final_outcomes_export['Own'] = final_outcomes['Own']
                        final_outcomes_export['Proj'] = final_outcomes['Proj']
                        if site_var1 == 'Draftkings':
                            final_outcomes_export['QB'].replace(dkid_dict, inplace=True)
                            final_outcomes_export['RB1'].replace(dkid_dict, inplace=True)
                            final_outcomes_export['RB2'].replace(dkid_dict, inplace=True)
                            final_outcomes_export['WR1'].replace(dkid_dict, inplace=True)
                            final_outcomes_export['WR2'].replace(dkid_dict, inplace=True)
                            final_outcomes_export['WR3'].replace(dkid_dict, inplace=True)
                            final_outcomes_export['TE'].replace(dkid_dict, inplace=True)
                            final_outcomes_export['UTIL'].replace(dkid_dict, inplace=True)
                            final_outcomes_export['DST'].replace(dkid_dict, inplace=True)
                        elif site_var1 == 'Fanduel':
                            final_outcomes_export['QB'].replace(fdid_dict, inplace=True)
                            final_outcomes_export['RB1'].replace(fdid_dict, inplace=True)
                            final_outcomes_export['RB2'].replace(fdid_dict, inplace=True)
                            final_outcomes_export['WR1'].replace(fdid_dict, inplace=True)
                            final_outcomes_export['WR2'].replace(fdid_dict, inplace=True)
                            final_outcomes_export['WR3'].replace(fdid_dict, inplace=True)
                            final_outcomes_export['TE'].replace(fdid_dict, inplace=True)
                            final_outcomes_export['UTIL'].replace(fdid_dict, inplace=True)
                            final_outcomes_export['DST'].replace(fdid_dict, inplace=True)

                        player_freq = pd.DataFrame(np.column_stack(np.unique(portfolio.iloc[:,0:8].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)
          
                        player_freq = player_freq[['Player', 'Position', 'Team', 'Salary', 'Proj Own', 'Exposure']]
                        player_freq = player_freq.set_index('Player')
    
                with optimize_container:
                    optimize_container = st.empty()
                    st.dataframe(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()
                    st.download_button(
                        label="Export Optimals",
                        data=convert_df_to_csv(final_outcomes_export),
                        file_name='NFL_optimals_export.csv',
                        mime='text/csv',
                    )
                with freq_container:
                    freq_container = st.empty()
                    st.dataframe(player_freq.style.background_gradient(axis=0).background_gradient(cmap='RdYlGn').format(expose_format, precision=2), use_container_width = True)