File size: 17,619 Bytes
dfb2f96
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
29f62e2
dfb2f96
 
 
 
 
 
 
 
 
 
29f62e2
 
 
 
dfb2f96
 
 
29f62e2
dfb2f96
 
 
 
 
 
 
 
 
563b3ae
 
b482280
 
 
 
dfb2f96
 
 
 
 
 
 
 
b482280
 
dfb2f96
 
 
 
 
 
 
b482280
 
1a2fb86
 
 
 
 
0573513
1a2fb86
b482280
 
1a2fb86
 
 
 
 
0573513
1a2fb86
b482280
 
a11d086
0e788d9
6a86553
ed2133a
1efb29a
4ea6358
b482280
a11d086
dfb2f96
 
b8708f4
cfe4530
8fdabcf
133a923
07a95f7
b482280
 
 
 
 
 
 
 
dfb2f96
 
 
 
b482280
 
dfb2f96
 
ab079c4
a11d086
 
 
5586c8f
aa723b8
5586c8f
b482280
ab079c4
a2ca848
ab079c4
5586c8f
 
 
b482280
 
 
 
5586c8f
 
 
29ed0ed
5586c8f
876e35b
9804a32
ab079c4
 
 
1e2f35d
f73cc82
b597d67
a2ca848
 
b482280
 
 
 
 
ab079c4
1e2f35d
5586c8f
 
d714ad1
ab079c4
 
b25f109
b482280
b25f109
5586c8f
1e2f35d
a2ca848
 
 
 
 
 
ab079c4
 
 
 
 
 
 
 
 
 
 
 
4dc7379
ab079c4
 
 
 
 
 
 
 
4dc7379
 
 
 
ab079c4
 
 
 
4dc7379
6f99a73
ab079c4
 
 
 
4dc7379
6f99a73
ab079c4
 
 
 
6f99a73
ab079c4
 
 
 
6f99a73
ab079c4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import pulp
import numpy as np
import pandas as pd
import streamlit as st
import gspread
import time
import random
import scipy.stats

@st.cache_resource
def init_conn():
          scope = ['https://www.googleapis.com/auth/spreadsheets',
                    "https://www.googleapis.com/auth/drive"]
          
          credentials = {
            "type": "service_account",
            "project_id": "sheets-api-connect-378620",
            "private_key_id": st.secrets['sheets_api_connect_pk'],
            "private_key": "-----BEGIN PRIVATE KEY-----\nMIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQCtKa01beXwc88R\nnPZVQTNPVQuBnbwoOfc66gW3547ja/UEyIGAF112dt/VqHprRafkKGmlg55jqJNt\na4zceLKV+wTm7vBu7lDISTJfGzCf2TrxQYNqwMKE2LOjI69dBM8u4Dcb4k0wcp9v\ntW1ZzLVVuwTvmrg7JBHjiSaB+x5wxm/r3FOiJDXdlAgFlytzqgcyeZMJVKKBQHyJ\njEGg/1720A0numuOCt71w/2G0bDmijuj1e6tH32MwRWcvRNZ19K9ssyDz2S9p68s\nYDhIxX69OWxwScTIHLY6J2t8txf/XMivL/636fPlDADvBEVTdlT606n8CcKUVQeq\npUVdG+lfAgMBAAECggEAP38SUA7B69eTfRpo658ycOs3Amr0JW4H/bb1rNeAul0K\nZhwd/HnU4E07y81xQmey5kN5ZeNrD5EvqkZvSyMJHV0EEahZStwhjCfnDB/cxyix\nZ+kFhv4y9eK+kFpUAhBy5nX6T0O+2T6WvzAwbmbVsZ+X8kJyPuF9m8ldcPlD0sce\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IVATE KEY-----\n",
            "client_email": "gspread-connection@sheets-api-connect-378620.iam.gserviceaccount.com",
            "client_id": "106625872877651920064",
            "auth_uri": "https://accounts.google.com/o/oauth2/auth",
            "token_uri": "https://oauth2.googleapis.com/token",
            "auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs",
            "client_x509_cert_url": "https://www.googleapis.com/robot/v1/metadata/x509/gspread-connection%40sheets-api-connect-378620.iam.gserviceaccount.com"
          }

          gc = gspread.service_account_from_dict(credentials)
          
          all_dk_player_projections = st.secrets['NFL_Data']
          
          return gc, all_dk_player_projections

