import streamlit as st st.set_page_config(layout="wide") for name in dir(): if not name.startswith('_'): del globals()[name] import numpy as np import pandas as pd import streamlit as st import gspread import plotly.express as px import random import gc @st.cache_resource def init_conn(): scope = ['https://spreadsheets.google.com/feeds', 'https://www.googleapis.com/auth/drive'] credentials = { "type": "service_account", "project_id": "dfsnew", "private_key_id": "2432f6c3771f70a410c5c878d1359869fc9dddc8", "private_key": "-----BEGIN PRIVATE KEY-----\nMIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQDBNBDU2aJuEr6n\ne0o7pDY8gjg1+g1e3oHlpyY/CHMByZuEwfXewsZYP/TApfr8zxXDNG9X31CloWXH\n6ef8H0h6TjhRppE/2YCUZlbgtvpwlDg+1aKTKY5Lc/L937I6V512mgMDhDmTwX+p\noV0vhPuJnyFy+Fuo+xu8D9A46lhTTIK4EZhHc04SUBxUI3pDdfvuMbjciD/Pskn2\nMwBSEG/FQoe4GYrSmm7jzYdSHItVBakr26xl117m8BrIuceU7IEWrnJGDza8TtTZ\n+4Wp7PY9v6DgVt2+rnnDaF/g7kocLqoj2xWp1eS7OALwmqaIPFljIUkL5AJJiLC1\n+/ve6iwVAgMBAAECggEADTFsPdCvwBL9HGw1nT2BK6AbzQnKfHI2zhMcMD04N0TI\nXygsjT3hM/kIElizOyy7+HS97rLz65+KFvzwx71uIlXxkBfO/txwJJIZeCZeky33\n6kiF3cU+b4YXL4FlRwkhGk55irWuhdm2iUOY3KwYziTE8LgncDJXij/NMPnFtshZ\n/2Dc/7sKLi1tna5tfXr5v4N7LhyFOfHme8ZSZIhnpV+WnFM/VAVghwi+3vfzeV+a\nVgvv+QwRUBF+MYpoW8aDw3Y1jKuKKxcG0qHR1mQQTDK6eAymy28lJ9LfgKkZBLS3\nVEGH8O+gLQj2l8VR8koRxA1FETJ9BnIiV4OF+uLQQQKBgQDyYkeBnpPKnw3MXKgy\nxtpt7hLdrrQiR69PHEvHj9z6b60KTH9jDMKcbCU/ouwbTtLQnvtwta2RoWD/1xk+\n3uaeQv/jOtgKGE+Sa0FvJuDWZwBfUORnyqb+s5G9MpVlqNLLkUmE5myyrDbFdxei\nwzisIjvQxtJDLB3pucTRyd6a1QKBgQDMDoWUfNpQI/up3r0RWVCl3odpwOMnpN0S\nhf8uLyvEvtbcMnpxCQCl+4KWnOiX4GH4N9sZGF8YTPazO2Kd85/GioUoNo5u6vJo\ncxD0BTvg5meyUjfZsmuU620/eVQBa88TRdo3isLmBqUp7SAC+g4vTHpgxn00dRYv\neSfZN0dsQQKBgQDkxR34mVOkyrqbSFj4k/dWCn6D/YDHWiF86ZgcowxO01jff5Q8\nSK7mNKxzg7KVk7Amd+eaWd+YtFh5IOwTCw9gEJy0O7Xs0UVJTTJVVryfoFgZnp/1\n1rAHdjT3/eZELTPILzjU1yeA/Eo11lHYramvzh/mzcFm5RzWnR/HYmFYgQKBgFOy\nbSX/pAgVCkedvc0c5lBymvZMkJ+VJrxPS+Ckpn43jKea6M/uUl7Cb8jZKSoKdgS6\n3FpJvc+Y2eOgKw4AfHuSG5Xn8roaEj23XK/KacoQl130DUZ0wV2+xvuvBz7h+ni8\nQQphFxoEhcBRq7ys1h6ebt+86mQW1ne4aRjWbKxBAoGARA+rBNIC9Z1vyRzMAXfj\nnQ9/wShd/NGpVRNrm7sdUastfoyK8Ip3HkJac3xE1ARpQTvxAz742mdeDxPWI8wZ\nHDsjIrRqGLKMN7tSIoM720y6PY/Tsg89SdY4y0h6M75rrEi4Lv5b7s4EmqAZdfKT\nbEyuT7sCPCLeOX/RLy/lCpA=\n-----END PRIVATE KEY-----\n", "client_email": "dfsapps@dfsnew.iam.gserviceaccount.com", "client_id": "105107448378741046480", "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/dfsapps%40dfsnew.iam.gserviceaccount.com", "universe_domain": "googleapis.com" } header= {'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) ' 'AppleWebKit/537.11 (KHTML, like Gecko) ' 'Chrome/23.0.1271.64 Safari/537.11', 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8', 'Accept-Charset': 'ISO-8859-1,utf-8;q=0.7,*;q=0.3', 'Accept-Encoding': 'none', 'Accept-Language': 'en-US,en;q=0.8', 'Connection': 'keep-alive'} gc_con = gspread.service_account_from_dict(credentials, scope) return gc_con gcservice_account = init_conn() NBAGetGameData = 'https://docs.google.com/spreadsheets/d/1tRQrF_I5rS7Q0g9vE8NrENDZ2P3_DvtbBZzKEakwOI0/edit#gid=1373653837' NBABettingModel = 'https://docs.google.com/spreadsheets/d/1WBnvOHQi_zVTGF63efejK5ho02AY00HiYrMHnMJXY1E/edit#gid=1157978351' game_format = {'Win %', 'Injury and Rotation Adjusted Win %'} percentages_format = {'Playoff Odds': '{:.2%}', 'Division Odds': '{:.2%}', 'Top 4 Seed Odds': '{:.2%}', '1 Seed Odds': '{:.2%}', 'Win 1st Round': '{:.2%}', 'Win 2nd Round': '{:.2%}', 'Win Conference': '{:.2%}', 'Win Title': '{:.2%}', '1': '{:.2%}', '2': '{:.2%}', '3': '{:.2%}', '4': '{:.2%}', '5': '{:.2%}', '6': '{:.2%}', '7': '{:.2%}', '8': '{:.2%}', '9': '{:.2%}', '10': '{:.2%}', '11': '{:.2%}', '12': '{:.2%}', '13': '{:.2%}', '14': '{:.2%}', '15': '{:.2%}'} @st.cache_resource(ttl = 300) def init_baselines(): sh = gcservice_account.open_by_url(NBABettingModel) worksheet = sh.worksheet('ExportTable') raw_display = pd.DataFrame(worksheet.get_values()) raw_display.columns = raw_display.iloc[0] raw_display = raw_display[1:] raw_display = raw_display.reset_index(drop=True) raw_display.replace('', np.nan, inplace=True) cols_to_check = ['Win %', 'Injury and Rotation Adjusted Win %'] raw_display.loc[:, cols_to_check] = raw_display.loc[:, cols_to_check].replace({'%': ''}, regex=True).astype(float) / 100 raw_display = raw_display.apply(pd.to_numeric, errors='coerce').fillna(raw_display) raw_display['Team Date'] = raw_display['Team'] + " " + raw_display['Date'] raw_display = raw_display.drop(columns=['Day of Season', 'Team', 'Opp', 'Date Num', 'DR Team', 'In Minutes File']) game_model = raw_display[raw_display['Injury and Rotation Adjusted Win %'] != ""] just_win_probs = game_model[['Team Date', 'Time', 'Acro', 'Opponent', 'Injury and Rotation Adjusted Win %', 'Total Proj', 'Projected Points']] just_win_probs['Projected Spread'] = (just_win_probs['Total Proj'] / 2) - just_win_probs['Projected Points'] worksheet = sh.worksheet('SeasonExport') raw_display = pd.DataFrame(worksheet.get_values()) raw_display.columns = raw_display.iloc[0] raw_display = raw_display[1:] raw_display = raw_display.reset_index(drop=True) raw_display.replace('', 0, inplace=True) cols_to_check = ['Playoff Odds', 'Division Odds', 'Top 4 Seed Odds', '1 Seed Odds', 'Win 1st Round', 'Win 2nd Round', 'Win Conference', 'Win Title', '1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12', '13', '14', '15'] raw_display.loc[:, cols_to_check] = raw_display.loc[:, cols_to_check].replace({'%': ''}, regex=True).astype(float) / 100 raw_display = raw_display.apply(pd.to_numeric, errors='coerce').fillna(raw_display) season_model = raw_display[raw_display['Team'] != ""] title_sims = season_model[['Team', 'Conference', 'Division', 'Power Rank', 'Team PointMarginPerGame', 'SeasonSimLookup', 'Win Projection Now', 'Playoff Odds', 'Division Odds', 'Top 4 Seed Odds', '1 Seed Odds', 'Win 1st Round', 'Win 2nd Round', 'Win Conference', 'Win Title']] seed_probs = season_model[['Team', 'Conference', 'Division', 'Avg Seed', '1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12', '13', '14', '15']] return game_model, season_model, seed_probs, title_sims, just_win_probs def convert_df_to_csv(df): return df.to_csv().encode('utf-8') game_model, season_model, seed_probs, title_sims, just_win_probs = init_baselines() tab1, tab2 = st.tabs(["Game Betting Model", "Season and Futures"]) with tab1: col1, col2 = st.columns([1, 9]) with col1: if st.button("Reset Data", key='reset1'): st.cache_data.clear() game_model, season_model, seed_probs, title_sims, just_win_probs = init_baselines() view_var1 = st.radio("Would you like to view math and stuff or just the win percentages and margins?", ('Just win probs', 'Gimme details'), key='view_var1') split_var1 = st.radio("Would you like to view all teams or specific ones?", ('All', 'Specific Teams'), key='split_var1') if split_var1 == 'Specific Teams': team_var1 = st.multiselect('Which teams would you like to include in the tables?', options = game_model['Acro'].unique(), key='team_var1') elif split_var1 == 'All': team_var1 = game_model.Acro.values.tolist() date_split_var1 = st.radio("Would you like to view all Dates or specific ones?", ('All', 'Specific Dates'), key='date_split_var1') if date_split_var1 == 'Specific Dates': date_var1 = st.multiselect('Which Dates would you like to include in the tables?', options = game_model['Date'].unique(), key='date_var1') elif date_split_var1 == 'All': date_var1 = game_model.Date.values.tolist() with col2: if view_var1 == 'Just win probs': game_display = just_win_probs[just_win_probs['Acro'].isin(team_var1)] game_display = game_display[game_display['Date'].isin(date_var1)] game_display = game_display.set_index('Team Date') st.dataframe(game_display.style.background_gradient(axis=0).background_gradient(cmap='RdYlGn').format(precision=2), use_container_width = True) st.download_button( label="Export Game Model", data=convert_df_to_csv(game_model), file_name='AmericanNumbers_Game_Model_export.csv', mime='text/csv', ) elif view_var1 == 'Gimme details': game_display = game_model[game_model['Acro'].isin(team_var1)] game_display = game_display[game_display['Date'].isin(date_var1)] game_display = game_display.set_index('Team Date') st.dataframe(game_display.style.background_gradient(axis=0).background_gradient(cmap='RdYlGn').format(precision=2), use_container_width = True) st.download_button( label="Export Game Model", data=convert_df_to_csv(game_model), file_name='AmericanNumbers_Game_Model_export.csv', mime='text/csv', ) with tab2: col1, col2 = st.columns([1, 9]) with col1: if st.button("Reset Data", key='reset2'): st.cache_data.clear() game_model, season_model, seed_probs, title_sims, just_win_probs = init_baselines() view_var2 = st.radio("Would you like to view title odds and win projections or seeding probabilities?", ('Win Odds', 'Seed Probabilities'), key='view_var2') split_var2 = st.radio("Would you like to view all teams or specific ones?", ('All', 'Specific Teams'), key='split_var2') if split_var2 == 'Specific Teams': team_var2 = st.multiselect('Which teams would you like to include in the tables?', options = season_model['Team'].unique(), key='team_var2') elif split_var2 == 'All': team_var2 = season_model.Team.values.tolist() conf_var2 = st.radio("Would you like to view all conferences or specific ones?", ('All', 'Specific Conferences'), key='conf_var2') if conf_var2 == 'Specific Conferences': conf_choice_var2 = st.multiselect('Which conferences would you like to include in the tables?', options = season_model['Conference'].unique(), key='conf_choice_var2') elif conf_var2 == 'All': conf_choice_var2 = season_model.Conference.values.tolist() div_var2 = st.radio("Would you like to view all divisions or specific ones?", ('All', 'Specific Divisions'), key='div_var2') if div_var2 == 'Specific Divisions': div_choice_var2 = st.multiselect('Which divisions would you like to include in the tables?', options = season_model['Division'].unique(), key='div_choice_var2') elif div_var2 == 'All': div_choice_var2 = season_model.Division.values.tolist() with col2: if view_var2 == 'Win Odds': title_sims = title_sims[title_sims['Team'].isin(team_var2)] title_sims = title_sims[title_sims['Conference'].isin(conf_choice_var2)] title_sims = title_sims[title_sims['Division'].isin(div_choice_var2)] season_display = title_sims.set_index('Team') season_display = season_display.sort_values(by=['Win Projection Now'], ascending=False) st.dataframe(season_display.style.background_gradient(axis=0).background_gradient(cmap='RdYlGn').format(percentages_format, precision=2), use_container_width = True) st.download_button( label="Export Futures Model", data=convert_df_to_csv(title_sims), file_name='AmericanNumbers_Season_Futures.csv', mime='text/csv', ) elif view_var2 == 'Seed Probabilities': seed_probs = seed_probs[seed_probs['Team'].isin(team_var2)] seed_probs = seed_probs[seed_probs['Conference'].isin(conf_choice_var2)] seed_probs = seed_probs[seed_probs['Division'].isin(div_choice_var2)] season_display = seed_probs.set_index('Team') season_display = season_display.sort_values(by=['Avg Seed'], ascending=True) st.dataframe(season_display.style.background_gradient(axis=0).background_gradient(cmap='RdYlGn').format(percentages_format, precision=2), use_container_width = True) st.download_button( label="Export Futures Model", data=convert_df_to_csv(seed_probs), file_name='AmericanNumbers_Season_Futures.csv', mime='text/csv', )