Ejemplo n.º 1
0
def test_deterministic_exposure_limits():
    iterations = 2
    players = salary_download.generate_players_from_csvs(
        salary_file_location=salary_file,
        projection_file_location=projection_file,
        game=rules.DRAFT_KINGS,
    )
    rosters, exposure_diffs = run_multi(iterations=2,
                                        rule_set=rules.DK_NFL_RULE_SET,
                                        player_pool=players,
                                        exposure_bounds=[
                                            {
                                                'name': 'Andrew Luck',
                                                'min': 0.5,
                                                'max': 0.7
                                            },
                                            {
                                                'name': 'Alshon Jeffery',
                                                'min': 1,
                                                'max': 1
                                            },
                                        ])
    ntools.assert_equal(len(rosters), iterations)
    ntools.assert_equal(len(exposure_diffs), 0)

    players = [p.name for p in rosters[0].players]
    ntools.assert_true('Andrew Luck' in players)
    ntools.assert_true('Alshon Jeffery' in players)

    players = [p.name for p in rosters[1].players]
    ntools.assert_true('Andrew Luck' not in players)
    ntools.assert_true('Alshon Jeffery' in players)
Ejemplo n.º 2
0
def test_random_exposure_limits():
    iterations = 10
    players = salary_download.generate_players_from_csvs(
        salary_file_location=salary_file,
        projection_file_location=projection_file,
        game=rules.DRAFT_KINGS,
    )
    rosters, exposure_diffs = run_multi(
        iterations=iterations,
        exposure_random_seed=42,
        rule_set=rules.DK_NFL_RULE_SET,
        player_pool=players,
    )
    ntools.assert_equal(len(rosters), iterations)
    ntools.assert_equal(len(exposure_diffs), 0)
Ejemplo n.º 3
0
def Optimize(date, top_k, slate_id, projection_source = 'rotogrinders'):
	projections_path = GetMetaDataPath() + '/rotogrinders/projections/%s.csv' % (date)
	if not os.path.exists(projections_path):
		print("projections for %s not exists" % date)
		return
	projections = pd.read_csv(projections_path, header = 0, index_col = 0)

	slates_path = GetMetaDataPath() + '/draftkings/slates/%s.csv' % (date)
	if not os.path.exists(slates_path):
		print("slates for %s not exists" % date)
		return
	slates = pd.read_csv(slates_path, header = 0, index_col = 0)

	if slate_id not in slates['SLATE_ID'].tolist():
		print("slate %d not exist!" % slate_id)
		return
	if slates[slates['SLATE_ID'] == slate_id]['SLATE_TYPE'].values[0] != 'CLASSIC':
		print("slate type %s not supported!" % slate_type)
		return

	players_path = GetMetaDataPath() + '/draftkings/players/%s.csv' % (date)
	players = pd.read_csv(players_path, header = 0, index_col = 0)
	players = players[players['SLATE_ID'] == slate_id]
	players.set_index('NAME', inplace=True)

	players_with_projection = projections.join(players, how='inner')

	player_pool = []
	for name, data in players_with_projection.iterrows():
		for pos in data['POSITION'].split('/'):
			player_pool.append(Player(
								name=name,
								cost=data['SALARY'],
								proj=data['PROJECTION'],
								pos=pos,
								possible_positions=data['POSITION'],
								multi_position='/' in data['POSITION'],
								team=data['TEAM'],
								matchup=data['GAME_INFO'],
								average_score=data['DKP'],))

	roster = run_multi(
		iterations=top_k,
		rule_set=rules.DK_NBA_RULE_SET,
		player_pool=player_pool,
		verbose=True,
	)
Ejemplo n.º 4
0
    def _generate_rosters(self) -> Roster:

        players = self._generate_players()
        custom_rules = self._set_additional_rules()

        try:
            constraints, exposures, optimizers = self._compile_params()
        except NameError as e:
            raise ("Constrains error {}".format(e))
        try:
            return run_multi(
                iterations=self.entries,
                exposure_bounds=exposures,
                rule_set=custom_rules,
                player_pool=players,
                optimizer_settings=optimizers,
                constraints=constraints,
                verbose=True,
            )
        except InvalidBoundsException as e:
            raise ("Error: {}".format(e))