st.set_page_config(layout="wide")

gc, all_dk_player_projections = init_conn()

game_format = {'Dropback% Proj': '{:.2%}', 'DesRush%': '{:.2%}', 'Rush%': '{:.2%}'}

rb_util = {'Player Snaps%': '{:.2%}','Rush Att%': '{:.2%}', 'Routes%': '{:.2%}', 'Targets%': '{:.2%}', 'SDD Snaps%': '{:.2%}', 'i5 Rush%': '{:.2%}',
                   'LDD Snaps%': '{:.2%}','2-min%': '{:.2%}'}

wr_te_util = {'Routes%': '{:.2%}','Targets%': '{:.2%}', 'Air Yards%': '{:.2%}', 'Endzone Targets%': '{:.2%}', 'Third/Fourth%': '{:.2%}', 'Third/Fourth Targets%': '{:.2%}',
                   'Play Action Targets%': '{:.2%}','2-min%': '{:.2%}'}

wr_matchups_form = {'Opp Man%': '{:.2%}','Opp Zone%': '{:.2%}'}

trending_form = {'Trend': '{:.2%}'}

@st.cache_resource(ttl = 600)
def pull_baselines():
    sh = gc.open_by_url(all_dk_player_projections)
    worksheet = sh.worksheet('RB_Util')
    raw_display = pd.DataFrame(worksheet.get_all_records())
    raw_display = raw_display.replace('', np.nan)      
    raw_display = raw_display[['player_name', 'position', 'week', 'team_season', 'player_snaps_per', 'rush_attempts_per', 'routes_per', 'targets_per',
                               'tprr', 'player_SDD_snaps_per', 'inside_five_rush_per', 'player_LDD_snaps_per', 'two_min_per', 'exPPR', 'ppr_fantasy', 'UR_Rank']]
    raw_display = raw_display.set_axis(['Player', 'Position', 'Week', 'Team-Season', 'Player Snaps%', 'Rush Att%', 'Routes%', 'Targets%',
                               'TPRR', 'SDD Snaps%', 'i5 Rush%', 'LDD Snaps%', '2-min%', 'Expected PPR', 'PPR', 'Utilization Rank'], axis='columns')
    rb_search = raw_display.sort_values(by='Utilization Rank', ascending=True)
    
    worksheet = sh.worksheet('WR_TE_Util')
    raw_display = pd.DataFrame(worksheet.get_all_records())
    raw_display = raw_display.replace('', np.nan)      
    raw_display = raw_display[['player_name', 'position', 'week', 'team_season', 'routes_per', 'targets_per', 'tprr' , 'adot', 'air_yards_per',
                               'ayprr', 'endzone_targets_per', 'third_fourth_per', 'third_fourth_target_per', 'play_action_targets_per', 'exPPR', 'ppr_fantasy', 'UR_Rank']]
    raw_display = raw_display.set_axis(['Player', 'Position', 'Week', 'Team-Season', 'Routes%', 'Targets%', 'TPRR' , 'ADOT', 'Air Yards%',
                               'AYPRR', 'Endzone Targets%', 'Third/Fourth%', 'Third/Fourth Targets%', 'Play Action Targets%', 'Expected PPR', 'PPR', 'Utilization Rank'], axis='columns')
    wr_search = raw_display.sort_values(by='Utilization Rank', ascending=True)
    
    worksheet = sh.worksheet('RB_Util_Season')
    raw_display = pd.DataFrame(worksheet.get_all_records())
    raw_display = raw_display.replace('', np.nan)      
    raw_display = raw_display[['player_name', 'position', 'team_season', 'player_snaps_per', 'rush_attempts_per', 'routes_per', 'targets_per',
                               'tprr', 'player_SDD_snaps_per', 'inside_five_rush_per', 'player_LDD_snaps_per', 'two_min_per', 'exPPR', 'ppr_fantasy', 'UR_Rank']]
    raw_display = raw_display.set_axis(['Player', 'Position', 'Team-Season', 'Player Snaps%', 'Rush Att%', 'Routes%', 'Targets%',
                               'TPRR', 'SDD Snaps%', 'i5 Rush%', 'LDD Snaps%', '2-min%', 'Expected PPR', 'PPR', 'Utilization Rank'], axis='columns')
    rb_season = raw_display.sort_values(by='Utilization Rank', ascending=True)
    
    worksheet = sh.worksheet('WR_TE_Util_Season')
    raw_display = pd.DataFrame(worksheet.get_all_records())
    raw_display = raw_display.replace('', np.nan)      
    raw_display = raw_display[['player_name', 'position', 'team_season', 'routes_per', 'targets_per', 'tprr' , 'adot', 'air_yards_per',
                               'ayprr', 'endzone_targets_per', 'third_fourth_per', 'third_fourth_target_per', 'play_action_targets_per', 'exPPR', 'ppr_fantasy', 'UR_Rank']]
    raw_display = raw_display.set_axis(['Player', 'Position', 'Team-Season', 'Routes%', 'Targets%', 'TPRR' , 'ADOT', 'Air Yards%',
                               'AYPRR', 'Endzone Targets%', 'Third/Fourth%', 'Third/Fourth Targets%', 'Play Action Targets%', 'Expected PPR', 'PPR', 'Utilization Rank'], axis='columns')
    wr_season = raw_display.sort_values(by='Utilization Rank', ascending=True)
    
    worksheet = sh.worksheet('Defensive Matchups')
    raw_display = pd.DataFrame(worksheet.get_all_records())
    raw_display = raw_display.replace('', np.nan)
    raw_display = raw_display.dropna(subset='Weighted Targets')
    raw_display = raw_display[raw_display['Weighted Targets'] != '#DIV/0!']
    raw_display = raw_display[raw_display['Weighted Targets'] != '#N/A']
    wr_matchups = raw_display.sort_values(by='Weighted Targets', ascending=False)
    
    worksheet = sh.worksheet('FL_Macro')
    raw_display = pd.DataFrame(worksheet.get_all_records())
    raw_display = raw_display.replace('', np.nan)
    raw_display = raw_display[raw_display['Active'] == 1]
    raw_display = raw_display.dropna(subset='Team')
    macro_data = raw_display.drop('Active', axis=1)
    macro_data = macro_data.sort_values(by='Team Total', ascending=False)
    
    worksheet = sh.worksheet('Ownership Trend')
    raw_display = pd.DataFrame(worksheet.get_all_records())
    raw_display = raw_display.replace('', np.nan)
    raw_display = raw_display.dropna(subset='Team')
    trending_data = raw_display.sort_values(by='Trend', ascending=False)
    
    return rb_search, wr_search, rb_season, wr_season, wr_matchups, macro_data, trending_data

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

