James McCool commited on
Commit
84e63b7
·
1 Parent(s): 78229f5

Initial commit and dockerization

Browse files
.streamlit/secrets.toml ADDED
@@ -0,0 +1 @@
 
 
1
+ mongo_uri = "mongodb+srv://multichem:Xr1q5wZdXPbxdUmJ@testcluster.lgwtp5i.mongodb.net/?retryWrites=true&w=majority&appName=TestCluster"
Dockerfile CHANGED
@@ -5,11 +5,24 @@ WORKDIR /app
5
  RUN apt-get update && apt-get install -y \
6
  build-essential \
7
  curl \
 
8
  git \
9
  && rm -rf /var/lib/apt/lists/*
10
 
11
  COPY requirements.txt ./
12
  COPY src/ ./src/
 
 
 
 
 
 
 
 
 
 
 
 
13
 
14
  RUN pip3 install -r requirements.txt
15
 
 
5
  RUN apt-get update && apt-get install -y \
6
  build-essential \
7
  curl \
8
+ software-properties-common \
9
  git \
10
  && rm -rf /var/lib/apt/lists/*
11
 
12
  COPY requirements.txt ./
13
  COPY src/ ./src/
14
+ COPY .streamlit/ ./.streamlit/
15
+
16
+
17
+
18
+ ENV MONGO_URI="mongodb+srv://multichem:Xr1q5wZdXPbxdUmJ@testcluster.lgwtp5i.mongodb.net/?retryWrites=true&w=majority&appName=TestCluster"
19
+ RUN useradd -m -u 1000 user
20
+ USER user
21
+ ENV HOME=/home/user\
22
+ PATH=/home/user/.local/bin:$PATH
23
+ WORKDIR $HOME/app
24
+ RUN pip install --no-cache-dir --upgrade pip
25
+ COPY --chown=user . $HOME/app
26
 
27
  RUN pip3 install -r requirements.txt
28
 
requirements.txt CHANGED
@@ -1,3 +1,8 @@
1
- altair
2
- pandas
3
- streamlit
 
 
 
 
 
 
1
+ streamlit
2
+ openpyxl
3
+ matplotlib
4
+ pulp
5
+ docker
6
+ plotly
7
+ scipy
8
+ pymongo
src/database.py ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+ import pymongo
3
+ import os
4
+
5
+ @st.cache_resource
6
+ def init_conn():
7
+ # Try to get from environment variable first, fall back to secrets
8
+ uri = os.getenv('MONGO_URI')
9
+ if not uri:
10
+ uri = st.secrets['mongo_uri']
11
+ client = pymongo.MongoClient(uri, retryWrites=True, serverSelectionTimeoutMS=500000)
12
+ db = client["NFL_Database"]
13
+
14
+ return db
15
+
16
+ db = init_conn()
src/streamlit_app.py CHANGED
@@ -1,40 +1,400 @@
1
- import altair as alt
2
  import numpy as np
3
  import pandas as pd
4
- import streamlit as st
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5
 
6
- """
7
- # Welcome to Streamlit!
8
-
9
- Edit `/streamlit_app.py` to customize this app to your heart's desire :heart:.
10
- If you have any questions, checkout our [documentation](https://docs.streamlit.io) and [community
11
- forums](https://discuss.streamlit.io).
12
-
13
- In the meantime, below is an example of what you can do with just a few lines of code:
14
- """
15
-
16
- num_points = st.slider("Number of points in spiral", 1, 10000, 1100)
17
- num_turns = st.slider("Number of turns in spiral", 1, 300, 31)
18
-
19
- indices = np.linspace(0, 1, num_points)
20
- theta = 2 * np.pi * num_turns * indices
21
- radius = indices
22
-
23
- x = radius * np.cos(theta)
24
- y = radius * np.sin(theta)
25
-
26
- df = pd.DataFrame({
27
- "x": x,
28
- "y": y,
29
- "idx": indices,
30
- "rand": np.random.randn(num_points),
31
- })
32
-
33
- st.altair_chart(alt.Chart(df, height=700, width=700)
34
- .mark_point(filled=True)
35
- .encode(
36
- x=alt.X("x", axis=None),
37
- y=alt.Y("y", axis=None),
38
- color=alt.Color("idx", legend=None, scale=alt.Scale()),
39
- size=alt.Size("rand", legend=None, scale=alt.Scale(range=[1, 150])),
40
- ))
 
1
+ import streamlit as st
2
  import numpy as np
3
  import pandas as pd
4
+ import re
5
+ from database import db
6
+
7
+ st.set_page_config(layout="wide")
8
+
9
+ wrong_acro = ['WSH', 'AZ']
10
+ right_acro = ['WAS', 'ARI']
11
+
12
+ game_format = {'Win Percentage': '{:.2%}','First Inning Lead Percentage': '{:.2%}',
13
+ 'Fifth Inning Lead Percentage': '{:.2%}', '8+ runs': '{:.2%}', 'DK LevX': '{:.2%}', 'FD LevX': '{:.2%}'}
14
+
15
+ team_roo_format = {'Top Score%': '{:.2%}','0 Runs': '{:.2%}', '1 Run': '{:.2%}', '2 Runs': '{:.2%}', '3 Runs': '{:.2%}', '4 Runs': '{:.2%}',
16
+ '5 Runs': '{:.2%}','6 Runs': '{:.2%}', '7 Runs': '{:.2%}', '8 Runs': '{:.2%}', '9 Runs': '{:.2%}', '10 Runs': '{:.2%}'}
17
+
18
+ player_roo_format = {'Top_finish': '{:.2%}','Top_5_finish': '{:.2%}', 'Top_10_finish': '{:.2%}', '20+%': '{:.2%}', '2x%': '{:.2%}', '3x%': '{:.2%}',
19
+ '4x%': '{:.2%}','GPP%': '{:.2%}'}
20
+
21
+ st.markdown("""
22
+ <style>
23
+ /* Tab styling */
24
+ .stElementContainer [data-baseweb="button-group"] {
25
+ gap: 2.000rem;
26
+ padding: 4px;
27
+ }
28
+ .stElementContainer [kind="segmented_control"] {
29
+ height: 2.000rem;
30
+ white-space: pre-wrap;
31
+ background-color: #68B1E7;
32
+ color: white;
33
+ border-radius: 20px;
34
+ gap: 1px;
35
+ padding: 10px 20px;
36
+ font-weight: bold;
37
+ transition: all 0.3s ease;
38
+ }
39
+ .stElementContainer [kind="segmented_controlActive"] {
40
+ height: 3.000rem;
41
+ background-color: #68B1E7;
42
+ border: 3px solid #4FB286;
43
+ border-radius: 10px;
44
+ color: black;
45
+ }
46
+ .stElementContainer [kind="segmented_control"]:hover {
47
+ background-color: #4FB286;
48
+ cursor: pointer;
49
+ }
50
+
51
+ div[data-baseweb="select"] > div {
52
+ background-color: #68B1E7;
53
+ color: white;
54
+ }
55
+
56
+ </style>""", unsafe_allow_html=True)
57
+
58
+ @st.cache_resource(ttl=600)
59
+ def init_baselines():
60
+
61
+ collection = db["Player_Baselines"]
62
+ cursor = collection.find()
63
+
64
+ raw_display = pd.DataFrame(list(cursor))
65
+ raw_display = raw_display[['name', 'Team', 'Opp', 'Position', 'Salary', 'team_plays', 'team_pass', 'team_rush', 'team_tds', 'team_pass_tds', 'team_rush_tds', 'dropbacks', 'pass_yards', 'pass_tds',
66
+ 'rush_att', 'rush_yards', 'rush_tds', 'targets', 'rec', 'rec_yards', 'rec_tds', 'PPR', 'Half_PPR', 'Own']]
67
+ player_stats = raw_display[raw_display['Position'] != 'K']
68
+
69
+ collection = db["DK_NFL_ROO"]
70
+ cursor = collection.find()
71
+
72
+ raw_display = pd.DataFrame(list(cursor))
73
+ raw_display = raw_display.rename(columns={'player_ID': 'player_id'})
74
+ raw_display = raw_display[['Player', 'Position', 'Team', 'Opp', 'Salary', 'Floor', 'Median', 'Ceiling', 'Top_finish', 'Top_5_finish', 'Top_10_finish', '20+%', '2x%', '3x%', '4x%',
75
+ 'Own', 'Small_Field_Own', 'Large_Field_Own', 'Cash_Field_Own', 'CPT_Own', 'LevX', 'version', 'slate', 'timestamp', 'player_id', 'site']]
76
+ load_display = raw_display[raw_display['Position'] != 'K']
77
+ dk_roo_raw = load_display.dropna(subset=['Median'])
78
+
79
+ collection = db["FD_NFL_ROO"]
80
+ cursor = collection.find()
81
+
82
+ raw_display = pd.DataFrame(list(cursor))
83
+ raw_display = raw_display.rename(columns={'player_ID': 'player_id'})
84
+ raw_display = raw_display[['Player', 'Position', 'Team', 'Opp', 'Salary', 'Floor', 'Median', 'Ceiling', 'Top_finish', 'Top_5_finish', 'Top_10_finish', '20+%', '2x%', '3x%', '4x%',
85
+ 'Own', 'Small_Field_Own', 'Large_Field_Own', 'Cash_Field_Own', 'CPT_Own', 'LevX', 'version', 'slate', 'timestamp', 'player_id', 'site']]
86
+ load_display = raw_display[raw_display['Position'] != 'K']
87
+ fd_roo_raw = load_display.dropna(subset=['Median'])
88
+
89
+ return player_stats, dk_roo_raw, fd_roo_raw
90
+
91
+ @st.cache_data
92
+ def convert_df_to_csv(df):
93
+ return df.to_csv().encode('utf-8')
94
+
95
+ player_stats, dk_roo_raw, fd_roo_raw = init_baselines()
96
+ opp_dict = dict(zip(dk_roo_raw.Team, dk_roo_raw.Opp))
97
+ t_stamp = f"Last Update: " + str(dk_roo_raw['timestamp'][0]) + f" CST"
98
+
99
+ app_load_reset_column, app_view_site_column = st.columns([1, 9])
100
+ with app_load_reset_column:
101
+ if st.button("Load/Reset Data", key='reset_data_button'):
102
+ st.cache_data.clear()
103
+ player_stats, dk_roo_raw, fd_roo_raw = init_baselines()
104
+ for key in st.session_state.keys():
105
+ del st.session_state[key]
106
+ with app_view_site_column:
107
+ with st.container():
108
+ app_view_column, app_site_column = st.columns([3, 3])
109
+ with app_view_column:
110
+ view_var = st.selectbox("Select view", ["Simple", "Advanced"], key='view_selectbox')
111
+ with app_site_column:
112
+ site_var = st.selectbox("What site do you want to view?", ('Draftkings', 'Fanduel'), key='site_selectbox')
113
+
114
+ selected_tab = st.segmented_control(
115
+ "Select Tab",
116
+ options=["Pivot Finder", "User Upload"],
117
+ selection_mode='single',
118
+ default='Pivot Finder',
119
+ width='stretch',
120
+ label_visibility='collapsed',
121
+ key='tab_selector'
122
+ )
123
+
124
+ if selected_tab == 'Pivot Finder':
125
+ with st.expander("Infos and Filters"):
126
+ st.info("Welcome to the Pivot Finder! Select a player or a set of players and run the algorithm to find the best spots to pivot for maximum relative value.")
127
+ app_info_column, player_select_column, micro_filter_column, macro_filter_column = st.columns(4)
128
+ with app_info_column:
129
+ st.info(t_stamp)
130
+ if st.button("Load/Reset Data", key='reset1'):
131
+ st.cache_data.clear()
132
+ player_stats, dk_stacks_raw, fd_stacks_raw, dk_roo_raw, fd_roo_raw = init_baselines()
133
+ opp_dict = dict(zip(dk_roo_raw.Team, dk_roo_raw.Opp))
134
+ t_stamp = f"Last Update: " + str(dk_roo_raw['timestamp'][0]) + f" CST"
135
+ data_var1 = st.radio("Which data are you loading?", ('Paydirt', 'User'), key='data_var1')
136
+ if site_var == 'Draftkings':
137
+ if data_var1 == 'User':
138
+ raw_baselines = st.session_state['proj_dataframe']
139
+ elif data_var1 != 'User':
140
+ raw_baselines = dk_roo_raw[dk_roo_raw['slate'] == 'Main Slate']
141
+ raw_baselines = raw_baselines[raw_baselines['version'] == 'overall']
142
+ raw_baselines = raw_baselines.sort_values(by='Own', ascending=False)
143
+ elif site_var == 'Fanduel':
144
+ if data_var1 == 'User':
145
+ raw_baselines = st.session_state['proj_dataframe']
146
+ elif data_var1 != 'User':
147
+ raw_baselines = fd_roo_raw[fd_roo_raw['slate'] == 'Main Slate']
148
+ raw_baselines = raw_baselines[raw_baselines['version'] == 'overall']
149
+ raw_baselines = raw_baselines.sort_values(by='Own', ascending=False)
150
+ with player_select_column:
151
+ check_seq = st.radio("Do you want to check a single player or the top 10 in ownership?", ('Single Player', 'Top X Owned'), key='check_seq')
152
+ if check_seq == 'Single Player':
153
+ player_check = st.selectbox('Select player to create comps', options = raw_baselines['Player'].unique(), key='dk_player')
154
+ elif check_seq == 'Top X Owned':
155
+ top_x_var = st.number_input('How many players would you like to check?', min_value = 1, max_value = 10, value = 5, step = 1)
156
+ with micro_filter_column:
157
+ Salary_var = st.number_input('Acceptable +/- Salary range', min_value = 0, max_value = 1000, value = 300, step = 100)
158
+ Median_var = st.number_input('Acceptable +/- Median range', min_value = 0, max_value = 10, value = 3, step = 1)
159
+ with macro_filter_column:
160
+ pos_var1 = st.radio("Compare to all positions or specific positions?", ('All Positions', 'Specific Positions'), key='pos_var1')
161
+ if pos_var1 == 'Specific Positions':
162
+ pos_var_list = st.multiselect('Which positions would you like to include?', options = raw_baselines['Position'].unique(), key='pos_var_list')
163
+ elif pos_var1 == 'All Positions':
164
+ pos_var_list = raw_baselines.Position.values.tolist()
165
+ split_var1 = st.radio("Are you running the full slate or certain games?", ('Full Slate Run', 'Specific Games'), key='split_var1')
166
+ if split_var1 == 'Specific Games':
167
+ team_var1 = st.multiselect('Which teams would you like to include?', options = raw_baselines['Team'].unique(), key='team_var1')
168
+ elif split_var1 == 'Full Slate Run':
169
+ team_var1 = raw_baselines.Team.values.tolist()
170
+
171
+ placeholder = st.empty()
172
+ displayholder = st.empty()
173
+
174
+ if st.button('Simulate appropriate pivots'):
175
+ with placeholder:
176
+ if site_var == 'Draftkings':
177
+ working_roo = raw_baselines
178
+ working_roo.replace('', 0, inplace=True)
179
+ if site_var == 'Fanduel':
180
+ working_roo = raw_baselines
181
+ working_roo.replace('', 0, inplace=True)
182
+
183
+ own_dict = dict(zip(working_roo.Player, working_roo.Own))
184
+ team_dict = dict(zip(working_roo.Player, working_roo.Team))
185
+ opp_dict = dict(zip(working_roo.Player, working_roo.Opp))
186
+ pos_dict = dict(zip(working_roo.Player, working_roo.Position))
187
+ total_sims = 1000
188
+
189
+ if check_seq == 'Single Player':
190
+ player_var = working_roo.loc[working_roo['Player'] == player_check]
191
+ player_var = player_var.reset_index()
192
+ working_roo = working_roo[working_roo['Position'].isin(pos_var_list)]
193
+ working_roo = working_roo[working_roo['Team'].isin(team_var1)]
194
+ working_roo = working_roo.loc[(working_roo['Salary'] >= player_var['Salary'][0] - Salary_var) & (working_roo['Salary'] <= player_var['Salary'][0] + Salary_var)]
195
+ working_roo = working_roo.loc[(working_roo['Median'] >= player_var['Median'][0] - Median_var) & (working_roo['Median'] <= player_var['Median'][0] + Median_var)]
196
+
197
+ flex_file = working_roo[['Player', 'Position', 'Salary', 'Median']]
198
+ flex_file['Floor_raw'] = flex_file['Median'] * .25
199
+ flex_file['Ceiling_raw'] = flex_file['Median'] * 1.75
200
+ flex_file['Floor'] = np.where(flex_file['Position'] == 'QB', (flex_file['Median'] * .33), flex_file['Floor_raw'])
201
+ flex_file['Floor'] = np.where(flex_file['Position'] == 'WR', (flex_file['Median'] * .15), flex_file['Floor_raw'])
202
+ flex_file['Ceiling'] = np.where(flex_file['Position'] == 'QB', (flex_file['Median'] * 1.75), flex_file['Ceiling_raw'])
203
+ flex_file['Ceiling'] = np.where(flex_file['Position'] == 'WR', (flex_file['Median'] * 1.85), flex_file['Ceiling_raw'])
204
+ flex_file['STD'] = flex_file['Median'] / 4
205
+ flex_file = flex_file[['Player', 'Position', 'Salary', 'Floor', 'Median', 'Ceiling', 'STD']]
206
+ hold_file = flex_file.copy()
207
+ overall_file = flex_file.copy()
208
+ salary_file = flex_file.copy()
209
+
210
+ overall_players = overall_file[['Player']]
211
+
212
+ for x in range(0,total_sims):
213
+ salary_file[x] = salary_file['Salary']
214
+
215
+ salary_file=salary_file.drop(['Player', 'Position', 'Salary', 'Floor', 'Median', 'Ceiling', 'STD'], axis=1)
216
+
217
+ salary_file = salary_file.div(1000)
218
+
219
+ for x in range(0,total_sims):
220
+ overall_file[x] = np.random.normal(overall_file['Median'],overall_file['STD'])
221
+
222
+ overall_file=overall_file.drop(['Player', 'Position', 'Salary', 'Floor', 'Median', 'Ceiling', 'STD'], axis=1)
223
+
224
+ players_only = hold_file[['Player']]
225
+ raw_lineups_file = players_only
226
+
227
+ for x in range(0,total_sims):
228
+ maps_dict = {'proj_map':dict(zip(hold_file.Player,overall_file[x]))}
229
+ raw_lineups_file[x] = sum([raw_lineups_file['Player'].map(maps_dict['proj_map'])])
230
+ players_only[x] = raw_lineups_file[x].rank(ascending=False)
231
+
232
+ players_only=players_only.drop(['Player'], axis=1)
233
+
234
+ salary_2x_check = (overall_file - (salary_file*2))
235
+ salary_3x_check = (overall_file - (salary_file*3))
236
+ salary_4x_check = (overall_file - (salary_file*4))
237
+
238
+ players_only['Average_Rank'] = players_only.mean(axis=1)
239
+ players_only['Top_finish'] = players_only[players_only == 1].count(axis=1)/total_sims
240
+ players_only['Top_5_finish'] = players_only[players_only <= 5].count(axis=1)/total_sims
241
+ players_only['Top_10_finish'] = players_only[players_only <= 10].count(axis=1)/total_sims
242
+ players_only['20+%'] = overall_file[overall_file >= 20].count(axis=1)/float(total_sims)
243
+ players_only['2x%'] = salary_2x_check[salary_2x_check >= 1].count(axis=1)/float(total_sims)
244
+ players_only['3x%'] = salary_3x_check[salary_3x_check >= 1].count(axis=1)/float(total_sims)
245
+ players_only['4x%'] = salary_4x_check[salary_4x_check >= 1].count(axis=1)/float(total_sims)
246
+
247
+ players_only['Player'] = hold_file[['Player']]
248
+
249
+ final_outcomes = players_only[['Player', 'Top_finish', 'Top_5_finish', 'Top_10_finish', '20+%', '2x%', '3x%', '4x%']]
250
+
251
+ final_Proj = pd.merge(hold_file, final_outcomes, on="Player")
252
+ final_Proj = final_Proj[['Player', 'Position', 'Salary', 'Floor', 'Median', 'Ceiling', 'Top_finish', 'Top_5_finish', 'Top_10_finish', '20+%', '2x%', '3x%', '4x%']]
253
+ final_Proj['Own'] = final_Proj['Player'].map(own_dict)
254
+ final_Proj['Team'] = final_Proj['Player'].map(team_dict)
255
+ final_Proj['Opp'] = final_Proj['Player'].map(opp_dict)
256
+ final_Proj = final_Proj[['Player', 'Position', 'Team', 'Opp', 'Salary', 'Floor', 'Median', 'Ceiling', 'Top_finish', 'Top_5_finish', 'Top_10_finish', '20+%', '2x%', '3x%', '4x%', 'Own']]
257
+ final_Proj['Projection Rank'] = final_Proj.Median.rank(pct = True)
258
+ final_Proj['Own Rank'] = final_Proj.Own.rank(pct = True)
259
+ final_Proj['LevX'] = 0
260
+ final_Proj['LevX'] = np.where(final_Proj['Position'] == 'QB', final_Proj[['Projection Rank', 'Top_5_finish']].mean(axis=1) + final_Proj['4x%'] - final_Proj['Own Rank'], final_Proj['LevX'])
261
+ final_Proj['LevX'] = np.where(final_Proj['Position'] == 'TE', final_Proj[['Projection Rank', '2x%']].mean(axis=1) + final_Proj['4x%'] - final_Proj['Own Rank'], final_Proj['LevX'])
262
+ final_Proj['LevX'] = np.where(final_Proj['Position'] == 'RB', final_Proj[['Projection Rank', 'Top_5_finish']].mean(axis=1) + final_Proj['20+%'] - final_Proj['Own Rank'], final_Proj['LevX'])
263
+ final_Proj['LevX'] = np.where(final_Proj['Position'] == 'WR', final_Proj[['Projection Rank', 'Top_10_finish']].mean(axis=1) + final_Proj['4x%'] - final_Proj['Own Rank'], final_Proj['LevX'])
264
+ final_Proj['CPT_Own'] = final_Proj['Own'] / 4
265
+
266
+ final_Proj = final_Proj[['Player', 'Position', 'Team', 'Opp', 'Salary', 'Floor', 'Median', 'Ceiling', 'Top_finish', 'Top_5_finish', 'Top_10_finish', '20+%', '2x%', '3x%', '4x%', 'Own', 'LevX']]
267
+ final_Proj = final_Proj.set_index('Player')
268
+ st.session_state.final_Proj = final_Proj.sort_values(by='Top_finish', ascending=False)
269
+
270
+ elif check_seq == 'Top X Owned':
271
+ if pos_var1 == 'Specific Positions':
272
+ raw_baselines = raw_baselines[raw_baselines['Position'].isin(pos_var_list)]
273
+ player_check = raw_baselines['Player'].head(top_x_var).tolist()
274
+ final_proj_list = []
275
+ for players in player_check:
276
+ players_pos = pos_dict[players]
277
+ player_var = working_roo.loc[working_roo['Player'] == players]
278
+ player_var = player_var.reset_index()
279
+ working_roo_temp = working_roo[working_roo['Position'] == players_pos]
280
+ working_roo_temp = working_roo_temp[working_roo_temp['Team'].isin(team_var1)]
281
+ working_roo_temp = working_roo_temp.loc[(working_roo_temp['Salary'] >= player_var['Salary'][0] - Salary_var) & (working_roo_temp['Salary'] <= player_var['Salary'][0] + Salary_var)]
282
+ working_roo_temp = working_roo_temp.loc[(working_roo_temp['Median'] >= player_var['Median'][0] - Median_var) & (working_roo_temp['Median'] <= player_var['Median'][0] + Median_var)]
283
+
284
+ flex_file = working_roo_temp[['Player', 'Position', 'Salary', 'Median']]
285
+ flex_file['Floor_raw'] = flex_file['Median'] * .25
286
+ flex_file['Ceiling_raw'] = flex_file['Median'] * 1.75
287
+ flex_file['Floor'] = np.where(flex_file['Position'] == 'QB', (flex_file['Median'] * .33), flex_file['Floor_raw'])
288
+ flex_file['Floor'] = np.where(flex_file['Position'] == 'WR', (flex_file['Median'] * .15), flex_file['Floor_raw'])
289
+ flex_file['Ceiling'] = np.where(flex_file['Position'] == 'QB', (flex_file['Median'] * 1.75), flex_file['Ceiling_raw'])
290
+ flex_file['Ceiling'] = np.where(flex_file['Position'] == 'WR', (flex_file['Median'] * 1.85), flex_file['Ceiling_raw'])
291
+ flex_file['STD'] = flex_file['Median'] / 4
292
+ flex_file = flex_file[['Player', 'Position', 'Salary', 'Floor', 'Median', 'Ceiling', 'STD']]
293
+ hold_file = flex_file.copy()
294
+ overall_file = flex_file.copy()
295
+ salary_file = flex_file.copy()
296
+
297
+ overall_players = overall_file[['Player']]
298
+
299
+ for x in range(0,total_sims):
300
+ salary_file[x] = salary_file['Salary']
301
+
302
+ salary_file=salary_file.drop(['Player', 'Position', 'Salary', 'Floor', 'Median', 'Ceiling', 'STD'], axis=1)
303
+
304
+ salary_file = salary_file.div(1000)
305
+
306
+ for x in range(0,total_sims):
307
+ overall_file[x] = np.random.normal(overall_file['Median'],overall_file['STD'])
308
+
309
+ overall_file=overall_file.drop(['Player', 'Position', 'Salary', 'Floor', 'Median', 'Ceiling', 'STD'], axis=1)
310
+
311
+ players_only = hold_file[['Player']]
312
+ raw_lineups_file = players_only
313
+
314
+ for x in range(0,total_sims):
315
+ maps_dict = {'proj_map':dict(zip(hold_file.Player,overall_file[x]))}
316
+ raw_lineups_file[x] = sum([raw_lineups_file['Player'].map(maps_dict['proj_map'])])
317
+ players_only[x] = raw_lineups_file[x].rank(ascending=False)
318
+
319
+ players_only=players_only.drop(['Player'], axis=1)
320
+
321
+ salary_2x_check = (overall_file - (salary_file*2))
322
+ salary_3x_check = (overall_file - (salary_file*3))
323
+ salary_4x_check = (overall_file - (salary_file*4))
324
+
325
+ players_only['Average_Rank'] = players_only.mean(axis=1)
326
+ players_only['Top_finish'] = players_only[players_only == 1].count(axis=1)/total_sims
327
+ players_only['Top_5_finish'] = players_only[players_only <= 5].count(axis=1)/total_sims
328
+ players_only['Top_10_finish'] = players_only[players_only <= 10].count(axis=1)/total_sims
329
+ players_only['20+%'] = overall_file[overall_file >= 20].count(axis=1)/float(total_sims)
330
+ players_only['2x%'] = salary_2x_check[salary_2x_check >= 1].count(axis=1)/float(total_sims)
331
+ players_only['3x%'] = salary_3x_check[salary_3x_check >= 1].count(axis=1)/float(total_sims)
332
+ players_only['4x%'] = salary_4x_check[salary_4x_check >= 1].count(axis=1)/float(total_sims)
333
+
334
+ players_only['Player'] = hold_file[['Player']]
335
+
336
+ final_outcomes = players_only[['Player', 'Top_finish', 'Top_5_finish', 'Top_10_finish', '20+%', '2x%', '3x%', '4x%']]
337
+
338
+ final_Proj = pd.merge(hold_file, final_outcomes, on="Player")
339
+ final_Proj = final_Proj[['Player', 'Position', 'Salary', 'Floor', 'Median', 'Ceiling', 'Top_finish', 'Top_5_finish', 'Top_10_finish', '20+%', '2x%', '3x%', '4x%']]
340
+ final_Proj['Own'] = final_Proj['Player'].map(own_dict)
341
+ final_Proj['Team'] = final_Proj['Player'].map(team_dict)
342
+ final_Proj['Opp'] = final_Proj['Player'].map(opp_dict)
343
+ final_Proj = final_Proj[['Player', 'Position', 'Team', 'Opp', 'Salary', 'Floor', 'Median', 'Ceiling', 'Top_finish', 'Top_5_finish', 'Top_10_finish', '20+%', '2x%', '3x%', '4x%', 'Own']]
344
+ final_Proj['Projection Rank'] = final_Proj.Median.rank(pct = True)
345
+ final_Proj['Own Rank'] = final_Proj.Own.rank(pct = True)
346
+ final_Proj['LevX'] = 0
347
+ final_Proj['LevX'] = np.where(final_Proj['Position'] == 'QB', final_Proj[['Projection Rank', 'Top_5_finish']].mean(axis=1) + final_Proj['4x%'] - final_Proj['Own Rank'], final_Proj['LevX'])
348
+ final_Proj['LevX'] = np.where(final_Proj['Position'] == 'TE', final_Proj[['Projection Rank', '2x%']].mean(axis=1) + final_Proj['4x%'] - final_Proj['Own Rank'], final_Proj['LevX'])
349
+ final_Proj['LevX'] = np.where(final_Proj['Position'] == 'RB', final_Proj[['Projection Rank', 'Top_5_finish']].mean(axis=1) + final_Proj['20+%'] - final_Proj['Own Rank'], final_Proj['LevX'])
350
+ final_Proj['LevX'] = np.where(final_Proj['Position'] == 'WR', final_Proj[['Projection Rank', 'Top_10_finish']].mean(axis=1) + final_Proj['4x%'] - final_Proj['Own Rank'], final_Proj['LevX'])
351
+ final_Proj['CPT_Own'] = final_Proj['Own'] / 4
352
+ final_Proj['Pivot_source'] = players
353
+
354
+ final_Proj = final_Proj[['Player', 'Pivot_source', 'Position', 'Team', 'Opp', 'Salary', 'Floor', 'Median', 'Ceiling', 'Top_finish', 'Top_5_finish', 'Top_10_finish', '20+%', '2x%', '3x%', '4x%', 'Own', 'LevX']]
355
+
356
+ final_Proj = final_Proj.sort_values(by='Top_finish', ascending=False)
357
+ final_proj_list.append(final_Proj)
358
+ st.write(f'finished run for {players}')
359
+
360
+ # Concatenate all the final_Proj dataframes
361
+ final_Proj_combined = pd.concat(final_proj_list)
362
+ final_Proj_combined = final_Proj_combined.sort_values(by='LevX', ascending=False)
363
+ final_Proj_combined = final_Proj_combined[final_Proj_combined['Player'] != final_Proj_combined['Pivot_source']]
364
+ st.session_state.final_Proj = final_Proj_combined.reset_index(drop=True) # Assign the combined dataframe back to final_Proj
365
+
366
+ placeholder.empty()
367
+
368
+ with displayholder.container():
369
+ if 'final_Proj' in st.session_state:
370
+ if view_var == 'Simple':
371
+ display_table = st.session_state['final_Proj'][['Position', 'Team', 'Salary', 'Median', 'Own', 'LevX']]
372
+ st.dataframe(display_table.style.background_gradient(axis=0).background_gradient(cmap='RdYlGn').format(player_roo_format, precision=2), use_container_width = True)
373
+ if view_var == 'Advanced':
374
+ display_table = st.session_state['final_Proj']
375
+ st.dataframe(display_table.style.background_gradient(axis=0).background_gradient(cmap='RdYlGn').format(player_roo_format, precision=2), use_container_width = True)
376
+
377
+ st.download_button(
378
+ label="Export Tables",
379
+ data=convert_df_to_csv(st.session_state.final_Proj),
380
+ file_name='NFL_pivot_export.csv',
381
+ mime='text/csv',
382
+ )
383
+ else:
384
+ st.write("Run some pivots my dude/dudette")
385
+
386
+ if selected_tab == 'User Upload':
387
+ 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'.")
388
+ col1, col2 = st.columns([1, 5])
389
 
390
+ with col1:
391
+ proj_file = st.file_uploader("Upload Projections File", key = 'proj_uploader')
392
+
393
+ if proj_file is not None:
394
+ try:
395
+ st.session_state['proj_dataframe'] = pd.read_csv(proj_file)
396
+ except:
397
+ st.session_state['proj_dataframe'] = pd.read_excel(proj_file)
398
+ with col2:
399
+ if proj_file is not None:
400
+ st.dataframe(st.session_state['proj_dataframe'].style.background_gradient(axis=0).background_gradient(cmap='RdYlGn').format(precision=2), use_container_width = True)