File size: 72,583 Bytes
eaab5cb
e0df468
 
eaab5cb
 
 
c3ad087
eaab5cb
 
 
c3ad087
eaab5cb
 
c3ad087
eaab5cb
 
 
 
 
 
 
 
 
 
 
 
 
c3ad087
eaab5cb
 
c3ad087
 
 
eaab5cb
 
 
 
2b9562f
eaab5cb
c3ad087
 
eaab5cb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a711b32
 
eaab5cb
 
 
 
 
 
 
 
a711b32
eaab5cb
 
 
46f54e7
 
eaab5cb
46f54e7
 
eaab5cb
46f54e7
 
 
 
eaab5cb
46f54e7
 
 
 
 
dcd9f86
 
a8ec7fe
 
 
46f54e7
 
 
 
 
 
eaab5cb
dcd9f86
eaab5cb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
46f54e7
 
 
 
 
eaab5cb
 
6e1f05e
686c32a
fac7bbc
6e1f05e
 
eaab5cb
 
 
 
 
 
 
 
 
 
 
46f54e7
 
eaab5cb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4cc9b5c
 
 
 
 
 
 
eaab5cb
 
 
4cc9b5c
48caae0
 
 
 
 
 
 
 
 
 
 
 
 
 
6fba1cb
48caae0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
eaab5cb
ba53c0d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
48caae0
04efa78
 
48caae0
46c3722
48caae0
46c3722
 
8d04544
 
04efa78
bae4ae7
 
05483ab
eaab5cb
 
ba53c0d
14318ba
ba53c0d
 
eb434e0
 
 
 
9a3c09c
04efa78
9a3c09c
 
 
04efa78
85c727e
afba186
90ad8a3
0f9ef0f
8ad0664
491456e
 
9a3c09c
 
04efa78
ba53c0d
8a7fead
ba53c0d
 
5cde114
b4fd05e
 
ec54e74
 
5f5581b
c562a1b
d982efa
5cde114
aa579ad
91350d8
ba53c0d
 
75a3284
ba53c0d
 
 
 
 
 
 
 
04efa78
aa579ad
75a3284
ba53c0d
 
 
 
04efa78
ba8dc14
ba53c0d
42557d9
919f740
c551cdd
eaab5cb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d92c977
4cc9b5c
 
 
 
eaab5cb
 
 
 
 
 
 
 
 
 
 
ba53c0d
ea42c54
ba53c0d
5104390
7d412d5
95741f9
eaab5cb
 
ba53c0d
 
 
 
da868a8
 
941c813
 
 
 
 
 
 
 
 
 
 
 
 
 
da868a8
b4e00b7
 
da868a8
 
941c813
 
 
 
 
 
 
da868a8
 
941c813
da868a8
 
 
 
b4e00b7
da868a8
941c813
da868a8
 
 
 
941c813
 
 
 
da868a8
941c813
 
 
 
da868a8
 
 
 
 
 
 
ba53c0d
 
b4e00b7
 
 
 
 
 
 
 
 
 
 
dc4baad
 
 
 
bf0a8f9
51bac5c
ba53c0d
 
b4e00b7
 
 
 
 
 
 
 
 
 
 
 
dc4baad
 
 
 
b4e00b7
bf0a8f9
 
 
ba53c0d
 
 
 
eaab5cb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1f8793d
eaab5cb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bae4ae7
eaab5cb
 
 
 
ba53c0d
 
 
 
 
 
bae4ae7
ba53c0d
2e9cf0a
ba53c0d
2e9cf0a
ba53c0d
 
 
 
 
 
2e9cf0a
ba53c0d
2e9cf0a
ba53c0d
 
 
 
fda3b08
7d412d5
 
 
 
9da6545
7d412d5
 
 
 
9da6545
7d412d5
 
 
 
9da6545
7d412d5
 
 
 
 
9da6545
ba53c0d
 
 
 
fda3b08
ba53c0d
 
 
 
 
 
 
 
 
 
 
 
 
fda3b08
ba53c0d
 
 
 
fda3b08
e0df468
 
eaab5cb
 
 
ef4cc9e
e0df468
 
eaab5cb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4cc9b5c
 
eaab5cb
 
 
 
 
 
 
 
 
 
 
 
4cc9b5c
 
 
 
eaab5cb
 
4cc9b5c
 
eaab5cb
 
 
 
 
 
 
 
e8b5dba
eaab5cb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ba53c0d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b166b68
ba53c0d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
11e3993
7d412d5
ba53c0d
 
11e3993
ba53c0d
 
11e3993
5104390
 
ba53c0d
11e3993
 
 
ba53c0d
 
 
 
 
 
 
 
 
 
 
89f5aa4
586a61c
ba53c0d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b166b68
ba53c0d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
11e3993
7d412d5
ba53c0d
 
11e3993
ba53c0d
 
11e3993
ba53c0d
11e3993
 
 
 
 
ba53c0d
 
 
 
 
 
 
 
 
 
 
 
918ec9b
586a61c
ba53c0d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
eaab5cb
ba53c0d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b166b68
ba53c0d
 
 
 
 
 
 
 
 
 
88d8846
ba53c0d
 
 
 
 
 
 
 
11e3993
7d412d5
ba53c0d
 
11e3993
ba53c0d
 
11e3993
ba53c0d
 
 
11e3993
 
 
 
 
 
 
ba53c0d
 
 
 
 
 
 
 
 
 
 
586a61c
ba53c0d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b166b68
ba53c0d
 
 
 
 
 
 
 
 
 
88d8846
ba53c0d
 
 
 
 
 
 
 
11e3993
7d412d5
ba53c0d
 
11e3993
ba53c0d
 
11e3993
ba53c0d
 
 
11e3993
 
 
 
 
 
 
ba53c0d
 
 
 
 
 
 
 
 
 
 
586a61c
ba53c0d
 
 
 
 
 
eaab5cb
 
 
 
 
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
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
import requests
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
from matplotlib.pyplot import figure
from matplotlib.offsetbox import OffsetImage, AnnotationBbox
#from scipy import stats
import matplotlib.lines as mlines
import matplotlib.transforms as mtransforms
import numpy as np
#import plotly.express as px
#!pip install chart_studio
# import chart_studio.tools as tls
#from bs4 import BeautifulSoup
import matplotlib.pyplot as plt
import numpy as np
import matplotlib.font_manager as font_manager
from datetime import datetime
import pytz
from datetime import date
datetime.now(pytz.timezone('US/Pacific')).strftime('%B %d, %Y')
# Configure Notebook
#%matplotlib inline
plt.style.use('fivethirtyeight')
sns.set_context("notebook")
import warnings
warnings.filterwarnings('ignore')
#from urllib.request import urlopen
import json
from datetime import date, timedelta
#import dataframe_image as dfi
#from os import listdir
#from os.path import isfile, join
import datetime
import seaborn as sns
import os
import calendar
#from IPython.display import display, HTML
import matplotlib.image as mpimg
#from skimage import io
#import difflib 


from datetime import datetime
import pytz
datetime.now(pytz.timezone('US/Pacific')).strftime('%B %d, %Y')
# Configure Notebook
#%matplotlib inline
plt.style.use('fivethirtyeight')
sns.set_context("notebook")
import warnings
warnings.filterwarnings('ignore')
# import yfpy
# from yfpy.query import YahooFantasySportsQuery
# import yahoo_oauth
import json
#import openpyxl
#from sklearn import preprocessing
from PIL import Image
import logging
import matplotlib.patches as patches
from matplotlib.patches import Rectangle
from matplotlib.font_manager import FontProperties
from matplotlib.offsetbox import OffsetImage, AnnotationBbox

import requests
#import pickle
import pandas as pd

# # Loop over the counter and format the API call
# r = requests.get('https://statsapi.web.nhl.com/api/v1/schedule?startDate=2023-10-01&endDate=2024-06-01')
# schedule = r.json()

# def flatten(t):
#     return [item for sublist in t for item in sublist]

# game_id = flatten([[x['gamePk'] for x in schedule['dates'][y]['games']] for y in range(0,len(schedule['dates']))])
# game_date = flatten([[x['gameDate'] for x in schedule['dates'][y]['games']] for y in range(0,len(schedule['dates']))])
# game_home = flatten([[x['teams']['home']['team']['name'] for x in schedule['dates'][y]['games']] for y in range(0,len(schedule['dates']))])
# game_away = flatten([[x['teams']['away']['team']['name'] for x in schedule['dates'][y]['games']] for y in range(0,len(schedule['dates']))])

# schedule_df = pd.DataFrame(data={'game_id': game_id, 'game_date' : game_date, 'game_home' : game_home, 'game_away' : game_away})
# schedule_df.game_date = pd.to_datetime(schedule_df['game_date']).dt.tz_convert(tz='US/Eastern').dt.date
# schedule_df = schedule_df.replace('Montréal Canadiens','Montreal Canadiens')
# schedule_df.head()

team_abv = pd.read_csv('team_abv.csv')

schedule = pd.read_html('https://www.hockey-reference.com/leagues/NHL_2025_games.html')[0]
    # schedule.to_csv('schedule/schedule_'+str(date.today())+'.csv')
# schedule = pd.read_csv('2024_schedule_href.csv')
schedule = schedule.replace('St Louis Blues','St. Louis Blues')

schedule_df = schedule.merge(right=team_abv,left_on='Visitor',right_on='team_name',how='inner',suffixes=['','_away']) 
schedule_df = schedule_df.merge(right=team_abv,left_on='Home',right_on='team_name',how='inner',suffixes=['','_home']) 
schedule_df['away_sym'] = '@'
schedule_df['home_sym'] = 'vs'


yahoo_weeks = pd.read_csv('yahoo_weeks.csv')
#yahoo_weeks['Number'] = yahoo_weeks['Number'].astype(int)
yahoo_weeks['Start'] = pd.to_datetime(yahoo_weeks['Start'])
yahoo_weeks['End'] = pd.to_datetime(yahoo_weeks['End'])
yahoo_weeks.head(5)

def highlight_cols(s):
    color = '#C2FEE9'
    return 'background-color: %s' % color
def highlight_cells(val):
    color = 'white' if val == ' ' else ''
    return 'background-color: {}'.format(color)