rb_search, wr_search, rb_season, wr_season, wr_matchups, macro_data, trending_data = pull_baselines()
pos_list = ['RB', 'WR', 'TE']

tab1, tab2 = st.tabs(["Slate Specific", "Season Long Research"])
with tab1:
    col1, col2 = st.columns([1, 8])
    
    with col1:
        if st.button("Load/Reset Data", key='reset2'):
              st.cache_data.clear()
              rb_search, wr_search, rb_season, wr_season, wr_matchups, macro_data, trending_data = pull_baselines()
        stat_type_var2 = st.radio("What table are you loading?", ('Macro Stats', 'WR/TE Coverage Matchups', 'Ownership Trends', 'Nothing idk lol'))
        if stat_type_var2 == 'WR/TE Coverage Matchups':
            routes_var2 = st.slider("Is there a certain range of routes you want to include?", 0, 50, (10, 50), key='sal_var2')
        split_var2 = st.radio("Are you running the the whole league or certain teams?", ('All Teams', 'Specific Teams'))
        pos_split2 = st.radio("Are you viewing all positions or specific positions?", ('All Positions', 'Specific Positions'))      
        if pos_split2 == 'Specific Positions':
            if stat_type_var2 == 'WR/TE Coverage Matchups':
                pos_var2 = st.multiselect('What Positions would you like to view?', options = ['RB', 'WR', 'TE'])
            elif stat_type_var2 == 'Ownership Trends':
                pos_var2 = st.multiselect('What Positions would you like to view?', options = ['QB', 'RB', 'WR', 'TE', 'DST'])
        elif pos_split2 == 'All Positions':
            pos_var2 = pos_list 
        if split_var2 == 'Specific Teams':
            team_var2 = st.multiselect('Which teams would you like to include in the Table?', options = wr_matchups['Team'].unique())
        elif split_var2 == 'All Teams':
            team_var2 = wr_matchups['Team'].unique().tolist()
        if stat_type_var2 == 'Macro Stats':
            slate_table_instance = macro_data
            slate_table_instance = slate_table_instance.set_index('Team')  
        elif stat_type_var2 == 'WR/TE Coverage Matchups':
            slate_table_instance = wr_matchups
            slate_table_instance = slate_table_instance[slate_table_instance['Team'].isin(team_var2)]  
            slate_table_instance = slate_table_instance[slate_table_instance['Position'].isin(pos_var2)]
            slate_table_instance = slate_table_instance[slate_table_instance['Avg Routes'] >= routes_var2[0]]
            slate_table_instance = slate_table_instance[slate_table_instance['Avg Routes'] <= routes_var2[1]]
            slate_table_instance = slate_table_instance.set_index('name')
        elif stat_type_var2 == 'Ownership Trends':
            slate_table_instance = trending_data
            slate_table_instance = slate_table_instance[slate_table_instance['Team'].isin(team_var2)]  
            slate_table_instance = slate_table_instance[slate_table_instance['Position'].isin(pos_var2)]
        elif stat_type_var2 == 'Nothing idk lol':
            slate_table_instance = wr_matchups
    
    with col2:
        if stat_type_var2 == 'Macro Stats':
            st.dataframe(slate_table_instance.style.background_gradient(axis=0).background_gradient(cmap = 'RdYlGn').format(game_format, precision=2), height=1000, use_container_width = True)
        elif stat_type_var2 == 'WR/TE Coverage Matchups':
            st.dataframe(slate_table_instance.style.background_gradient(axis=0).background_gradient(cmap = 'RdYlGn').format(wr_matchups_form, precision=2), height=1000, use_container_width = True)
        elif stat_type_var2 == 'Ownership Trends':
            st.dataframe(slate_table_instance.style.background_gradient(axis=0).background_gradient(cmap = 'RdYlGn').format(trending_form, precision=2), height=1000, use_container_width = True)
        elif stat_type_var2 == 'Nothing idk lol':
            st.write('lol same bro but yo the vibes immaculate')
        if stat_type_var2 == 'WR/TE Coverage Matchups':
            st.download_button(
                            label="Export Tables",
                            data=convert_df_to_csv(slate_table_instance),
                            file_name='NFL_Slate_Research_export.csv',
                            mime='text/csv',
            )

