NFL_Research_Sheets / streamlit_app.py
Multichem's picture
Upload streamlit_app.py
dfb2f96
raw
history blame
8.9 kB
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": "1005124050c80d085e2c5b344345715978dd9cc9",
"private_key": "-----BEGIN PRIVATE KEY-----\nMIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQCtKa01beXwc88R\nnPZVQTNPVQuBnbwoOfc66gW3547ja/UEyIGAF112dt/VqHprRafkKGmlg55jqJNt\na4zceLKV+wTm7vBu7lDISTJfGzCf2TrxQYNqwMKE2LOjI69dBM8u4Dcb4k0wcp9v\ntW1ZzLVVuwTvmrg7JBHjiSaB+x5wxm/r3FOiJDXdlAgFlytzqgcyeZMJVKKBQHyJ\njEGg/1720A0numuOCt71w/2G0bDmijuj1e6tH32MwRWcvRNZ19K9ssyDz2S9p68s\nYDhIxX69OWxwScTIHLY6J2t8txf/XMivL/636fPlDADvBEVTdlT606n8CcKUVQeq\npUVdG+lfAgMBAAECggEAP38SUA7B69eTfRpo658ycOs3Amr0JW4H/bb1rNeAul0K\nZhwd/HnU4E07y81xQmey5kN5ZeNrD5EvqkZvSyMJHV0EEahZStwhjCfnDB/cxyix\nZ+kFhv4y9eK+kFpUAhBy5nX6T0O+2T6WvzAwbmbVsZ+X8kJyPuF9m8ldcPlD0sce\ntj8NwVq1ys52eosqs7zi2vjt+eMcaY393l4ls+vNq8Yf27cfyFw45W45CH/97/Nu\n5AmuzlCOAfFF+z4OC5g4rei4E/Qgpxa7/uom+BVfv9G0DIGW/tU6Sne0+37uoGKt\nW6DzhgtebUtoYkG7ZJ05BTXGp2lwgVcNRoPwnKJDxQKBgQDT5wYPUBDW+FHbvZSp\nd1m1UQuXyerqOTA9smFaM8sr/UraeH85DJPEIEk8qsntMBVMhvD3Pw8uIUeFNMYj\naLmZFObsL+WctepXrVo5NB6RtLB/jZYxiKMatMLUJIYtcKIp+2z/YtKiWcLnwotB\nWdCjVnPTxpkurmF2fWP/eewZ+wKBgQDRMtJg7etjvKyjYNQ5fARnCc+XsI3gkBe1\nX9oeXfhyfZFeBXWnZzN1ITgFHplDznmBdxAyYGiQdbbkdKQSghviUQ0igBvoDMYy\n1rWcy+a17Mj98uyNEfmb3X2cC6WpvOZaGHwg9+GY67BThwI3FqHIbyk6Ko09WlTX\nQpRQjMzU7QKBgAfi1iflu+q0LR+3a3vvFCiaToskmZiD7latd9AKk2ocsBd3Woy9\n+hXXecJHPOKV4oUJlJgvAZqe5HGBqEoTEK0wyPNLSQlO/9ypd+0fEnArwFHO7CMF\nycQprAKHJXM1eOOFFuZeQCaInqdPZy1UcV5Szla4UmUZWkk1m24blHzXAoGBAMcA\nyH4qdbxX9AYrC1dvsSRvgcnzytMvX05LU0uF6tzGtG0zVlub4ahvpEHCfNuy44UT\nxRWW/oFFaWjjyFxO5sWggpUqNuHEnRopg3QXx22SRRTGbN45li/+QAocTkgsiRh1\nqEcYZsO4mPCsQqAy6E2p6RcK+Xa+omxvSnVhq0x1AoGAKr8GdkCl4CF6rieLMAQ7\nLNBuuoYGaHoh8l5E2uOQpzwxVy/nMBcAv+2+KqHEzHryUv1owOi6pMLv7A9mTFoS\n18B0QRLuz5fSOsVnmldfC9fpUc6H8cH1SINZpzajqQA74bPwELJjnzrCnH79TnHG\nJuElxA33rFEjbgbzdyrE768=\n-----END PRIVATE KEY-----\n",
"client_email": "gspread-connection@sheets-api-connect-378620.iam.gserviceaccount.com",
"client_id": "106625872877651920064",
"auth_uri": "https://accounts.google.com/o/oauth2/auth",
"token_uri": "https://oauth2.googleapis.com/token",
"auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs",
"client_x509_cert_url": "https://www.googleapis.com/robot/v1/metadata/x509/gspread-connection%40sheets-api-connect-378620.iam.gserviceaccount.com"
}
gc = gspread.service_account_from_dict(credentials)
return gc
st.set_page_config(layout="wide")
gc = init_conn()
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%}'}
all_dk_player_projections = 'https://docs.google.com/spreadsheets/d/1I_1Ve3F4tftgfLQQoRKOJ351XfEG48s36OxXUKxmgS8/edit#gid=179416653'
@st.cache_resource(ttl = 300)
def rb_util_season():
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')
raw_display = raw_display.sort_values(by='Utilization Rank', ascending=True)
return raw_display
@st.cache_resource(ttl = 300)
def wr_te_util_season():
sh = gc.open_by_url(all_dk_player_projections)
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')
raw_display = raw_display.sort_values(by='Utilization Rank', ascending=True)
return raw_display
@st.cache_resource(ttl = 300)
def macro_pull():
sh = gc.open_by_url(all_dk_player_projections)
worksheet = sh.worksheet('FL_Macro')
raw_display = pd.DataFrame(worksheet.get_all_records())
raw_display = raw_display.sort_values(by='Team Total', ascending=False)
return raw_display
@st.cache_data
def convert_df_to_csv(df):
return df.to_csv().encode('utf-8')
rb_search = rb_util_season()
wr_search = wr_te_util_season()
macro_data = macro_pull()
pos_list = ['RB', 'WR', 'TE']
col1, col2 = st.columns([1, 8])
with col1:
if st.button("Load/Reset Data", key='reset1'):
st.cache_data.clear()
rb_search = rb_util_season()
wr_search = wr_te_util_season()
macro_data = macro_pull()
stat_type_var1 = st.radio("What table are you loading?", ('Macro Table', 'RB Usage', 'WR/TE Usage'), 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')
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 stat_type_var1 == 'Macro Table':
table_instance = macro_data
table_instance = table_instance.set_index('team')
elif stat_type_var1 == 'RB Usage':
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)]
elif stat_type_var1 == 'WR/TE Usage':
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)]
with col2:
if stat_type_var1 == 'Macro Table':
st.dataframe(table_instance.style.background_gradient(axis=0).background_gradient(cmap = 'RdYlGn').format(game_format, precision=2), use_container_width = True)
elif stat_type_var1 == 'RB Usage':
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), use_container_width = True)
elif stat_type_var1 == 'WR/TE Usage':
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), use_container_width = True)
st.download_button(
label="Export Tables",
data=convert_df_to_csv(table_instance),
file_name='MLB_Research_export.csv',
mime='text/csv',
)