Multichem commited on
Commit
b3306ca
·
1 Parent(s): 892d73a

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +318 -355
app.py CHANGED
@@ -8,7 +8,6 @@ for name in dir():
8
  import pulp
9
  import numpy as np
10
  import pandas as pd
11
- import polars as pl
12
  import streamlit as st
13
  import gspread
14
  import time
@@ -67,18 +66,10 @@ def player_stat_table():
67
  def load_dk_player_projections():
68
  sh = gc.open_by_url('https://docs.google.com/spreadsheets/d/1I_1Ve3F4tftgfLQQoRKOJ351XfEG48s36OxXUKxmgS8/edit#gid=1391856348')
69
  worksheet = sh.worksheet('DK_ROO')
70
-
71
- # Get all records from the Google Sheet
72
- records = worksheet.get_all_records()
73
-
74
- # Convert to Polars DataFrame
75
- load_display = pl.DataFrame(records)
76
-
77
- # Replace empty strings with np.nan
78
- load_display = load_display.apply(lambda df: df.replace("", np.nan))
79
-
80
- # Drop rows where 'Median' is NaN
81
- raw_display = load_display.filter(pl.col("Median").is_not_null())
82
 
83
  return raw_display
84
 
@@ -86,39 +77,30 @@ def load_dk_player_projections():
86
  def load_fd_player_projections():
87
  sh = gc.open_by_url('https://docs.google.com/spreadsheets/d/1I_1Ve3F4tftgfLQQoRKOJ351XfEG48s36OxXUKxmgS8/edit#gid=1391856348')
88
  worksheet = sh.worksheet('FD_ROO')
89
-
90
- # Get all records from the Google Sheet
91
- records = worksheet.get_all_records()
92
-
93
- # Convert to Polars DataFrame
94
- load_display = pl.DataFrame(records)
95
-
96
- # Replace empty strings with np.nan
97
- load_display = load_display.apply(lambda df: df.replace("", np.nan))
98
-
99
- # Drop rows where 'Median' is NaN
100
- raw_display = load_display.filter(pl.col("Median").is_not_null())
101
 
102
  return raw_display
103
 
104
  @st.cache_resource(ttl = 60)
105
  def set_export_ids():
106
  sh = gc.open_by_url('https://docs.google.com/spreadsheets/d/1I_1Ve3F4tftgfLQQoRKOJ351XfEG48s36OxXUKxmgS8/edit#gid=1391856348')
107
- # Fetch DK_ROO worksheet and prepare Polars DataFrame
108
- worksheet_dk = sh.worksheet('DK_ROO')
109
- records_dk = worksheet_dk.get_all_records()
110
- load_display_dk = pl.DataFrame(records_dk)
111
- load_display_dk = load_display_dk.apply(lambda df: df.replace("", np.nan))
112
- raw_display_dk = load_display_dk.filter(pl.col("Median").is_not_null())
113
- dk_ids = dict(zip(raw_display_dk["Player"].to_list(), raw_display_dk["player_id"].to_list()))
114
 
115
- # Fetch FD_ROO worksheet and prepare Polars DataFrame
116
- worksheet_fd = sh.worksheet('FD_ROO')
117
- records_fd = worksheet_fd.get_all_records()
118
- load_display_fd = pl.DataFrame(records_fd)
119
- load_display_fd = load_display_fd.apply(lambda df: df.replace("", np.nan))
120
- raw_display_fd = load_display_fd.filter(pl.col("Median").is_not_null())
121
- fd_ids = dict(zip(raw_display_fd["Player"].to_list(), raw_display_fd["player_id"].to_list()))
 
122
 
123
  return dk_ids, fd_ids
124
 