with tab2:
    col1, col2 = st.columns([1, 8])
    
    with col1:
        if st.button("Load/Reset Data", key='reset1'):
              st.cache_data.clear()
              rb_search, wr_search, rb_season, wr_season, wr_matchups, macro_data, trending_data = pull_baselines()
        stat_type_var1 = st.radio("What table are you loading?", ('RB Usage (Weekly)', 'WR/TE Usage (Weekly)', 'RB Usage (Season)', 'WR/TE Usage (Season)'), key='stat_type_var1')
        split_var1 = st.radio("Are you running the the whole league or certain teams?", ('All Teams', 'Specific Teams'), key='split_var1')
        pos_split1 = st.radio("Are you viewing all positions or specific positions?", ('All Positions', 'Specific Positions'), key='pos_split1')      
        week_split1 = st.radio("Are you viewing all weeks or specific weeks?", ('All Weeks', 'Specific Weeks'), key='week_split1')
        if pos_split1 == 'Specific Positions':
            pos_var1 = st.multiselect('What Positions would you like to view?', options = ['RB', 'WR', 'TE'])
        elif pos_split1 == 'All Positions':
            pos_var1 = pos_list 
        if split_var1 == 'Specific Teams':
            team_var1 = st.multiselect('Which teams would you like to include in the Table?', options = rb_search['Team-Season'].unique(), key='team_var1')
        elif split_var1 == 'All Teams':
            team_var1 = rb_search['Team-Season'].unique().tolist()
        if week_split1 == 'Specific Weeks':
            week_var1 = st.multiselect('Which weeks would you like to include in the Table?', options = rb_search['Week'].unique(), key='week_var1')
        elif week_split1 == 'All Weeks':
            week_var1 = rb_search['Week'].unique().tolist()
        if stat_type_var1 == 'RB Usage (Weekly)':
            table_instance = rb_search
            table_instance = table_instance[table_instance['Team-Season'].isin(team_var1)]  
            table_instance = table_instance[table_instance['Position'].isin(pos_var1)]
            table_instance = table_instance[table_instance['Week'].isin(week_var1)]
            table_instance['PPR_Diff'] = table_instance['Expected PPR'] - table_instance['PPR']
        elif stat_type_var1 == 'WR/TE Usage (Weekly)':
            table_instance = wr_search    
            table_instance = table_instance[table_instance['Team-Season'].isin(team_var1)]  
            table_instance = table_instance[table_instance['Position'].isin(pos_var1)]
            table_instance = table_instance[table_instance['Week'].isin(week_var1)]
            table_instance['PPR_Diff'] = table_instance['Expected PPR'] - table_instance['PPR']
        elif stat_type_var1 == 'RB Usage (Season)':
            table_instance = rb_season
            table_instance = table_instance[table_instance['Team-Season'].isin(team_var1)]  
            table_instance = table_instance[table_instance['Position'].isin(pos_var1)]
            table_instance['PPR_Diff'] = table_instance['Expected PPR'] - table_instance['PPR']
        elif stat_type_var1 == 'WR/TE Usage (Season)':
            table_instance = wr_season
            table_instance = table_instance[table_instance['Team-Season'].isin(team_var1)]  
            table_instance = table_instance[table_instance['Position'].isin(pos_var1)]
            table_instance['PPR_Diff'] = table_instance['Expected PPR'] - table_instance['PPR']
    with col2:
        if stat_type_var1 == 'RB Usage (Weekly)':
            st.dataframe(table_instance.style.background_gradient(axis=0).background_gradient(cmap = 'RdYlGn').background_gradient(cmap='RdYlGn_r', subset = 'Utilization Rank').format(rb_util, precision=2), height=1000, use_container_width = True)
        elif stat_type_var1 == 'WR/TE Usage (Weekly)':
            st.dataframe(table_instance.style.background_gradient(axis=0).background_gradient(cmap = 'RdYlGn').background_gradient(cmap='RdYlGn_r', subset = 'Utilization Rank').format(wr_te_util, precision=2), height=1000, use_container_width = True)
        elif stat_type_var1 == 'RB Usage (Season)':
            st.dataframe(table_instance.style.background_gradient(axis=0).background_gradient(cmap = 'RdYlGn').background_gradient(cmap='RdYlGn_r', subset = 'Utilization Rank').format(rb_util, precision=2), height=1000, use_container_width = True)
        elif stat_type_var1 == 'WR/TE Usage (Season)':
            st.dataframe(table_instance.style.background_gradient(axis=0).background_gradient(cmap = 'RdYlGn').background_gradient(cmap='RdYlGn_r', subset = 'Utilization Rank').format(wr_te_util, precision=2), height=1000, use_container_width = True)
    
        st.download_button(
                        label="Export Tables",
                        data=convert_df_to_csv(table_instance),
                        file_name='NFL_Research_export.csv',
                        mime='text/csv',
        )