File size: 21,365 Bytes
9a59ac4
 
eaab5cb
e0df468
 
eaab5cb
 
 
9a59ac4
eaab5cb
 
 
9a59ac4
c3ad087
eaab5cb
9a59ac4
 
eaab5cb
 
 
 
 
9a59ac4
 
 
 
eaab5cb
 
 
 
 
 
 
 
 
 
 
a711b32
1faf464
9a59ac4
1faf464
9a59ac4
 
 
 
 
 
eaab5cb
1faf464
 
 
 
 
 
9a59ac4
 
1faf464
 
9a59ac4
1faf464
 
 
 
 
ae30f51
9a59ac4
1faf464
9a59ac4
eaab5cb
611e6cc
 
 
b124522
611e6cc
 
b124522
9a59ac4
eaab5cb
9a59ac4
677c08e
 
e03f991
10ccea2
 
eaab5cb
 
2de228e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
46232ea
 
 
ee434ed
9a59ac4
3f2f598
073a4a7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9a59ac4
 
 
 
 
3cbecca
9a59ac4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7dfd7fc
9a59ac4
 
 
d1f3cb7
0cdc2da
92c725c
d1f3cb7
90005c6
 
d1f3cb7
 
 
e0c722e
d1f3cb7
 
 
 
9a59ac4
 
 
 
 
 
 
 
 
3f2f598
9a59ac4
3f2f598
9a59ac4
eaab5cb
9a59ac4
 
3f2f598
9a59ac4
 
3f2f598
9a59ac4
eaab5cb
9a59ac4
1880996
9a59ac4
 
 
 
9f33b01
db59c68
9a59ac4
 
eaab5cb
0aa580e
eaab5cb
0aa580e
 
9a59ac4
 
 
 
 
 
 
eaab5cb
 
 
 
 
9a59ac4
 
eaab5cb
 
 
 
 
9a59ac4
eaab5cb
 
9a59ac4
eaab5cb
 
 
3f938af
9a59ac4
eaab5cb
 
 
9a59ac4
 
eaab5cb
 
 
 
 
9a59ac4
 
 
eaab5cb
9a59ac4
 
 
 
eaab5cb
9a59ac4
 
eaab5cb
9a59ac4
 
eaab5cb
9a59ac4
 
 
d1f3cb7
9a59ac4
 
 
 
eaab5cb
d1f3cb7
9a59ac4
 
 
 
eaab5cb
d1f3cb7
e0c722e
9a59ac4
 
90005c6
 
eaab5cb
80c68e2
257874f
90005c6
80c68e2
257874f
d1f3cb7
80c68e2
257874f
d1f3cb7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9a59ac4
 
 
d1f3cb7
9a59ac4
eaab5cb
d1f3cb7
9a59ac4
 
 
183d7a7
 
 
39fd284
 
a429213
 
eaab5cb
f154443
bd36e6d
f154443
 
6de20f1
 
f154443
9a59ac4
 
eaab5cb
ae30f51
9a59ac4
 
 
24f10d8
9a59ac4
eaab5cb
a429213
882e353
3ae80cc
f154443
 
9a59ac4
eaab5cb
 
9a59ac4
eaab5cb
4fc67c7
 
9a59ac4
 
eaab5cb
1ed759c
 
68a734b
1ed759c
975fccf
 
 
 
1ed759c
c5ca604
9a59ac4
 
 
 
 
 
 
 
 
ae30f51
9a59ac4
 
 
 
 
 
ae30f51
f746204
eaab5cb
 
 
 
 
 
 
 
 
 
24f10d8
 
6fa3751
 
eaab5cb
 
510d471
 
6fa3751
24f10d8
 
d1f3cb7
 
24f10d8
 
 
49de2a2
9a59ac4
 
eaab5cb
 
 
9a59ac4
 
