def optimize_lineup(df, good_list, alright_list, meh_list): optimizer = get_optimizer(Site.FANDUEL, Sport.BASKETBALL) optimizer.load_players_from_csv("fanduel.csv") df['name'] = df.apply(lambda row: (str.split(row['name'], ' Jr.')[0]), axis=1) for player in optimizer.players: if player.full_name in df['name'].unique(): projected_score = df.loc[ (df['name'] == player.full_name) & (df['team'] == NBA_TEAMS.find_NBA_abrev(player.team))][ 'Projected Score'].tolist() if len(projected_score) > 0: player.fppg = projected_score[0] else: player.fppg = 0 # print(f"{player.full_name:}{projected_score}") else: player.fppg = 0 optimizer.set_min_salary_cap(60000) optimizer.set_max_repeating_players(2) optimizer.add_stack(TeamStack(2, for_teams=good_list)) optimizer.add_stack(TeamStack(2, for_teams=alright_list)) optimizer.add_stack(TeamStack(1, for_teams=meh_list)) # for lineup in optimizer.optimize(n=50): # print(lineup) # print(lineup.players) # list of players # print(lineup.fantasy_points_projection) # print(lineup.salary_costs) exporter = CSVLineupExporter(optimizer.optimize(n=50)) exporter.export('lineups.csv') print("Lineups optimized and exported!")
def dk_lineup(request): import requests # check if most recent lineups were already created. from pydfs_lineup_optimizer import get_optimizer, Site, Sport, CSVLineupExporter project = os.environ["PROJECT_ID"] bucket = os.environ["BUCKET"] dataset_base = os.environ["DATASET_BASE"] dataset_dfs = os.environ["DATASET_DFS"] today = (datetime.now() - timedelta(hours=4)).strftime('%Y-%m-%d') request_json = request.get_json(silent=True) starting_lineups = "https://us-central1-{}.cloudfunctions.net/starting_lineups" r = requests.post(starting_lineups.format(project)) if request_json and "n_lineups" in request_json: n_lineups = int(request_json.get("n_lineups")) if n_lineups > 100: n_lineups = 100 else: n_lineups = 100 df = get_draftkings_predictions(project=project, dataset_base=dataset_base, dataset_dfs=dataset_dfs, dt=today.replace("-", "")) df.to_csv("/tmp/mlb_dk.csv", index=False) optimizer = get_optimizer(Site.DRAFTKINGS, Sport.BASEBALL) optimizer.load_players_from_csv("/tmp/mlb_dk.csv") exporter = CSVLineupExporter(optimizer.optimize(n_lineups)) exporter.export("/tmp/lineups.csv") # lineups = pd.DataFrame() # cols = ["pos", "first", "last", "position", "team", "opp", "fppg", "salary"] # i=1 # for lineup in optimizer.optimize(n=n_lineups): # lineup_list = lineup.printer.print_lineup(lineup).split("\n")[0:10] # lineup_df = pd.concat([pd.DataFrame(dict(zip(cols,re.split("\s{1,}",x.strip())[1:9])),index=[0]) # for x in lineup_list], axis=0, ignore_index=True) # lineup_df["lineup_number"] = i # i+=1 # lineups = pd.concat([lineups, lineup_df], ignore_index=True) # # # lineups.columns = ["pos", "first", "last", "position", "team", "opp", "projection", "salary", "lineup_number"] # lineups.to_csv("/tmp/lineups.csv", index=False) upload_blob(bucket_name=bucket, source_file_name="/tmp/lineups.csv", destination_blob_name="lineups/daily_dk_lineups.csv") upload_blob(bucket_name=bucket, source_file_name="/tmp/lineups.csv", destination_blob_name="lineups/mlb/dk_lineups_{}.csv".format( today.replace("-", ""))) lineup_link = "https://storage.cloud.google.com/{bucket}/lineups/daily_dk_lineups.csv" return lineup_link.format(bucket=bucket, dt=today.replace("-", ""))
def test_csv_exporter(self, mocked_open): filename = 'test.csv' CSVLineupExporter(self.lineups).export(filename) mocked_open.assert_called_once_with(filename, 'w') lineup = self.lineups[0] header = ','.join(['PG', 'SG', 'SF', 'PF', 'C', 'G', 'F', 'UTIL', 'Budget', 'FPPG']) + '\r\n' body = [CSVLineupExporter.render_player(player) for player in lineup.lineup] body.extend((str(lineup.salary_costs), str(lineup.fantasy_points_projection))) body = ','.join(body) + '\r\n' mocked_open.return_value.write.assert_any_call(header) mocked_open.return_value.write.assert_any_call(body)
def save_click(): init_dir = "" if (selected_sport.get() == 1): init_dir = '/home/pete/Documents/dk_lineups' elif (selected_sport.get() == 2): init_dir = '/home/pete/Documents/nhl/dk_lineups' results = filedialog.asksaveasfilename(initialdir=init_dir, title='Save File', initialfile='results.csv') LockPlayers() ExcludePlayers() exporter = CSVLineupExporter(optimizer.optimize(int(num_lineups.get()))) exporter.export(results) DraftKingsRefromatting(results) save_button.state(['disabled'])
"dsSalary", str(universe)]] players = list() for index, row in data.iterrows(): player = Player( row["draftstarsID"], row['playerName'].split(" ")[0], row['playerName'].split(" ")[1], [row['draftstarsPosition']] if str(row['draftstarsPosition2']) == "nan" else [row['draftstarsPosition'], row['draftstarsPosition2']], row["team"], row["dsSalary"], row[str(universe)] ) players.append(player) return players @staticmethod def _import_data(filename): data = pd.read_csv(filename) return data if __name__ == "__main__": generator = GenerateDraftstarsLineups() lineups = generator.process() lineup_generator = chain.from_iterable(lineups) exporter = CSVLineupExporter(lineup_generator) exporter.export("universeLineups.csv") print("CSV exported")
from pydfs_lineup_optimizer import get_optimizer, Site, Sport, CSVLineupExporter import pandas week = 'week4' tournament = 'thur-mon' csv_player_path = "/home/pete/Documents/dk_player_exports/WEEK/TOURNAMENT/DKSalaries_ffa.csv" lineups_file = "/home/pete/Documents/dk_lineups/WEEK/TOURNAMENT/results.csv" csv_player_path = csv_player_path.replace("WEEK", week).replace( "TOURNAMENT", tournament) lineups_file = lineups_file.replace("WEEK", week).replace("TOURNAMENT", tournament) optimizer = get_optimizer(Site.DRAFTKINGS, Sport.FOOTBALL) optimizer.load_players_from_csv(csv_player_path) number_of_lineups = 20 for lineup in optimizer.optimize(number_of_lineups): print(lineup) # print(lineup.players) # print(lineup.fantasy_points_projection) # print(lineup.salary_costs) exporter = CSVLineupExporter(optimizer.optimize(number_of_lineups)) exporter.export(lineups_file) # TODO: reformat the headers to match the approriate upload order for Draft Kings (QB, RB, RB, WR, WR, WR, TE, FLEX, DST)
SITE = Site.DRAFTKINGS elif platform == 'draftkings-showdown': SITE = Site.DRAFTKINGS_CAPTAIN_MODE elif platform == 'draftkings-tiers': SITE = Site.DRAFTKINGS_TIERS elif platform == 'fanduel': SITE = Site.FANDUEL # Sport if sport == 'nfl': SPORT = Sport.FOOTBALL elif sport == 'nba': SPORT = Sport.BASKETBALL # make optimizer # class CustomPuLPSolver(PuLPSolver): # LP_SOLVER = PULP_CBC_CMD(threads=8, options=['preprocess off'], msg=False) # LP_SOLVER = PULP_CHOCO_CMD() # define optimizer # optimizer = get_optimizer(site = SITE, sport = SPORT, solver=CustomPuLPSolver) optimizer = get_optimizer(site=SITE, sport=SPORT) optimizer.load_players_from_csv(input_string) optimizer.set_max_repeating_players(int(maxrepplyr)) # export exporter = CSVLineupExporter( optimizer.optimize(n=int(nlineups), max_exposure=float(maxexp))) output_string = str( input_string[:input_string.rfind('/') + 1]) + 'optimized.csv' exporter.export(output_string)
optimizer = get_optimizer(Site.DRAFTKINGS_CAPTAIN_MODE, Sport.FOOTBALL) optimizer.load_players_from_csv("DKSalaries1pmshowdown.csv") #optimizer.add_stack(TeamStack(3)) #optimizer.add_stack(TeamStack(3, for_positions=['QB', 'WR'])) #optimizer.add_stack(PositionsStack(['QB', 'WR', 'WR'])) #optimizer.force_positions_for_opposing_team(('QB', 'WR')) #optimizer.restrict_positions_for_same_team(('RB', 'RB')) #optimizer.restrict_positions_for_opposing_team(['QB'], ['DST']) optimizer.set_deviation(0.05, 0.3) optimizer.set_max_repeating_players(5) for player in optimizer.players: if player.fppg < 1: optimizer.remove_player(player) #mekale = optimizer.get_player_by_name('Phillip Walker') #optimizer.add_player_to_lineup(mekale) #dc_wrs = [] #for name in ['Eli Rogers', 'Rashad Ross', 'Deandre Thompkins', 'Malachi Dupre']: # for p in optimizer.find_players(name): # dc_wrs.append(p) #group = PlayersGroup(dc_wrs, min_from_group=1) #optimizer.add_stack(Stack([cardale, group])) optimizer.restrict_positions_for_opposing_team(['K'], ['K']) exporter = CSVLineupExporter( optimizer.optimize(LINES, randomness=True, generate_exposures=True)) exporter.export('result1pm.csv') optimizer.player_exposures.write_exposures_csv(total_lineups=LINES, csv_filename='exposures1pm.csv')
# to lock in players if (i % (1 + len(player_include))) > 0: player = optimizer.get_player_by_name( player_include[-1 + (i % (1 + len(player_include)))] ) # find player with specified name in your optimizer #second_player = optimizer.get_player_by_id('12864605') # find player with player id optimizer.add_player_to_lineup(player) # lock this player in lineup #optimizer.add_player_to_lineup(second_player) if (math.floor(i / (1 + len(player_include))) > 0): player = optimizer.get_player_by_name( player_exclude[math.floor(-1 + (i / (1 + len(player_include))))]) optimizer.remove_player(player) #optimizer.restore_player(player) if i == 0: exporter = CSVLineupExporter(optimizer.optimize(lineups)) else: exporter = JohnCSVLineupExporter(optimizer.optimize(lineups)) exporter.export(resultlocation) #%% for lineup in optimizer.optimize(n=1): print(lineup) print(lineup.players) # list of players print(lineup.fantasy_points_projection) print(lineup.salary_costs) #%% #put in right format from pydfs_lineup_optimizer import get_optimizer, Site, Sport, CSVLineupExporter import pandas import math
def create_optimizer(request): if request.method == 'POST': form = OptimizerForm(request.POST) form2 = SlateForm(request.POST) if form2.is_valid() and 'change_slate' in request.POST: slate = form2.cleaned_data['slate'] form = OptimizerForm() form2 = SlateForm(initial={'slate': slate}) df = get_daily_roster( Path( '//home/ubuntu/Fantasy-Fire/website/optimizer/prediction.csv' )) # df = create_predictions(df) df = create_predictions( df, slate=Path( '//home/ubuntu/Fantasy-Fire/website/optimizer/Slates/' + slate + '.csv')) df['Min Exposure'] = 0 df['Max Exposure'] = 1 df['Value'] = round(df['Predicted_FP'] / (df['Salary'] / 1000), 2) df.insert(0, "Include", '', True) for ind in df.index: df['Predicted_FP'][ ind] = "<input type='number' step='any' form='optimizer' name='fantasy_points_" + str( ind) + "' value=" + str( round(df['Predicted_FP'][ind], 2)) + " id='id_predicted_fp'>" # df['Predicted FP'] = df['Predicted FP'].apply(lambda x: round(float(x), 2)) # df['Predicted FP'] = df['Predicted FP'].apply( # lambda x: "<input type='text' form='optimizer' name='fantasy_points_" + df['Name'] + "' value=" + str( # x) + " id='id_predicted_fp'>") df['Min Exposure'][ ind] = "<input type='number' step='any' name='min_exposure_" + str( ind) + "' value=" + str(0) + ">" df['Max Exposure'][ ind] = "<input type='number' step='any' name='max_exposure_" + str( ind) + "' value=" + str(1) + ">" df['Include'][ ind] = "<input type='checkbox' id='child' name='include_" + str( ind) + "' checked>" df = df[[ 'Include', 'Name', 'ID', 'Roster Position', 'Salary', 'TeamAbbrev', 'Opp', 'Predicted_FP', 'Min Exposure', 'Max Exposure', 'Value' ]] df.rename(columns={ 'Include': "<input type='checkbox' id='parent' onclick='checkAll()' checked>" }, inplace=True) html_table = df.to_html( index=False, justify='left', escape=False, table_id='slateData', classes=[ 'table w3-table-all table-bordered table-striped table-hover table-responsive table-sm searchable sortable tablesorter tablesorter-default, container-fluid' ]) return render( request, 'optimizer/optimizer.html', { 'form': form, 'player_table': html_table, 'form2': form2, 'slate': slate }) if form.is_valid(): slate = form2.cleaned_data['slate'] min_salary = form.cleaned_data['min_salary'] max_exposure = form.cleaned_data['max_exposure'] no_lineups = form.cleaned_data['no_lineups'] deviation = form.cleaned_data['deviation'] generation_type = form.cleaned_data['generation_type'] with_replacement = form.cleaned_data['with_replacement'] if "Showdown" in slate: optimizer = get_optimizer(Site.DRAFTKINGS_CAPTAIN_MODE, Sport.BASKETBALL) else: optimizer = get_optimizer(Site.DRAFTKINGS, Sport.BASKETBALL) df = pd.read_csv( Path("//home/ubuntu/Fantasy-Fire/website/optimizer/Slates/" + slate + ".csv")) df2 = pd.read_csv( Path( r"//home/ubuntu/Fantasy-Fire/website/optimizer/prediction.csv" )) result = df.merge(df2, left_on='Name', right_on='name', how='left') # result = result.drop( # columns=['AvgPointsPerGame']) result = result.fillna(0) includes = [] fantasy_points = [] min_exposures = [] max_exposures = [] deviations = [] for key, value in request.POST.items(): if 'include' in key: includes.append(key) elif 'fantasy_points' in key: fantasy_points.append(value) elif 'min_exposure' in key: min_exposures.append(value) elif 'max_exposure' in key: max_exposures.append(value) elif 'deviation' in key: deviations.append(value) result['Min Exposure'] = 0 result['Max Exposure'] = 1 for ind in result.index: result['AvgPointsPerGame'][ind] = fantasy_points[ind] if int(max_exposure) != int(max_exposures[ind]) and int( max_exposures[ind]) > 1: result['Max Exposure'][ind] = int(max_exposures[ind]) / 100 result['Min Exposure'][ind] = int(min_exposures[ind]) / 100 # result = result.rename(columns={'max_exposure': 'Max Exposure', 'min_exposure': 'Min Exposure'}) result.to_csv( Path( "//home/ubuntu/Fantasy-Fire/website/optimizer/Predictions.csv" )) optimizer.load_players_from_csv( Path( '//home/ubuntu/Fantasy-Fire/website/optimizer/Predictions.csv' )) optimizer.set_deviation(0, int(deviation) / 100) optimizer.set_min_salary_cap(min_salary) for player in optimizer.players: id = player.id playa = optimizer.get_player_by_id(id) optimizer.remove_player(playa) for i in includes: id = str(result['ID'][int(i[i.find('_') + 1:])]) player = optimizer.get_player_by_id(id) optimizer.restore_player(player) exporter = CSVLineupExporter( optimizer.optimize(no_lineups, randomness=generation_type, with_replacement=with_replacement, max_exposure=max_exposure / 100)) exporter.export( Path('//home/ubuntu/Fantasy-Fire/website/optimizer/lineups.csv' )) with open( '//home/ubuntu/Fantasy-Fire/website/optimizer/lineups.csv' ) as myfile: response = HttpResponse(myfile, content_type='text/csv') response[ 'Content-Disposition'] = 'attachment; filename=lineups.csv' return response else: form = OptimizerForm() form2 = SlateForm(initial={'slate': 'Main_Slate'}) df = get_daily_roster( Path( '//home/ubuntu/Fantasy-Fire/website/optimizer/prediction.csv')) # df = create_predictions(df) df = create_predictions( df, slate=Path( '//home/ubuntu/Fantasy-Fire/website/optimizer/Slates/Main_Slate.csv' )) df['Min Exposure'] = 0 df['Max Exposure'] = 1 df['Value'] = round(df['Predicted_FP'] / (df['Salary'] / 1000), 2) df.insert(0, "Include", '', True) for ind in df.index: df['Predicted_FP'][ ind] = "<input type='number' step='any' form='optimizer' name='fantasy_points_" + str( ind) + "' value=" + str(round( df['Predicted_FP'][ind], 2)) + " id='id_predicted_fp'>" # df['Predicted FP'] = df['Predicted FP'].apply(lambda x: round(float(x), 2)) # df['Predicted FP'] = df['Predicted FP'].apply( # lambda x: "<input type='text' form='optimizer' name='fantasy_points_" + df['Name'] + "' value=" + str( # x) + " id='id_predicted_fp'>") df['Min Exposure'][ ind] = "<input type='number' step='any' name='min_exposure_" + str( ind) + "' value=" + str(0) + ">" df['Max Exposure'][ ind] = "<input type='number' step='any' name='max_exposure_" + str( ind) + "' value=" + str(1) + ">" df['Include'][ ind] = "<input type='checkbox' id='child' name='include_" + str( ind) + "' checked>" df = df[[ 'Include', 'Name', 'ID', 'Roster Position', 'Salary', 'TeamAbbrev', 'Opp', 'Predicted_FP', 'Min Exposure', 'Max Exposure', 'Value' ]] df.rename(columns={ 'Include': "<input type='checkbox' id='parent' onclick='checkAll()' checked>" }, inplace=True) # df['Value'] = df['Predicted_FP'] / (df['Salary'] / 1000) html_table = df.to_html( index=False, justify='left', escape=False, table_id='slateData', classes=[ 'table w3-table-all table-bordered table-striped table-hover table-responsive table-sm searchable sortable tablesorter tablesorter-default, container-fluid' ]) # 'table table-bordered table-striped']) return render( request, 'optimizer/optimizer.html', { 'form': form, 'player_table': html_table, 'form2': form2, 'slate': 'Main_Slate' })
# for lineup in optimizer.optimize(n=10, randomness=True): # optimizer.add_player_to_lineup(drummond) # lock this player in lineup # optimizer.add_player_to_lineup(curry) # lock this player in lineup # optimizer.add_player_to_lineup(gordon) # optimizer.add_player_to_lineup(robinson) # # optimizer.remove_player_from_lineup(player1) # optimizer.remove_player(burks) # optimizer.restore_player(player2) # player1.max_exposure = 0.5 # set max exposure # young.min_exposure = 0.3 # set min exposure # gordon.min_exposure = 0.6 # set min exposure # harden.min_exposure = 0.1 # curry.min_exposure = 0.7 # draymond.fppg = 100 # chriss.min_exposure = 0.1 # robinson.min_exposure = 0.3 # reddish.fppg = 19 # print(lineup) # print(lineup.players) # list of players # print(lineup.fantasy_points_projection) # print(lineup.salary_costs) optimizer.set_deviation(0, 0.1) # changing defaults of 0.06 and 0.12 optimizer.set_min_salary_cap(49500) # optimizer.set_max_repeating_players(5) #restricts how many unique players each team must have # optimizer.set_team_stacking([3, 3]) #in this case, two teams must have at least 3 players present # optimizer.set_players_from_one_team({'GS': 2, 'LAC': 2}) exporter = CSVLineupExporter(optimizer.optimize(300, randomness=True)) exporter.export( r'C:\Users\Charlie\Documents\GitHub\Fantasy-Fire\website\optimizer\lineups.csv' )