import matplotlib.pyplot as plt
import matplotlib.colors
cmap_total = matplotlib.colors.LinearSegmentedColormap.from_list("", ["#56B4E9","#FFFFFF","#F0E442"])
cmap_off = matplotlib.colors.LinearSegmentedColormap.from_list("", ["#FFFFFF","#F0E442"])
cmap_back = matplotlib.colors.LinearSegmentedColormap.from_list("", ["#FFFFFF","#56B4E9"])
cmap_sum = matplotlib.colors.LinearSegmentedColormap.from_list("", ["#FFFFFF","#F0E442"])

# schedule_df = schedule_df.merge(right=team_abv,left_on='game_away',right_on='team_name',how='inner',suffixes=['','_away']) 
# schedule_df = schedule_df.merge(right=team_abv,left_on='game_home',right_on='team_name',how='inner',suffixes=['','_home']) 
# schedule_df['away_sym'] = '@'
# schedule_df['home_sym'] = 'vs'



#if not os.path.isfile('standings/standings_'+str(date.today())+'.csv'):   
standings_df_old = pd.read_html('https://www.hockey-reference.com/leagues/NHL_2025_standings.html')[0].append(pd.read_html('https://www.hockey-reference.com/leagues/NHL_2025_standings.html')[1])
# standings_df_old = pd.read_csv('2024_standings_href.csv')
#    standings_df_old.to_csv('standings/standings_'+str(date.today())+'.csv')
#standings_df_old = pd.read_csv('standings/standings_'+str(date.today())+'.csv',index_col=[0])

standings_df = standings_df_old[standings_df_old['Unnamed: 0'].str[-8:] != 'Division'].sort_values('Unnamed: 0').reset_index(drop=True).rename(columns={'Unnamed: 0':'Team'})#.drop(columns='Unnamed: 0')
#standings_df = standings_df.replace('St. Louis Blues','St Louis Blues')
standings_df['GF/GP'] = standings_df['GF'].astype(int)/standings_df['GP'].astype(int)
standings_df['GA/GP'] = standings_df['GA'].astype(int)/standings_df['GP'].astype(int)
standings_df['GF_Rank']  = standings_df['GF/GP'].rank(ascending=True,method='first')/10-1.65
standings_df['GA_Rank'] = standings_df['GA/GP'].rank(ascending=False,method='first')/10-1.65
standings_df.Team = standings_df.Team.str.strip('*') 
standings_df = standings_df.merge(right=team_abv,left_on='Team',right_on='team_name')

schedule_stack = pd.DataFrame()
# schedule_stack['date'] = pd.to_datetime(list(schedule_df['game_date'])+list(schedule_df['game_date']))
schedule_stack['date'] = pd.to_datetime(list(schedule_df['Date'])+list(schedule_df['Date']))
schedule_stack['team'] = list(schedule_df['team_name'])+list(schedule_df['team_name_home'])
schedule_stack['team_abv'] = list(schedule_df['team_abv'])+list(schedule_df['team_abv_home'])
schedule_stack['symbol'] = list(schedule_df['away_sym'])+list(schedule_df['home_sym'])
schedule_stack['team_opponent'] =  list(schedule_df['team_name_home'])+list(schedule_df['team_name'])
schedule_stack['team_abv_home'] = list(schedule_df['team_abv_home'])+list(schedule_df['team_abv'])
schedule_stack = schedule_stack.merge(right=standings_df[['team_abv','GF_Rank']],left_on='team_abv',right_on='team_abv',how='inner',suffixes=("",'_y'))
schedule_stack = schedule_stack.merge(right=standings_df[['team_abv','GA_Rank']],left_on='team_abv_home',right_on='team_abv',how='inner',suffixes=("",'_y'))

schedule_stack = schedule_stack.merge(right=standings_df[['team_abv','GF_Rank']],left_on='team_abv',right_on='team_abv',how='inner',suffixes=("",'_y'))
schedule_stack = schedule_stack.merge(right=standings_df[['team_abv','GA_Rank']],left_on='team_abv_home',right_on='team_abv',how='inner',suffixes=("",'_y'))
 
 
list_o = schedule_stack.sort_values(['team','date'],ascending=[True,True]).reset_index(drop=True)
new_list = [x - y for x, y in zip(list_o['date'][1:], list_o['date'])]
b2b_list = [0] + [x.days for x in new_list]
b2b_list = [1 if x==1 else 0 for x in b2b_list]
test = list(schedule_stack.groupby(by='date').count()['team'])
offnight = [1 if x<15 else 0 for x in test]
offnight_df = pd.DataFrame({'date':schedule_stack.sort_values('date').date.unique(),'offnight':offnight}).sort_values('date').reset_index(drop=True)
schedule_stack = schedule_stack.merge(right=offnight_df,left_on='date',right_on='date',how='right')
schedule_stack = schedule_stack.sort_values(['team','date'],ascending=[True,True]).reset_index(drop=True)
schedule_stack['b2b'] = b2b_list

schedule_stack.date = pd.to_datetime(schedule_stack.date)

away_b2b = []
home_b2b = []
for i in range(0,len(schedule_stack)):
    away_b2b.append(schedule_stack[(schedule_stack.date[i]==schedule_stack.date)&(schedule_stack.team_opponent[i]==schedule_stack.team)].reset_index(drop=True)['b2b'][0])
    home_b2b.append(schedule_stack[(schedule_stack.date[i]==schedule_stack.date)&(schedule_stack.team[i]==schedule_stack.team)].reset_index(drop=True)['b2b'][0])

schedule_stack['away_b2b'] = away_b2b
schedule_stack['home_b2b'] = home_b2b

schedule_stack['away_b2b'] = schedule_stack['away_b2b'].replace(1,' &#128564;')
schedule_stack['away_b2b'] = schedule_stack['away_b2b'].replace(0,'')

schedule_stack['offnight_score'] = schedule_stack.groupby('date').team.transform('count')
print('we made it',schedule_stack.offnight_score.max())
schedule_stack.offnight_score = schedule_stack.offnight_score - 16
#schedule_stack.loc[schedule_stack['offnight_score'] > 0,'offnight_score'] = 0
schedule_stack.offnight_score = -1*schedule_stack.offnight_score
#print(schedule_stack.offnight_score.max())
schedule_stack.head()

FontProperties(fname='/System/Library/Fonts/Apple Color Emoji.ttc')

try: 
    data_r = requests.get("https://pub-api-ro.fantasysports.yahoo.com/fantasy/v2/league/453.l.public;out=settings/players;position=ALL;start=0;count=3000;sort=rank_season;search=;out=percent_owned;out=auction_values,ranks;ranks=season;ranks_by_position=season;out=expert_ranks;expert_ranks.rank_type=projected_season_remaining/draft_analysis;cut_types=diamond;slices=last7days?format=json_f").json()
    key_check = data_r['fantasy_content']['league']['players']

except KeyError:
    data_r = requests.get("https://pub-api-ro.fantasysports.yahoo.com/fantasy/v2/league/453.l.public;out=settings/players;position=ALL;start=0;count=400;sort=rank_season;search=;out=percent_owned;out=auction_values,ranks;ranks=season;ranks_by_position=season;out=expert_ranks;expert_ranks.rank_type=projected_season_remaining/draft_analysis;cut_types=diamond;slices=last7days?format=json_f").json()
    print('key_checked')

total_list = []

for x in data_r['fantasy_content']['league']['players']:
    single_list = []

    single_list.append(int(x['player']['player_id']))
    single_list.append(x['player']['player_ranks'][0]['player_rank']['rank_value'])
    single_list.append(x['player']['name']['full'])
    single_list.append(x['player']['name']['first'])
    single_list.append(x['player']['name']['last'])
    single_list.append(x['player']['draft_analysis']['average_pick'])
    single_list.append(x['player']['average_auction_cost'])
    single_list.append(x['player']['projected_auction_value'])
    single_list.append(x['player']['display_position'])
    single_list.append(x['player']['editorial_team_abbr'])
    if 'value' in x['player']['percent_owned']:
        single_list.append(x['player']['percent_owned']['value']/100)
    else:
        single_list.append(0)

    if 'status' in x['player']:
        single_list.append(x['player']['status'])
    else:
        single_list.append(True)
    
    total_list.append(single_list)


def get_all_teams():
    url = "https://statsapi.web.nhl.com/api/v1/teams"
    response = requests.get(url)
    data = response.json()

    # Extract team information from the response
    teams = []

    for team in data["teams"]:
        team_id = team["id"]
        team_name = team["name"]
        team_abbreviation = team["abbreviation"]
        team_city = team["locationName"]
        teams.append({"team_id": team_id, "team_name": team_name, "team_abb": team_abbreviation, "team_city": team_city})

    return teams


def get_all_players_teams():
    url = "https://statsapi.web.nhl.com/api/v1/teams?expand=team.roster"
    response = requests.get(url)
    data = response.json()

    # Extract player information from the response
    players_teams = []

    for team in data["teams"]:
        team_name = team["id"]
        #full_name = team["fullName"]

        for player in team["roster"]["roster"]:
            player_id = player["person"]["id"]
            full_name = player["person"]["fullName"]
            players_teams.append({"player_id": player_id,"full_name":full_name,"team_id": team_name})

    return players_teams

df_2023 = pd.DataFrame(data=total_list,columns=['player_id','rank_value','full','first','last','average_pick', 'average_cost','display_position','projected_auction_value','editorial_team_abbr','percent_owned','status'])


# df_2023 = pd.read_csv('df_2023_small.csv',index_col=[0])
df_2023.percent_owned = df_2023.percent_owned.astype(float)
#df_2023.columns = ['player_id','rank_value','full','first','last','average_pick', 'average_cost','display_position','projected_auction_value','editorial_team_abbr','percent_owned','status']
df_2023.status = df_2023.status.astype(str)
df_2023 = df_2023[df_2023.status.isin(['True','DTD'])]

df_2023.percent_owned = df_2023.percent_owned.astype(float)
print('Jack Hughes',df_2023[df_2023.full == 'Jack Hughes'])

yahoo_weeks['Number'] = yahoo_weeks['Number'].astype(float).astype(int)
#yahoo_weeks['Week'] = yahoo_weeks['Week'].astype(float).astype(int)
week_dict = yahoo_weeks.set_index('Number')['Week'].sort_index().to_dict()