eaab5cb
 
 
073a4a7
d1f3cb7
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
print('Running')
import time
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 time
#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 matplotlib.ticker import MaxNLocator
from matplotlib.patches import Ellipse
import matplotlib.transforms as transforms
from matplotlib.gridspec import GridSpec
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 datetime import timedelta
# import dataframe_image as dfi
# from google.colab import drive
def percentile(n):
    def percentile_(x):
        return np.percentile(x, n)
    percentile_.__name__ = 'percentile_%s' % n
    return percentile_

# import os
# import praw
# import matplotlib.pyplot as plt
# import matplotlib.colors
# import matplotlib.colors as mcolors
# cmap_sum = matplotlib.colors.LinearSegmentedColormap.from_list("", ["#4285f4","#FFFFFF","#F0E442"])
#import pybaseball
import math
# import matplotlib.ticker as mtick
# import matplotlib.ticker as ticker

# colour_palette = ['#FFB000','#648FFF','#785EF0',
                #   '#DC267F','#FE6100','#3D1EB2','#894D80','#16AA02','#B5592B','#A3C1ED']
# import matplotlib.colors as mcolors
# from  matplotlib.ticker import FuncFormatter
# from matplotlib.font_manager import FontProperties

import numpy as np
# import matplotlib.pyplot as plt
import matplotlib.colors

# import undetected_chromedriver as uc
# from selenium import webdriver
# from seleniumbase import Driver

# driver = Driver(uc=True)
# driver.get('https://www.naturalstattrick.com')

#x,y,c = zip(*np.random.rand(30,3)*4-2)

#norm=plt.Normalize(-2,2)
#co = matplotlib.colors.LinearSegmentedColormap.from_list("", ["#ffffff","#F0E442"])
co = matplotlib.colors.LinearSegmentedColormap.from_list("", ["#56B4E9","#FFFFFF","#F0E442"])
#co = matplotlib.colors.LinearSegmentedColormap.from_list("", ["#FFFFFF","#56B4E9"])




# try: 
#     data_r = requests.get("https://pub-api-ro.fantasysports.yahoo.com/fantasy/v2/league/427.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/427.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(int(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']['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)
#     total_list.append(single_list)

yahoo_df = pd.read_csv('df_2023_small.csv',index_col=[0])
yahoo_df.percent_owned = yahoo_df.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 = pd.DataFrame(total_list,columns = ['player_id','rank_value','full','first','last','average_pick','average_auction_cost','display_position','editorial_team_abbr','percent_owned'])

# yahoo_df = pd.read_csv('df_2023_small.csv',index_col=[0],usecols=range(12))
# yahoo_df.columns = ['rank_value','player_id','full','first','last','average_pick', 'average_cost','display_position','projected_auction_value','editorial_team_abbr','percent_owned']

yahoo_df_2 = yahoo_df.copy()

# # Write your code here.
# response = requests.get("https://www.naturalstattrick.com/playerlist.php?fromseason=20232024&thruseason=20232024&stype=2&sit=all&stdoi=oi&rate=n")
# soup = BeautifulSoup(response.text, 'html.parser')
# table_rows = soup.findAll('tr')
# table_rows = table_rows[1:-1]
# table_rows[0].findAll('td')

# player_name = []
# player_position = []
# player_team = []
# player_id = []

# for i in range(0,len(table_rows)-1):
#     player_name.append(str(table_rows[i].findAll('td')[0].contents[0]))
#     player_position.append(table_rows[i].findAll('td')[1].contents[0])
#     player_team.append(table_rows[i].findAll('td')[2].contents[0])
#     player_id.append(str(table_rows[i].findAll('td')[3].contents[0])[-76:][:7])

# player_id_df = pd.DataFrame({'Player':player_name,'Player ID':player_id,'Position':player_position,'Team':player_team})
# #player_id_df.index.name = 'Player Name'
# player_id_df.head()

# skater_df = player_id_df[player_id_df['Position'] != 'G']
# goalie_df = player_id_df[player_id_df['Position'] == 'G']