Ejemplo n.º 5
0
def optimizeJSON(payload):
    raw = pd.read_json((payload["raw"]))
    data = pd.read_json((payload["posted"]))
    optimizer = None
    if (payload["site"] == "DRAFTKINGS"):
        if (payload["sport_type"] == "PGA"):
            optimizer = get_optimizer(Site.DRAFTKINGS, Sport.GOLF)
        elif (payload["sport_type"] == "NFL"):
            optimizer = get_optimizer(Site.DRAFTKINGS, Sport.FOOTBALL)
        else:
            optimizer = get_optimizer(Site.DRAFTKINGS, Sport.BASKETBALL)
        raw['AvgPointsPerGame'] = raw[payload["projection"]]
        raw['AvgPointsPerGame'] = pd.to_numeric(raw["AvgPointsPerGame"]).fillna(0)
    else:
        if (payload["sport_type"] != "PGA"):
            optimizer = get_optimizer(Site.FANDUEL, Sport.FOOTBALL)
        if (payload["sport_type"] == "NBA"):
            optimizer = get_optimizer(Site.FANDUEL, Sport.BASKETBALL)
        raw['FPPG'] = raw[payload["projection"]]
        raw['FPPG'] = pd.to_numeric(raw["FPPG"]).fillna(0)
        raw['First Name'] = raw['Name']
        raw['Last Name'] = raw['Name']
        raw['Nickname'] = raw['Name']
        raw["Injury Indicator"] = ""
        raw['Team'] = raw['TeamAbbrev']
    # if os.path.exists("lineup.csv"):
        # os.remove("lineup.csv")
    lineup_writer = open('/home/johnh/lineup.csv', 'w+')
    lineup_writer.close()
    raw.to_csv("/home/johnh/lineup.csv")

    del raw
     
    if payload["site"] == "FANDUEL" and payload["sport_type"] == "PGA":
        
        players = salary_download.generate_players_from_csvs(
            salary_file_location='/home/johnh/lineup.csv',
            game=rules.FAN_DUEL,
        )
        
        iterations=payload["lineups"]
        index = 0
        exposure_players = []
        locked = []
        removed = []

        for r in data["Name"]:
            if (data["Lock"][index] == 0) and (data["Remove"][index] == 0):
                exp_player = {}
                exp_player["name"] = r
                exp_player["min"] = 0.1
                exp_player["max"] = data["Exposure"][index] / 100.0
                exposure_players.append(exp_player)
            if (data["Lock"][index] == 1) and (data["Remove"][index] == 0):
                locked.append(data["Name"][index])
            if (data["Lock"][index] == 0) and (data["Remove"][index] == 1):
                removed.append(data["Name"][index])
            index = index + 1
        
        rosters, exposure_diffs  = run_multi(
            iterations=iterations,
            rule_set=rules.FD_PGA_RULE_SET,
            player_pool=players,
            exposure_bounds=exposure_players,
            constraints=LineupConstraints(
                locked=locked,
                banned=removed
            )
        )
               
        ntools.assert_equal(len(rosters), iterations)
        ntools.assert_equal(len(exposure_diffs), 0)

        lineups = []
        exports = []
        exports.append(["G","G","G","G","G","G","Budget","FPPG"])
        for r in rosters:
            export = []
            for p in r.sorted_players():
                lineup = []
                lineup.append("G")
                lineup.append(p.name)
                lineup.append(p.team)
                lineup.append(p.proj)
                lineup.append(p.cost)
                lineups.append(lineup)
                name_index = list(data["Name"]).index(p.name)
                export.append(data["ID"][name_index] + ":" + p.name)
            total = ["", "", ""]
            total.append("{0:.2f}".format(round(r.projected(),2)))
            total.append(r.spent())
            lineups.append(total)
            exports.append(export)
        
        del lineups
        del exports
        del total
        del iterations
        del exposure_players
        del locked
        del removed

        result = {"lineups": lineups,
                  "export": exports}
        return result

    optimizer.load_players_from_csv("/home/johnh/lineup.csv")

    # advanced options (lock, remove and exposure)
    
    for index, row in data.iterrows():

        if (row['Remove'] == 1):
            print("Removing player: " + row['Name'], row['Remove'])
            player = optimizer.get_player_by_id(row['ID'])
            optimizer.remove_player(player)
        if (row['Lock'] == 1):
            print("Lock player: " + row['Name'], row['Remove'])
            player = optimizer.get_player_by_id(row['ID'])
            optimizer.add_player_to_lineup(player)
        if ((row['Exposure'] >= 0) and (row['Exposure'] < 100)):
            #print("Set exposure : " + row['Name'], row['Exposure'] / 100.0)
            player = optimizer.get_player_by_id(row['ID'])
            #print(player)
            player.max_exposure = row['Exposure'] / 100.0
    if (payload["sport_type"] == "NFL") and (payload["site"] == "DRAFTKINGS"):
        optimizer.set_min_salary_cap(49500)        
    lineupGenerator = optimizer.optimize(payload["lineups"])

    def render_player(player):
        # type: (LineupPlayer) -> str
        result = player.full_name
        #print player.id
        if player.id:
            # if payload["site"] == "FANDUEL" and payload["sport_type"] == "NFL":
                # result = player.id + ":" + result
            # else:
            result += '(%s)' % player.id
        return result

    rows = []
    header = None
    print(lineupGenerator)
    for index, lineup in enumerate(lineupGenerator):
        if index == 0:
            header = [player.lineup_position for player in lineup.lineup]
            header.extend(('Budget', 'FPPG'))
        row = [(render_player)(player) for player in lineup.lineup]
        row.append(str(lineup.salary_costs))
        row.append(str(lineup.fantasy_points_projection))
        rows.append(row)

    data = pd.DataFrame.from_records(rows, columns = header)

    lineups = pd.DataFrame()

    names = []
    positions = []
    teams = []
    fppgs = []
    salaries = []

    # add number to duplicate cols
    def rename_duplicates(old):
        new = []
        seen = {}
        for x in old:
            if x in seen:
                seen[x] += 1
                new.append( "%s_%d" % (x, seen[x]))
            else:
                seen[x] = 0
                new.append(x)
        return new

    data.columns = rename_duplicates(list(data.columns))

    for index, row in data.iterrows():
        for player in data.columns[:-2]:
            playerName = row[player].split("(")[0]
            names.append(playerName)
            positions.append(player)
            player = optimizer.get_player_by_name(playerName)
            fppgs.append(player.fppg)
            teams.append(player.team)
            salaries.append(player.salary)
        positions.append("Totals")
        names.append("")
        teams.append("")
        fppgs.append(row["FPPG"])
        salaries.append(row["Budget"])

        positions.append("")
        names.append("")
        teams.append("")
        fppgs.append("")
        salaries.append("")

        # print row["PG"]

    lineups["Positions"] = positions
    lineups["Name"] = names
    lineups["Team"] = teams
    lineups["Projection"] = fppgs
    lineups["salaries"] = salaries

    result = {"lineups": lineups.values.tolist(),
              "export": [list(data.columns)] + data.values.tolist()}
    
    del payload
    
    return jsonify(result)