player_games = pd.read_csv('data/player_games_cards.csv',index_col=[0]).sort_values(by='date').drop_duplicates(subset=['player_id','date'])
team_games = pd.read_csv('data/team_games.csv',index_col=[0])


team_last = player_games.drop_duplicates(subset=['player_id'],keep='last')[['player_id','Team']].set_index('player_id')['Team'].to_dict()

player_games['Team'] = player_games['player_id'].map(team_last)
# players_df = pd.DataFrame(get_all_players_teams())

# teams_df = pd.DataFrame(get_all_teams())
# teams_df.team_name = teams_df.team_name.replace({'Montréal Canadiens':'Montreal Canadiens'})
# teams_df.team_abb  = teams_df.team_name.map(team_abv.set_index('team_name').team_abv.to_dict())

teams_df = pd.read_csv('teams.csv',index_col=[0])
team_games = team_games.replace('St. Louis Blues','St Louis Blues')
team_games = team_games.replace('St Louis Blues','St. Louis Blues')
# team_games = team_games.replace('Montréal Canadiens','Montreal Canadiens')
# team_games = team_games.replace('Montreal Canadiens','Montréal Canadiens')
team_games = team_games.merge(teams_df,left_on='team',right_on='team_name')
team_games.team_abv = team_games.team.map(team_abv.set_index('team_name').team_abv.to_dict())

# players_df = players_df.merge(teams_df)


team_games.team_abb = team_games.team_abv.replace({'LAK':'L.A','SJS':'S.J','NJD':'N.J','TBL':'T.B'})
yahoo_to_nhl = pd.read_csv("data/yahoo_to_nhl.csv",index_col=[0], encoding='unicode_escape')

#yahoo_df_scrape = pd.read_csv('df_2023_small.csv',index_col=[0])


# yahoo_df_scrape = pd.read_csv('df_2023_small.csv',index_col=[0])
yahoo_df_scrape = df_2023.copy()
yahoo_df_scrape.percent_owned = yahoo_df_scrape.percent_owned.astype(float)
yahoo_df_scrape.columns = ['yahoo_id','idx','full','first','last','average_pick','average_auction_cost','projected_auction_value','position','team','percent_owned','status']
yahoo_df_scrape.status = yahoo_df_scrape.status.astype(str)
yahoo_df_scrape = yahoo_df_scrape[yahoo_df_scrape.status.isin(['True','DTD'])]
#percent_roster_dict = yahoo_df_scrape.
#yahoo_df_scrape = pd.DataFrame(total_list,columns=['yahoo_id','idx','full','first','last','average_pick','average_auction_cost','projected_auction_value','position','team','percent_owned'])

yahoo_final_df = yahoo_df_scrape.merge(right=yahoo_to_nhl,left_on='yahoo_id',right_index=True,how='left',suffixes=['','_x'])
#yahoo_final_df = yahoo_final_df.dropna(subset=['status']) 
player_games_dd = player_games.drop_duplicates(['player_id']).reset_index(drop=True)

player_games = player_games.merge(right=yahoo_to_nhl.reset_index(),left_on='player_id',right_on='nhl_id',how='left')

player_games = player_games.merge(yahoo_final_df,left_on='player_id_yahoo',right_on='yahoo_id',how='left')
player_games.loc[player_games.position.isna(),'position'] = player_games.loc[player_games.position.isna(),'Position']

player_games.position = player_games.position.replace({'L':'LW','R':'RW'})
print('Jack Hughes',player_games[player_games.Player == 'Jack Hughes'].percent_owned)
player_games.percent_owned = player_games.percent_owned.fillna(0)
player_games = player_games.dropna(subset=['status'])

player_games['S_H_B'] = player_games['Shots'] + player_games['Hits'] + player_games['Shots Blocked']


player_games = player_games.merge(right=team_games,left_on=['date','Team'],right_on=['date','team_abb'],how='left')
player_games = player_games.fillna(0)

player_games = player_games.drop_duplicates(subset=['player_id','date'])
#player_games = player_games.replace([np.inf, -np.inf], 0, inplace=True)

from shiny import ui, render, App
import matplotlib.image as mpimg
# app_ui = ui.page_fluid(

#     # ui.output_plot("plot"),
#     #ui.h2('MLB Batter Launch Angle vs Exit Velocity'),
#     ui.layout_sidebar(
#         ui.panel_sidebar(
#             ui.input_select("id", "Select Batter",batter_dict),

#             ui.input_select("plot_id", "Select Plot",{'scatter':'Scatter Plot','dist':'Distribution Plot'})))
#         ,

#     ui.panel_main(ui.output_plot("plot",height = "750px",width="1250px")),
#     #ui.download_button('test','Download'),
# )
#import shinyswatch
app_ui = ui.page_fluid(
    #shinyswatch.theme.cosmo(),
    ui.layout_sidebar(
    
    # Available themes:
    #  cerulean, cosmo, cyborg, darkly, flatly, journal, litera, lumen, lux,
    #  materia, minty, morph, pulse, quartz, sandstone, simplex, sketchy, slate,
    #  solar, spacelab, superhero, united, vapor, yeti, zephyr
        
      ui.panel_sidebar(
            ui.input_select("week_id", "Select Week (Set as Season for Custom Date Range)",week_dict,width=1),
            ui.input_select("sort_id", "Sort Column",['Score','Team','Total','Off-Night','B2B'],width=1),
            ui.input_switch("a_d_id", "Ascending?"),
            #ui.input_select("date_id", "Select Date",yahoo_weeks['Week'],width=1),
            ui.input_date_range("date_range_id", "Date range input",start = datetime.today().date(), end = datetime.today().date() + timedelta(days=6)),
            
            ui.input_date_range("scorer_date_id", "Streamer Stats Date Range",start = max(datetime.today().date()- timedelta(days=21),pd.to_datetime('2023-10-10')), end = datetime.today().date()),
            ui.input_numeric('min_games','Min. Games (Streamers)',value=3),
            ui.input_numeric('max_head','Number of Rows (Streamers)',value=15),
            ui.input_numeric('roster_p','Max Roster Percent% (Streamers)',value=50),
            ui.output_table("result"),width=3),
         
        
        ui.panel_main(
            
            ui.navset_tab(
                    ui.nav("Schedule",
                        ui.div(
                            ui.tags.head(
                                ui.tags.script({"src": "https://html2canvas.hertzen.com/dist/html2canvas.min.js"}),
                                ui.tags.style("""
                                    #capture-div {
                                        display: inline-block;
                                        background-color: white; 
                                        padding: 20px;
                                        width: fit-content;
                                        height: fit-content;
                                    }
                                    .table-container {
                                        width: auto;
                                        height: auto;
                                    }
                                """)
                            ),
                            
                            ui.row(ui.tags.button(
                                "Download as PNG",
                                {"onclick": """
                                    html2canvas(document.getElementById('capture-div'), {
                                        scale: 2,
                                        useCORS: true,
                                        backgroundColor: '#ffffff',
                                        windowWidth: document.getElementById('capture-div').scrollWidth,
                                        windowHeight: document.getElementById('capture-div').scrollHeight
                                    }).then(function(canvas) {
                                        var link = document.createElement('a');
                                        link.download = 'fantasy-hockey-schedule.png';
                                        link.href = canvas.toDataURL('image/png');
                                        link.click();
                                    });
                                """},
                                {"style": "margin: 10px 0;"}
                            )),
                            ui.div(
                                {"id": "capture-div"},
                                ui.tags.h3(""),
                                ui.div({"style": "font-size:2em;"}, ui.output_text("txt_title")),
                                ui.tags.h5("Created By: @TJStats,     Data: NHL"),
                                ui.div({"style": "font-size:1.2em;"}, ui.output_text("txt")),
                                ui.div(
                                    {"class": "table-container"},
                                    ui.output_table("schedule_result")
                                ),
                                ui.tags.h5('Legend'),
                                ui.div(
                                    {"class": "table-container"},
                                    ui.output_table("schedule_result_legend")
                                ),
                                ui.tags.h6('An Off Night is defined as a day in which less than half the teams in the NHL are playing'),
                                ui.tags.h6('The scores are determined by using games played, off-nights, B2B, and strength of opponents')
                            )
                        )
                )
                
                ,

                    ui.nav("Scorers Streamers",
                                ui.tags.h3(""),
                                ui.div({"style": "font-size:2.7em;"}, ui.output_text("txt_title_streamers")),
                                ui.tags.h5("Created By: @TJStats,     Data: NHL, Natural Stat Trick, Yahoo Fantasy"),
                                ui.div({"style": "font-size:2em;"}, ui.output_text("txt_title_streamers_roster_f")),
                                ui.div({"style": "font-size:1em;"}, ui.output_text("txt_title_streamers_dates_f")),
                                ui.div(
                                    {"class": "table-container"},
                                    ui.output_table("scorer_streamers_f")
                                ),
                                ui.tags.h3(""),
                                ui.div({"style": "font-size:2em;"}, ui.output_text("txt_title_streamers_roster_d")),
                                                           ui.div(
                                    {"class": "table-container"},
                                    ui.output_table("scorer_streamers_d")
                                )
 
                                ),

                    ui.nav("Bangers Streamers",
                                ui.tags.h3(""),
                                ui.div({"style": "font-size:2.7em;"}, ui.output_text("txt_title_streamers_bang")),
                                ui.tags.h5("Created By: @TJStats,     Data: NHL, Natural Stat Trick, Yahoo Fantasy"),
                                ui.div({"style": "font-size:2em;"}, ui.output_text("txt_title_streamers_roster_f_bang")),
                                ui.div({"style": "font-size:1em;"}, ui.output_text("txt_title_streamers_dates_f_bang")),
                                ui.div(
                                    {"class": "table-container"},
                                    ui.output_table("banger_streamers_f")
                                ),
                                ui.tags.h3(""),
                                ui.div({"style": "font-size:2em;"}, ui.output_text("txt_title_streamers_roster_d_bang")),
                                ui.div({"style": "font-size:1em;"}, ui.output_text("txt_title_streamers_dates_d_bang")),
                                ui.div(
                                    {"class": "table-container"},
                                    ui.output_table("banger_streamers_d")
                                )
                                )
                            
                        
                           
                    
                           

        ))))
        #  ui.row(
        #         ui.column(
        #             3,
        #                 ui.input_date("x", "Date input"),),
        #         ui.column(
        #             1,
        #             ui.input_select("level_id", "Select Level",level_dict,width=1)),
        #         ui.column(
        #             3,
        #             ui.input_select("stat_id", "Select Stat",plot_dict_small,width=1)),
        #         ui.column(
        #             2,
        #             ui.input_numeric("n", "Rolling Window Size", value=50)),
        #         ),
        #             ui.output_table("result_batters")),

                # ui.nav(
                #     "Pitchers",

                #                 ui.row(
                # ui.column(
                #     3,
                #     ui.input_select("id_pitch", "Select Pitcher",pitcher_dict,width=1,selected=675911),
                #     ),
                # ui.column(
                #     1,
                #     ui.input_select("level_id_pitch", "Select Level",level_dict,width=1)),
                # ui.column(
                #     3,
                #     ui.input_select("stat_id_pitch", "Select Stat",plot_dict_small_pitch,width=1)),
                # ui.column(
                #     2,
                #         ui.input_numeric("n_pitch", "Rolling Window Size", value=50)),
                # ),
                #     ui.output_table("result_pitchers")),