season = 20232024
seasontype = 2

def nat_stat_trick_range_pp_gp(rookie='n',start_date='2022-10-01',end_date=str(pd.to_datetime(datetime.now(pytz.timezone('US/Pacific')).strftime('%Y-%m-%d')).date()),sit='all',gp=1):
    time.sleep(2)
    url = f'https://www.naturalstattrick.com/playerteams.php?fromseason={season}&thruseason={season}&stype={seasontype}&sit=pp&score=all&stdoi=std&rate=y&team=ALL&pos=S&loc=B&toi=0&gpfilt=gpteam&fd=&td=&tgp='+str(gp)+'&lines=single&draftteam=ALL'

    player_list_all = []
    response = requests.get(url)
    soup = BeautifulSoup(response.text, 'html.parser')
    table_rows = soup.findAll('tr')
    table_rows = table_rows[1:]

    for j in range(0,len(table_rows)):
      p_string = [str(x).strip('<td>').strip('</') for x  in list(table_rows[j].findAll('td')) if "<td>" in str(x)]
      player_list_all.append([p_string[0]]+[str(table_rows[j].findAll('td')[1]).split('>')[2].split('<')[0]]+p_string[1:]+[str(table_rows[j].findAll('td')[1])[98:105].strip('</a></td>')])
    #table_rows[0].findAll('td')

    if soup != "":
      columns_list = [str(x).split('>')[1].split('<')[0] for x in soup.findAll('th')]+['player_id']
      df_url = pd.DataFrame(data=player_list_all,columns=columns_list)

    df_url = df_url.fillna(0)
    df_url['Shots+Hits+Blocks/60'] = df_url['Shots/60'].astype(float)+df_url['Hits/60'].astype(float)+df_url['Shots Blocked/60'].astype(float)
    df_url['Shots+Hits/60'] = df_url['Shots/60'].astype(float)+df_url['Hits/60'].astype(float)
    #print(url)
    return df_url

team_abv = pd.read_csv('team_abv.csv')
team_dict = team_abv.set_index('team_abv').to_dict()['team_name']

yahoo_nhl_df = pd.read_csv('yahoo_to_nhl.csv', encoding='unicode_escape')


player_games_df_old = pd.read_csv('player_games_cards.csv',index_col=[0]).sort_values(by='date',ascending=False)
team_games_df = pd.read_csv('team_games.csv',index_col=[0])#.sort_values(by='date',ascending=False)

player_games_df_2 = player_games_df_old.copy()

team_games_df['game_count'] = team_games_df.groupby('team')['team'].cumcount()+1
team_games_df['max_games'] = team_games_df.groupby('team').game_count.transform('max')
team_games_df['abv'] = team_games_df.team.map(team_abv.set_index('team_name')['team_abv'].to_dict())
team_games_df = team_games_df.sort_values(by='game_count',ascending=False)
#team_abv = pd.read_csv('team_abv.csv')



def nat_stat_convert(df):
    for i in range(0,len(df.columns)):
        if df.columns[i][-3:]=='/60':
            if 'ix' not in df.columns[i]:
                df[df.columns[i]] = np.round(df[df.columns[i]].astype(float)*df['TOI'].astype(float)/60,0)
                df = df.rename(columns={df.columns[i]: df.columns[i].replace('/60','')})
            else:
                df[df.columns[i]] = df[df.columns[i]].astype(float)*df['TOI'].astype(float)/60
                df = df.rename(columns={df.columns[i]: df.columns[i].replace('/60','')})

    df['Faceoffs %'] = df['Faceoffs Won']/(df['Faceoffs Won']+df['Faceoffs Lost'])

    return df