@@ -133,31 +115,23 @@ def run_seed_frame(seed_depth1, Strength_var, strength_grow, Teams_used, Total_R
133
  strength_grow_def = strength_grow
134
  Teams_used_def = Teams_used
135
  Total_Runs_def = Total_Runs
136
-
137
  while RunsVar <= seed_depth_def:
138
  if RunsVar <= 3:
139
  FieldStrength = Strength_var_def
140
- RandomPortfolio, maps_dict = get_correlated_portfolio_for_sim(Total_Runs_def * 0.1)
141
  FinalPortfolio = RandomPortfolio
142
- FinalPortfolio2, maps_dict2 = get_uncorrelated_portfolio_for_sim(Total_Runs_def * 0.1)
143
-
144
- # Replace pd.concat with pl.vstack
145
- FinalPortfolio = pl.vstack([FinalPortfolio, FinalPortfolio2])
146
-
147
  maps_dict.update(maps_dict2)
148
  del FinalPortfolio2
149
  del maps_dict2
150
- elif 3 < RunsVar <= 4:
151
- FieldStrength += (strength_grow_def + ((30 - len(Teams_used_def)) * 0.001))
152
- FinalPortfolio3, maps_dict3 = get_correlated_portfolio_for_sim(Total_Runs_def * 0.1)
153
- FinalPortfolio4, maps_dict4 = get_uncorrelated_portfolio_for_sim(Total_Runs_def * 0.1)
154
-
155
- # Replace pd.concat with pl.vstack
156
- FinalPortfolio = pl.vstack([FinalPortfolio, FinalPortfolio3, FinalPortfolio4])
157
-
158
- # Replace drop_duplicates and reset_index
159
- FinalPortfolio = FinalPortfolio.drop_duplicates(subset=["Projection", "Own"]).sort("index")
160
-
161
  maps_dict.update(maps_dict3)
162
  maps_dict.update(maps_dict4)
163
  del FinalPortfolio3
@@ -166,95 +140,76 @@ def run_seed_frame(seed_depth1, Strength_var, strength_grow, Teams_used, Total_R
166
  del maps_dict4
167
  elif RunsVar > 4:
168
  FieldStrength = 1
169
- FinalPortfolio3, maps_dict3 = get_correlated_portfolio_for_sim(Total_Runs_def * 0.1)
170
- FinalPortfolio4, maps_dict4 = get_uncorrelated_portfolio_for_sim(Total_Runs_def * 0.1)
171
-
172
- # Replace pd.concat with pl.vstack
173
- FinalPortfolio = pl.vstack([FinalPortfolio, FinalPortfolio3, FinalPortfolio4])
174
-
175
- # Replace drop_duplicates and reset_index
176
- FinalPortfolio = FinalPortfolio.drop_duplicates(subset=["Projection", "Own"]).sort("index")
177
-
178
  maps_dict.update(maps_dict3)
179
  maps_dict.update(maps_dict4)
180
  del FinalPortfolio3
181
  del maps_dict3
182
  del FinalPortfolio4
183
  del maps_dict4
184
-
185
  RunsVar += 1
186
-
187
  return FinalPortfolio, maps_dict
188
 
189
  def create_stack_options(player_data, wr_var):
190
- # Assuming player_data is already a Polars DataFrame
191
- # Sort player_data by 'Median' in descending order
192
- data_raw = player_data.sort("Median", reverse=True)
193
-
194
- merged_frame = pl.DataFrame(
195
- {
196
- "QB": [],
197
- "Player": []
198
- }
199
- )
200
-
201
- for team in data_raw.select("Team").unique().get("Team"):
202
- data_split = data_raw.filter(pl.col("Team") == team)
203
-
204
- qb_frame = data_split.filter(pl.col("Position") == "QB")
205
- wr_frame = data_split.filter(pl.col("Position") == "WR").slice(wr_var - 1, wr_var)
206
 
207
- qb_name = qb_frame.head(1).get("Player")[0] if qb_frame.shape[0] > 0 else None
208
- if qb_name is not None:
209
- wr_frame = wr_frame.with_column(pl.lit(qb_name).alias("QB"))
210
- merge_slice = wr_frame.select("QB", "Player")
211
- merged_frame = merged_frame.vstack(merge_slice)
212
 
213
- # Reset index (not necessary in Polars as index doesn't exist in the same way as Pandas)
214
- # Build a dictionary from the DataFrame
215
- correl_dict = dict(zip(merged_frame.get("QB"), merged_frame.get("Player")))
216
-
217
- del merged_frame
218
- del data_raw
219
-
220
- return correl_dict
221
-
222
- @st.cache_data
223
- def apply_range(s: pl.Series) -> pl.Series:
224
- return pl.Series("Var", list(range(s.len())))
225
 
226
  def create_overall_dfs(pos_players, table_name, dict_name, pos):
227
  if pos == "FLEX":
228
- pos_players = pos_players.sort("Value", reverse=True)
229
- overall_table_name = pos_players.slice(0, round(pos_players.shape[0]))
230
- overall_table_name = overall_table_name.with_column(pl.col("Var").apply_range())
231
- overall_dict_name = {row[0]: row[1] for row in overall_table_name.select(["Var", "Player"]).collect()}
 
232
 
233
  del pos_players
 
234
  elif pos != "FLEX":
235
- table_name_raw = pos_players.filter(pl.col("Position").str_contains(pos))
236
- overall_table_name = table_name_raw.slice(0, round(table_name_raw.shape[0]))
237
- overall_table_name = overall_table_name.with_column(pl.col("Var").apply_range())
238
- overall_dict_name = {row[0]: row[1] for row in overall_table_name.select(["Var", "Player"]).collect()}
239
 
240
  del pos_players
 
241
 
242
  return overall_table_name, overall_dict_name
243
 
244
 
245
  def get_overall_merged_df():
246
  ref_dict = {
247
- 'pos': ['RB', 'WR', 'TE', 'FLEX'],
248
- 'pos_dfs': ['RB_Table', 'WR_Table', 'TE_Table', 'FLEX_Table'],
249
- 'pos_dicts': ['rb_dict', 'wr_dict', 'te_dict', 'flex_dict']
250
- }
251
 
252
- for i in range(0, 4):
253
- ref_dict['pos_dfs'][i], ref_dict['pos_dicts'][i] = \
254
  create_overall_dfs(pos_players, ref_dict['pos_dfs'][i], ref_dict['pos_dicts'][i], ref_dict['pos'][i])
 
 
255
 
256
- # Assuming ref_dict['pos_dfs'] is a list of polars.Dataframe
257
- df_out = pl.concat(ref_dict['pos_dfs'], rechunk=True)
258
 
259
  def calculate_range_var(count, min_val, FieldStrength, field_growth):
260
  var = round(len(count[0]) * FieldStrength)
@@ -263,289 +218,297 @@ def calculate_range_var(count, min_val, FieldStrength, field_growth):
263
  return min(var, len(count[0]))
264
 
265
  def create_random_portfolio(Total_Sample_Size, raw_baselines):
266
-
267
- O_merge, full_pos_player_dict = get_overall_merged_df()
268
- max_var = len(raw_baselines.filter(pl.col("Position") == "QB"))
269
-
270
- field_growth_rounded = round(field_growth)
271
- ranges_dict = {}
272
-
273
- # Calculate ranges
274
- for df, dict_val, min_val, key in zip(ref_dict['pos_dfs'], ref_dict['pos_dicts'], [10, 20, 30, 10], ['RB', 'WR', 'TE', 'FLEX']):
275
- count = create_overall_dfs(pos_players, df, dict_val, key)
276
- ranges_dict[f"{key.lower()}_range"] = calculate_range_var(count, min_val, FieldStrength, field_growth_rounded)
277
 
278
- if max_var <= 10:
279
- ranges_dict['qb_range'] = round(max_var)
280
- ranges_dict['dst_range'] = round(max_var)
281
- elif max_var > 10 and max_var <= 16:
282
- ranges_dict['qb_range'] = round(max_var / 1.5)
283
- ranges_dict['dst_range'] = round(max_var)
284
- elif max_var > 16:
285
- ranges_dict['qb_range'] = round(max_var / 2)
286
- ranges_dict['dst_range'] = round(max_var)
287
-
288
- # Generate random portfolios
289
- rng = np.random.default_rng()
290
- total_elements = [1, 2, 3, 1, 1, 1]
291
- keys = ['qb', 'rb', 'wr', 'te', 'flex', 'dst']
292
-
293
- all_choices = [rng.choice(ranges_dict[f"{key}_range"], size=(Total_Sample_Size, elem)) for key, elem in zip(keys, total_elements)]
294
-
295
- # Create a Polars DataFrame
296
- RandomPortfolio = pl.DataFrame(
297
- {name: np.hstack([choice[:, i] if choice.shape[1] > i else choice[:, 0] for choice in all_choices]) for i, name in enumerate(['QB', 'RB1', 'RB2', 'WR1', 'WR2', 'WR3', 'TE', 'FLEX', 'DST'])}
298
- )
299
- RandomPortfolio = RandomPortfolio.with_column(pl.col("User/Field").fill_none(0))
300
-
301
-
302
- del O_merge
303
-
304
- return RandomPortfolio, maps_dict, ranges_dict, full_pos_player_dict
 
 
 
 
 
 
 
 
305
 
306
  def get_correlated_portfolio_for_sim(Total_Sample_Size):
307
 
308
  sizesplit = round(Total_Sample_Size * sharp_split)
 
309
  RandomPortfolio, maps_dict, ranges_dict, full_pos_player_dict = create_random_portfolio(sizesplit, raw_baselines)
310
  stack_num = random.randint(1, 3)
311
  stacking_dict = create_stack_options(raw_baselines, stack_num)
312
 
313
- # Mapping series
314
- RandomPortfolio = RandomPortfolio.with_column(
315
- pl.col("QB").apply(lambda x: qb_dict.get(x, x), return_dtype=pl.Utf8)
316
- )
317
- RandomPortfolio = RandomPortfolio.with_column(
318
- pl.col("RB1").apply(lambda x: full_pos_player_dict['pos_dicts'][0].get(x, x), return_dtype=pl.Utf8)
319
- )
320
- RandomPortfolio = RandomPortfolio.with_column(
321
- pl.col("RB2").apply(lambda x: full_pos_player_dict['pos_dicts'][0].get(x, x), return_dtype=pl.Utf8)
322
- )
323
- RandomPortfolio = RandomPortfolio.with_column(
324
- pl.col("WR1").apply(lambda x: stacking_dict.get(x, x), return_dtype=pl.Utf8)
325
- )
326
- RandomPortfolio = RandomPortfolio.with_column(
327
- pl.col("WR2").apply(lambda x: full_pos_player_dict['pos_dicts'][1].get(x, x), return_dtype=pl.Utf8)
328
- )
329
- RandomPortfolio = RandomPortfolio.with_column(
330
- pl.col("WR3").apply(lambda x: full_pos_player_dict['pos_dicts'][1].get(x, x), return_dtype=pl.Utf8)
331
- )
332
- RandomPortfolio = RandomPortfolio.with_column(
333
- pl.col("TE").apply(lambda x: full_pos_player_dict['pos_dicts'][2].get(x, x), return_dtype=pl.Utf8)
334
- )
335
- RandomPortfolio = RandomPortfolio.with_column(
336
- pl.col("FLEX").apply(lambda x: full_pos_player_dict['pos_dicts'][3].get(x, x), return_dtype=pl.Utf8)
337
- )
338
- RandomPortfolio = RandomPortfolio.with_column(
339
- pl.col("DST").apply(lambda x: def_dict.get(x, x), return_dtype=pl.Utf8)
340
- )
341
 
342
- # Creating 'plyr_list' and 'plyr_count'
343
- plyr_list_exprs = [pl.col(name).alias(f"{name}_item") for name in RandomPortfolio.columns]
344
- plyr_list = pl.col(plyr_list_exprs).apply(lambda x: list(set(x)), return_dtype=pl.List(pl.Utf8)).alias("plyr_list")
345
- plyr_count = plyr_list.apply(lambda x: len(set(x)), return_dtype=pl.Int64).alias("plyr_count")
346
 
347
- # Add these to RandomPortfolio
348
- RandomPortfolio = RandomPortfolio.with_columns([plyr_list, plyr_count])
 
 
 
 
 
 
 
 
 
 
 
349
 
350
- # Filter out rows where 'plyr_count' is not 10
351
- RandomPortfolio = RandomPortfolio.filter(pl.col("plyr_count") == 10).select_except("plyr_list", "plyr_count")
 
 
 
352
 
353
- # Since polars DataFrame is lazy, you may want to call .collect() to materialize it
354
- RandomPortfolio = RandomPortfolio.collect()
355
 
356
- # Map and cast to specific data types
357
- positions = ['QB', 'RB1', 'RB2', 'WR1', 'WR2', 'WR3', 'TE', 'FLEX', 'DST']
358
- for pos in positions:
359
- RandomPortfolio = RandomPortfolio.with_column(
360
- pl.col(pos).apply(lambda x: maps_dict['Salary_map'].get(x, x), return_dtype=pl.Int32).alias(f"{pos}s")
361
- )
362
- RandomPortfolio = RandomPortfolio.with_column(
363
- pl.col(pos).apply(lambda x: maps_dict['Projection_map'].get(x, x), return_dtype=pl.Float32).alias(f"{pos}p")
364
- )
365
- RandomPortfolio = RandomPortfolio.with_column(
366
- pl.col(pos).apply(lambda x: maps_dict['Own_map'].get(x, x), return_dtype=pl.Float32).alias(f"{pos}o")
367
- )
368
 
369
- # Equivalent of converting to numpy array and performing einsum
370
- RandomPortfolio = RandomPortfolio.with_columns([
371
- pl.sum([pl.col(f"{pos}s") for pos in positions]).alias('Salary'),
372
- pl.sum([pl.col(f"{pos}p") for pos in positions]).alias('Projection'),
373
- pl.sum([pl.col(f"{pos}o") for pos in positions]).alias('Own')
374
- ])
 
 
 
375
 
376
- # Select the columns you want in the final DataFrame
377
- RandomPortfolio = RandomPortfolio.select(
378
- positions + ['User/Field', 'Salary', 'Projection', 'Own']
379
- )
 
 
 
 
 
380
 
381
- # Since DataFrame is lazy, call collect() to materialize
382
- RandomPortfolio = RandomPortfolio.collect()
 
 
 
 
 
 
 
383
 
384
- # Sorting based on some function
385
- # Note: Replace 'Sim_function' with the actual column name or expression you want to sort by
386
- RandomPortfolio = RandomPortfolio.sort('Sim_function', reverse=True)
387
 
388
- positions = ['QB', 'RB1', 'RB2', 'WR1', 'WR2', 'WR3', 'TE', 'FLEX', 'DST']
 
 
 
 
 
 
 
 
389
 
390
  if insert_port == 1:
391
- CleanPortfolio = CleanPortfolio.with_column(
392
- pl.sum([
393
- pl.col(pos).apply(lambda x: maps_dict['Salary_map'].get(x, x), return_dtype=pl.Int16)
394
- for pos in positions
395
- ]).alias('Salary')
396
- )
397
-
398
- CleanPortfolio = CleanPortfolio.with_column(
399
- pl.sum([
400
- pl.col(pos).apply(lambda x: up_dict['Projection_map'].get(x, x), return_dtype=pl.Float16)
401
- for pos in positions
402
- ]).alias('Projection')
403
- )
404
-
405
- CleanPortfolio = CleanPortfolio.with_column(
406
- pl.sum([
407
- pl.col(pos).apply(lambda x: maps_dict['Own_map'].get(x, x), return_dtype=pl.Float16)
408
- for pos in positions
409
- ]).alias('Own')
410
- )
 
 
 
 
 
 
 
 
 
 
 
 
411
 
412
  if site_var1 == 'Draftkings':
413
- RandomPortfolioDF = RandomPortfolioDF.filter(pl.col('Salary') <= 50000)
414
- RandomPortfolioDF = RandomPortfolioDF.filter(pl.col('Salary') >= (49500 - (5000 * (1 - (len(Teams_used) / 32))) - (FieldStrength * 1000)))
415
-
416
  elif site_var1 == 'Fanduel':
417
- RandomPortfolioDF = RandomPortfolioDF.filter(pl.col('Salary') <= 60000)
418
- RandomPortfolioDF = RandomPortfolioDF.filter(pl.col('Salary') >= (59500 - (5000 * (1 - (len(Teams_used) / 32))) - (FieldStrength * 1000)))
419
 
420
- # Sorting the DataFrame
421
- # Note: Replace 'Sim_function' with the actual column name or expression you want to sort by
422
- RandomPortfolioDF = RandomPortfolioDF.sort('Sim_function', reverse=True)
423
 
424
- # Selecting the columns you want to keep
425
- RandomPortfolioDF = RandomPortfolioDF.select(['QB', 'RB1', 'RB2', 'WR1', 'WR2', 'WR3', 'TE', 'FLEX', 'DST', 'User/Field', 'Salary', 'Projection', 'Own'])
426
 
427
  return RandomPortfolio, maps_dict
428
 
429
  def get_uncorrelated_portfolio_for_sim(Total_Sample_Size):
430
 
431
- sizesplit = round(Total_Sample_Size * sharp_split)
 
432
  RandomPortfolio, maps_dict, ranges_dict, full_pos_player_dict = create_random_portfolio(sizesplit, raw_baselines)
433
- stack_num = random.randint(1, 3)
434
- stacking_dict = create_stack_options(raw_baselines, stack_num)
435
-
436
- # Mapping series
437
- RandomPortfolio = RandomPortfolio.with_column(
438
- pl.col("QB").apply(lambda x: qb_dict.get(x, x), return_dtype=pl.Utf8)
439
- )
440
- RandomPortfolio = RandomPortfolio.with_column(
441
- pl.col("RB1").apply(lambda x: full_pos_player_dict['pos_dicts'][0].get(x, x), return_dtype=pl.Utf8)
442
- )
443
- RandomPortfolio = RandomPortfolio.with_column(
444
- pl.col("RB2").apply(lambda x: full_pos_player_dict['pos_dicts'][0].get(x, x), return_dtype=pl.Utf8)
445
- )
446
- RandomPortfolio = RandomPortfolio.with_column(
447
- pl.col("WR1").apply(lambda x: stacking_dict.get(x, x), return_dtype=pl.Utf8)
448
- )
449
- RandomPortfolio = RandomPortfolio.with_column(
450
- pl.col("WR2").apply(lambda x: full_pos_player_dict['pos_dicts'][1].get(x, x), return_dtype=pl.Utf8)
451
- )
452
- RandomPortfolio = RandomPortfolio.with_column(
453
- pl.col("WR3").apply(lambda x: full_pos_player_dict['pos_dicts'][1].get(x, x), return_dtype=pl.Utf8)
454
- )
455
- RandomPortfolio = RandomPortfolio.with_column(
456
- pl.col("TE").apply(lambda x: full_pos_player_dict['pos_dicts'][2].get(x, x), return_dtype=pl.Utf8)
457
- )
458
- RandomPortfolio = RandomPortfolio.with_column(
459
- pl.col("FLEX").apply(lambda x: full_pos_player_dict['pos_dicts'][3].get(x, x), return_dtype=pl.Utf8)
460
- )
461
- RandomPortfolio = RandomPortfolio.with_column(
462
- pl.col("DST").apply(lambda x: def_dict.get(x, x), return_dtype=pl.Utf8)
463
- )
464
-
465
- # Creating 'plyr_list' and 'plyr_count'
466
- plyr_list_exprs = [pl.col(name).alias(f"{name}_item") for name in RandomPortfolio.columns]
467
- plyr_list = pl.col(plyr_list_exprs).apply(lambda x: list(set(x)), return_dtype=pl.List(pl.Utf8)).alias("plyr_list")
468
- plyr_count = plyr_list.apply(lambda x: len(set(x)), return_dtype=pl.Int64).alias("plyr_count")
469
-
470
- # Add these to RandomPortfolio
471
- RandomPortfolio = RandomPortfolio.with_columns([plyr_list, plyr_count])
472
-
473
- # Filter out rows where 'plyr_count' is not 10
474
- RandomPortfolio = RandomPortfolio.filter(pl.col("plyr_count") == 10).select_except("plyr_list", "plyr_count")
475
-
476
- # Since polars DataFrame is lazy, you may want to call .collect() to materialize it
477
- RandomPortfolio = RandomPortfolio.collect()
478
 
479
- # Map and cast to specific data types
480
- positions = ['QB', 'RB1', 'RB2', 'WR1', 'WR2', 'WR3', 'TE', 'FLEX', 'DST']
481
- for pos in positions:
482
- RandomPortfolio = RandomPortfolio.with_column(
483
- pl.col(pos).apply(lambda x: maps_dict['Salary_map'].get(x, x), return_dtype=pl.Int32).alias(f"{pos}s")
484
- )
485
- RandomPortfolio = RandomPortfolio.with_column(
486
- pl.col(pos).apply(lambda x: maps_dict['Projection_map'].get(x, x), return_dtype=pl.Float32).alias(f"{pos}p")
487
- )
488
- RandomPortfolio = RandomPortfolio.with_column(
489
- pl.col(pos).apply(lambda x: maps_dict['Own_map'].get(x, x), return_dtype=pl.Float32).alias(f"{pos}o")
490
- )
491
 
492
- # Equivalent of converting to numpy array and performing einsum
493
- RandomPortfolio = RandomPortfolio.with_columns([
494
- pl.sum([pl.col(f"{pos}s") for pos in positions]).alias('Salary'),
495
- pl.sum([pl.col(f"{pos}p") for pos in positions]).alias('Projection'),
496
- pl.sum([pl.col(f"{pos}o") for pos in positions]).alias('Own')
497
- ])
 
 
 
498
 
499
- # Select the columns you want in the final DataFrame
500
- RandomPortfolio = RandomPortfolio.select(
501
- positions + ['User/Field', 'Salary', 'Projection', 'Own']
502
- )
 
 
 
 
 
503
 
504
- # Since DataFrame is lazy, call collect() to materialize
505
- RandomPortfolio = RandomPortfolio.collect()
 
 
 
 
 
 
 
506
 
507
- # Sorting based on some function
508
- # Note: Replace 'Sim_function' with the actual column name or expression you want to sort by
509
- RandomPortfolio = RandomPortfolio.sort('Sim_function', reverse=True)
510
 
511
- positions = ['QB', 'RB1', 'RB2', 'WR1', 'WR2', 'WR3', 'TE', 'FLEX', 'DST']
 
 
512
 
 
 
 
 
 
 
 
513
  if insert_port == 1:
514
- CleanPortfolio = CleanPortfolio.with_column(
515
- pl.sum([
516
- pl.col(pos).apply(lambda x: maps_dict['Salary_map'].get(x, x), return_dtype=pl.Int16)
517
- for pos in positions
518
- ]).alias('Salary')
519
- )
520
-
521
- CleanPortfolio = CleanPortfolio.with_column(
522
- pl.sum([
523
- pl.col(pos).apply(lambda x: up_dict['Projection_map'].get(x, x), return_dtype=pl.Float16)
524
- for pos in positions
525
- ]).alias('Projection')
526
- )
527
-
528
- CleanPortfolio = CleanPortfolio.with_column(
529
- pl.sum([
530
- pl.col(pos).apply(lambda x: maps_dict['Own_map'].get(x, x), return_dtype=pl.Float16)
531
- for pos in positions
532
- ]).alias('Own')
533
- )
 
 
 
 
 
 
 
 
 
 
 
 
534
 
535
  if site_var1 == 'Draftkings':
536
- RandomPortfolioDF = RandomPortfolioDF.filter(pl.col('Salary') <= 50000)
537
- RandomPortfolioDF = RandomPortfolioDF.filter(pl.col('Salary') >= (49500 - (5000 * (1 - (len(Teams_used) / 32))) - (FieldStrength * 1000)))
538
-
539
  elif site_var1 == 'Fanduel':
540
- RandomPortfolioDF = RandomPortfolioDF.filter(pl.col('Salary') <= 60000)
541
- RandomPortfolioDF = RandomPortfolioDF.filter(pl.col('Salary') >= (59500 - (5000 * (1 - (len(Teams_used) / 32))) - (FieldStrength * 1000)))
542
 
543
- # Sorting the DataFrame
544
- # Note: Replace 'Sim_function' with the actual column name or expression you want to sort by
545
- RandomPortfolioDF = RandomPortfolioDF.sort('Sim_function', reverse=True)
546
 
547
- # Selecting the columns you want to keep
548
- RandomPortfolioDF = RandomPortfolioDF.select(['QB', 'RB1', 'RB2', 'WR1', 'WR2', 'WR3', 'TE', 'FLEX', 'DST', 'User/Field', 'Salary', 'Projection', 'Own'])
549
 
550
  return RandomPortfolio, maps_dict
551
 
 
8
  import pulp
9
  import numpy as np
10
  import pandas as pd
 
11
  import streamlit as st
12
  import gspread
13
  import time
 
66
  def load_dk_player_projections():
67
  sh = gc.open_by_url('https://docs.google.com/spreadsheets/d/1I_1Ve3F4tftgfLQQoRKOJ351XfEG48s36OxXUKxmgS8/edit#gid=1391856348')
68
  worksheet = sh.worksheet('DK_ROO')
69
+ load_display = pd.DataFrame(worksheet.get_all_records())
70
+ load_display.replace('', np.nan, inplace=True)
71
+ raw_display = load_display.dropna(subset=['Median'])
72
+ del load_display
 
 
 
 
 
 
 
 
73
 
74
  return raw_display
75
 
 
77
  def load_fd_player_projections():
78
  sh = gc.open_by_url('https://docs.google.com/spreadsheets/d/1I_1Ve3F4tftgfLQQoRKOJ351XfEG48s36OxXUKxmgS8/edit#gid=1391856348')
79
  worksheet = sh.worksheet('FD_ROO')
80
+ load_display = pd.DataFrame(worksheet.get_all_records())
81
+ load_display.replace('', np.nan, inplace=True)
82
+ raw_display = load_display.dropna(subset=['Median'])
83
+ del load_display
 
 
 
 
 
 
 
 
84
 
85
  return raw_display
86
 
87
  @st.cache_resource(ttl = 60)
88
  def set_export_ids():
89
  sh = gc.open_by_url('https://docs.google.com/spreadsheets/d/1I_1Ve3F4tftgfLQQoRKOJ351XfEG48s36OxXUKxmgS8/edit#gid=1391856348')
90
+ worksheet = sh.worksheet('DK_ROO')
91
+ load_display = pd.DataFrame(worksheet.get_all_records())
92
+ load_display.replace('', np.nan, inplace=True)
93
+ raw_display = load_display.dropna(subset=['Median'])
94
+ dk_ids = dict(zip(raw_display['Player'], raw_display['player_id']))
 
 
95
 
96
+ worksheet = sh.worksheet('FD_ROO')
97
+ load_display = pd.DataFrame(worksheet.get_all_records())
98
+ load_display.replace('', np.nan, inplace=True)
99
+ raw_display = load_display.dropna(subset=['Median'])
100
+ fd_ids = dict(zip(raw_display['Player'], raw_display['player_id']))
101
+
102
+ del load_display
103
+ del raw_display
104
 
105
  return dk_ids, fd_ids
106
 
 
115
  strength_grow_def = strength_grow
116
  Teams_used_def = Teams_used
117
  Total_Runs_def = Total_Runs
 
118
  while RunsVar <= seed_depth_def:
119
  if RunsVar <= 3:
120
  FieldStrength = Strength_var_def
121
+ RandomPortfolio, maps_dict = get_correlated_portfolio_for_sim(Total_Runs_def * .1)
122
  FinalPortfolio = RandomPortfolio
123
+ FinalPortfolio2, maps_dict2 = get_uncorrelated_portfolio_for_sim(Total_Runs_def * .1)
124
+ FinalPortfolio = pd.concat([FinalPortfolio, FinalPortfolio2], axis=0)
 
 
 
125
  maps_dict.update(maps_dict2)
126
  del FinalPortfolio2
127
  del maps_dict2
128
+ elif RunsVar > 3 and RunsVar <= 4:
129
+ FieldStrength += (strength_grow_def + ((30 - len(Teams_used_def)) * .001))
130
+ FinalPortfolio3, maps_dict3 = get_correlated_portfolio_for_sim(Total_Runs_def * .1)
131
+ FinalPortfolio4, maps_dict4 = get_uncorrelated_portfolio_for_sim(Total_Runs_def * .1)
132
+ FinalPortfolio = pd.concat([FinalPortfolio, FinalPortfolio3], axis=0)
133
+ FinalPortfolio = pd.concat([FinalPortfolio, FinalPortfolio4], axis=0)
134
+ FinalPortfolio = FinalPortfolio.drop_duplicates(subset = ['Projection', 'Own'],keep = 'last').reset_index(drop = True)
 
 
 
 
135
  maps_dict.update(maps_dict3)
136
  maps_dict.update(maps_dict4)
137
  del FinalPortfolio3
 
140
  del maps_dict4
141
  elif RunsVar > 4:
142
  FieldStrength = 1
143
+ FinalPortfolio3, maps_dict3 = get_correlated_portfolio_for_sim(Total_Runs_def * .1)
144
+ FinalPortfolio4, maps_dict4 = get_uncorrelated_portfolio_for_sim(Total_Runs_def * .1)
145
+ FinalPortfolio = pd.concat([FinalPortfolio, FinalPortfolio3], axis=0)
146
+ FinalPortfolio = pd.concat([FinalPortfolio, FinalPortfolio4], axis=0)
147
+ FinalPortfolio = FinalPortfolio.drop_duplicates(subset = ['Projection', 'Own'],keep = 'last').reset_index(drop = True)
 
 
 
 
148
  maps_dict.update(maps_dict3)
149
  maps_dict.update(maps_dict4)
150
  del FinalPortfolio3
151
  del maps_dict3
152
  del FinalPortfolio4
153
  del maps_dict4
 
154
  RunsVar += 1
155
+
156
  return FinalPortfolio, maps_dict
157
 
158
  def create_stack_options(player_data, wr_var):
159
+ merged_frame = pd.DataFrame(columns = ['QB', 'Player'])
160
+ data_raw = player_data.sort_values(by='Median', ascending=False)
161
+
162
+ for team in data_raw['Team'].unique():
163
+ data_split = data_raw.loc[data_raw['Team'] == team]
164
+ qb_frame = data_split.loc[data_split['Position'] == 'QB'].reset_index()
165
+ wr_frame = data_split.loc[data_split['Position'] == 'WR'].iloc[wr_var-1:wr_var]
166
+ wr_frame['QB'] = qb_frame['Player'][0]
167
+ merge_slice = wr_frame[['QB', 'Player']]
168
+ merged_frame = pd.concat([merged_frame, merge_slice])
169
+ merged_frame = merged_frame.reset_index()
170
+ correl_dict = dict(zip(merged_frame.QB, merged_frame.Player))
 
 
 
 
171
 
172
+ del merged_frame
173
+ del data_raw
 
 
 
174
 
175
+ return correl_dict
 
 
 
 
 
 
 
 
 
 
 
176
 
177
  def create_overall_dfs(pos_players, table_name, dict_name, pos):
178
  if pos == "FLEX":
179
+ pos_players = pos_players.sort_values(by='Value', ascending=False)
180
+ table_name_raw = pos_players.reset_index(drop=True)
181
+ overall_table_name = table_name_raw.head(round(len(table_name_raw)))
182
+ overall_table_name = overall_table_name.assign(Var = range(0,len(overall_table_name)))
183
+ overall_dict_name = pd.Series(overall_table_name.Player.values, index=overall_table_name.Var).to_dict()
184
 
185
  del pos_players
186
+ del table_name_raw
187
  elif pos != "FLEX":
188
+ table_name_raw = pos_players[pos_players['Position'].str.contains(pos)].reset_index(drop=True)
189
+ overall_table_name = table_name_raw.head(round(len(table_name_raw)))
190
+ overall_table_name = overall_table_name.assign(Var = range(0,len(overall_table_name)))
191
+ overall_dict_name = pd.Series(overall_table_name.Player.values, index=overall_table_name.Var).to_dict()
192
 
193
  del pos_players
194
+ del table_name_raw
195
 
196
  return overall_table_name, overall_dict_name
197
 
198
 
199
  def get_overall_merged_df():
200
  ref_dict = {
201
+ 'pos':['RB', 'WR', 'TE', 'FLEX'],
202
+ 'pos_dfs':['RB_Table', 'WR_Table', 'TE_Table', 'FLEX_Table'],
203
+ 'pos_dicts':['rb_dict', 'wr_dict', 'te_dict', 'flex_dict']
204
+ }
205
 
206
+ for i in range(0,4):
207
+ ref_dict['pos_dfs'][i], ref_dict['pos_dicts'][i] =\
208
  create_overall_dfs(pos_players, ref_dict['pos_dfs'][i], ref_dict['pos_dicts'][i], ref_dict['pos'][i])
209
+
210
+ df_out = pd.concat(ref_dict['pos_dfs'], ignore_index=True)
211
 
212
+ return df_out, ref_dict
 
213
 
214
  def calculate_range_var(count, min_val, FieldStrength, field_growth):
215
  var = round(len(count[0]) * FieldStrength)
 
218
  return min(var, len(count[0]))
219
 
220
  def create_random_portfolio(Total_Sample_Size, raw_baselines):
 
 
 
 
 
 
 
 
 
 
 
221
 
222
+ O_merge, full_pos_player_dict = get_overall_merged_df()
223
+ max_var = len(raw_baselines[raw_baselines['Position'] == 'QB'])
224
+
225
+ field_growth_rounded = round(field_growth)
226
+ ranges_dict = {}
227
+
228
+ # Calculate ranges
229
+ for df, dict_val, min_val, key in zip(ref_dict['pos_dfs'], ref_dict['pos_dicts'], [10, 20, 30, 10], ['RB', 'WR', 'TE', 'FLEX']):
230
+ count = create_overall_dfs(pos_players, df, dict_val, key)
231
+ ranges_dict[f"{key.lower()}_range"] = calculate_range_var(count, min_val, FieldStrength, field_growth_rounded)
232
+ if max_var <= 10:
233
+ ranges_dict['qb_range'] = round(max_var)
234
+ ranges_dict['dst_range'] = round(max_var)
235
+ elif max_var > 10 and max_var <= 16:
236
+ ranges_dict['qb_range'] = round(max_var / 1.5)
237
+ ranges_dict['dst_range'] = round(max_var)
238
+ elif max_var > 16:
239
+ ranges_dict['qb_range'] = round(max_var / 2)
240
+ ranges_dict['dst_range'] = round(max_var)
241
+ # Generate unique ranges
242
+ # for key, value in ranges_dict.items():
243
+ # ranges_dict[f"{key}_Uniques"] = list(range(0, value, 1))
244
+
245
+ # Generate random portfolios
246
+ rng = np.random.default_rng()
247
+ total_elements = [1, 2, 3, 1, 1, 1]
248
+ keys = ['qb', 'rb', 'wr', 'te', 'flex', 'dst']
249
+
250
+ all_choices = [rng.choice(ranges_dict[f"{key}_range"], size=(Total_Sample_Size, elem)) for key, elem in zip(keys, total_elements)]
251
+ RandomPortfolio = pd.DataFrame(np.hstack(all_choices), columns=['QB', 'RB1', 'RB2', 'WR1', 'WR2', 'WR3', 'TE', 'FLEX', 'DST'])
252
+ RandomPortfolio['User/Field'] = 0
253
+
254
+ del O_merge
255
+
256
+ return RandomPortfolio, maps_dict, ranges_dict, full_pos_player_dict
257
 
258
  def get_correlated_portfolio_for_sim(Total_Sample_Size):
259
 
260
  sizesplit = round(Total_Sample_Size * sharp_split)
261
+
262
  RandomPortfolio, maps_dict, ranges_dict, full_pos_player_dict = create_random_portfolio(sizesplit, raw_baselines)
263
  stack_num = random.randint(1, 3)
264
  stacking_dict = create_stack_options(raw_baselines, stack_num)
265
 
266
+ # # Create a dictionary for mapping positions to their corresponding dictionaries
267
+ # dict_map = {
268
+ # 'QB': qb_dict,
269
+ # 'RB1': full_pos_player_dict['pos_dicts'][0],
270
+ # 'RB2': full_pos_player_dict['pos_dicts'][0],
271
+ # 'WR1': full_pos_player_dict['pos_dicts'][1],
272
+ # 'WR2': full_pos_player_dict['pos_dicts'][1],
273
+ # 'WR3': full_pos_player_dict['pos_dicts'][1],
274
+ # 'TE': full_pos_player_dict['pos_dicts'][2],
275
+ # 'FLEX': full_pos_player_dict['pos_dicts'][3],
276
+ # 'DST': def_dict
277
+ # }
278
+
279
+ # # Apply mapping for each position
280
+ # for pos, mapping in dict_map.items():
281
+ # RandomPortfolio[pos] = RandomPortfolio[pos].map(mapping).astype("string[pyarrow]")
 
 
 
 
 
 
 
 
 
 
 
 
282
 
283
+ # # This part appears to be for filtering. Consider if it can be optimized depending on the data characteristics
284
+ # RandomPortfolio['plyr_list'] = RandomPortfolio.values.tolist()
285
+ # RandomPortfolio['plyr_count'] = RandomPortfolio['plyr_list'].apply(lambda x: len(set(x)))
286
+ # RandomPortfolio = RandomPortfolio[RandomPortfolio['plyr_count'] == 10].drop(columns=['plyr_list','plyr_count']).reset_index(drop=True)
287
 
288
+ RandomPortfolio['QB'] = pd.Series(list(RandomPortfolio['QB'].map(qb_dict)), dtype="string[pyarrow]")
289
+ RandomPortfolio['RB1'] = pd.Series(list(RandomPortfolio['RB1'].map(full_pos_player_dict['pos_dicts'][0])), dtype="string[pyarrow]")
290
+ RandomPortfolio['RB2'] = pd.Series(list(RandomPortfolio['RB2'].map(full_pos_player_dict['pos_dicts'][0])), dtype="string[pyarrow]")
291
+ RandomPortfolio['WR1'] = pd.Series(list(RandomPortfolio['QB'].map(stacking_dict)), dtype="string[pyarrow]")
292
+ RandomPortfolio['WR2'] = pd.Series(list(RandomPortfolio['WR2'].map(full_pos_player_dict['pos_dicts'][1])), dtype="string[pyarrow]")
293
+ RandomPortfolio['WR3'] = pd.Series(list(RandomPortfolio['WR3'].map(full_pos_player_dict['pos_dicts'][1])), dtype="string[pyarrow]")
294
+ RandomPortfolio['TE'] = pd.Series(list(RandomPortfolio['TE'].map(full_pos_player_dict['pos_dicts'][2])), dtype="string[pyarrow]")
295
+ RandomPortfolio['FLEX'] = pd.Series(list(RandomPortfolio['FLEX'].map(full_pos_player_dict['pos_dicts'][3])), dtype="string[pyarrow]")
296
+ RandomPortfolio['DST'] = pd.Series(list(RandomPortfolio['DST'].map(def_dict)), dtype="string[pyarrow]")
297
+ RandomPortfolio['plyr_list'] = RandomPortfolio[RandomPortfolio.columns.values.tolist()].values.tolist()
298
+ RandomPortfolio['plyr_count'] = RandomPortfolio['plyr_list'].apply(lambda x: len(set(x)))
299
+ RandomPortfolio = RandomPortfolio[RandomPortfolio['plyr_count'] == 10].drop(columns=['plyr_list','plyr_count']).\
300
+ reset_index(drop=True)
301
 
302
+ del sizesplit
303
+ del full_pos_player_dict
304
+ del ranges_dict
305
+ del stack_num
306
+ del stacking_dict
307
 
 
 
308
 
 
 
 
 
 
 
 
 
 
 
 
 
309
 
310
+ RandomPortfolio['QBs'] = RandomPortfolio['QB'].map(maps_dict['Salary_map']).astype(np.int32)
311
+ RandomPortfolio['RB1s'] = RandomPortfolio['RB1'].map(maps_dict['Salary_map']).astype(np.int32)
312
+ RandomPortfolio['RB2s'] = RandomPortfolio['RB2'].map(maps_dict['Salary_map']).astype(np.int32)
313
+ RandomPortfolio['WR1s'] = RandomPortfolio['WR1'].map(maps_dict['Salary_map']).astype(np.int32)
314
+ RandomPortfolio['WR2s'] = RandomPortfolio['WR2'].map(maps_dict['Salary_map']).astype(np.int32)
315
+ RandomPortfolio['WR3s'] = RandomPortfolio['WR3'].map(maps_dict['Salary_map']).astype(np.int32)
316
+ RandomPortfolio['TEs'] = RandomPortfolio['TE'].map(maps_dict['Salary_map']).astype(np.int32)
317
+ RandomPortfolio['FLEXs'] = RandomPortfolio['FLEX'].map(maps_dict['Salary_map']).astype(np.int32)
318
+ RandomPortfolio['DSTs'] = RandomPortfolio['DST'].map(maps_dict['Salary_map']).astype(np.int32)
319
 
320
+ RandomPortfolio['QBp'] = RandomPortfolio['QB'].map(maps_dict['Projection_map']).astype(np.float16)
321
+ RandomPortfolio['RB1p'] = RandomPortfolio['RB1'].map(maps_dict['Projection_map']).astype(np.float16)
322
+ RandomPortfolio['RB2p'] = RandomPortfolio['RB2'].map(maps_dict['Projection_map']).astype(np.float16)
323
+ RandomPortfolio['WR1p'] = RandomPortfolio['WR1'].map(maps_dict['Projection_map']).astype(np.float16)
324
+ RandomPortfolio['WR2p'] = RandomPortfolio['WR2'].map(maps_dict['Projection_map']).astype(np.float16)
325
+ RandomPortfolio['WR3p'] = RandomPortfolio['WR3'].map(maps_dict['Projection_map']).astype(np.float16)
326
+ RandomPortfolio['TEp'] = RandomPortfolio['TE'].map(maps_dict['Projection_map']).astype(np.float16)
327
+ RandomPortfolio['FLEXp'] = RandomPortfolio['FLEX'].map(maps_dict['Projection_map']).astype(np.float16)
328
+ RandomPortfolio['DSTp'] = RandomPortfolio['DST'].map(maps_dict['Projection_map']).astype(np.float16)
329
 
330
+ RandomPortfolio['QBo'] = RandomPortfolio['QB'].map(maps_dict['Own_map']).astype(np.float16)
331
+ RandomPortfolio['RB1o'] = RandomPortfolio['RB1'].map(maps_dict['Own_map']).astype(np.float16)
332
+ RandomPortfolio['RB2o'] = RandomPortfolio['RB2'].map(maps_dict['Own_map']).astype(np.float16)
333
+ RandomPortfolio['WR1o'] = RandomPortfolio['WR1'].map(maps_dict['Own_map']).astype(np.float16)
334
+ RandomPortfolio['WR2o'] = RandomPortfolio['WR2'].map(maps_dict['Own_map']).astype(np.float16)
335
+ RandomPortfolio['WR3o'] = RandomPortfolio['WR3'].map(maps_dict['Own_map']).astype(np.float16)
336
+ RandomPortfolio['TEo'] = RandomPortfolio['TE'].map(maps_dict['Own_map']).astype(np.float16)
337
+ RandomPortfolio['FLEXo'] = RandomPortfolio['FLEX'].map(maps_dict['Own_map']).astype(np.float16)
338
+ RandomPortfolio['DSTo'] = RandomPortfolio['DST'].map(maps_dict['Own_map']).astype(np.float16)
339
 
340
+ RandomPortArray = RandomPortfolio.to_numpy()
341
+ del RandomPortfolio
 
342
 
343
+ RandomPortArray = np.c_[RandomPortArray, np.einsum('ij->i',RandomPortArray[:,10:19].astype(int))]
344
+ RandomPortArray = np.c_[RandomPortArray, np.einsum('ij->i',RandomPortArray[:,19:28].astype(np.double))]
345
+ RandomPortArray = np.c_[RandomPortArray, np.einsum('ij->i',RandomPortArray[:,28:37].astype(np.double))]
346
+
347
+ RandomPortArrayOut = np.delete(RandomPortArray, np.s_[10:37], axis=1)
348
+ RandomPortfolioDF = pd.DataFrame(RandomPortArrayOut, columns = ['QB', 'RB1', 'RB2', 'WR1', 'WR2', 'WR3', 'TE', 'FLEX', 'DST', 'User/Field', 'Salary', 'Projection', 'Own'])
349
+ RandomPortfolioDF = RandomPortfolioDF.sort_values(by=Sim_function, ascending=False)
350
+ del RandomPortArray
351
+ del RandomPortArrayOut
352
 
353
  if insert_port == 1:
354
+ CleanPortfolio['Salary'] = sum([CleanPortfolio['QB'].map(maps_dict['Salary_map']),
355
+ CleanPortfolio['RB1'].map(maps_dict['Salary_map']),
356
+ CleanPortfolio['RB2'].map(maps_dict['Salary_map']),
357
+ CleanPortfolio['WR1'].map(maps_dict['Salary_map']),
358
+ CleanPortfolio['WR2'].map(maps_dict['Salary_map']),
359
+ CleanPortfolio['WR3'].map(maps_dict['Salary_map']),
360
+ CleanPortfolio['TE'].map(maps_dict['Salary_map']),
361
+ CleanPortfolio['FLEX'].map(maps_dict['Salary_map']),
362
+ CleanPortfolio['DST'].map(maps_dict['Salary_map'])
363
+ ]).astype(np.int16)
364
+ if insert_port == 1:
365
+ CleanPortfolio['Projection'] = sum([CleanPortfolio['QB'].map(up_dict['Projection_map']),
366
+ CleanPortfolio['RB1'].map(up_dict['Projection_map']),
367
+ CleanPortfolio['RB2'].map(up_dict['Projection_map']),
368
+ CleanPortfolio['WR1'].map(up_dict['Projection_map']),
369
+ CleanPortfolio['WR2'].map(up_dict['Projection_map']),
370
+ CleanPortfolio['WR3'].map(up_dict['Projection_map']),
371
+ CleanPortfolio['TE'].map(up_dict['Projection_map']),
372
+ CleanPortfolio['FLEX'].map(up_dict['Projection_map']),
373
+ CleanPortfolio['DST'].map(up_dict['Projection_map'])
374
+ ]).astype(np.float16)
375
+ if insert_port == 1:
376
+ CleanPortfolio['Own'] = sum([CleanPortfolio['QB'].map(maps_dict['Own_map']),
377
+ CleanPortfolio['RB1'].map(maps_dict['Own_map']),
378
+ CleanPortfolio['RB2'].map(maps_dict['Own_map']),
379
+ CleanPortfolio['WR1'].map(maps_dict['Own_map']),
380
+ CleanPortfolio['WR2'].map(maps_dict['Own_map']),
381
+ CleanPortfolio['WR3'].map(maps_dict['Own_map']),
382
+ CleanPortfolio['TE'].map(maps_dict['Own_map']),
383
+ CleanPortfolio['FLEX'].map(maps_dict['Own_map']),
384
+ CleanPortfolio['DST'].map(maps_dict['Own_map'])
385
+ ]).astype(np.float16)
386
 
387
  if site_var1 == 'Draftkings':
388
+ RandomPortfolioDF = RandomPortfolioDF[RandomPortfolioDF['Salary'] <= 50000].reset_index(drop=True)
389
+ RandomPortfolioDF = RandomPortfolioDF[RandomPortfolioDF['Salary'] >= (49500 - (5000 * (1 - (len(Teams_used) / 32)))) - (FieldStrength * 1000)].reset_index(drop=True)
 
390
  elif site_var1 == 'Fanduel':
391
+ RandomPortfolioDF = RandomPortfolioDF[RandomPortfolioDF['Salary'] <= 60000].reset_index(drop=True)
392
+ RandomPortfolioDF = RandomPortfolioDF[RandomPortfolioDF['Salary'] >= (59500 - (5000 * (1 - (len(Teams_used) / 32)))) - (FieldStrength * 1000)].reset_index(drop=True)
393
 
394
+ RandomPortfolio = RandomPortfolioDF.sort_values(by=Sim_function, ascending=False)
 
 
395
 
396
+ RandomPortfolio = RandomPortfolio[['QB', 'RB1', 'RB2', 'WR1', 'WR2', 'WR3', 'TE', 'FLEX', 'DST', 'User/Field', 'Salary', 'Projection', 'Own']]
 
397
 
398
  return RandomPortfolio, maps_dict
399
 
400
  def get_uncorrelated_portfolio_for_sim(Total_Sample_Size):
401
 
402
+ sizesplit = round(Total_Sample_Size * (1-sharp_split))
403
+
404
  RandomPortfolio, maps_dict, ranges_dict, full_pos_player_dict = create_random_portfolio(sizesplit, raw_baselines)
405
+
406
+ RandomPortfolio['QB'] = pd.Series(list(RandomPortfolio['QB'].map(qb_dict)), dtype="string[pyarrow]")
407
+ RandomPortfolio['RB1'] = pd.Series(list(RandomPortfolio['RB1'].map(full_pos_player_dict['pos_dicts'][0])), dtype="string[pyarrow]")
408
+ RandomPortfolio['RB2'] = pd.Series(list(RandomPortfolio['RB2'].map(full_pos_player_dict['pos_dicts'][0])), dtype="string[pyarrow]")
409
+ RandomPortfolio['WR1'] = pd.Series(list(RandomPortfolio['WR1'].map(full_pos_player_dict['pos_dicts'][1])), dtype="string[pyarrow]")
410
+ RandomPortfolio['WR2'] = pd.Series(list(RandomPortfolio['WR2'].map(full_pos_player_dict['pos_dicts'][1])), dtype="string[pyarrow]")
411
+ RandomPortfolio['WR3'] = pd.Series(list(RandomPortfolio['WR3'].map(full_pos_player_dict['pos_dicts'][1])), dtype="string[pyarrow]")
412
+ RandomPortfolio['TE'] = pd.Series(list(RandomPortfolio['TE'].map(full_pos_player_dict['pos_dicts'][2])), dtype="string[pyarrow]")
413
+ RandomPortfolio['FLEX'] = pd.Series(list(RandomPortfolio['FLEX'].map(full_pos_player_dict['pos_dicts'][3])), dtype="string[pyarrow]")
414
+ RandomPortfolio['DST'] = pd.Series(list(RandomPortfolio['DST'].map(def_dict)), dtype="string[pyarrow]")
415
+ RandomPortfolio['plyr_list'] = RandomPortfolio[RandomPortfolio.columns.values.tolist()].values.tolist()
416
+ RandomPortfolio['plyr_count'] = RandomPortfolio['plyr_list'].apply(lambda x: len(set(x)))
417
+ RandomPortfolio = RandomPortfolio[RandomPortfolio['plyr_count'] == 10].drop(columns=['plyr_list','plyr_count']).\
418
+ reset_index(drop=True)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
419
 
420
+ del sizesplit
421
+ del full_pos_player_dict
422
+ del ranges_dict
 
 
 
 
 
 
 
 
 
423
 
424
+ RandomPortfolio['QBs'] = RandomPortfolio['QB'].map(maps_dict['Salary_map']).astype(np.int32)
425
+ RandomPortfolio['RB1s'] = RandomPortfolio['RB1'].map(maps_dict['Salary_map']).astype(np.int32)
426
+ RandomPortfolio['RB2s'] = RandomPortfolio['RB2'].map(maps_dict['Salary_map']).astype(np.int32)
427
+ RandomPortfolio['WR1s'] = RandomPortfolio['WR1'].map(maps_dict['Salary_map']).astype(np.int32)
428
+ RandomPortfolio['WR2s'] = RandomPortfolio['WR2'].map(maps_dict['Salary_map']).astype(np.int32)
429
+ RandomPortfolio['WR3s'] = RandomPortfolio['WR3'].map(maps_dict['Salary_map']).astype(np.int32)
430
+ RandomPortfolio['TEs'] = RandomPortfolio['TE'].map(maps_dict['Salary_map']).astype(np.int32)
431
+ RandomPortfolio['FLEXs'] = RandomPortfolio['FLEX'].map(maps_dict['Salary_map']).astype(np.int32)
432
+ RandomPortfolio['DSTs'] = RandomPortfolio['DST'].map(maps_dict['Salary_map']).astype(np.int32)
433
 
434
+ RandomPortfolio['QBp'] = RandomPortfolio['QB'].map(maps_dict['Projection_map']).astype(np.float16)
435
+ RandomPortfolio['RB1p'] = RandomPortfolio['RB1'].map(maps_dict['Projection_map']).astype(np.float16)
436
+ RandomPortfolio['RB2p'] = RandomPortfolio['RB2'].map(maps_dict['Projection_map']).astype(np.float16)
437
+ RandomPortfolio['WR1p'] = RandomPortfolio['WR1'].map(maps_dict['Projection_map']).astype(np.float16)
438
+ RandomPortfolio['WR2p'] = RandomPortfolio['WR2'].map(maps_dict['Projection_map']).astype(np.float16)
439
+ RandomPortfolio['WR3p'] = RandomPortfolio['WR3'].map(maps_dict['Projection_map']).astype(np.float16)
440
+ RandomPortfolio['TEp'] = RandomPortfolio['TE'].map(maps_dict['Projection_map']).astype(np.float16)
441
+ RandomPortfolio['FLEXp'] = RandomPortfolio['FLEX'].map(maps_dict['Projection_map']).astype(np.float16)
442
+ RandomPortfolio['DSTp'] = RandomPortfolio['DST'].map(maps_dict['Projection_map']).astype(np.float16)
443
 
444
+ RandomPortfolio['QBo'] = RandomPortfolio['QB'].map(maps_dict['Own_map']).astype(np.float16)
445
+ RandomPortfolio['RB1o'] = RandomPortfolio['RB1'].map(maps_dict['Own_map']).astype(np.float16)
446
+ RandomPortfolio['RB2o'] = RandomPortfolio['RB2'].map(maps_dict['Own_map']).astype(np.float16)
447
+ RandomPortfolio['WR1o'] = RandomPortfolio['WR1'].map(maps_dict['Own_map']).astype(np.float16)
448
+ RandomPortfolio['WR2o'] = RandomPortfolio['WR2'].map(maps_dict['Own_map']).astype(np.float16)
449
+ RandomPortfolio['WR3o'] = RandomPortfolio['WR3'].map(maps_dict['Own_map']).astype(np.float16)
450
+ RandomPortfolio['TEo'] = RandomPortfolio['TE'].map(maps_dict['Own_map']).astype(np.float16)
451
+ RandomPortfolio['FLEXo'] = RandomPortfolio['FLEX'].map(maps_dict['Own_map']).astype(np.float16)
452
+ RandomPortfolio['DSTo'] = RandomPortfolio['DST'].map(maps_dict['Own_map']).astype(np.float16)
453
 
454
+ RandomPortArray = RandomPortfolio.to_numpy()
455
+ del RandomPortfolio
 
456
 
457
+ RandomPortArray = np.c_[RandomPortArray, np.einsum('ij->i',RandomPortArray[:,10:19].astype(int))]
458
+ RandomPortArray = np.c_[RandomPortArray, np.einsum('ij->i',RandomPortArray[:,19:28].astype(np.double))]
459
+ RandomPortArray = np.c_[RandomPortArray, np.einsum('ij->i',RandomPortArray[:,28:37].astype(np.double))]
460
 
461
+ RandomPortArrayOut = np.delete(RandomPortArray, np.s_[10:37], axis=1)
462
+ RandomPortfolioDF = pd.DataFrame(RandomPortArrayOut, columns = ['QB', 'RB1', 'RB2', 'WR1', 'WR2', 'WR3', 'TE', 'FLEX', 'DST', 'User/Field', 'Salary', 'Projection', 'Own'])
463
+ RandomPortfolioDF = RandomPortfolioDF.sort_values(by=Sim_function, ascending=False)
464
+ del RandomPortArray
465
+ del RandomPortArrayOut
466
+ # st.table(RandomPortfolioDF.head(50))
467
+
468
  if insert_port == 1:
469
+ CleanPortfolio['Salary'] = sum([CleanPortfolio['QB'].map(maps_dict['Salary_map']),
470
+ CleanPortfolio['RB1'].map(maps_dict['Salary_map']),
471
+ CleanPortfolio['RB2'].map(maps_dict['Salary_map']),
472
+ CleanPortfolio['WR1'].map(maps_dict['Salary_map']),
473
+ CleanPortfolio['WR2'].map(maps_dict['Salary_map']),
474
+ CleanPortfolio['WR3'].map(maps_dict['Salary_map']),
475
+ CleanPortfolio['TE'].map(maps_dict['Salary_map']),
476
+ CleanPortfolio['FLEX'].map(maps_dict['Salary_map']),
477
+ CleanPortfolio['DST'].map(maps_dict['Salary_map'])
478
+ ]).astype(np.int16)
479
+ if insert_port == 1:
480
+ CleanPortfolio['Projection'] = sum([CleanPortfolio['QB'].map(up_dict['Projection_map']),
481
+ CleanPortfolio['RB1'].map(up_dict['Projection_map']),
482
+ CleanPortfolio['RB2'].map(up_dict['Projection_map']),
483
+ CleanPortfolio['WR1'].map(up_dict['Projection_map']),
484
+ CleanPortfolio['WR2'].map(up_dict['Projection_map']),
485
+ CleanPortfolio['WR3'].map(up_dict['Projection_map']),
486
+ CleanPortfolio['TE'].map(up_dict['Projection_map']),
487
+ CleanPortfolio['FLEX'].map(up_dict['Projection_map']),
488
+ CleanPortfolio['DST'].map(up_dict['Projection_map'])
489
+ ]).astype(np.float16)
490
+ if insert_port == 1:
491
+ CleanPortfolio['Own'] = sum([CleanPortfolio['QB'].map(maps_dict['Own_map']),
492
+ CleanPortfolio['RB1'].map(maps_dict['Own_map']),
493
+ CleanPortfolio['RB2'].map(maps_dict['Own_map']),
494
+ CleanPortfolio['WR1'].map(maps_dict['Own_map']),
495
+ CleanPortfolio['WR2'].map(maps_dict['Own_map']),
496
+ CleanPortfolio['WR3'].map(maps_dict['Own_map']),
497
+ CleanPortfolio['TE'].map(maps_dict['Own_map']),
498
+ CleanPortfolio['FLEX'].map(maps_dict['Own_map']),
499
+ CleanPortfolio['DST'].map(maps_dict['Own_map'])
500
+ ]).astype(np.float16)
501
 
502
  if site_var1 == 'Draftkings':
503
+ RandomPortfolioDF = RandomPortfolioDF[RandomPortfolioDF['Salary'] <= 50000].reset_index(drop=True)
504
+ RandomPortfolioDF = RandomPortfolioDF[RandomPortfolioDF['Salary'] >= (49500 - (5000 * (1 - (len(Teams_used) / 32)))) - (FieldStrength * 1000)].reset_index(drop=True)
 
505
  elif site_var1 == 'Fanduel':
506
+ RandomPortfolioDF = RandomPortfolioDF[RandomPortfolioDF['Salary'] <= 60000].reset_index(drop=True)
507
+ RandomPortfolioDF = RandomPortfolioDF[RandomPortfolioDF['Salary'] >= (59500 - (5000 * (1 - (len(Teams_used) / 32)))) - (FieldStrength * 1000)].reset_index(drop=True)
508
 
509
+ RandomPortfolio = RandomPortfolioDF.sort_values(by=Sim_function, ascending=False)
 
 
510
 
511
+ RandomPortfolio = RandomPortfolio[['QB', 'RB1', 'RB2', 'WR1', 'WR2', 'WR3', 'TE', 'FLEX', 'DST', 'User/Field', 'Salary', 'Projection', 'Own']]
 
512
 
513
  return RandomPortfolio, maps_dict
514