Ejemplo n.º 6
0
from draftfast.lineup_contraints import LineupConstraints

import csv

player_pool = []

with open('input.csv') as inputfile:
    csvreader = csv.reader(inputfile)
    isHeader = True
    for row in csvreader:
        if isHeader:
            minSalary = float(row[0])
            maxSalary = float(row[1])
            lineups = int(row[2])
            isHeader = False
        else:
            player = Player(name=row[1] + '(' + row[0] + ')', cost=float(row[2]), proj=float(row[5]), pos='D')
            player_pool.append(player)


player_settings = PlayerPoolSettings(min_salary=minSalary, max_salary=maxSalary)

rosters = run_multi(lineups, rule_set=rules.FD_NASCAR_RULE_SET, player_pool=player_pool, verbose=True)

with open('output.csv', 'w') as outputfile:
    csvwriter = csv.writer(outputfile)
    for roster in rosters[0]:
        players = roster.players
        cost = players[0].cost + players[1].cost + players[2].cost + players[3].cost + players[4].cost + players[5].cost
        csvwriter.writerow([players[0].name, players[1].name, players[2].name, players[3].name, players[4].name, players[5].name, cost])
Ejemplo n.º 7
0
  the filenames listed in the script.
"""
downloads = environ.get('downloads')
players = salary_download.generate_players_from_csvs(
    salary_file_location='{}/NBA_SALS.csv'.format(downloads),
    projection_file_location='{}/NBA_PROJECTIONS.csv'.format(downloads),
    game=rules.DRAFT_KINGS,
)

rosters, _ = run_multi(
    iterations=20,
    exposure_bounds=[
        {
            'name': 'Damian Lillard',
            'min': 0.3,
            'max': 0.5,
        },
        {
            'name': 'LaMarcus Aldridge',
            'min': 0.5,
            'max': 0.7,
        },
    ],
    rule_set=rules.DK_NBA_RULE_SET,
    player_pool=players,
    verbose=True,
)

uploader = uploaders.DraftKingsNBAUploader(
    pid_file='{}/NBA_PIDS.csv'.format(downloads), )
uploader.write_rosters(rosters)