from shiny import ui, render, App
import matplotlib.image as mpimg
app_ui = ui.page_fluid(
    #ui.panel_title("Simulate a normal distribution"),

    ui.layout_sidebar(

      ui.panel_sidebar(
        #ui.input_date_range("date_range_id", "Date range input",start = statcast_df.game_date.min(), end = statcast_df.game_date.max()),
        ui.input_select("team_id", "Select Team",team_dict,width=1,size=1,selected='ANA',),
        ui.input_numeric("n_1", "Last Games x", value=1),
        ui.input_numeric("n_2", "Last Games y", value=0),
        ui.input_numeric("n_3", "Last Games z", value=0),
        ui.input_numeric("top_n", "Show top 'n'", value=10),
        ui.input_switch("x", "Drop N/A"),
        #ui.input_select("ignore_id", "Remove Columns",['Position','Roster%'],multiple=True,selectize=True),
      ),

        ui.panel_main(ui.tags.h3(""),
                      ui.div({"style": "font-size:2.7em;"},ui.output_text("txt_title")),
                      #ui.tags.h2("Fantasy Hockey Schedule Summary"),
                      ui.tags.h5("Created By: @TJStats,     Data: Natural Stat Trick, Yahoo Fantasy"),
                      ui.div({"style": "font-size:1.6em;"},ui.output_text("txt")),
                      ui.output_table("pp_roundup"),
                      #ui.tags.h5('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') )
        )
    ),
)




from urllib.request import Request, urlopen
from shiny import App, reactive, ui
from shiny.ui import h2, tags
# importing OpenCV(cv2) module




