def optimize(all_players: list, player_settings: PlayerPoolSettings = PlayerPoolSettings(), constraints: LineupConstraints = LineupConstraints()): lineup_players = [] all_players = list( filter(add_pickem_contraints(player_settings), all_players)) if constraints.has_group_constraints(): raise NotImplementedError('Groups are not supported for pickem') for p in all_players: if constraints.is_banned(p.name): p.ban = True for t in TIERS: best = sorted( [p for p in all_players if p.tier == t and not p.ban], key=lambda p: p.proj, reverse=True, )[0] lineup_players.append(best) lineup = TieredLineup(lineup_players) for p in all_players: if constraints.is_locked(p.name): p.lock = True setattr(lineup, p.tier, p) return lineup
def run_multi( iterations: int, rule_set: RuleSet, player_pool: list, constraints: LineupConstraints = LineupConstraints(), player_settings: PlayerPoolSettings = PlayerPoolSettings(), optimizer_settings: OptimizerSettings = OptimizerSettings(), verbose=False, exposure_bounds: List[dict] = list(), exposure_random_seed=None, ) -> [List[Roster], list]: # set the random seed globally for random lineup exposure random.seed(exposure_random_seed) rosters = [] for _ in range(0, iterations): exposure_dict = get_exposure_args( existing_rosters=optimizer_settings.existing_rosters, exposure_bounds=exposure_bounds, n=iterations, use_random=bool(exposure_random_seed), random_seed=exposure_random_seed, ) roster = run( rule_set=rule_set, player_pool=player_pool, optimizer_settings=optimizer_settings, player_settings=player_settings, exposure_dict=exposure_dict, constraints=constraints, verbose=verbose, ) if roster: optimizer_settings.existing_rosters += [roster] if roster: rosters.append(roster) else: break # clear ban/lock to reset exposure between iterations reset_player_ban_lock(player_pool) exposure_diffs = {} if rosters and verbose: print(get_exposure_table(rosters, exposure_bounds)) print() print(get_exposure_matrix(rosters)) print() exposure_diffs = check_exposure(rosters, exposure_bounds) for n, d in exposure_diffs.items(): if d < 0: print('{} is UNDER exposure by {} lineups'.format(n, d)) else: print('{} is OVER exposure by {} lineups'.format(n, d)) return rosters, exposure_diffs
def test_banned_players(): players = _generate_test_player_data() optimized = optimize(players, player_settings=PlayerPoolSettings(), constraints=LineupConstraints(banned=['A', 'C'])) ntools.assert_equal(optimized.total, 49 + 47 + 46 + 44 + 42 + 40)
def test_force_combo(): # no combo players = salary_download.generate_players_from_csvs( salary_file_location=salary_file, projection_file_location=projection_file, game=rules.DRAFT_KINGS, ) roster = run(rule_set=rules.DK_NFL_RULE_SET, player_pool=players, player_settings=PlayerPoolSettings(locked=['Sam Bradford'], ), optimizer_settings=OptimizerSettings( stack_team='NE', stack_count=5, )) qb = roster.sorted_players()[0] team_count = len([x for x in roster.sorted_players() if x.team == qb.team]) ntools.assert_equals(team_count, 1) # QB/WR combo players = salary_download.generate_players_from_csvs( salary_file_location=salary_file, projection_file_location=projection_file, game=rules.DRAFT_KINGS, ) roster = run(rule_set=rules.DK_NFL_RULE_SET, player_pool=players, optimizer_settings=OptimizerSettings(force_combo=True, )) qb = roster.sorted_players()[0] ntools.assert_equal(qb.pos, 'QB')
def test_respects_locked(): pool = filter_pool(mock_player_pool, PlayerPoolSettings( locked=['A2'], min_proj=31, )) ntools.assert_equals(pool, [p_b, p_c])
def optimize(all_players, player_settings=PlayerPoolSettings(), pickem_settings=PickemSettings()): lineup_players = [] all_players = list( filter(add_pickem_contraints(player_settings), all_players)) for t in TIERS: best = sorted( [p for p in all_players if p.tier == t], key=lambda p: p.proj, reverse=True, )[0] lineup_players.append(best) lineup = TieredLineup(lineup_players) locked = pickem_settings.locked if locked: for lock in locked: player_lock = _get_player(lock, all_players) player_lock.locked = True setattr( lineup, player_lock.tier, player_lock, ) return lineup
def run_multi( iterations: int, rule_set: RuleSet, player_pool: list, player_settings=PlayerPoolSettings(), optimizer_settings=OptimizerSettings(), verbose=False, exposure_bounds=None, exposure_random_seed=None, ) -> [List[Roster], list]: # set the random seed globally for random lineup exposure if exposure_random_seed: random.seed(exposure_random_seed) rosters = [] for _ in range(0, iterations): if exposure_bounds: exposure_dct = get_exposure_args( existing_rosters=optimizer_settings.existing_rosters, exposure_bounds=exposure_bounds, n=iterations, use_random=bool(exposure_random_seed), random_seed=exposure_random_seed, ) player_settings.banned = exposure_dct['banned'] player_settings.locked = exposure_dct['locked'] roster = run( rule_set=rule_set, player_pool=player_pool, optimizer_settings=optimizer_settings, player_settings=player_settings, verbose=verbose, ) if roster: optimizer_settings.existing_rosters += [roster] if roster: rosters.append(roster) else: break exposure_diffs = {} if rosters and verbose: print(get_exposure_table(rosters, exposure_bounds)) print() print(get_exposure_matrix(rosters)) print() exposure_diffs = check_exposure(rosters, exposure_bounds) for n, d in exposure_diffs.items(): if d < 0: print('{} is UNDER exposure by {} lineups'.format(n, d)) else: print('{} is OVER exposure by {} lineups'.format(n, d)) return rosters, exposure_diffs
def test_no_double_te(): players = salary_download.generate_players_from_csvs( salary_file_location=salary_file, projection_file_location=projection_file, game=rules.DRAFT_KINGS, ) roster = run(rule_set=rules.DK_NFL_RULE_SET, player_pool=players, player_settings=PlayerPoolSettings(locked=['Rob Gronkowski'])) qb = roster.sorted_players()[0] ntools.assert_equal(qb.pos, 'QB')
def test_soccer_dk_no_opp_d(): player_pool = salary_download.generate_players_from_csvs( salary_file_location=salary_file, game=rules.DRAFT_KINGS, ) roster = run( rule_set=rules.DK_SOCCER_RULE_SET, player_pool=player_pool, player_settings=PlayerPoolSettings(locked=['Maxi Gomez'], ), optimizer_settings=OptimizerSettings( no_offense_against_defense=False, ), verbose=True, ) cel_off_players = [ p for p in roster.players if p.team == 'CEL' and p.pos in ['M', 'F'] ] lgn_d_players = [ p for p in roster.players if p.team == 'LGN' and p.pos in ['D', 'GK'] ] ntools.assert_equal(len(cel_off_players), 2) ntools.assert_equal(len(lgn_d_players), 2) roster = run( rule_set=rules.DK_SOCCER_RULE_SET, player_pool=player_pool, player_settings=PlayerPoolSettings(locked=['Maxi Gomez'], ), optimizer_settings=OptimizerSettings( no_offense_against_defense=True, ), verbose=True, ) cel_off_players = [ p for p in roster.players if p.team == 'CEL' and p.pos in ['M', 'F'] ] lgn_d_players = [ p for p in roster.players if p.team == 'LGN' and p.pos in ['D', 'GK'] ] ntools.assert_equal(len(cel_off_players), 2) ntools.assert_equal(len(lgn_d_players), 0)
def test_multi_position(): players = salary_download.generate_players_from_csvs( salary_file_location=salary_file, projection_file_location=projection_file, game=rules.DRAFT_KINGS, ) roster = run( rule_set=rules.DK_NFL_RULE_SET, player_pool=players, player_settings=PlayerPoolSettings(locked=['Eli Manning'], ), ) ntools.assert_not_equals(roster, None) multi_pos = [p for p in roster.players if p.name == 'Eli Manning'] ntools.assert_equal(len(multi_pos), 1) ntools.assert_equal(multi_pos[0].pos, 'TE')
def test_respects_max_proj(): pool = filter_pool(mock_player_pool, PlayerPoolSettings(max_proj=50)) ntools.assert_equals(pool, [p_a, p_b])
def test_no_settings(): pool = filter_pool(mock_player_pool, PlayerPoolSettings()) ntools.assert_equals(pool, mock_player_pool)
def run(rule_set: RuleSet, player_pool: list, constraints: LineupConstraints = LineupConstraints(), optimizer_settings: OptimizerSettings = OptimizerSettings(), player_settings: PlayerPoolSettings = PlayerPoolSettings(), exposure_dict: dict = dict(), roster_gen: Roster = None, verbose=False) -> Roster: players = pool.filter_pool( player_pool, player_settings, ) if rule_set.game_type == 'showdown': if optimizer_settings.no_offense_against_defense: print('WARNING:') print('no_offense_against_defense setting ignored for showdown') print('game types. Use no_defense_against_captain instead.') print() optimizer = Optimizer( players=players, rule_set=rule_set, settings=optimizer_settings, lineup_constraints=constraints, exposure_dict=exposure_dict, ) variables = optimizer.variables if optimizer.solve(): if roster_gen: roster = roster_gen() else: roster = RosterSelect().roster_gen(rule_set.league) for i, player in enumerate(players): if variables[i].solution_value() == 1: roster.add_player(player) if verbose: print('Optimal roster for: {}'.format(rule_set.league)) print(roster) return roster if verbose: print(''' No solution found. Try adjusting your query by taking away constraints. OPTIMIZER CONSTRAINTS: {} LINEUP CONSTRAINTS: {} PLAYER POOL SETTINGS: {} PLAYER COUNT: {} '''.format(optimizer_settings, constraints, player_settings, len(players or []))) return None
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])
def test_respects_max_cost(): pool = filter_pool(mock_player_pool, PlayerPoolSettings(max_salary=7001)) ntools.assert_equals(pool, [p_a, p_b])
def test_respects_banned(): pool = filter_pool(mock_player_pool, PlayerPoolSettings(banned=['A1', 'A2'])) ntools.assert_equals(pool, [p_c])
def test_banned_players(): players = _generate_test_player_data() player_settings = PlayerPoolSettings(banned=['A', 'C'], ) optimized = optimize(players, player_settings=player_settings) ntools.assert_equal(optimized.total, 49 + 47 + 46 + 44 + 42 + 40)
def test_randomize(): random.seed(1) pool = filter_pool(mock_player_pool, PlayerPoolSettings(randomize=0.1, )) ntools.assert_equals(pool[0].proj, 18.537456976449604)
def run_multi( iterations: int, rule_set: RuleSet, player_pool: list, constraints: LineupConstraints = LineupConstraints(), player_settings: PlayerPoolSettings = PlayerPoolSettings(), optimizer_settings: OptimizerSettings = OptimizerSettings(), verbose=False, exposure_bounds: List[dict] = list(), exposure_random_seed=None, progress_recorder=None, locked_pos=None, locked=None, lowest_salary=None, ) -> [List[Roster], list]: if not isinstance(rule_set, RuleSet): raise Exception("RuleSet not defined. Please refer to the docs") # set the random seed globally for random lineup exposure random.seed(exposure_random_seed) rosters = [] for idx in range(0, iterations): progress_recorder.set_progress(idx, iterations) exposure_dict = get_exposure_args( existing_rosters=optimizer_settings.existing_rosters, exposure_bounds=exposure_bounds, n=iterations, use_random=bool(exposure_random_seed), random_seed=exposure_random_seed, locked_pos=locked_pos, constraints=constraints, rule_set=rule_set, locked=locked, ) roster = run( rule_set=rule_set, player_pool=player_pool, optimizer_settings=optimizer_settings, player_settings=player_settings, exposure_dict=exposure_dict, constraints=constraints, verbose=verbose, lowest_salary=lowest_salary, ) if roster: optimizer_settings.existing_rosters += [roster] if roster: rosters.append(roster) else: break # clear ban/lock to reset exposure between iterations reset_player_ban_lock(player_pool) exposure_diffs = {} if rosters and verbose: print(get_exposure_table(rosters, exposure_bounds)) print() print(get_exposure_matrix(rosters)) print() exposure_diffs = check_exposure(rosters, exposure_bounds) for n, d in exposure_diffs.items(): if d < 0: print('{} is UNDER exposure by {} lineups'.format(n, d)) else: print('{} is OVER exposure by {} lineups'.format(n, d)) return rosters, exposure_diffs