#             )
#         )
# )




from urllib.request import Request, urlopen
# importing OpenCV(cv2) module




def server(input, output, session):

    @output
    @render.text
    def txt():
        
        week_set = int(float(input.week_id()))
        if week_set != 0:
            if pd.to_datetime(yahoo_weeks[yahoo_weeks.Number == week_set]['Start'].values[0]).year != pd.to_datetime(yahoo_weeks[yahoo_weeks.Number == week_set]['End'].values[0]).year:

                return f'{pd.to_datetime(yahoo_weeks[yahoo_weeks.Number == week_set]["Start"].values[0]).strftime("%B %d, %Y")} to {pd.to_datetime(yahoo_weeks[yahoo_weeks.Number == week_set]["End"].values[0]).strftime("%B %d, %Y")}'
            else:
                if pd.to_datetime(yahoo_weeks[yahoo_weeks.Number == week_set]["Start"].values[0]).month != pd.to_datetime(yahoo_weeks[yahoo_weeks.Number == week_set]["End"].values[0]).month:
                    return f'{pd.to_datetime(yahoo_weeks[yahoo_weeks.Number == week_set]["Start"].values[0]).strftime("%B %d")} to {pd.to_datetime(yahoo_weeks[yahoo_weeks.Number == week_set]["End"].values[0]).strftime("%B %d, %Y")}'
                else:
                    return f'{pd.to_datetime(yahoo_weeks[yahoo_weeks.Number == week_set]["Start"].values[0]).strftime("%B %d")} to {pd.to_datetime(yahoo_weeks[yahoo_weeks.Number == week_set]["End"].values[0]).strftime("%d, %Y")}'
        else:
            if input.date_range_id()[0].year != input.date_range_id()[1].year:

                return f'{input.date_range_id()[0].strftime("%B %d, %Y")} to {input.date_range_id()[1].strftime("%B %d, %Y")}'
            else:
                if input.date_range_id()[0].month != input.date_range_id()[1].month:
                    return f'{input.date_range_id()[0].strftime("%B %d")} to {input.date_range_id()[1].strftime("%B %d, %Y")}'
                else:
                    return f'{input.date_range_id()[0].strftime("%B %d")} to {input.date_range_id()[1].strftime("%d, %Y")}'            


    @output
    @render.text
    def txt_title():
        week_set = int(float(input.week_id()))
        if week_set != 0:
            return f'Fantasy Hockey Schedule Summary - Yahoo - Week {input.week_id()}'
        else:
            return f'Fantasy Hockey Schedule Summary'
        


    @output
    @render.text
    def txt_title_streamers():
        week_set = int(float(input.week_id()))
        if week_set != 0:
            return f'Fantasy Hockey Scorers Targets - Week {input.week_id()}'
        else:
            return f'Fantasy Hockey Scorers Targets'

    @output
    @render.text
    def txt_title_streamers_bang():
        week_set = int(input.week_id())
        if week_set != 0:
            return f'Fantasy Hockey Bangers Targets - Week {input.week_id()}'
        else:
            return f'Fantasy Hockey Bangers Targets'

    @output
    @render.text
    def txt_title_streamers_dates_f():
        return f'2024-25 Season - {input.scorer_date_id()[0]} to {input.scorer_date_id()[1]} (min. {input.min_games()} GP)'
    
    @output
    @render.text
    def txt_title_streamers_roster_f():
        return f'Forwards Scorers Targets (<{input.roster_p()/100:.0%} Rostered)'
    
    @output
    @render.text
    def txt_title_streamers_roster_d():
        return f'Defense Scorers Targets (<{input.roster_p()/100:.0%} Rostered)'
    
    @output
    @render.text
    def txt_title_streamers_roster_f_bang():
        return f'Forwards Bangers Targets (<{input.roster_p()/100:.0%} Rostered)'


    @output
    @render.text
    def txt_title_streamers_roster_d_bang():
        return f'Defense Bangers Targets (<{input.roster_p()/100:.0%} Rostered)'

    @output
    @render.text
    def txt_title_streamers_dates_d():
        return f'2024-25 Season - {input.scorer_date_id()[0]} to {input.scorer_date_id()[1]} (min. {input.min_games()} GP)'
    

    def txt_title_streamers_bang():
        week_set = int(input.week_id())
        if week_set != 0:
            return f'Fantasy Hockey Scorers Streamers - Week {input.week_id()}'
        else:
            return f'Fantasy Hockey Scorers Streamers'
        

    @output
    @render.text
    def txt_title_streamers_dates_f_bang():
        return f'2024-25 Season - {input.scorer_date_id()[0]} to {input.scorer_date_id()[1]} (min. {input.min_games()} GP)'

    @output
    @render.text
    def txt_title_streamers_dates_d_bang():
        return f'2024-25 Season - {input.scorer_date_id()[0]} to {input.scorer_date_id()[1]} (min. {input.min_games()} GP)'

    @output
    @render.table
    def result():
        #print(yahoo_weeks)
        return yahoo_weeks[['Week','Start','End']]

    @output
    @render.table
    def schedule_result():
        

        week_set = int(input.week_id())
        print(week_set)

        if week_set == 0:
            start_point = input.date_range_id()[0]
            end_point = input.date_range_id()[1]
        else:   
            start_point = yahoo_weeks[yahoo_weeks.Number==week_set].reset_index(drop=True)['Start'][0]
            end_point = yahoo_weeks[yahoo_weeks.Number==week_set].reset_index(drop=True)['End'][0]


        sort_value='Score'
        ascend=False

        weekly_stack = schedule_stack[(schedule_stack['date'].dt.date>=start_point)&(schedule_stack['date'].dt.date<=end_point)]
        date_list = pd.date_range(start_point,end_point,freq='d')
        test_list = [[]] * len(date_list)



        for i in range(0,len(date_list)):
            test_list[i]  = team_abv.merge(right=weekly_stack[weekly_stack['date']==date_list[i]],left_on='team_abv',right_on='team_abv',how='left')
            test_list[i] = test_list[i].fillna("")
            test_list[i]['new_text'] = test_list[i]['symbol'] + ' '+ test_list[i]['team_abv_home'] + test_list[i]['away_b2b']


        test_df = pd.DataFrame()
        test_df['Team'] = list(team_abv['team_abv'])
        test_df['Total'] = test_df.merge(right=weekly_stack.groupby('team_abv')['team_abv'].apply(lambda x: x[x != ''].count()),left_on=['Team'],right_index=True,how='left').fillna(0)['team_abv']

        test_df['Off-Night'] = test_df.merge(right=weekly_stack.groupby('team_abv').sum()['offnight_score'],left_on=['Team'],right_index=True,how='left').fillna(0)['offnight_score']
        test_df['B2B']= test_df.merge(right=weekly_stack.groupby('team_abv').sum()['b2b'],left_on=['Team'],right_index=True,how='left').fillna(0)['b2b']



        gf_rank = np.array(test_df.merge(right=weekly_stack.groupby('team_abv').mean()['GF_Rank'],left_on=['Team'],right_index=True,how='left').fillna(0)['GF_Rank'])
        ga_rank = np.array(test_df.merge(right=weekly_stack.groupby('team_abv').mean()['GA_Rank'],left_on=['Team'],right_index=True,how='left').fillna(0)['GA_Rank'])


        #games_vs_tired = np.array([float(i)*0.4 for i in list(weekly_stack.groupby('team_abv')['away_b2b'].apply(lambda x: x[x != ''].count()))])

        games_vs_tired = 0.4*np.array(test_df.merge(right=weekly_stack.groupby('team_abv')['away_b2b'].apply(lambda x: x[x != ''].count()),left_on=['Team'],right_index=True,how='left').fillna(0)['away_b2b'])

        print('test_df')
        print(test_df)
        #team_score = test_df['Total']+test_df['Off-Night']*0.5+test_df['B2B']*-0.2+games_vs_tired*0.3+gf_rank*0.1+ga_rank*0.1
        team_score = test_df['Total']+test_df['Off-Night']*0.03+test_df['B2B']*-0.2+games_vs_tired*0.3+gf_rank*0.1+ga_rank*0.1
        test_df['Score'] = team_score

        test_df['Off-Night'] = test_df.merge(right=weekly_stack.groupby('team_abv').sum()['offnight'],left_on=['Team'],right_index=True,how='left').fillna(0)['offnight']
        
        cols = test_df.columns.tolist();
        L = len(cols) 
        test_df = test_df[cols[4:]+cols[0:4]]
        #return test_df#[cols[4:]+cols[0:4]]

        test_df = test_df.sort_values(by=[sort_value,'Score'],ascending = ascend)

        for i in range(0,len(date_list)):
            test_df[calendar.day_name[date_list[i].weekday()]+'<br>'+str(date_list[i].month).zfill(2)+'-'+'{:02d}'.format(date_list[i].day)] = test_list[i]['new_text']

        row = ['']*L
        for x in  test_df[test_df.columns[L:]]:
            row.append(int(sum(test_df[x]!=" ")/2))

        test_df = test_df.sort_values(by=input.sort_id(),ascending=input.a_d_id())

        test_df.loc[32] = row
        #test_df_html = HTML( test_df.to_html().replace("\\n","<br>") ) 
        offnight_list = [True if x <8 else False for x in test_df.iloc[-1][L:]]

        test_df.style.applymap(highlight_cols,subset = ((list(test_df.index[:-1]),test_df.columns[L:][offnight_list])))
        test_df_style = test_df.style.set_properties(**{'border': '3 px'},overwrite=False).set_table_styles([{
            'selector': 'caption',
            'props': [
                ('color', ''),
                ('fontname', 'Century Gothic'),
                ('font-size', '20px'),
                ('font-style', 'italic'),
                ('font-weight', ''),
                ('text-align', 'centre'),
                ]

                },{'selector' :'th', 'props':[('text-align', 'center'),('Height','px'),('color','black'),('border', '1px black solid !important')]},{'selector' :'td', 'props':[('text-align', 'center'),('font-size', '18px'),('color','black')]}],overwrite=False).set_properties(
                    **{'background-color':'White','index':'White','min-width':'75px'},overwrite=False).set_properties(
                    **{'background-color':'White','index':'White','min-width':'100px'},overwrite=False,subset = ((list(test_df.index[:]),test_df.columns[5:]))).set_table_styles(
            [{'selector': 'th:first-child', 'props': [('background-color', 'white')]}],overwrite=False).set_table_styles(
            [{'selector': 'tr:first-child', 'props': [('background-color', 'white')]}],overwrite=False).set_table_styles(
            [{'selector': 'tr', 'props': [('line-height', '20px')]}],overwrite=False).set_properties(
            **{'Height': '8px'},**{'text-align': 'center'},overwrite=False).hide_index()

        test_df_style = test_df_style.applymap(highlight_cols,subset = ((list(test_df.index[:-1]),test_df.columns[L:][offnight_list])))

        test_df_style = test_df_style.applymap(highlight_cells)
        test_df_style = test_df_style.background_gradient(cmap=cmap_total,subset = ((list(test_df.index[:-1]),test_df.columns[0])))
        test_df_style = test_df_style.background_gradient(cmap=cmap_total,vmin=0,vmax=np.max(test_df.Total[:len(test_df)-1]),subset = ((list(test_df.index[:-1]),test_df.columns[2])))
        test_df_style = test_df_style.background_gradient(cmap=cmap_off,subset = ((list(test_df.index[:-1]),test_df.columns[3])))
        test_df_style = test_df_style.background_gradient(cmap=cmap_back,subset = ((list(test_df.index[:-1]),test_df.columns[4])))
        test_df_style = test_df_style.background_gradient(cmap=cmap_sum,subset = ((list(test_df.index[-1:]),test_df.columns[L:])),axis=1)
        test_df_style = test_df_style.set_properties(
                    **{'border': '1px black solid !important'},subset = ((list(test_df.index[:-1]),test_df.columns[:]))).set_properties(
                    **{'min-width':'85px'},subset = ((list(test_df.index[:-1]),test_df.columns[L:])),overwrite=False).set_properties(**{
                                'color': 'black'},overwrite=False).set_properties(
                    **{'border': '1px black solid !important'},subset = ((list(test_df.index[:]),test_df.columns[L:])))

        test_df_style = test_df_style.format(
            '{:.0f}',subset=(test_df.index[:-1],test_df.columns[2:L]))

        test_df_style = test_df_style.format(
            '{:.1f}',subset=(test_df.index[:-1],test_df.columns[0]))


        print('made it to teh end')
        return test_df_style


        #return exit_velo_df_codes_summ_time_style_set

    # @output
    # @render.plot(alt="A histogram")
    # def plot_pitch():
    #     p
    @output
    @render.table
    def schedule_result_legend():

        off_b2b_df = pd.DataFrame(data={'off':'Off-Night','b2b':'Tired Opp. &#128564;'},index=[0])
        #off_b2b_df.style.applymap(highlight_cols,subset = ((list(off_b2b_df.index[:-1]),off_b2b_df.columns[0])))
        off_b2b_df_style = off_b2b_df.style.set_properties(**{'border': '3 px'},overwrite=False).set_table_styles([{
            'selector': 'caption',
            'props': [
                ('color', ''),
                ('fontname', 'Century Gothic'),
                ('font-size', '20px'),
                ('font-style', 'italic'),
                ('font-weight', ''),
                ('text-align', 'centre'),
                ]

                },{'selector' :'th', 'props':[('text-align', 'center'),('Height','px'),('color','black'),(
                    'border', '1px black solid !important')]},{'selector' :'td', 'props':[('text-align', 'center'),('font-size', '18px'),('color','black')]}],overwrite=False).set_properties(
                    **{'background-color':'White','index':'White','min-width':'150px'},overwrite=False).set_table_styles(
            [{'selector': 'th:first-child', 'props': [('background-color', 'white')]}],overwrite=False).set_table_styles(
            [{'selector': 'tr:first-child', 'props': [('background-color', 'white')]}],overwrite=False).set_table_styles(
            [{'selector': 'tr', 'props': [('line-height', '20px')]}],overwrite=False).set_properties(
            **{'Height': '8px'},**{'text-align': 'center'},overwrite=False).set_properties(
                **{'background-color':'#C2FEE9'},subset=off_b2b_df.columns[0]).set_properties(
                **{'color':'black'},subset=off_b2b_df.columns[:]).hide_index().set_table_styles([
            {'selector': 'thead', 'props': [('display', 'none')]}
            ]).set_properties(**{'border': '3 px','color':'black'},overwrite=False).set_properties(
                    **{'border': '1px black solid !important'},subset = ((list(off_b2b_df.index[:]),off_b2b_df.columns[:]))).set_properties(
                    **{'min-width':'130'},subset = ((list(off_b2b_df.index[:]),off_b2b_df.columns[:])),overwrite=False).set_properties(**{
                                'color': 'black'},overwrite=False).set_properties(
                    **{'border': '1px black solid !important'},subset = ((list(off_b2b_df.index[:]),off_b2b_df.columns[:])))
        
        return off_b2b_df_style

    @output
    @render.table
    def scorer_streamers_f():
        

        week_set = int(input.week_id())
        print(week_set)

        if week_set == 0:
            start_point = input.date_range_id()[0]
            end_point = input.date_range_id()[1]
        else:   
            start_point = yahoo_weeks[yahoo_weeks.Number==week_set].reset_index(drop=True)['Start'][0]
            end_point = yahoo_weeks[yahoo_weeks.Number==week_set].reset_index(drop=True)['End'][0]


        sort_value='Score'
        ascend=False

        weekly_stack = schedule_stack[(schedule_stack['date'].dt.date>=start_point)&(schedule_stack['date'].dt.date<=end_point)]
        date_list = pd.date_range(start_point,end_point,freq='d')
        test_list = [[]] * len(date_list)



        for i in range(0,len(date_list)):
            test_list[i]  = team_abv.merge(right=weekly_stack[weekly_stack['date']==date_list[i]],left_on='team_abv',right_on='team_abv',how='left')
            test_list[i] = test_list[i].fillna("")
            test_list[i]['new_text'] = test_list[i]['symbol'] + ' '+ test_list[i]['team_abv_home'] + test_list[i]['away_b2b']


        test_df = pd.DataFrame()
        test_df['Team'] = list(team_abv['team_abv'])
        test_df['Total'] = test_df.merge(right=weekly_stack.groupby('team_abv')['team_abv'].apply(lambda x: x[x != ''].count()),left_on=['Team'],right_index=True,how='left').fillna(0)['team_abv']

        test_df['Off-Night'] = test_df.merge(right=weekly_stack.groupby('team_abv').sum()['offnight_score'],left_on=['Team'],right_index=True,how='left').fillna(0)['offnight_score']
        test_df['B2B']= test_df.merge(right=weekly_stack.groupby('team_abv').sum()['b2b'],left_on=['Team'],right_index=True,how='left').fillna(0)['b2b']



        gf_rank = np.array(test_df.merge(right=weekly_stack.groupby('team_abv').mean()['GF_Rank'],left_on=['Team'],right_index=True,how='left').fillna(0)['GF_Rank'])
        ga_rank = np.array(test_df.merge(right=weekly_stack.groupby('team_abv').mean()['GA_Rank'],left_on=['Team'],right_index=True,how='left').fillna(0)['GA_Rank'])


        #games_vs_tired = np.array([float(i)*0.4 for i in list(weekly_stack.groupby('team_abv')['away_b2b'].apply(lambda x: x[x != ''].count()))])

        games_vs_tired = 0.4*np.array(test_df.merge(right=weekly_stack.groupby('team_abv')['away_b2b'].apply(lambda x: x[x != ''].count()),left_on=['Team'],right_index=True,how='left').fillna(0)['away_b2b'])

        print('test_df')
        print(test_df)
        #team_score = test_df['Total']+test_df['Off-Night']*0.5+test_df['B2B']*-0.2+games_vs_tired*0.3+gf_rank*0.1+ga_rank*0.1
        team_score = test_df['Total']+test_df['Off-Night']*0.03+test_df['B2B']*-0.2+games_vs_tired*0.3+gf_rank*0.1+ga_rank*0.1
        test_df['Score'] = team_score

        test_df['Off-Night'] = test_df.merge(right=weekly_stack.groupby('team_abv').sum()['offnight'],left_on=['Team'],right_index=True,how='left').fillna(0)['offnight']
        
        cols = test_df.columns.tolist();
        L = len(cols) 
        test_df = test_df[cols[4:]+cols[0:4]]
        #return test_df#[cols[4:]+cols[0:4]]

        test_df = test_df.sort_values(by=[sort_value,'Score'],ascending = ascend)

        for i in range(0,len(date_list)):
            test_df[calendar.day_name[date_list[i].weekday()]+'<br>'+str(date_list[i].month)+'-'+'{:02d}'.format(date_list[i].day)] = test_list[i]['new_text']

        row = ['']*L
        for x in  test_df[test_df.columns[L:]]:
            row.append(int(sum(test_df[x]!=" ")/2))

        test_df = test_df.sort_values(by=input.sort_id(),ascending=input.a_d_id())

        test_df.loc[32] = row
        #test_df_html = HTML( test_df.to_html().replace("\\n","<br>") ) 
        offnight_list = [True if x <8 else False for x in test_df.iloc[-1][L:]]



        
        start_date = input.scorer_date_id()[0]
        end_date = input.scorer_date_id()[1]
        gp_min = input.min_games()

        df_dated = player_games[(pd.to_datetime(player_games.date) >= pd.to_datetime(start_date))&(pd.to_datetime(player_games.date) <= pd.to_datetime(end_date))]

        team_top = test_df[test_df.Score!=''][np.array(test_df[test_df.Score!=''].Score) >= np.array(test_df[test_df.Score!='']['Score']).max()*0.75]['Team'].values
        if(len(team_top)) < 5:
            team_top = test_df.Team.values[:5]

        df_dated_score_group = df_dated.groupby(['player_id','Player','Team','position','percent_owned']).agg(
            GP = ('GP','sum'),
            TOI = ('TOI','sum'),
            Goals = ('Goals','sum'),
            ixG = ('ixG','sum'),
            Assists = ('Total Assists','sum'),
            Points = ('Total Points','sum'),
            Shots = ('Shots','sum'),
            PP_Points = ('Total Points_pp','sum'),
            PP_toi = ('TOI_pp','sum'),
            team_pp = ('pp_toi','sum'),
        )#.reset_index()

        df_dated_score_group = df_dated_score_group[(df_dated_score_group.GP >= gp_min)]
        df_dated_score_group[df_dated_score_group.columns[1:]] = df_dated_score_group[df_dated_score_group.columns[1:]].divide(df_dated_score_group.GP,axis=0)
        df_dated_score_group['PP_percent'] = df_dated_score_group.PP_toi / df_dated_score_group.team_pp
        df_dated_score_group = df_dated_score_group.reset_index()
        df_dated_score_group = df_dated_score_group.merge(test_df[['Team','Off-Night']],left_on=['Team'],right_on=['Team'])
        df_dated_score_group = df_dated_score_group[(df_dated_score_group.Team.isin(team_top))&(df_dated_score_group.percent_owned <= input.roster_p()/100 )]
        df_dated_score_group['TOI'] = ["%d:%02d" % (int(x),(x*60)%60) for x in df_dated_score_group['TOI'].astype(float)]
        df_dated_score_group_table = df_dated_score_group[['Player','Team' ,'position', 'percent_owned', 'GP', 'TOI',
            'Goals', 'ixG', 'Assists', 'Points', 'Shots', 'PP_Points', 'PP_percent','Off-Night']].sort_values(['Points','Off-Night','PP_percent','Goals','Shots'],ascending=False)

        df_dated_score_group_table.columns = ['Player','Team' ,'Position', 'Roster%', 'GP', 'TOI/GP',
            'Goals/GP', 'ixG/GP','Assists/GP', 'Points/GP', 'Shots/GP', 'PPP/GP', 'PP%','Off-Night']
        
        

        return df_dated_score_group_table[df_dated_score_group_table.Position != 'D'].head(input.max_head()).style.background_gradient(
            cmap=cmap_off, subset=['Points/GP']).background_gradient(cmap=cmap_total, subset=['Roster%']).background_gradient(cmap=cmap_off, subset=['Off-Night'],vmin=0,vmax=df_dated_score_group_table['Off-Night'].max()).hide_index().set_properties(**{'Height': '12px'},**{'text-align': 'center'})\
            .set_table_styles([{
            'selector': 'caption',
            'props': [
                ('color', ''),
                ('fontname', 'Century Gothic'),
                ('font-size', '20px'),
                ('font-style', 'italic'),
                ('font-weight', ''),
                ('text-align', 'centre'),
                ]

                },{'selector' :'th', 'props':[('text-align', 'center'),('Height','5px'),('border', '1px black solid !important') ]},{'selector' :'td', 'props':[('text-align', 'center'),('font-size', '13px'),('border', '1px black solid !important')]}]).format(
                    {'Roster%': '{:.0%}','GP': '{:.0f}','Goals/GP': '{:.2f}','ixG/GP': '{:.2f}','Assists/GP': '{:.2f}',
                    'Points/GP': '{:.2f}','Shots/GP': '{:.2f}','PPP/GP': '{:.2f}','PP%': '{:.0%}','Off-Night': '{:.0f}'},).set_properties(
                        **{'border': '1px black solid !important'}).set_properties(
                    **{'min-width':'175px'},subset = ((df_dated_score_group_table.columns[0])),overwrite=False).set_properties(
                    **{'min-width':'50px'},subset = ((df_dated_score_group_table.columns[1:])),overwrite=False)
    

    @output
    @render.table
    def scorer_streamers_d():
        

        week_set = int(input.week_id())
        print(week_set)

        if week_set == 0:
            start_point = input.date_range_id()[0]
            end_point = input.date_range_id()[1]
        else:   
            start_point = yahoo_weeks[yahoo_weeks.Number==week_set].reset_index(drop=True)['Start'][0]
            end_point = yahoo_weeks[yahoo_weeks.Number==week_set].reset_index(drop=True)['End'][0]


        sort_value='Score'
        ascend=False

        weekly_stack = schedule_stack[(schedule_stack['date'].dt.date>=start_point)&(schedule_stack['date'].dt.date<=end_point)]
        date_list = pd.date_range(start_point,end_point,freq='d')
        test_list = [[]] * len(date_list)



        for i in range(0,len(date_list)):
            test_list[i]  = team_abv.merge(right=weekly_stack[weekly_stack['date']==date_list[i]],left_on='team_abv',right_on='team_abv',how='left')
            test_list[i] = test_list[i].fillna("")
            test_list[i]['new_text'] = test_list[i]['symbol'] + ' '+ test_list[i]['team_abv_home'] + test_list[i]['away_b2b']


        test_df = pd.DataFrame()
        test_df['Team'] = list(team_abv['team_abv'])
        test_df['Total'] = test_df.merge(right=weekly_stack.groupby('team_abv')['team_abv'].apply(lambda x: x[x != ''].count()),left_on=['Team'],right_index=True,how='left').fillna(0)['team_abv']

        test_df['Off-Night'] = test_df.merge(right=weekly_stack.groupby('team_abv').sum()['offnight_score'],left_on=['Team'],right_index=True,how='left').fillna(0)['offnight_score']
        test_df['B2B']= test_df.merge(right=weekly_stack.groupby('team_abv').sum()['b2b'],left_on=['Team'],right_index=True,how='left').fillna(0)['b2b']



        gf_rank = np.array(test_df.merge(right=weekly_stack.groupby('team_abv').mean()['GF_Rank'],left_on=['Team'],right_index=True,how='left').fillna(0)['GF_Rank'])
        ga_rank = np.array(test_df.merge(right=weekly_stack.groupby('team_abv').mean()['GA_Rank'],left_on=['Team'],right_index=True,how='left').fillna(0)['GA_Rank'])


        #games_vs_tired = np.array([float(i)*0.4 for i in list(weekly_stack.groupby('team_abv')['away_b2b'].apply(lambda x: x[x != ''].count()))])

        games_vs_tired = 0.4*np.array(test_df.merge(right=weekly_stack.groupby('team_abv')['away_b2b'].apply(lambda x: x[x != ''].count()),left_on=['Team'],right_index=True,how='left').fillna(0)['away_b2b'])

        print('test_df')
        print(test_df)
        #team_score = test_df['Total']+test_df['Off-Night']*0.5+test_df['B2B']*-0.2+games_vs_tired*0.3+gf_rank*0.1+ga_rank*0.1
        team_score = test_df['Total']+test_df['Off-Night']*0.03+test_df['B2B']*-0.2+games_vs_tired*0.3+gf_rank*0.1+ga_rank*0.1
        test_df['Score'] = team_score

        test_df['Off-Night'] = test_df.merge(right=weekly_stack.groupby('team_abv').sum()['offnight'],left_on=['Team'],right_index=True,how='left').fillna(0)['offnight']
        
        cols = test_df.columns.tolist();
        L = len(cols) 
        test_df = test_df[cols[4:]+cols[0:4]]
        #return test_df#[cols[4:]+cols[0:4]]

        test_df = test_df.sort_values(by=[sort_value,'Score'],ascending = ascend)

        for i in range(0,len(date_list)):
            test_df[calendar.day_name[date_list[i].weekday()]+'<br>'+str(date_list[i].month)+'-'+'{:02d}'.format(date_list[i].day)] = test_list[i]['new_text']

        row = ['']*L
        for x in  test_df[test_df.columns[L:]]:
            row.append(int(sum(test_df[x]!=" ")/2))

        test_df = test_df.sort_values(by=input.sort_id(),ascending=input.a_d_id())

        test_df.loc[32] = row
        #test_df_html = HTML( test_df.to_html().replace("\\n","<br>") ) 
        offnight_list = [True if x <8 else False for x in test_df.iloc[-1][L:]]



        
        start_date = input.scorer_date_id()[0]
        end_date = input.scorer_date_id()[1]
        gp_min = input.min_games()

        df_dated = player_games[(pd.to_datetime(player_games.date) >= pd.to_datetime(start_date))&(pd.to_datetime(player_games.date) <= pd.to_datetime(end_date))]

        team_top = test_df[test_df.Score!=''][np.array(test_df[test_df.Score!=''].Score) >= np.array(test_df[test_df.Score!='']['Score']).max()*0.75]['Team'].values
        if(len(team_top)) < 5:
            team_top = test_df.Team.values[:5]

        df_dated_score_group = df_dated.groupby(['player_id','Player','Team','position','percent_owned']).agg(
            GP = ('GP','sum'),
            TOI = ('TOI','sum'),
            Goals = ('Goals','sum'),
            ixG = ('ixG','sum'),
            Assists = ('Total Assists','sum'),
            Points = ('Total Points','sum'),
            Shots = ('Shots','sum'),
            PP_Points = ('Total Points_pp','sum'),
            PP_toi = ('TOI_pp','sum'),
            team_pp = ('pp_toi','sum'),
        )#.reset_index()

        df_dated_score_group = df_dated_score_group[(df_dated_score_group.GP >= gp_min)]
        df_dated_score_group[df_dated_score_group.columns[1:]] = df_dated_score_group[df_dated_score_group.columns[1:]].divide(df_dated_score_group.GP,axis=0)
        df_dated_score_group['PP_percent'] = df_dated_score_group.PP_toi / df_dated_score_group.team_pp
        df_dated_score_group = df_dated_score_group.reset_index()
        df_dated_score_group = df_dated_score_group.merge(test_df[['Team','Off-Night']],left_on=['Team'],right_on=['Team'])
        df_dated_score_group = df_dated_score_group[(df_dated_score_group.Team.isin(team_top))&(df_dated_score_group.percent_owned <= input.roster_p()/100 )]
        df_dated_score_group['TOI'] = ["%d:%02d" % (int(x),(x*60)%60) for x in df_dated_score_group['TOI'].astype(float)]
        df_dated_score_group_table = df_dated_score_group[['Player','Team' ,'position', 'percent_owned', 'GP', 'TOI',
            'Goals', 'ixG', 'Assists', 'Points', 'Shots', 'PP_Points', 'PP_percent','Off-Night']].sort_values(['Points','Off-Night','PP_percent','Goals','Shots'],ascending=False)

        df_dated_score_group_table.columns = ['Player','Team' ,'Position', 'Roster%', 'GP', 'TOI/GP',
            'Goals/GP', 'ixG/GP','Assists/GP', 'Points/GP', 'Shots/GP', 'PPP/GP', 'PP%','Off-Night']

        return df_dated_score_group_table[df_dated_score_group_table.Position == 'D'].head(input.max_head()) \
        .style.background_gradient(cmap=cmap_off, subset=['Points/GP']) \
        .background_gradient(cmap=cmap_total, subset=['Roster%']) \
        .background_gradient(cmap=cmap_off, subset=['Off-Night'],vmin=0,vmax=df_dated_score_group_table['Off-Night'].max()) \
        .hide_index().set_properties(**{'Height': '12px'},**{'text-align': 'center'})\
        .set_table_styles([{
            'selector': 'caption',
            'props': [
                ('color', ''),
                ('fontname', 'Century Gothic'),
                ('font-size', '20px'),
                ('font-style', 'italic'),
                ('font-weight', ''),
                ('text-align', 'centre'),
                ]

                },{'selector' :'th', 'props':[('text-align', 'center'),('Height','5px'),('border', '1px black solid !important') ]},{'selector' :'td', 'props':[('text-align', 'center'),('font-size', '13px'),('border', '1px black solid !important')]}]).format(
                    {'Roster%': '{:.0%}','GP': '{:.0f}','Goals/GP': '{:.2f}','ixG/GP': '{:.2f}','Assists/GP': '{:.2f}',
                    'Points/GP': '{:.2f}','Shots/GP': '{:.2f}','PPP/GP': '{:.2f}','PP%': '{:.0%}','Off-Night': '{:.0f}'},).set_properties(
                        **{'border': '1px black solid !important'}).set_properties(
                    **{'min-width':'175px'},subset = ((df_dated_score_group_table.columns[0])),overwrite=False).set_properties(
                    **{'min-width':'50px'},subset = ((df_dated_score_group_table.columns[1:])),overwrite=False)

    @output
    @render.table
    def banger_streamers_f():
        

        week_set = int(input.week_id())
        print(week_set)

        if week_set == 0:
            start_point = input.date_range_id()[0]
            end_point = input.date_range_id()[1]
        else:   
            start_point = yahoo_weeks[yahoo_weeks.Number==week_set].reset_index(drop=True)['Start'][0]
            end_point = yahoo_weeks[yahoo_weeks.Number==week_set].reset_index(drop=True)['End'][0]


        sort_value='Score'
        ascend=False

        weekly_stack = schedule_stack[(schedule_stack['date'].dt.date>=start_point)&(schedule_stack['date'].dt.date<=end_point)]
        date_list = pd.date_range(start_point,end_point,freq='d')
        test_list = [[]] * len(date_list)



        for i in range(0,len(date_list)):
            test_list[i]  = team_abv.merge(right=weekly_stack[weekly_stack['date']==date_list[i]],left_on='team_abv',right_on='team_abv',how='left')
            test_list[i] = test_list[i].fillna("")
            test_list[i]['new_text'] = test_list[i]['symbol'] + ' '+ test_list[i]['team_abv_home'] + test_list[i]['away_b2b']


        test_df = pd.DataFrame()
        test_df['Team'] = list(team_abv['team_abv'])
        test_df['Total'] = test_df.merge(right=weekly_stack.groupby('team_abv')['team_abv'].apply(lambda x: x[x != ''].count()),left_on=['Team'],right_index=True,how='left').fillna(0)['team_abv']

        test_df['Off-Night'] = test_df.merge(right=weekly_stack.groupby('team_abv').sum()['offnight_score'],left_on=['Team'],right_index=True,how='left').fillna(0)['offnight_score']
        test_df['B2B']= test_df.merge(right=weekly_stack.groupby('team_abv').sum()['b2b'],left_on=['Team'],right_index=True,how='left').fillna(0)['b2b']



        gf_rank = np.array(test_df.merge(right=weekly_stack.groupby('team_abv').mean()['GF_Rank'],left_on=['Team'],right_index=True,how='left').fillna(0)['GF_Rank'])
        ga_rank = np.array(test_df.merge(right=weekly_stack.groupby('team_abv').mean()['GA_Rank'],left_on=['Team'],right_index=True,how='left').fillna(0)['GA_Rank'])


        #games_vs_tired = np.array([float(i)*0.4 for i in list(weekly_stack.groupby('team_abv')['away_b2b'].apply(lambda x: x[x != ''].count()))])

        games_vs_tired = 0.4*np.array(test_df.merge(right=weekly_stack.groupby('team_abv')['away_b2b'].apply(lambda x: x[x != ''].count()),left_on=['Team'],right_index=True,how='left').fillna(0)['away_b2b'])

        print('test_df')
        print(test_df)
        #team_score = test_df['Total']+test_df['Off-Night']*0.5+test_df['B2B']*-0.2+games_vs_tired*0.3+gf_rank*0.1+ga_rank*0.1
        team_score = test_df['Total']+test_df['Off-Night']*0.03+test_df['B2B']*-0.2+games_vs_tired*0.3+gf_rank*0.1+ga_rank*0.1
        test_df['Score'] = team_score

        test_df['Off-Night'] = test_df.merge(right=weekly_stack.groupby('team_abv').sum()['offnight'],left_on=['Team'],right_index=True,how='left').fillna(0)['offnight']
        
        cols = test_df.columns.tolist();
        L = len(cols) 
        test_df = test_df[cols[4:]+cols[0:4]]
        #return test_df#[cols[4:]+cols[0:4]]

        test_df = test_df.sort_values(by=[sort_value,'Score'],ascending = ascend)

        for i in range(0,len(date_list)):
            test_df[calendar.day_name[date_list[i].weekday()]+'<br>'+str(date_list[i].month)+'-'+'{:02d}'.format(date_list[i].day)] = test_list[i]['new_text']

        row = ['']*L
        for x in  test_df[test_df.columns[L:]]:
            row.append(int(sum(test_df[x]!=" ")/2))

        test_df = test_df.sort_values(by=input.sort_id(),ascending=input.a_d_id())

        test_df.loc[32] = row
        #test_df_html = HTML( test_df.to_html().replace("\\n","<br>") ) 
        offnight_list = [True if x <8 else False for x in test_df.iloc[-1][L:]]



        
        start_date = input.scorer_date_id()[0]
        end_date = input.scorer_date_id()[1]
        gp_min = input.min_games()

        df_dated = player_games[(pd.to_datetime(player_games.date) >= pd.to_datetime(start_date))&(pd.to_datetime(player_games.date) <= pd.to_datetime(end_date))]

        team_top = test_df[test_df.Score!=''][np.array(test_df[test_df.Score!=''].Score) >= np.array(test_df[test_df.Score!='']['Score']).max()*0.75]['Team'].values
        if(len(team_top)) < 5:
            team_top = test_df.Team.values[:5]

        df_dated_bangers_group = df_dated.groupby(['player_id','Player','Team','position','percent_owned']).agg(
            GP = ('GP','sum'),
            TOI = ('TOI','sum'),
            Goals = ('Goals','sum'),
            Assists = ('Total Assists','sum'),  
            Points = ('Total Points','sum'),    
            Shots = ('Shots','sum'),
            Hits = ('Hits','sum'),
            Blocks = ('Shots Blocked','sum'),
            S_H_B = ('S_H_B','sum'),
        )#.reset_index()

        df_dated_bangers_group = df_dated_bangers_group[(df_dated_bangers_group.GP >= gp_min)]
        df_dated_bangers_group[df_dated_bangers_group.columns[1:]] = df_dated_bangers_group[df_dated_bangers_group.columns[1:]].divide(df_dated_bangers_group.GP,axis=0)
        #df_dated_bangers_group['PP_percent'] = df_dated_bangers_group.PP_toi / df_dated_bangers_group.team_pp
        df_dated_bangers_group = df_dated_bangers_group.reset_index()
        df_dated_bangers_group = df_dated_bangers_group.merge(test_df[['Team','Off-Night']],left_on=['Team'],right_on=['Team'])
        df_dated_bangers_group = df_dated_bangers_group[(df_dated_bangers_group.Team.isin(team_top))&(df_dated_bangers_group.percent_owned <= input.roster_p()/100 )]
        df_dated_bangers_group['TOI'] = ["%d:%02d" % (int(x),(x*60)%60) for x in df_dated_bangers_group['TOI'].astype(float)]
        df_dated_bangers_group_table = df_dated_bangers_group[['Player','Team' ,'position', 'percent_owned', 'GP', 'TOI',
            'Goals', 'Assists', 'Points', 'Shots', 'Hits', 'Blocks','S_H_B','Off-Night']].sort_values(['S_H_B','Off-Night','Shots','Hits','Blocks','Points'],ascending=False)
            
        df_dated_bangers_group_table.columns = ['Player','Team' ,'Position', 'Roster%', 'GP', 'TOI/GP',
            'Goals/GP', 'Assists/GP', 'Points/GP', 'Shots/GP', 'Hits/GP', 'Blocks/GP','S+H+B/GP','Off-Night']

        #df_dated_bangers_group_table.head(15)

        return df_dated_bangers_group_table[df_dated_bangers_group_table.Position != 'D'] \
            .head(input.max_head()).style.background_gradient(cmap=cmap_off, subset=['S+H+B/GP'])\
            .background_gradient(cmap=cmap_total, subset=['Roster%'])\
            .background_gradient(cmap=cmap_off, subset=['Off-Night'],vmin=0,vmax=df_dated_bangers_group_table['Off-Night'].max())\
            .hide_index()\
            .set_properties(**{'Height': '12px'},**{'text-align': 'center'})\
            .set_table_styles([{
            'selector': 'caption',
            'props': [
                ('color', ''),
                ('fontname', 'Century Gothic'),
                ('font-size', '20px'),
                ('font-style', 'italic'),
                ('font-weight', ''),
                ('text-align', 'centre'),
                ]

                },{'selector' :'th', 'props':[('text-align', 'center'),('Height','5px'),('border', '1px black solid !important') ]},{'selector' :'td', 'props':[('text-align', 'center'),('font-size', '13px'),('border', '1px black solid !important')]}]).format(
                    {'Roster%': '{:.0%}','GP': '{:.0f}','Goals/GP': '{:.2f}','Assists/GP': '{:.2f}','Points/GP': '{:.2f}','PIM/GP': '{:.2f}','Shots/GP': '{:.2f}','Hits/GP': '{:.2f}','Blocks/GP': '{:.2f}','S+H+B/GP': '{:.2f}','Off-Night': '{:.0f}'},).set_properties(
                **{'border': '1px black solid !important'}).set_properties(
                    **{'min-width':'175px'},subset = ((df_dated_bangers_group_table.columns[0])),overwrite=False).set_properties(
                    **{'min-width':'50px'},subset = ((df_dated_bangers_group_table.columns[1:])),overwrite=False)
        

    @output
    @render.table
    def banger_streamers_d():
        

        week_set = int(input.week_id())
        print(week_set)

        if week_set == 0:
            start_point = input.date_range_id()[0]
            end_point = input.date_range_id()[1]
        else:   
            start_point = yahoo_weeks[yahoo_weeks.Number==week_set].reset_index(drop=True)['Start'][0]
            end_point = yahoo_weeks[yahoo_weeks.Number==week_set].reset_index(drop=True)['End'][0]


        sort_value='Score'
        ascend=False

        weekly_stack = schedule_stack[(schedule_stack['date'].dt.date>=start_point)&(schedule_stack['date'].dt.date<=end_point)]
        date_list = pd.date_range(start_point,end_point,freq='d')
        test_list = [[]] * len(date_list)



        for i in range(0,len(date_list)):
            test_list[i]  = team_abv.merge(right=weekly_stack[weekly_stack['date']==date_list[i]],left_on='team_abv',right_on='team_abv',how='left')
            test_list[i] = test_list[i].fillna("")
            test_list[i]['new_text'] = test_list[i]['symbol'] + ' '+ test_list[i]['team_abv_home'] + test_list[i]['away_b2b']


        test_df = pd.DataFrame()
        test_df['Team'] = list(team_abv['team_abv'])
        test_df['Total'] = test_df.merge(right=weekly_stack.groupby('team_abv')['team_abv'].apply(lambda x: x[x != ''].count()),left_on=['Team'],right_index=True,how='left').fillna(0)['team_abv']

        test_df['Off-Night'] = test_df.merge(right=weekly_stack.groupby('team_abv').sum()['offnight_score'],left_on=['Team'],right_index=True,how='left').fillna(0)['offnight_score']
        test_df['B2B']= test_df.merge(right=weekly_stack.groupby('team_abv').sum()['b2b'],left_on=['Team'],right_index=True,how='left').fillna(0)['b2b']



        gf_rank = np.array(test_df.merge(right=weekly_stack.groupby('team_abv').mean()['GF_Rank'],left_on=['Team'],right_index=True,how='left').fillna(0)['GF_Rank'])
        ga_rank = np.array(test_df.merge(right=weekly_stack.groupby('team_abv').mean()['GA_Rank'],left_on=['Team'],right_index=True,how='left').fillna(0)['GA_Rank'])


        #games_vs_tired = np.array([float(i)*0.4 for i in list(weekly_stack.groupby('team_abv')['away_b2b'].apply(lambda x: x[x != ''].count()))])

        games_vs_tired = 0.4*np.array(test_df.merge(right=weekly_stack.groupby('team_abv')['away_b2b'].apply(lambda x: x[x != ''].count()),left_on=['Team'],right_index=True,how='left').fillna(0)['away_b2b'])

        print('test_df')
        print(test_df)
        #team_score = test_df['Total']+test_df['Off-Night']*0.5+test_df['B2B']*-0.2+games_vs_tired*0.3+gf_rank*0.1+ga_rank*0.1
        team_score = test_df['Total']+test_df['Off-Night']*0.03+test_df['B2B']*-0.2+games_vs_tired*0.3+gf_rank*0.1+ga_rank*0.1
        test_df['Score'] = team_score

        test_df['Off-Night'] = test_df.merge(right=weekly_stack.groupby('team_abv').sum()['offnight'],left_on=['Team'],right_index=True,how='left').fillna(0)['offnight']
        
        cols = test_df.columns.tolist();
        L = len(cols) 
        test_df = test_df[cols[4:]+cols[0:4]]
        #return test_df#[cols[4:]+cols[0:4]]

        test_df = test_df.sort_values(by=[sort_value,'Score'],ascending = ascend)

        for i in range(0,len(date_list)):
            test_df[calendar.day_name[date_list[i].weekday()]+'<br>'+str(date_list[i].month)+'-'+'{:02d}'.format(date_list[i].day)] = test_list[i]['new_text']

        row = ['']*L
        for x in  test_df[test_df.columns[L:]]:
            row.append(int(sum(test_df[x]!=" ")/2))

        test_df = test_df.sort_values(by=input.sort_id(),ascending=input.a_d_id())

        test_df.loc[32] = row
        #test_df_html = HTML( test_df.to_html().replace("\\n","<br>") ) 
        offnight_list = [True if x <8 else False for x in test_df.iloc[-1][L:]]



        
        start_date = input.scorer_date_id()[0]
        end_date = input.scorer_date_id()[1]
        gp_min = input.min_games()

        df_dated = player_games[(pd.to_datetime(player_games.date) >= pd.to_datetime(start_date))&(pd.to_datetime(player_games.date) <= pd.to_datetime(end_date))]

        team_top = test_df[test_df.Score!=''][np.array(test_df[test_df.Score!=''].Score) >= np.array(test_df[test_df.Score!='']['Score']).max()*0.75]['Team'].values
        if(len(team_top)) < 5:
            team_top = test_df.Team.values[:5]

        df_dated_bangers_group = df_dated.groupby(['player_id','Player','Team','position','percent_owned']).agg(
            GP = ('GP','sum'),
            TOI = ('TOI','sum'),
            Goals = ('Goals','sum'),
            Assists = ('Total Assists','sum'),  
            Points = ('Total Points','sum'),    
            Shots = ('Shots','sum'),
            Hits = ('Hits','sum'),
            Blocks = ('Shots Blocked','sum'),
            S_H_B = ('S_H_B','sum'),
        )#.reset_index()

        df_dated_bangers_group = df_dated_bangers_group[(df_dated_bangers_group.GP >= gp_min)]
        df_dated_bangers_group[df_dated_bangers_group.columns[1:]] = df_dated_bangers_group[df_dated_bangers_group.columns[1:]].divide(df_dated_bangers_group.GP,axis=0)
        #df_dated_bangers_group['PP_percent'] = df_dated_bangers_group.PP_toi / df_dated_bangers_group.team_pp
        df_dated_bangers_group = df_dated_bangers_group.reset_index()
        df_dated_bangers_group = df_dated_bangers_group.merge(test_df[['Team','Off-Night']],left_on=['Team'],right_on=['Team'])
        df_dated_bangers_group = df_dated_bangers_group[(df_dated_bangers_group.Team.isin(team_top))&(df_dated_bangers_group.percent_owned <= input.roster_p()/100 )]
        df_dated_bangers_group['TOI'] = ["%d:%02d" % (int(x),(x*60)%60) for x in df_dated_bangers_group['TOI'].astype(float)]
        df_dated_bangers_group_table = df_dated_bangers_group[['Player','Team' ,'position', 'percent_owned', 'GP', 'TOI',
            'Goals', 'Assists', 'Points', 'Shots', 'Hits', 'Blocks','S_H_B','Off-Night']].sort_values(['S_H_B','Off-Night','Shots','Hits','Blocks','Points'],ascending=False)
            
        df_dated_bangers_group_table.columns = ['Player','Team' ,'Position', 'Roster%', 'GP', 'TOI/GP',
            'Goals/GP', 'Assists/GP', 'Points/GP', 'Shots/GP', 'Hits/GP', 'Blocks/GP','S+H+B/GP','Off-Night']

        #df_dated_bangers_group_table.head(15)

        return df_dated_bangers_group_table[df_dated_bangers_group_table.Position == 'D']\
            .head(input.max_head()).style.background_gradient(cmap=cmap_off, subset=['S+H+B/GP'])\
            .background_gradient(cmap=cmap_total, subset=['Roster%'])\
            .background_gradient(cmap=cmap_off, subset=['Off-Night'],vmin=0,vmax=df_dated_bangers_group_table['Off-Night'].max())\
            .hide_index()\
            .set_properties(**{'Height': '12px'},**{'text-align': 'center'})\
            .set_table_styles([{
            'selector': 'caption',
            'props': [
                ('color', ''),
                ('fontname', 'Century Gothic'),
                ('font-size', '20px'),
                ('font-style', 'italic'),
                ('font-weight', ''),
                ('text-align', 'centre'),
                ]

                },{'selector' :'th', 'props':[('text-align', 'center'),('Height','5px'),('border', '1px black solid !important') ]},{'selector' :'td', 'props':[('text-align', 'center'),('font-size', '13px'),('border', '1px black solid !important')]}]).format(
                    {'Roster%': '{:.0%}','GP': '{:.0f}','Goals/GP': '{:.2f}','Assists/GP': '{:.2f}','Points/GP': '{:.2f}','PIM/GP': '{:.2f}','Shots/GP': '{:.2f}','Hits/GP': '{:.2f}','Blocks/GP': '{:.2f}','S+H+B/GP': '{:.2f}','Off-Night': '{:.0f}'},).set_properties(
                **{'border': '1px black solid !important'}).set_properties(
                    **{'min-width':'175px'},subset = ((df_dated_bangers_group_table.columns[0])),overwrite=False).set_properties(
                    **{'min-width':'50px'},subset = ((df_dated_bangers_group_table.columns[1:])),overwrite=False)


        




app = App(app_ui, server)