#print(app_ui)
def server(input, output, session):


    @output
    @render.text
    def txt():
        return   f'{team_dict[input.team_id()]} Last Games PP Summary'
      
    @output
    @render.text
    def txt_title():
    
        return f'Team Last Games PP% Leaders'





    @output
    @render.table
    def pp_roundup():

        top_n = input.top_n()
        n_1 = input.n_1()
        n_2 = input.n_2()
        n_3 = input.n_3()

        list_of_columns =  ['Player', 'Team', 'display_position','percent_owned','L'+str(n_1)+' PP TOI','L'+str(n_2)+' PP TOI','L'+str(n_3)+' PP TOI',
                                 'L'+str(n_1)+' PP%','L'+str(n_2)+' PP%','L'+str(n_3)+' PP%']

        list_of_columns_name =  ['Player', 'Team', 'Position','Roster%','L'+str(n_1)+' PP TOI','L'+str(n_2)+' PP TOI','L'+str(n_3)+' PP TOI',
                                 'L'+str(n_1)+' PP%','L'+str(n_2)+' PP%','L'+str(n_3)+' PP%']

        if type(n_1) is not int:
            n_1 = 1
            
        if (n_2 == 0) or (n_2 == n_1) or (n_2 == None):
            list_of_columns.remove(f'L{str(n_2)} PP TOI')
            list_of_columns.remove(f'L{str(n_2)} PP%')
            list_of_columns_name.remove(f'L{str(n_2)} PP TOI')
            list_of_columns_name.remove(f'L{str(n_2)} PP%')

        if (n_3 == 0) or (n_3 == n_1) or (n_3 == n_2) or (n_3 == None):
            list_of_columns.remove(f'L{str(n_3)} PP TOI')
            list_of_columns.remove(f'L{str(n_3)} PP%')
            list_of_columns_name.remove(f'L{str(n_3)} PP TOI')
            list_of_columns_name.remove(f'L{str(n_3)} PP%')

            
        
        start_date ='2023-09-01'
        end_date = '2024-05-01'
        player_games_df = player_games_df_2.copy()
        player_games_df = player_games_df.merge(right=team_games_df,left_on=['Team','date'],right_on=['abv','date'])

        df_pp_1 = player_games_df.groupby('player_id').head(n_1)
        df_pp_1 = df_pp_1[df_pp_1.game_count > df_pp_1.max_games-n_1]

        df_pp_2 = df_pp_2 = player_games_df.groupby('player_id').head(n_2)
        df_pp_2[df_pp_2.game_count > df_pp_2.max_games-n_2]

        df_pp_3 = df_pp_3 = player_games_df.groupby('player_id').head(n_3)
        df_pp_3[df_pp_3.game_count > df_pp_3.max_games-n_3]

        team_games_df_1 = team_games_df.groupby('team').head(n_1)
        team_games_df_2 = team_games_df.groupby('team').head(n_2)
        team_games_df_3 = team_games_df.groupby('team').head(n_3)

        df_all_pp_1 = df_pp_1.copy()
        df_all_pp_2 = df_pp_2.copy()
        df_all_pp_3 = df_pp_3.copy()

        df_all_pp_1_final = df_all_pp_1.groupby(['player_id','Player','Team','Position']).sum()[['TOI_pp']].reset_index()
        df_all_pp_2_final = df_all_pp_2.groupby(['player_id','Player','Team','Position']).sum()[['TOI_pp']].reset_index()
        df_all_pp_3_final = df_all_pp_3.groupby(['player_id','Player','Team','Position']).sum()[['TOI_pp']].reset_index()

        team_games_df_1_final = team_games_df_1.groupby(['abv']).sum()[['pp_toi']].reset_index()
        team_games_df_2_final = team_games_df_2.groupby(['abv']).sum()[['pp_toi']].reset_index()
        team_games_df_3_final = team_games_df_3.groupby(['abv']).sum()[['pp_toi']].reset_index()

        df_final =  df_all_pp_1_final.merge( df_all_pp_2_final,how='outer',left_on=['player_id'],right_on=['player_id'],suffixes=("","_2"))
        df_final =  df_final.merge( df_all_pp_3_final,how='outer',left_on=['player_id'],right_on=['player_id'],suffixes=("_1","_3"))

        team_final =  team_games_df_1_final.merge( team_games_df_2_final,how='outer',left_on=['abv'],right_on=['abv'],suffixes=("","_2"))
        team_final =  team_final.merge( team_games_df_3_final,how='outer',left_on=['abv'],right_on=['abv'],suffixes=("_1","_3"))


        df_final = df_final.merge(team_final,left_on='Team_1',right_on='abv')

        test = df_final[['player_id','Player_1','Team_1','Position_1','TOI_pp_1','TOI_pp_2','TOI_pp_3','pp_toi_1','pp_toi_2','pp_toi_3']]
        test.columns = ['player_id','Player','Team','Position','TOI_1','TOI_2','TOI_3','pp_toi_1','pp_toi_2','pp_toi_3']
        test = test.fillna('0')


        test['PP%_1'] = test['TOI_1'].astype(float)/ test['pp_toi_1'].astype(float)
        test['PP%_2'] = test['TOI_2'].astype(float)/ test['pp_toi_2'].astype(float)
        test['PP%_3'] = test['TOI_3'].astype(float)/ test['pp_toi_3'].astype(float)
        # test = test.fillna(0)
        test['TOI_1'] = ["%d:%02d" % (int(x),(x*60)%60) for x in test['TOI_1'].astype(float)]
        test['TOI_2'] = ["%d:%02d" % (int(x),(x*60)%60) for x in test['TOI_2'].astype(float)]
        test['TOI_3'] = ["%d:%02d" % (int(x),(x*60)%60) for x in test['TOI_3'].astype(float)]
        test = test.drop(['pp_toi_1','pp_toi_2','pp_toi_3'],axis=1)
        test.columns = ['player_id','Player','Team','Position','L'+str(n_1)+' PP TOI','L'+str(n_2)+' PP TOI','L'+str(n_3)+' PP TOI','L'+str(n_1)+' PP%','L'+str(n_2)+' PP%','L'+str(n_3)+' PP%']


        yahoo_df = yahoo_df_2.merge(yahoo_nhl_df,left_on = 'player_id',right_on='player_id_yahoo',suffixes=['','_y'])
        yahoo_df.nhl_id = yahoo_df.nhl_id.astype(float)
        test.player_id = test.player_id.astype(float)


        test = test.merge(right=yahoo_df,left_on='player_id',right_on='nhl_id',suffixes=['','_y'],how='left')
        # if len(test[test.player_id == 8478427]) > 0:
        #     return test.style
            
            #print(test[test.nhl_id == 8478427])

        test.loc[test.display_position.isna(),'display_position'] = test.loc[test.display_position.isna(),'Position']
        test.display_position = test.display_position.replace({'L':'LW','R':'RW'})
        test.percent_owned = test.percent_owned.fillna(0)

        


        print('Column List')
        print(test.columns)


        print(list_of_columns)
        test = test[list_of_columns]
        test = test.rename(columns={'percent_owned':'Roster%'})
        test = test.rename(columns={'display_position':'Position'})
        

        top_d_score = test.copy()[(test.Team==input.team_id())].sort_values(by=['L'+str(n_1)+' PP%'],ascending=False).reset_index(drop=True)
        print(top_d_score)
        if input.x():
            top_d_score = top_d_score.dropna(axis='columns')
        
        top_d_score = top_d_score.head(min(len(top_d_score),top_n))


        #top_d_score.columns = list_of_columns_name

        

        top_d_score['Deployment'] = "PP2"
        top_d_score['Deployment'][0:5] = "PP1"

        
        cols = top_d_score.columns.tolist();
        print('we made it here',cols)

        # for i in list(input.ignore_id()):
        #     print('we made it here')
        #     print(i)
        #     cols.remove(i)

        # df_style_bang = top_d_score.head(10).style.background_gradient(cmap=co, subset=['L'+str(n_1)+' PP%','L'+str(n_2)+' PP%','L'+str(n_3)+' PP%','Roster%'],vmin=0,vmax=1).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')]},{'selector' :'td', 'props':[('text-align', 'center'),('font-size', '13px'),('fontname', 'Century Gothic')]}]).format(
        #                 {'L'+str(n_1)+' PP%': '{:.0%}',
        #                 'L'+str(n_2)+' PP%': '{:.0%}',
        #                 'L'+str(n_3)+' PP%': '{:.0%}',
        #                 'Roster%': '{:.0%}',
        #                 },)

        df_style_bang = top_d_score[cols].head(input.top_n()).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':'100px'},overwrite=False).set_properties(
                    **{'background-color':'White','index':'White','min-width':'200px'},overwrite=False,subset=cols[0]).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', '35px')]}],overwrite=False).set_properties(
            **{'Height': '35px'},**{'text-align': 'center'},overwrite=False).set_properties(**{'border': '3 px','color':'black'},overwrite=False).set_properties(**{'border': '3 px','color':'black'},overwrite=False).set_properties(
                    **{'border': '1px black solid !important'},subset = ((list(top_d_score.index[:]),top_d_score.columns[:]))).set_properties(**{
                                'color': 'black'},overwrite=False).set_properties(
                    **{'border': '1px black solid !important'},subset = ((list(top_d_score.index[:]),top_d_score.columns[:]))).format(
            {
            'L'+str(n_1)+' PP%': '{:.0%}',
            'L'+str(n_2)+' PP%': '{:.0%}',
            'L'+str(n_3)+' PP%': '{:.0%}',
            'Roster%': '{:.0%}',
            },).background_gradient(cmap=co, subset=[x for x in cols if x.endswith('PP%')]).hide_index().background_gradient(cmap=co,vmin=0.0,vmax=0.7, subset=[x for x in cols if x.endswith('PP%')])

        return df_style_bang



# test = test.fillna(0)
#test['PP TOI'] = ["%d:%02d" % (int(x),(x*60)%60) if x>0 else '0:00' for x in test['PP TOI']]



app = App(app_ui, server)
#time.sleep(60)