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 @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 gc = init_conn() game_format = {'Win Percentage': '{:.2%}','First Inning Lead Percentage': '{:.2%}', 'Fifth Inning Lead Percentage': '{:.2%}', '8+ runs': '{:.2%}', 'DK LevX': '{:.2%}', 'FD LevX': '{:.2%}'} player_roo_format = {'Top_finish': '{:.2%}','Top_5_finish': '{:.2%}', 'Top_10_finish': '{:.2%}', '20+%': '{:.2%}', '2x%': '{:.2%}', '3x%': '{:.2%}', '4x%': '{:.2%}','GPP%': '{:.2%}'} freq_format = {'Proj Own': '{:.2%}', 'Exposure': '{:.2%}', 'Edge': '{:.2%}'} @st.cache_resource(ttl=300) def load_dk_player_projections(): sh = gc.open_by_url('https://docs.google.com/spreadsheets/d/1aLVN4izjSuqZGRyz73Kip6U1q3rubh6v9GrckgEqbfs/edit?pli=1#gid=1205205406') worksheet = sh.worksheet('CSGO_ROO') load_display = pd.DataFrame(worksheet.get_all_records()) load_display['Own'] = load_display['Own'] * 100 load_display = load_display[load_display['Own'] > 0 ] load_display['Floor'] = load_display['Median'] * .25 load_display['Ceiling'] = load_display['Median'] + (load_display['Median'] * .75) load_display.replace('', np.nan, inplace=True) raw_display = load_display.dropna(subset=['Median']) return raw_display @st.cache_resource(ttl=300) def load_fd_player_projections(): sh = gc.open_by_url('https://docs.google.com/spreadsheets/d/1aLVN4izjSuqZGRyz73Kip6U1q3rubh6v9GrckgEqbfs/edit?pli=1#gid=1205205406') worksheet = sh.worksheet('CSGO_ROO') load_display = pd.DataFrame(worksheet.get_all_records()) load_display['Own'] = load_display['Own'] * 100 load_display = load_display[load_display['Own'] > 0 ] load_display['Floor'] = load_display['Median'] * .25 load_display['Ceiling'] = load_display['Median'] + (load_display['Median'] * .75) load_display.replace('', np.nan, inplace=True) raw_display = load_display.dropna(subset=['Median']) return raw_display @st.cache_data def convert_df_to_csv(df): return df.to_csv().encode('utf-8') def run_seed_frame(seed_depth1, Strength_var, strength_grow, Teams_used, Total_Runs): RunsVar = 1 seed_depth_def = seed_depth1 Strength_var_def = Strength_var strength_grow_def = strength_grow Teams_used_def = Teams_used Total_Runs_def = Total_Runs while RunsVar <= seed_depth_def: if RunsVar <= 3: FieldStrength = Strength_var_def RandomPortfolio, maps_dict = get_correlated_portfolio_for_sim(Total_Runs_def * .1) FinalPortfolio = RandomPortfolio FinalPortfolio2, maps_dict2 = get_uncorrelated_portfolio_for_sim(Total_Runs_def * .1) FinalPortfolio = pd.concat([FinalPortfolio, FinalPortfolio2], axis=0) maps_dict.update(maps_dict2) del FinalPortfolio2 del maps_dict2 elif RunsVar > 3 and RunsVar <= 4: FieldStrength += (strength_grow_def + ((30 - len(Teams_used_def)) * .001)) FinalPortfolio3, maps_dict3 = get_correlated_portfolio_for_sim(Total_Runs_def * .1) FinalPortfolio4, maps_dict4 = get_uncorrelated_portfolio_for_sim(Total_Runs_def * .1) FinalPortfolio = pd.concat([FinalPortfolio, FinalPortfolio3], axis=0) FinalPortfolio = pd.concat([FinalPortfolio, FinalPortfolio4], axis=0) FinalPortfolio = FinalPortfolio.drop_duplicates(subset = ['Projection', 'Own'],keep = 'last').reset_index(drop = True) maps_dict.update(maps_dict3) maps_dict.update(maps_dict4) del FinalPortfolio3 del maps_dict3 del FinalPortfolio4 del maps_dict4 elif RunsVar > 4: FieldStrength = 1 FinalPortfolio3, maps_dict3 = get_correlated_portfolio_for_sim(Total_Runs_def * .1) FinalPortfolio4, maps_dict4 = get_uncorrelated_portfolio_for_sim(Total_Runs_def * .1) FinalPortfolio = pd.concat([FinalPortfolio, FinalPortfolio3], axis=0) FinalPortfolio = pd.concat([FinalPortfolio, FinalPortfolio4], axis=0) FinalPortfolio = FinalPortfolio.drop_duplicates(subset = ['Projection', 'Own'],keep = 'last').reset_index(drop = True) maps_dict.update(maps_dict3) maps_dict.update(maps_dict4) del FinalPortfolio3 del maps_dict3 del FinalPortfolio4 del maps_dict4 RunsVar += 1 return FinalPortfolio, maps_dict def create_overall_dfs(pos_players, table_name, dict_name, pos): pos_players = pos_players.sort_values(by='Value', ascending=False) table_name_raw = pos_players.reset_index(drop=True) overall_table_name = table_name_raw.head(round(len(table_name_raw))) overall_table_name = overall_table_name.assign(Var = range(0,len(overall_table_name))) overall_dict_name = pd.Series(overall_table_name.Player.values, index=overall_table_name.Var).to_dict() del pos_players del table_name_raw return overall_table_name, overall_dict_name def get_overall_merged_df(): ref_dict = { 'pos':['FLEX'], 'pos_dfs':['FLEX_Table'], 'pos_dicts':['flex_dict'] } for i in range(0,1): ref_dict['pos_dfs'][i], ref_dict['pos_dicts'][i] =\ create_overall_dfs(pos_players, ref_dict['pos_dfs'][i], ref_dict['pos_dicts'][i], ref_dict['pos'][i]) df_out = pd.concat(ref_dict['pos_dfs'], ignore_index=True) return df_out, ref_dict def create_random_portfolio(Total_Sample_Size): O_merge, full_pos_player_dict = get_overall_merged_df() Overall_Merge = O_merge[['Var', 'Player', 'Team', 'Salary', 'Median', 'Own']].copy() # Calculate Floor, Ceiling, and STDev directly Overall_Merge['Floor'] = Overall_Merge['Median'] * .25 Overall_Merge['Ceiling'] = Overall_Merge['Median'] + Overall_Merge['Floor'] Overall_Merge['STDev'] = Overall_Merge['Median'] / 4 # Calculate the flex range and generate unique range list flex_range_var = len(Overall_Merge) ranges_dict = {'flex_range': flex_range_var} ranges_dict['flex_Uniques'] = list(range(0, flex_range_var)) # Generate random portfolios rng = np.random.default_rng() all_choices = rng.choice(flex_range_var, size=(Total_Sample_Size, 6)) # Create RandomPortfolio DataFrame RandomPortfolio = pd.DataFrame(all_choices, columns=['CPT', 'FLEX1', 'FLEX2', 'FLEX3', 'FLEX4', 'FLEX5']) RandomPortfolio['User/Field'] = 0 return RandomPortfolio, maps_dict, ranges_dict, full_pos_player_dict def get_correlated_portfolio_for_sim(Total_Sample_Size): sizesplit = round(Total_Sample_Size * .50) RandomPortfolio, maps_dict, ranges_dict, full_pos_player_dict = create_random_portfolio(sizesplit) RandomPortfolio['CPT'] = pd.Series(list(RandomPortfolio['CPT'].map(full_pos_player_dict['pos_dicts'][0])), dtype="string[pyarrow]") RandomPortfolio['FLEX1'] = pd.Series(list(RandomPortfolio['FLEX1'].map(full_pos_player_dict['pos_dicts'][0])), dtype="string[pyarrow]") RandomPortfolio['FLEX2'] = pd.Series(list(RandomPortfolio['FLEX2'].map(full_pos_player_dict['pos_dicts'][0])), dtype="string[pyarrow]") RandomPortfolio['FLEX3'] = pd.Series(list(RandomPortfolio['FLEX3'].map(full_pos_player_dict['pos_dicts'][0])), dtype="string[pyarrow]") RandomPortfolio['FLEX4'] = pd.Series(list(RandomPortfolio['FLEX4'].map(full_pos_player_dict['pos_dicts'][0])), dtype="string[pyarrow]") RandomPortfolio['FLEX5'] = pd.Series(list(RandomPortfolio['FLEX5'].map(full_pos_player_dict['pos_dicts'][0])), dtype="string[pyarrow]") RandomPortfolio['plyr_list'] = RandomPortfolio[RandomPortfolio.columns.values.tolist()].values.tolist() RandomPortfolio['plyr_count'] = RandomPortfolio['plyr_list'].apply(lambda x: len(set(x))) RandomPortfolio = RandomPortfolio[RandomPortfolio['plyr_count'] == 7].drop(columns=['plyr_list','plyr_count']).\ reset_index(drop=True) del sizesplit del full_pos_player_dict del ranges_dict RandomPortfolio['CPTs'] = RandomPortfolio['CPT'].map(maps_dict['Salary_map']).astype(np.int32) * 1.5 RandomPortfolio['FLEX1s'] = RandomPortfolio['FLEX1'].map(maps_dict['Salary_map']).astype(np.int32) RandomPortfolio['FLEX2s'] = RandomPortfolio['FLEX2'].map(maps_dict['Salary_map']).astype(np.int32) RandomPortfolio['FLEX3s'] = RandomPortfolio['FLEX3'].map(maps_dict['Salary_map']).astype(np.int32) RandomPortfolio['FLEX4s'] = RandomPortfolio['FLEX4'].map(maps_dict['Salary_map']).astype(np.int32) RandomPortfolio['FLEX5s'] = RandomPortfolio['FLEX5'].map(maps_dict['Salary_map']).astype(np.int32) RandomPortfolio['CPTp'] = RandomPortfolio['CPT'].map(maps_dict['Projection_map']).astype(np.float16) * 1.5 RandomPortfolio['FLEX1p'] = RandomPortfolio['FLEX1'].map(maps_dict['Projection_map']).astype(np.float16) RandomPortfolio['FLEX2p'] = RandomPortfolio['FLEX2'].map(maps_dict['Projection_map']).astype(np.float16) RandomPortfolio['FLEX3p'] = RandomPortfolio['FLEX3'].map(maps_dict['Projection_map']).astype(np.float16) RandomPortfolio['FLEX4p'] = RandomPortfolio['FLEX4'].map(maps_dict['Projection_map']).astype(np.float16) RandomPortfolio['FLEX5p'] = RandomPortfolio['FLEX5'].map(maps_dict['Projection_map']).astype(np.float16) RandomPortfolio['CPTo'] = RandomPortfolio['CPT'].map(maps_dict['Own_map']).astype(np.float16) / 4 RandomPortfolio['FLEX1o'] = RandomPortfolio['FLEX1'].map(maps_dict['Own_map']).astype(np.float16) RandomPortfolio['FLEX2o'] = RandomPortfolio['FLEX2'].map(maps_dict['Own_map']).astype(np.float16) RandomPortfolio['FLEX3o'] = RandomPortfolio['FLEX3'].map(maps_dict['Own_map']).astype(np.float16) RandomPortfolio['FLEX4o'] = RandomPortfolio['FLEX4'].map(maps_dict['Own_map']).astype(np.float16) RandomPortfolio['FLEX5o'] = RandomPortfolio['FLEX5'].map(maps_dict['Own_map']).astype(np.float16) portHeaderList = RandomPortfolio.columns.values.tolist() portHeaderList.append('Salary') portHeaderList.append('Projection') portHeaderList.append('Own') RandomPortArray = RandomPortfolio.to_numpy() del RandomPortfolio RandomPortArray = np.c_[RandomPortArray, np.einsum('ij->i',RandomPortArray[:,7:13].astype(int))] RandomPortArray = np.c_[RandomPortArray, np.einsum('ij->i',RandomPortArray[:,13:19].astype(np.double))] RandomPortArray = np.c_[RandomPortArray, np.einsum('ij->i',RandomPortArray[:,19:25].astype(np.double))] RandomPortArrayOut = np.delete(RandomPortArray, np.s_[7:25], axis=1) RandomPortfolioDF = pd.DataFrame(RandomPortArrayOut, columns = ['CPT', 'FLEX1', 'FLEX2', 'FLEX3', 'FLEX4', 'FLEX5', 'User/Field', 'Salary', 'Projection', 'Own']) RandomPortfolioDF = RandomPortfolioDF.sort_values(by=Sim_function, ascending=False) del RandomPortArray del RandomPortArrayOut # st.table(RandomPortfolioDF.head(50)) if insert_port == 1: CleanPortfolio['Salary'] = sum([CleanPortfolio['CPT'].map(maps_dict['Salary_map']) * 1.5, CleanPortfolio['FLEX1'].map(maps_dict['Salary_map']), CleanPortfolio['FLEX2'].map(maps_dict['Salary_map']), CleanPortfolio['FLEX3'].map(maps_dict['Salary_map']), CleanPortfolio['FLEX4'].map(maps_dict['Salary_map']), CleanPortfolio['FLEX5'].map(maps_dict['Salary_map']) ]).astype(np.int16) if insert_port == 1: CleanPortfolio['Projection'] = sum([CleanPortfolio['CPT'].map(maps_dict['Projection_map']) * 1.5, CleanPortfolio['FLEX1'].map(maps_dict['Projection_map']), CleanPortfolio['FLEX2'].map(maps_dict['Projection_map']), CleanPortfolio['FLEX3'].map(maps_dict['Projection_map']), CleanPortfolio['FLEX4'].map(maps_dict['Projection_map']), CleanPortfolio['FLEX5'].map(maps_dict['Projection_map']) ]).astype(np.float16) if insert_port == 1: CleanPortfolio['Own'] = sum([CleanPortfolio['CPT'].map(maps_dict['own_map']) / 4, CleanPortfolio['FLEX1'].map(maps_dict['own_map']), CleanPortfolio['FLEX2'].map(maps_dict['own_map']), CleanPortfolio['FLEX3'].map(maps_dict['own_map']), CleanPortfolio['FLEX4'].map(maps_dict['own_map']), CleanPortfolio['FLEX5'].map(maps_dict['own_map']) ]).astype(np.float16) if site_var1 == 'Draftkings': RandomPortfolioDF = RandomPortfolioDF[RandomPortfolioDF['Salary'] <= 50000].reset_index(drop=True) RandomPortfolioDF = RandomPortfolioDF[RandomPortfolioDF['Salary'] >= 49500 - (FieldStrength * 1000)].reset_index(drop=True) elif site_var1 == 'Fanduel': RandomPortfolioDF = RandomPortfolioDF[RandomPortfolioDF['Salary'] <= 60000].reset_index(drop=True) RandomPortfolioDF = RandomPortfolioDF[RandomPortfolioDF['Salary'] >= 59500 - (FieldStrength * 1000)].reset_index(drop=True) RandomPortfolio = RandomPortfolioDF.sort_values(by=Sim_function, ascending=False) RandomPortfolio = RandomPortfolio[['CPT', 'FLEX1', 'FLEX2', 'FLEX3', 'FLEX4', 'FLEX5', 'User/Field', 'Salary', 'Projection', 'Own']] return RandomPortfolio, maps_dict def get_uncorrelated_portfolio_for_sim(Total_Sample_Size): sizesplit = round(Total_Sample_Size * .50) RandomPortfolio, maps_dict, ranges_dict, full_pos_player_dict = create_random_portfolio(sizesplit) RandomPortfolio['CPT'] = pd.Series(list(RandomPortfolio['CPT'].map(full_pos_player_dict['pos_dicts'][0])), dtype="string[pyarrow]") RandomPortfolio['FLEX1'] = pd.Series(list(RandomPortfolio['FLEX1'].map(full_pos_player_dict['pos_dicts'][0])), dtype="string[pyarrow]") RandomPortfolio['FLEX2'] = pd.Series(list(RandomPortfolio['FLEX2'].map(full_pos_player_dict['pos_dicts'][0])), dtype="string[pyarrow]") RandomPortfolio['FLEX3'] = pd.Series(list(RandomPortfolio['FLEX3'].map(full_pos_player_dict['pos_dicts'][0])), dtype="string[pyarrow]") RandomPortfolio['FLEX4'] = pd.Series(list(RandomPortfolio['FLEX4'].map(full_pos_player_dict['pos_dicts'][0])), dtype="string[pyarrow]") RandomPortfolio['FLEX5'] = pd.Series(list(RandomPortfolio['FLEX5'].map(full_pos_player_dict['pos_dicts'][0])), dtype="string[pyarrow]") RandomPortfolio['plyr_list'] = RandomPortfolio[RandomPortfolio.columns.values.tolist()].values.tolist() RandomPortfolio['plyr_count'] = RandomPortfolio['plyr_list'].apply(lambda x: len(set(x))) RandomPortfolio = RandomPortfolio[RandomPortfolio['plyr_count'] == 7].drop(columns=['plyr_list','plyr_count']).\ reset_index(drop=True) del sizesplit del full_pos_player_dict del ranges_dict RandomPortfolio['CPTs'] = RandomPortfolio['CPT'].map(maps_dict['Salary_map']).astype(np.int32) * 1.5 RandomPortfolio['FLEX1s'] = RandomPortfolio['FLEX1'].map(maps_dict['Salary_map']).astype(np.int32) RandomPortfolio['FLEX2s'] = RandomPortfolio['FLEX2'].map(maps_dict['Salary_map']).astype(np.int32) RandomPortfolio['FLEX3s'] = RandomPortfolio['FLEX3'].map(maps_dict['Salary_map']).astype(np.int32) RandomPortfolio['FLEX4s'] = RandomPortfolio['FLEX4'].map(maps_dict['Salary_map']).astype(np.int32) RandomPortfolio['FLEX5s'] = RandomPortfolio['FLEX5'].map(maps_dict['Salary_map']).astype(np.int32) RandomPortfolio['CPTp'] = RandomPortfolio['CPT'].map(maps_dict['Projection_map']).astype(np.float16) * 1.5 RandomPortfolio['FLEX1p'] = RandomPortfolio['FLEX1'].map(maps_dict['Projection_map']).astype(np.float16) RandomPortfolio['FLEX2p'] = RandomPortfolio['FLEX2'].map(maps_dict['Projection_map']).astype(np.float16) RandomPortfolio['FLEX3p'] = RandomPortfolio['FLEX3'].map(maps_dict['Projection_map']).astype(np.float16) RandomPortfolio['FLEX4p'] = RandomPortfolio['FLEX4'].map(maps_dict['Projection_map']).astype(np.float16) RandomPortfolio['FLEX5p'] = RandomPortfolio['FLEX5'].map(maps_dict['Projection_map']).astype(np.float16) RandomPortfolio['CPTo'] = RandomPortfolio['CPT'].map(maps_dict['Own_map']).astype(np.float16) / 4 RandomPortfolio['FLEX1o'] = RandomPortfolio['FLEX1'].map(maps_dict['Own_map']).astype(np.float16) RandomPortfolio['FLEX2o'] = RandomPortfolio['FLEX2'].map(maps_dict['Own_map']).astype(np.float16) RandomPortfolio['FLEX3o'] = RandomPortfolio['FLEX3'].map(maps_dict['Own_map']).astype(np.float16) RandomPortfolio['FLEX4o'] = RandomPortfolio['FLEX4'].map(maps_dict['Own_map']).astype(np.float16) RandomPortfolio['FLEX5o'] = RandomPortfolio['FLEX5'].map(maps_dict['Own_map']).astype(np.float16) portHeaderList = RandomPortfolio.columns.values.tolist() portHeaderList.append('Salary') portHeaderList.append('Projection') portHeaderList.append('Own') RandomPortArray = RandomPortfolio.to_numpy() del RandomPortfolio RandomPortArray = np.c_[RandomPortArray, np.einsum('ij->i',RandomPortArray[:,7:13].astype(int))] RandomPortArray = np.c_[RandomPortArray, np.einsum('ij->i',RandomPortArray[:,13:19].astype(np.double))] RandomPortArray = np.c_[RandomPortArray, np.einsum('ij->i',RandomPortArray[:,19:25].astype(np.double))] RandomPortArrayOut = np.delete(RandomPortArray, np.s_[7:25], axis=1) RandomPortfolioDF = pd.DataFrame(RandomPortArrayOut, columns = ['CPT', 'FLEX1', 'FLEX2', 'FLEX3', 'FLEX4', 'FLEX5', 'User/Field', 'Salary', 'Projection', 'Own']) RandomPortfolioDF = RandomPortfolioDF.sort_values(by=Sim_function, ascending=False) del RandomPortArray del RandomPortArrayOut # st.table(RandomPortfolioDF.head(50)) if insert_port == 1: CleanPortfolio['Salary'] = sum([CleanPortfolio['CPT'].map(maps_dict['Salary_map']) * 1.5, CleanPortfolio['FLEX1'].map(maps_dict['Salary_map']), CleanPortfolio['FLEX2'].map(maps_dict['Salary_map']), CleanPortfolio['FLEX3'].map(maps_dict['Salary_map']), CleanPortfolio['FLEX4'].map(maps_dict['Salary_map']), CleanPortfolio['FLEX5'].map(maps_dict['Salary_map']) ]).astype(np.int16) if insert_port == 1: CleanPortfolio['Projection'] = sum([CleanPortfolio['CPT'].map(maps_dict['Projection_map']) * 1.5, CleanPortfolio['FLEX1'].map(maps_dict['Projection_map']), CleanPortfolio['FLEX2'].map(maps_dict['Projection_map']), CleanPortfolio['FLEX3'].map(maps_dict['Projection_map']), CleanPortfolio['FLEX4'].map(maps_dict['Projection_map']), CleanPortfolio['FLEX5'].map(maps_dict['Projection_map']) ]).astype(np.float16) if insert_port == 1: CleanPortfolio['Own'] = sum([CleanPortfolio['CPT'].map(maps_dict['own_map']) / 4, CleanPortfolio['FLEX1'].map(maps_dict['own_map']), CleanPortfolio['FLEX2'].map(maps_dict['own_map']), CleanPortfolio['FLEX3'].map(maps_dict['own_map']), CleanPortfolio['FLEX4'].map(maps_dict['own_map']), CleanPortfolio['FLEX5'].map(maps_dict['own_map']) ]).astype(np.float16) if site_var1 == 'Draftkings': RandomPortfolioDF = RandomPortfolioDF[RandomPortfolioDF['Salary'] <= 50000].reset_index(drop=True) RandomPortfolioDF = RandomPortfolioDF[RandomPortfolioDF['Salary'] >= 49500 - (FieldStrength * 1000)].reset_index(drop=True) elif site_var1 == 'Fanduel': RandomPortfolioDF = RandomPortfolioDF[RandomPortfolioDF['Salary'] <= 60000].reset_index(drop=True) RandomPortfolioDF = RandomPortfolioDF[RandomPortfolioDF['Salary'] >= 59500 - (FieldStrength * 1000)].reset_index(drop=True) RandomPortfolio = RandomPortfolioDF.sort_values(by=Sim_function, ascending=False) RandomPortfolio = RandomPortfolio[['CPT', 'FLEX1', 'FLEX2', 'FLEX3', 'FLEX4', 'FLEX5', 'User/Field', 'Salary', 'Projection', 'Own']] return RandomPortfolio, maps_dict dk_roo_raw = load_dk_player_projections() fd_roo_raw = load_fd_player_projections() static_exposure = pd.DataFrame(columns=['Player', 'count']) overall_exposure = pd.DataFrame(columns=['Player', 'count']) tab1, tab2 = st.tabs(['Uploads', 'Contest Sim']) with tab1: with st.container(): st.info("The Projections file can have any columns in any order, but must contain columns explicitly named: 'Player', 'Salary', 'Position', 'Team', 'Opp', 'Median', and 'Own'. Upload your projections first to avoid an error message.") col1, col2 = st.columns([3, 3]) with col1: proj_file = st.file_uploader("Upload Projections File", key = 'proj_uploader') if proj_file is not None: try: proj_dataframe = pd.read_csv(proj_file) proj_dataframe = proj_dataframe.dropna(subset='Median') except: proj_dataframe = pd.read_excel(proj_file) proj_dataframe = proj_dataframe.dropna(subset='Median') player_salary_dict = dict(zip(proj_dataframe.Player, proj_dataframe.Salary)) player_proj_dict = dict(zip(proj_dataframe.Player, proj_dataframe.Median)) player_own_dict = dict(zip(proj_dataframe.Player, proj_dataframe.Own)) player_team_dict = dict(zip(proj_dataframe.Player, proj_dataframe.Team)) with col2: portfolio_file = st.file_uploader("Upload Portfolio File", key = 'portfolio_uploader') if portfolio_file is not None: try: portfolio_dataframe = pd.read_csv(portfolio_file) except: portfolio_dataframe = pd.read_excel(portfolio_file) try: try: portfolio_dataframe.columns=["CPT", "FLEX1", "FLEX2", "FLEX3", "FLEX4", "FLEX5"] split_portfolio = portfolio_dataframe split_portfolio[['CPT', 'CPT_ID']] = split_portfolio.CPT.str.split("(", n=1, expand = True) split_portfolio[['FLEX1', 'FLEX1_ID']] = split_portfolio.FLEX1.str.split("(", n=1, expand = True) split_portfolio[['FLEX2', 'FLEX2_ID']] = split_portfolio.FLEX2.str.split("(", n=1, expand = True) split_portfolio[['FLEX3', 'FLEX3_ID']] = split_portfolio.FLEX3.str.split("(", n=1, expand = True) split_portfolio[['FLEX4', 'FLEX4_ID']] = split_portfolio.FLEX4.str.split("(", n=1, expand = True) split_portfolio[['FLEX5', 'FLEX5_ID']] = split_portfolio.FLEX5.str.split("(", n=1, expand = True) split_portfolio['CPT'] = split_portfolio['CPT'].str.strip() split_portfolio['FLEX1'] = split_portfolio['FLEX1'].str.strip() split_portfolio['FLEX2'] = split_portfolio['FLEX2'].str.strip() split_portfolio['FLEX3'] = split_portfolio['FLEX3'].str.strip() split_portfolio['FLEX4'] = split_portfolio['FLEX4'].str.strip() split_portfolio['FLEX5'] = split_portfolio['FLEX5'].str.strip() CPT_dict = dict(zip(split_portfolio.CPT, split_portfolio.CPT_ID)) FLEX1_dict = dict(zip(split_portfolio.FLEX1, split_portfolio.FLEX1_ID)) FLEX2_dict = dict(zip(split_portfolio.FLEX2, split_portfolio.FLEX2_ID)) FLEX3_dict = dict(zip(split_portfolio.FLEX3, split_portfolio.FLEX3_ID)) FLEX4_dict = dict(zip(split_portfolio.FLEX4, split_portfolio.FLEX4_ID)) FLEX5_dict = dict(zip(split_portfolio.FLEX5, split_portfolio.FLEX5_ID)) split_portfolio['Salary'] = sum([split_portfolio['CPT'].map(player_salary_dict) * 1.5, split_portfolio['FLEX1'].map(player_salary_dict), split_portfolio['FLEX2'].map(player_salary_dict), split_portfolio['FLEX3'].map(player_salary_dict), split_portfolio['FLEX4'].map(player_salary_dict), split_portfolio['FLEX5'].map(player_salary_dict)]) del player_salary_dict split_portfolio['Projection'] = sum([split_portfolio['CPT'].map(player_proj_dict) * 1.5, split_portfolio['FLEX1'].map(player_proj_dict), split_portfolio['FLEX2'].map(player_proj_dict), split_portfolio['FLEX3'].map(player_proj_dict), split_portfolio['FLEX4'].map(player_proj_dict), split_portfolio['FLEX5'].map(player_proj_dict)]) del player_proj_dict split_portfolio['Ownership'] = sum([split_portfolio['CPT'].map(player_own_dict) / 4, split_portfolio['FLEX1'].map(player_own_dict), split_portfolio['FLEX2'].map(player_own_dict), split_portfolio['FLEX3'].map(player_own_dict), split_portfolio['FLEX4'].map(player_own_dict), split_portfolio['FLEX5'].map(player_own_dict)]) del player_own_dict split_portfolio['CPT_team'] = split_portfolio['CPT'].map(player_team_dict) split_portfolio['FLEX1_team'] = split_portfolio['FLEX1'].map(player_team_dict) split_portfolio['FLEX2_team'] = split_portfolio['FLEX2'].map(player_team_dict) split_portfolio['FLEX3_team'] = split_portfolio['FLEX3'].map(player_team_dict) split_portfolio['FLEX4_team'] = split_portfolio['FLEX4'].map(player_team_dict) split_portfolio['FLEX5_team'] = split_portfolio['FLEX5'].map(player_team_dict) split_portfolio = split_portfolio[['CPT', 'FLEX1', 'FLEX2', 'FLEX3', 'FLEX4', 'FLEX5', 'Salary', 'Projection', 'Ownership', 'CPT_team', 'FLEX1_team', 'FLEX2_team', 'FLEX3_team', 'FLEX4_team', 'FLEX5_team']] split_portfolio['Main_Stack'] = 0 split_portfolio['Main_Stack_Size'] = 0 split_portfolio['Main_Stack_Size'] = 0 except: portfolio_dataframe.columns=["CPT", "FLEX1", "FLEX2", "FLEX3", "FLEX4", "FLEX5"] split_portfolio = portfolio_dataframe split_portfolio[['CPT_ID', 'CPT']] = split_portfolio.CPT.str.split(":", n=1, expand = True) split_portfolio[['FLEX1_ID', 'FLEX1']] = split_portfolio.FLEX1.str.split(":", n=1, expand = True) split_portfolio[['FLEX2_ID', 'FLEX2']] = split_portfolio.FLEX2.str.split(":", n=1, expand = True) split_portfolio[['FLEX3_ID', 'FLEX3']] = split_portfolio.FLEX3.str.split(":", n=1, expand = True) split_portfolio[['FLEX4_ID', 'FLEX4']] = split_portfolio.FLEX4.str.split(":", n=1, expand = True) split_portfolio[['FLEX5_ID', 'FLEX5']] = split_portfolio.FLEX5.str.split(":", n=1, expand = True) split_portfolio['CPT'] = split_portfolio['CPT'].str.strip() split_portfolio['FLEX1'] = split_portfolio['FLEX1'].str.strip() split_portfolio['FLEX2'] = split_portfolio['FLEX2'].str.strip() split_portfolio['FLEX3'] = split_portfolio['FLEX3'].str.strip() split_portfolio['FLEX4'] = split_portfolio['FLEX4'].str.strip() split_portfolio['FLEX5'] = split_portfolio['FLEX5'].str.strip() CPT_dict = dict(zip(split_portfolio.CPT, split_portfolio.CPT_ID)) FLEX1_dict = dict(zip(split_portfolio.FLEX1, split_portfolio.FLEX1_ID)) FLEX2_dict = dict(zip(split_portfolio.FLEX2, split_portfolio.FLEX2_ID)) FLEX3_dict = dict(zip(split_portfolio.FLEX3, split_portfolio.FLEX3_ID)) FLEX4_dict = dict(zip(split_portfolio.FLEX4, split_portfolio.FLEX4_ID)) FLEX5_dict = dict(zip(split_portfolio.FLEX5, split_portfolio.FLEX5_ID)) split_portfolio['Salary'] = sum([split_portfolio['CPT'].map(player_salary_dict), split_portfolio['FLEX1'].map(player_salary_dict), split_portfolio['FLEX2'].map(player_salary_dict), split_portfolio['FLEX3'].map(player_salary_dict), split_portfolio['FLEX4'].map(player_salary_dict), split_portfolio['FLEX5'].map(player_salary_dict)]) del player_salary_dict split_portfolio['Projection'] = sum([split_portfolio['CPT'].map(player_proj_dict) * 1.5, split_portfolio['FLEX1'].map(player_proj_dict), split_portfolio['FLEX2'].map(player_proj_dict), split_portfolio['FLEX3'].map(player_proj_dict), split_portfolio['FLEX4'].map(player_proj_dict), split_portfolio['FLEX5'].map(player_proj_dict)]) del player_proj_dict split_portfolio['Ownership'] = sum([split_portfolio['CPT'].map(player_own_dict) / 4, split_portfolio['FLEX1'].map(player_own_dict), split_portfolio['FLEX2'].map(player_own_dict), split_portfolio['FLEX3'].map(player_own_dict), split_portfolio['FLEX4'].map(player_own_dict), split_portfolio['FLEX5'].map(player_own_dict)]) del player_own_dict split_portfolio['CPT_team'] = split_portfolio['CPT'].map(player_team_dict) split_portfolio['FLEX1_team'] = split_portfolio['FLEX1'].map(player_team_dict) split_portfolio['FLEX2_team'] = split_portfolio['FLEX2'].map(player_team_dict) split_portfolio['FLEX3_team'] = split_portfolio['FLEX3'].map(player_team_dict) split_portfolio['FLEX4_team'] = split_portfolio['FLEX4'].map(player_team_dict) split_portfolio['FLEX5_team'] = split_portfolio['FLEX5'].map(player_team_dict) split_portfolio = split_portfolio[['CPT', 'FLEX1', 'FLEX2', 'FLEX3', 'FLEX4', 'FLEX5', 'Salary', 'Projection', 'Ownership', 'CPT_team', 'FLEX1_team', 'FLEX2_team', 'FLEX3_team', 'FLEX4_team', 'FLEX5_team']] split_portfolio['Main_Stack'] = 0 split_portfolio['Main_Stack_Size'] = 0 split_portfolio['Main_Stack_Size'] = 0 except: split_portfolio = portfolio_dataframe split_portfolio['CPT'] = split_portfolio['CPT'].str[:-6] split_portfolio['FLEX1'] = split_portfolio['FLEX1'].str[:-6] split_portfolio['FLEX2'] = split_portfolio['FLEX2'].str[:-6] split_portfolio['FLEX3'] = split_portfolio['FLEX3'].str[:-6] split_portfolio['FLEX4'] = split_portfolio['FLEX4'].str[:-6] split_portfolio['FLEX5'] = split_portfolio['FLEX5'].str[:-6] split_portfolio['CPT'] = split_portfolio['CPT'].str.strip() split_portfolio['FLEX1'] = split_portfolio['FLEX1'].str.strip() split_portfolio['FLEX2'] = split_portfolio['FLEX2'].str.strip() split_portfolio['FLEX3'] = split_portfolio['FLEX3'].str.strip() split_portfolio['FLEX4'] = split_portfolio['FLEX4'].str.strip() split_portfolio['FLEX5'] = split_portfolio['FLEX5'].str.strip() split_portfolio['Salary'] = sum([split_portfolio['CPT'].map(player_salary_dict) * 1.5, split_portfolio['FLEX1'].map(player_salary_dict), split_portfolio['FLEX2'].map(player_salary_dict), split_portfolio['FLEX3'].map(player_salary_dict), split_portfolio['FLEX4'].map(player_salary_dict), split_portfolio['FLEX5'].map(player_salary_dict)]) del player_salary_dict split_portfolio['Projection'] = sum([split_portfolio['CPT'].map(player_proj_dict) * 1.5, split_portfolio['FLEX1'].map(player_proj_dict), split_portfolio['FLEX2'].map(player_proj_dict), split_portfolio['FLEX3'].map(player_proj_dict), split_portfolio['FLEX4'].map(player_proj_dict), split_portfolio['FLEX5'].map(player_proj_dict)]) del player_proj_dict split_portfolio['Ownership'] = sum([split_portfolio['CPT'].map(player_own_dict) / 4, split_portfolio['FLEX1'].map(player_own_dict), split_portfolio['FLEX2'].map(player_own_dict), split_portfolio['FLEX3'].map(player_own_dict), split_portfolio['FLEX4'].map(player_own_dict), split_portfolio['FLEX5'].map(player_own_dict)]) del player_own_dict split_portfolio['CPT_team'] = split_portfolio['CPT'].map(player_team_dict) split_portfolio['FLEX1_team'] = split_portfolio['FLEX1'].map(player_team_dict) split_portfolio['FLEX2_team'] = split_portfolio['FLEX2'].map(player_team_dict) split_portfolio['FLEX3_team'] = split_portfolio['FLEX3'].map(player_team_dict) split_portfolio['FLEX4_team'] = split_portfolio['FLEX4'].map(player_team_dict) split_portfolio['FLEX5_team'] = split_portfolio['FLEX5'].map(player_team_dict) split_portfolio = split_portfolio[['CPT', 'FLEX1', 'FLEX2', 'FLEX3', 'FLEX4', 'FLEX5', 'Salary', 'Projection', 'Ownership', 'CPT_team', 'FLEX1_team', 'FLEX2_team', 'FLEX3_team', 'FLEX4_team', 'FLEX5_team']] split_portfolio['Main_Stack'] = 0 split_portfolio['Main_Stack_Size'] = 0 split_portfolio['Main_Stack_Size'] = 0 for player_cols in split_portfolio.iloc[:, 0:6]: static_col_raw = split_portfolio[player_cols].value_counts() static_col = static_col_raw.to_frame() static_col.reset_index(inplace=True) static_col.columns = ['Player', 'count'] static_exposure = pd.concat([static_exposure, static_col], ignore_index=True) static_exposure['Exposure'] = static_exposure['count'] / len(split_portfolio) static_exposure = static_exposure[['Player', 'Exposure']] del static_col_raw del static_col with st.container(): col1, col2 = st.columns([3, 3]) if portfolio_file is not None: with col1: st.write(len(portfolio_dataframe)) team_split_var1 = st.radio("Are you wanting to isolate any lineups with specific main stacks?", ('Full Portfolio', 'Specific Stacks')) if team_split_var1 == 'Specific Stacks': team_var1 = st.multiselect('Which main stacks would you like to include in the Portfolio?', options = split_portfolio['Main_Stack'].unique()) elif team_split_var1 == 'Full Portfolio': team_var1 = split_portfolio.Main_Stack.values.tolist() with col2: player_split_var1 = st.radio("Are you wanting to isolate any lineups with specific players?", ('Full Players', 'Specific Players')) if player_split_var1 == 'Specific Players': find_var1 = st.multiselect('Which players must be included in the lineups?', options = static_exposure['Player'].unique()) elif player_split_var1 == 'Full Players': find_var1 = static_exposure.Player.values.tolist() split_portfolio = split_portfolio[split_portfolio['Main_Stack'].isin(team_var1)] if player_split_var1 == 'Specific Players': split_portfolio = split_portfolio[np.equal.outer(split_portfolio.to_numpy(copy=False), find_var1).any(axis=1).all(axis=1)] elif player_split_var1 == 'Full Players': split_portfolio = split_portfolio for player_cols in split_portfolio.iloc[:, 0:6]: exposure_col_raw = split_portfolio[player_cols].value_counts() exposure_col = exposure_col_raw.to_frame() exposure_col.reset_index(inplace=True) exposure_col.columns = ['Player', 'count'] overall_exposure = pd.concat([overall_exposure, exposure_col], ignore_index=True) overall_exposure['Exposure'] = overall_exposure['count'] / len(split_portfolio) overall_exposure = overall_exposure.groupby('Player').sum() overall_exposure.reset_index(inplace=True) overall_exposure = overall_exposure[['Player', 'Exposure']] overall_exposure = overall_exposure.set_index('Player') overall_exposure = overall_exposure.sort_values(by='Exposure', ascending=False) overall_exposure['Exposure'] = overall_exposure['Exposure'].astype(float).map(lambda n: '{:.2%}'.format(n)) with st.container(): col1, col2 = st.columns([1, 6]) with col1: if portfolio_file is not None: st.header('Exposure View') st.dataframe(overall_exposure) with col2: if portfolio_file is not None: st.header('Portfolio View') split_portfolio = split_portfolio.reset_index() split_portfolio['Lineup'] = split_portfolio['index'] + 1 display_portfolio = split_portfolio[['Lineup', 'CPT', 'FLEX1', 'FLEX2', 'FLEX3', 'FLEX4', 'FLEX5', 'Salary', 'Main_Stack', 'Main_Stack_Size', 'Projection', 'Ownership']] hold_display = display_portfolio display_portfolio = display_portfolio.set_index('Lineup') st.dataframe(display_portfolio.style.background_gradient(axis=0).background_gradient(cmap='RdYlGn').background_gradient(cmap='RdYlGn_r', subset=['Ownership']).format(precision=2)) del split_portfolio del exposure_col_raw del exposure_col with tab2: col1, col2 = st.columns([1, 5]) with col1: if st.button("Load/Reset Data", key='reset1'): st.cache_data.clear() dk_roo_raw = load_dk_player_projections() fd_roo_raw = load_fd_player_projections() slate_var1 = st.radio("Which data are you loading?", ('Paydirt', 'User')) site_var1 = 'Draftkings' if site_var1 == 'Draftkings': if slate_var1 == 'User': raw_baselines = proj_dataframe[['Player', 'Salary', 'Position', 'Team', 'Opp', 'Median', 'Own']] elif slate_var1 != 'User': raw_baselines = dk_roo_raw elif site_var1 == 'Fanduel': if slate_var1 == 'User': raw_baselines = proj_dataframe elif slate_var1 != 'User': raw_baselines = fd_roo_raw st.info("If you are uploading a portfolio, note that there is an adjustments to projections and deviation mapping to prevent 'Projection Bias' and create a fair simulation") insert_port1 = st.selectbox("Are you uploading a portfolio?", ('No', 'Yes')) if insert_port1 == 'Yes': insert_port = 1 elif insert_port1 == 'No': insert_port = 0 contest_var1 = st.selectbox("What contest size are you simulating?", ('Small', 'Medium', 'Large')) if contest_var1 == 'Small': Contest_Size = 500 elif contest_var1 == 'Medium': Contest_Size = 2500 elif contest_var1 == 'Large': Contest_Size = 10000 linenum_var1 = 1000 strength_var1 = st.selectbox("How sharp is the field in the contest?", ('Not Very', 'Average', 'Very')) if strength_var1 == 'Not Very': Strength_var = 1 scaling_var = 5 elif strength_var1 == 'Average': Strength_var = .75 scaling_var = 10 elif strength_var1 == 'Very': Strength_var = .5 scaling_var = 15 with col2: if st.button("Simulate Contest", key='sim1'): try: del dst_freq del flex_freq del te_freq del wr_freq del rb_freq del qb_freq del player_freq del Sim_Winner_Export del Sim_Winner_Frame except: pass with st.container(): st.write('Contest Simulation Starting') Total_Runs = 1000000 seed_depth1 = 5 Total_Runs = 2500000 if Contest_Size <= 1000: strength_grow = .01 elif Contest_Size > 1000 and Contest_Size <= 2500: strength_grow = .025 elif Contest_Size > 2500 and Contest_Size <= 5000: strength_grow = .05 elif Contest_Size > 5000 and Contest_Size <= 20000: strength_grow = .075 elif Contest_Size > 20000: strength_grow = .1 field_growth = 100 * strength_grow Sort_function = 'Median' if Sort_function == 'Median': Sim_function = 'Projection' elif Sort_function == 'Own': Sim_function = 'Own' if slate_var1 == 'User': OwnFrame = proj_dataframe if contest_var1 == 'Large': OwnFrame['Own%'] = np.where((OwnFrame['Position'] == 'QB') & (OwnFrame['Own'] - OwnFrame.loc[OwnFrame['Position'] == 'QB', 'Own'].mean() >= 0), OwnFrame['Own'] * (10 * (OwnFrame['Own'] - OwnFrame.loc[OwnFrame['Position'] == 'QB', 'Own'].mean())/100) + OwnFrame.loc[OwnFrame['Position'] == 'QB', 'Own'].mean(), OwnFrame['Own']) OwnFrame['Own%'] = np.where((OwnFrame['Position'] != 'QB') & (OwnFrame['Own'] - OwnFrame.loc[OwnFrame['Position'] != 'QB', 'Own'].mean() >= 0), OwnFrame['Own'] * (5 * (OwnFrame['Own'] - OwnFrame.loc[OwnFrame['Position'] != 'QB', 'Own'].mean())/100) + OwnFrame.loc[OwnFrame['Position'] != 'QB', 'Own'].mean(), OwnFrame['Own%']) OwnFrame['Own%'] = np.where(OwnFrame['Own%'] > 75, 75, OwnFrame['Own%']) OwnFrame['Own'] = OwnFrame['Own%'] * (500 / OwnFrame['Own%'].sum()) if contest_var1 == 'Medium': OwnFrame['Own%'] = np.where((OwnFrame['Position'] == 'QB') & (OwnFrame['Own'] - OwnFrame.loc[OwnFrame['Position'] == 'QB', 'Own'].mean() >= 0), OwnFrame['Own'] * (6 * (OwnFrame['Own'] - OwnFrame.loc[OwnFrame['Position'] == 'QB', 'Own'].mean())/100) + OwnFrame.loc[OwnFrame['Position'] == 'QB', 'Own'].mean(), OwnFrame['Own']) OwnFrame['Own%'] = np.where((OwnFrame['Position'] != 'QB') & (OwnFrame['Own'] - OwnFrame.loc[OwnFrame['Position'] != 'QB', 'Own'].mean() >= 0), OwnFrame['Own'] * (3 * (OwnFrame['Own'] - OwnFrame.loc[OwnFrame['Position'] != 'QB', 'Own'].mean())/100) + OwnFrame.loc[OwnFrame['Position'] != 'QB', 'Own'].mean(), OwnFrame['Own%']) OwnFrame['Own%'] = np.where(OwnFrame['Own%'] > 75, 75, OwnFrame['Own%']) OwnFrame['Own'] = OwnFrame['Own%'] * (500 / OwnFrame['Own%'].sum()) if contest_var1 == 'Small': OwnFrame['Own%'] = np.where((OwnFrame['Position'] == 'QB') & (OwnFrame['Own'] - OwnFrame.loc[OwnFrame['Position'] == 'QB', 'Own'].mean() >= 0), OwnFrame['Own'] * (3 * (OwnFrame['Own'] - OwnFrame.loc[OwnFrame['Position'] == 'QB', 'Own'].mean())/100) + OwnFrame.loc[OwnFrame['Position'] == 'QB', 'Own'].mean(), OwnFrame['Own']) OwnFrame['Own%'] = np.where((OwnFrame['Position'] != 'QB') & (OwnFrame['Own'] - OwnFrame.loc[OwnFrame['Position'] != 'QB', 'Own'].mean() >= 0), OwnFrame['Own'] * (1.5 * (OwnFrame['Own'] - OwnFrame.loc[OwnFrame['Position'] != 'QB', 'Own'].mean())/100) + OwnFrame.loc[OwnFrame['Position'] != 'QB', 'Own'].mean(), OwnFrame['Own%']) OwnFrame['Own%'] = np.where(OwnFrame['Own%'] > 75, 75, OwnFrame['Own%']) OwnFrame['Own'] = OwnFrame['Own%'] * (500 / OwnFrame['Own%'].sum()) Overall_Proj = OwnFrame[['Player', 'Team', 'Position', 'Median', 'Own', 'Salary']] del OwnFrame elif slate_var1 != 'User': initial_proj = raw_baselines drop_frame = initial_proj.drop_duplicates(subset = 'Player',keep = 'first') OwnFrame = drop_frame[['Player', 'Team', 'Position', 'Median', 'Own', 'Floor', 'Ceiling', 'Salary']] if contest_var1 == 'Large': OwnFrame['Own%'] = np.where((OwnFrame['Position'] == 'QB') & (OwnFrame['Own'] - OwnFrame.loc[OwnFrame['Position'] == 'QB', 'Own'].mean() >= 0), OwnFrame['Own'] * (10 * (OwnFrame['Own'] - OwnFrame.loc[OwnFrame['Position'] == 'QB', 'Own'].mean())/100) + OwnFrame.loc[OwnFrame['Position'] == 'QB', 'Own'].mean(), OwnFrame['Own']) OwnFrame['Own%'] = np.where((OwnFrame['Position'] != 'QB') & (OwnFrame['Own'] - OwnFrame.loc[OwnFrame['Position'] != 'QB', 'Own'].mean() >= 0), OwnFrame['Own'] * (5 * (OwnFrame['Own'] - OwnFrame.loc[OwnFrame['Position'] != 'QB', 'Own'].mean())/100) + OwnFrame.loc[OwnFrame['Position'] != 'QB', 'Own'].mean(), OwnFrame['Own%']) OwnFrame['Own%'] = np.where(OwnFrame['Own%'] > 75, 75, OwnFrame['Own%']) OwnFrame['Own'] = OwnFrame['Own%'] * (500 / OwnFrame['Own%'].sum()) if contest_var1 == 'Medium': OwnFrame['Own%'] = np.where((OwnFrame['Position'] == 'QB') & (OwnFrame['Own'] - OwnFrame.loc[OwnFrame['Position'] == 'QB', 'Own'].mean() >= 0), OwnFrame['Own'] * (6 * (OwnFrame['Own'] - OwnFrame.loc[OwnFrame['Position'] == 'QB', 'Own'].mean())/100) + OwnFrame.loc[OwnFrame['Position'] == 'QB', 'Own'].mean(), OwnFrame['Own']) OwnFrame['Own%'] = np.where((OwnFrame['Position'] != 'QB') & (OwnFrame['Own'] - OwnFrame.loc[OwnFrame['Position'] != 'QB', 'Own'].mean() >= 0), OwnFrame['Own'] * (3 * (OwnFrame['Own'] - OwnFrame.loc[OwnFrame['Position'] != 'QB', 'Own'].mean())/100) + OwnFrame.loc[OwnFrame['Position'] != 'QB', 'Own'].mean(), OwnFrame['Own%']) OwnFrame['Own%'] = np.where(OwnFrame['Own%'] > 75, 75, OwnFrame['Own%']) OwnFrame['Own'] = OwnFrame['Own%'] * (500 / OwnFrame['Own%'].sum()) if contest_var1 == 'Small': OwnFrame['Own%'] = np.where((OwnFrame['Position'] == 'QB') & (OwnFrame['Own'] - OwnFrame.loc[OwnFrame['Position'] == 'QB', 'Own'].mean() >= 0), OwnFrame['Own'] * (3 * (OwnFrame['Own'] - OwnFrame.loc[OwnFrame['Position'] == 'QB', 'Own'].mean())/100) + OwnFrame.loc[OwnFrame['Position'] == 'QB', 'Own'].mean(), OwnFrame['Own']) OwnFrame['Own%'] = np.where((OwnFrame['Position'] != 'QB') & (OwnFrame['Own'] - OwnFrame.loc[OwnFrame['Position'] != 'QB', 'Own'].mean() >= 0), OwnFrame['Own'] * (1.5 * (OwnFrame['Own'] - OwnFrame.loc[OwnFrame['Position'] != 'QB', 'Own'].mean())/100) + OwnFrame.loc[OwnFrame['Position'] != 'QB', 'Own'].mean(), OwnFrame['Own%']) OwnFrame['Own%'] = np.where(OwnFrame['Own%'] > 75, 75, OwnFrame['Own%']) OwnFrame['Own'] = OwnFrame['Own%'] * (500 / OwnFrame['Own%'].sum()) Overall_Proj = OwnFrame[['Player', 'Team', 'Position', 'Median', 'Own', 'Floor', 'Ceiling', 'Salary']] del initial_proj del drop_frame del OwnFrame if insert_port == 1: UserPortfolio = portfolio_dataframe[['CPT', 'FLEX1', 'FLEX2', 'FLEX3', 'FLEX4', 'FLEX5']] elif insert_port == 0: UserPortfolio = pd.DataFrame(columns = ['CPT', 'FLEX1', 'FLEX2', 'FLEX3', 'FLEX4', 'FLEX5']) Overall_Proj.replace('', np.nan, inplace=True) Overall_Proj = Overall_Proj.dropna(subset=['Median']) Overall_Proj = Overall_Proj.assign(Value=lambda x: (x.Median / (x.Salary / 1000))) Overall_Proj['Sort_var'] = (Overall_Proj['Median'].rank(ascending=False) + Overall_Proj['Value'].rank(ascending=False)) / 2 Overall_Proj = Overall_Proj.sort_values(by='Sort_var', ascending=False) Overall_Proj['Own'] = np.where((Overall_Proj['Median'] > 0) & (Overall_Proj['Own'] == 0), 1, Overall_Proj['Own']) Overall_Proj = Overall_Proj.loc[Overall_Proj['Own'] > 0] Overall_Proj['Floor'] = np.where(Overall_Proj['Position'] == 'QB', Overall_Proj['Median'] * .5, Overall_Proj['Median'] * .25) Overall_Proj['Ceiling'] = np.where(Overall_Proj['Position'] == 'WR', Overall_Proj['Median'] + Overall_Proj['Median'], Overall_Proj['Median'] + Overall_Proj['Floor']) Overall_Proj['STDev'] = Overall_Proj['Median'] / 4 Teams_used = Overall_Proj['Team'].drop_duplicates().reset_index(drop=True) Teams_used = Teams_used.reset_index() Teams_used['team_item'] = Teams_used['index'] + 1 Teams_used = Teams_used.drop(columns=['index']) Teams_used_dictraw = Teams_used.drop(columns=['team_item']) Teams_used_dict = Teams_used_dictraw.to_dict() del Teams_used_dictraw team_list = Teams_used['Team'].to_list() item_list = Teams_used['team_item'].to_list() FieldStrength_raw = Strength_var + ((30 - len(Teams_used)) * .01) FieldStrength = FieldStrength_raw - (FieldStrength_raw * (20000 / Contest_Size)) del FieldStrength_raw if FieldStrength < 0: FieldStrength = Strength_var field_split = Strength_var for checkVar in range(len(team_list)): Overall_Proj['Team'] = Overall_Proj['Team'].replace(team_list, item_list) flex_raw = Overall_Proj flex_raw.dropna(subset=['Median']).reset_index(drop=True) flex_raw = flex_raw.reset_index(drop=True) flex_raw = flex_raw.sort_values(by='Own', ascending=False) pos_players = flex_raw pos_players.dropna(subset=['Median']).reset_index(drop=True) pos_players = pos_players.reset_index(drop=True) del flex_raw if insert_port == 1: try: # Initialize an empty DataFrame to store raw portfolio data Raw_Portfolio = pd.DataFrame() # Split each portfolio column and concatenate to Raw_Portfolio columns_to_process = ['CPT', 'FLEX1', 'FLEX2', 'FLEX3', 'FLEX4', 'FLEX5'] for col in columns_to_process: temp_df = UserPortfolio[col].str.split("(", n=1, expand=True) temp_df.columns = [col, 'Drop'] Raw_Portfolio = pd.concat([Raw_Portfolio, temp_df], axis=1) # Keep only required variables and remove whitespace keep_vars = columns_to_process CleanPortfolio = Raw_Portfolio[keep_vars] CleanPortfolio = CleanPortfolio.apply(lambda x: x.str.strip()) # Reset index and clean up the DataFrame CleanPortfolio.reset_index(inplace=True) CleanPortfolio['User/Field'] = CleanPortfolio['index'] + 1 CleanPortfolio.drop(columns=['index'], inplace=True) CleanPortfolio.replace('', np.nan, inplace=True) CleanPortfolio.dropna(subset=['QB'], inplace=True) # Create cleaport_players DataFrame unique_vals, counts = np.unique(CleanPortfolio.iloc[:, 0:6].values, return_counts=True) cleaport_players = pd.DataFrame(np.column_stack([unique_vals, counts]), columns=['Player', 'Freq']).astype({'Freq': int}).sort_values('Freq', ascending=False).reset_index(drop=True) # Merge and update nerf_frame DataFrame nerf_frame = pd.merge(cleaport_players, Overall_Proj, on='Player', how='left') nerf_frame[['Median', 'Floor', 'Ceiling', 'STDev']] *= 0.9 del Raw_Portfolio except: # Reset index and perform column-wise operations CleanPortfolio = UserPortfolio.reset_index(drop=True) CleanPortfolio['User/Field'] = CleanPortfolio.index + 1 CleanPortfolio.replace('', np.nan, inplace=True) CleanPortfolio.dropna(subset=['QB'], inplace=True) # Create cleaport_players DataFrame unique_vals, counts = np.unique(CleanPortfolio.iloc[:, 0:6].values, return_counts=True) cleaport_players = pd.DataFrame({'Player': unique_vals, 'Freq': counts}).sort_values('Freq', ascending=False).reset_index(drop=True).astype({'Freq': int}) # Merge and update nerf_frame DataFrame nerf_frame = pd.merge(cleaport_players, Overall_Proj, on='Player', how='left') nerf_frame[['Median', 'Floor', 'Ceiling', 'STDev']] *= 0.9 elif insert_port == 0: CleanPortfolio = UserPortfolio cleaport_players = pd.DataFrame(np.column_stack(np.unique(CleanPortfolio.iloc[:,0:6].values, return_counts=True)), columns=['Player','Freq']).sort_values('Freq', ascending=False).reset_index(drop=True) cleaport_players['Freq'] = cleaport_players['Freq'].astype(int) nerf_frame = Overall_Proj ref_dict = { 'pos':['FLEX'], 'pos_dfs':['FLEX_Table'], 'pos_dicts':['flex_dict'] } maps_dict = { 'Floor_map':dict(zip(Overall_Proj.Player,Overall_Proj.Floor)), 'Projection_map':dict(zip(Overall_Proj.Player,Overall_Proj.Median)), 'Ceiling_map':dict(zip(Overall_Proj.Player,Overall_Proj.Ceiling)), 'Salary_map':dict(zip(Overall_Proj.Player,Overall_Proj.Salary)), 'Pos_map':dict(zip(Overall_Proj.Player,Overall_Proj.Position)), 'Own_map':dict(zip(Overall_Proj.Player,Overall_Proj.Own)), 'Team_map':dict(zip(Overall_Proj.Player,Overall_Proj.Team)), 'STDev_map':dict(zip(Overall_Proj.Player,Overall_Proj.STDev)), 'team_check_map':dict(zip(Overall_Proj.Player,Overall_Proj.Team)) } up_dict = { 'Floor_map':dict(zip(cleaport_players.Player,nerf_frame.Floor)), 'Projection_map':dict(zip(cleaport_players.Player,nerf_frame.Median)), 'Ceiling_map':dict(zip(cleaport_players.Player,nerf_frame.Ceiling)), 'Salary_map':dict(zip(cleaport_players.Player,nerf_frame.Salary)), 'Pos_map':dict(zip(cleaport_players.Player,nerf_frame.Position)), 'Own_map':dict(zip(cleaport_players.Player,nerf_frame.Own)), 'Team_map':dict(zip(cleaport_players.Player,nerf_frame.Team)), 'STDev_map':dict(zip(cleaport_players.Player,nerf_frame.STDev)), 'team_check_map':dict(zip(cleaport_players.Player,nerf_frame.Team)) } del Overall_Proj del nerf_frame RunsVar = 1 st.write('Seed frame creation') FinalPortfolio, maps_dict = run_seed_frame(seed_depth1, Strength_var, strength_grow, Teams_used, Total_Runs) Sim_size = linenum_var1 SimVar = 1 Sim_Winners = [] fp_array = FinalPortfolio.values if insert_port == 1: up_array = CleanPortfolio.values st.write('Simulating contest on frames') while SimVar <= Sim_size: try: fp_random = fp_array[np.random.choice(fp_array.shape[0], Contest_Size-len(CleanPortfolio), replace=False)] smple_arrays1 = np.c_[fp_random, np.sum(np.random.normal( loc = np.vectorize(maps_dict['Projection_map'].__getitem__)(fp_random[:,:-5]), scale = np.vectorize(maps_dict['STDev_map'].__getitem__)(fp_random[:,:-5])), axis=1)] try: smple_arrays2 = np.c_[up_array, np.sum(np.random.normal( loc = np.vectorize(up_dict['Projection_map'].__getitem__)(up_array[:,:-5]), scale = np.vectorize(up_dict['STDev_map'].__getitem__)(up_array[:,:-5])), axis=1)] except: pass try: smple_arrays = np.vstack((smple_arrays1, smple_arrays2)) except: smple_arrays = smple_arrays1 final_array = smple_arrays[smple_arrays[:, 7].argsort()[::-1]] best_lineup = final_array[final_array[:, -1].argsort(kind='stable')[::-1][:1]] Sim_Winners.append(best_lineup) SimVar += 1 except: FieldStrength += (strength_grow + ((30 - len(Teams_used)) * .001)) FinalPortfolio3, maps_dict3 = get_correlated_portfolio_for_sim(Total_Runs * field_split) FinalPortfolio4, maps_dict4 = get_uncorrelated_portfolio_for_sim(Total_Runs * field_split) FinalPortfolio = pd.concat([FinalPortfolio, FinalPortfolio3], axis=0) FinalPortfolio = pd.concat([FinalPortfolio, FinalPortfolio4], axis=0) try: FinalPortfolio = FinalPortfolio.drop_duplicates(subset = ['Projection', 'Ownership'],keep = 'last').reset_index(drop = True) except: FinalPortfolio = FinalPortfolio.drop_duplicates(subset = ['Projection', 'Own'],keep = 'last').reset_index(drop = True) maps_dict.update(maps_dict3) maps_dict.update(maps_dict4) del FinalPortfolio3 del maps_dict3 del FinalPortfolio4 del maps_dict4 fp_array = FinalPortfolio.values if insert_port == 1: up_array = CleanPortfolio.values SimVar = SimVar st.write('Contest simulation complete') Sim_Winner_Frame = pd.DataFrame(np.concatenate(Sim_Winners), columns=FinalPortfolio.columns.tolist() + ['Fantasy']) Sim_Winner_Frame['GPP_Proj'] = (Sim_Winner_Frame['Projection'] + Sim_Winner_Frame['Fantasy']) / 2 Sim_Winner_Frame['Salary'] = Sim_Winner_Frame['Salary'].astype(int) Sim_Winner_Frame['Projection'] = Sim_Winner_Frame['Projection'].astype(np.float16) Sim_Winner_Frame['Fantasy'] = Sim_Winner_Frame['Fantasy'].astype(np.float16) Sim_Winner_Frame['GPP_Proj'] = Sim_Winner_Frame['GPP_Proj'].astype(np.float16) Sim_Winner_Frame = Sim_Winner_Frame.sort_values(by='GPP_Proj', ascending=False) player_freq = pd.DataFrame(np.column_stack(np.unique(Sim_Winner_Frame.iloc[:,0:6].values, return_counts=True)), columns=['Player','Freq']).sort_values('Freq', ascending=False).reset_index(drop=True) player_freq['Freq'] = player_freq['Freq'].astype(int) player_freq['Position'] = player_freq['Player'].map(maps_dict['Pos_map']) player_freq['Salary'] = player_freq['Player'].map(maps_dict['Salary_map']) player_freq['Proj Own'] = (player_freq['Player'].map(maps_dict['Own_map']) / 100) player_freq['Exposure'] = player_freq['Freq']/(Sim_size) player_freq['Edge'] = player_freq['Exposure'] - player_freq['Proj Own'] player_freq['Team'] = player_freq['Player'].map(maps_dict['Team_map']) for checkVar in range(len(team_list)): player_freq['Team'] = player_freq['Team'].replace(item_list, team_list) player_freq = player_freq[['Player', 'Position', 'Team', 'Salary', 'Proj Own', 'Exposure', 'Edge']] cpt_freq = pd.DataFrame(np.column_stack(np.unique(Sim_Winner_Frame.iloc[:,0:1].values, return_counts=True)), columns=['Player','Freq']).sort_values('Freq', ascending=False).reset_index(drop=True) cpt_freq['Freq'] = cpt_freq['Freq'].astype(int) cpt_freq['Position'] = cpt_freq['Player'].map(maps_dict['Pos_map']) cpt_freq['Salary'] = cpt_freq['Player'].map(maps_dict['Salary_map']) cpt_freq['Proj Own'] = (cpt_freq['Player'].map(maps_dict['Own_map']) / 4) / 100 cpt_freq['Exposure'] = cpt_freq['Freq']/(Sim_size) cpt_freq['Edge'] = cpt_freq['Exposure'] - cpt_freq['Proj Own'] cpt_freq['Team'] = cpt_freq['Player'].map(maps_dict['Team_map']) for checkVar in range(len(team_list)): cpt_freq['Team'] = cpt_freq['Team'].replace(item_list, team_list) cpt_freq = cpt_freq[['Player', 'Position', 'Team', 'Salary', 'Proj Own', 'Exposure', 'Edge']] flex_freq = pd.DataFrame(np.column_stack(np.unique(Sim_Winner_Frame.iloc[:,[1, 2, 3, 4, 5]].values, return_counts=True)), columns=['Player','Freq']).sort_values('Freq', ascending=False).reset_index(drop=True) flex_freq['Freq'] = flex_freq['Freq'].astype(int) flex_freq['Position'] = flex_freq['Player'].map(maps_dict['Pos_map']) flex_freq['Salary'] = flex_freq['Player'].map(maps_dict['Salary_map']) flex_freq['Proj Own'] = (flex_freq['Player'].map(maps_dict['Own_map']) / 100) - ((flex_freq['Player'].map(maps_dict['Own_map']) / 4) / 100) flex_freq['Exposure'] = flex_freq['Freq']/(Sim_size) flex_freq['Edge'] = flex_freq['Exposure'] - flex_freq['Proj Own'] flex_freq['Team'] = flex_freq['Player'].map(maps_dict['Team_map']) for checkVar in range(len(team_list)): flex_freq['Team'] = flex_freq['Team'].replace(item_list, team_list) flex_freq = flex_freq[['Player', 'Position', 'Team', 'Salary', 'Proj Own', 'Exposure', 'Edge']] del fp_random del smple_arrays del final_array del fp_array try: del up_array except: pass del best_lineup del CleanPortfolio del FinalPortfolio del maps_dict del team_list del item_list del Sim_size with st.container(): st.dataframe(Sim_Winner_Frame.style.background_gradient(axis=0).background_gradient(cmap='RdYlGn').background_gradient(cmap='RdYlGn_r', subset=['Own']).format(precision=2), use_container_width = True) with st.container(): tab1, tab2, tab3 = st.tabs(['Overall Exposures', 'CPT Exposures', 'FLEX Exposures']) with tab1: st.dataframe(player_freq.style.background_gradient(axis=0).background_gradient(cmap='RdYlGn').format(freq_format, precision=2), use_container_width = True) st.download_button( label="Export Exposures", data=convert_df_to_csv(player_freq), file_name='player_freq_export.csv', mime='text/csv', ) with tab2: st.dataframe(cpt_freq.style.background_gradient(axis=0).background_gradient(cmap='RdYlGn').format(freq_format, precision=2), use_container_width = True) st.download_button( label="Export Exposures", data=convert_df_to_csv(cpt_freq), file_name='cpt_freq_export.csv', mime='text/csv', ) with tab3: st.dataframe(flex_freq.style.background_gradient(axis=0).background_gradient(cmap='RdYlGn').format(freq_format, precision=2), use_container_width = True) st.download_button( label="Export Exposures", data=convert_df_to_csv(flex_freq), file_name='flex_freq_export.csv', mime='text/csv', ) st.download_button( label="Export Tables", data=convert_df_to_csv(Sim_Winner_Frame), file_name='NFL_consim_export.csv', mime='text/csv', )