Exemple #1
0
def generate_player(pos, row, args):
    '''
    Parses CSV row for DraftKings or FanDuel
    and returns a player. Note that DraftKings
    has different CSV formats for different
    sports.
    '''
    avg_key = GAME_KEY_MAP[args.game]['avg']
    name_key = GAME_KEY_MAP[args.game]['name']
    team_key = GAME_KEY_MAP[args.game]['team']
    team_alt_key = GAME_KEY_MAP[args.game]['team_alt']
    game_key = GAME_KEY_MAP[args.game]['game']
    game_alt_key = GAME_KEY_MAP[args.game]['game_alt']

    avg = float(row.get(avg_key, 0))

    player = Player(pos,
                    row[name_key],
                    row['Salary'],
                    possible_positions=row['Position'],
                    multi_position=('/' in row['Position']),
                    team=row.get(team_key) or row.get(team_alt_key),
                    matchup=row.get(game_key) or row.get(game_alt_key),
                    average_score=avg,
                    lock=(args.locked and row[name_key] in args.locked))

    if args.source == 'DK_AVG':
        player.proj = avg

    return player
Exemple #2
0
async def create_player():
    form = await request.get_json()
    p = Player()
    p.name = form["name"]
    session: Session = SessionMaker()
    session.add(p)
    session.commit()

    return p.to_json()
def test_same_roster():
    roster_one = NFLRoster()
    roster_two = NFLRoster()
    for pos in POSITIONS['NFL']:
        for x in range(0, pos[1]):
            roster_one.add_player(Player(pos[0], 'Kacper{}'.format(x), 4000))
            roster_two.add_player(Player(pos[0], 'Kacper{}'.format(x), 4000))
    roster_one.add_player(Player('WR', 'Kacper8'.format(x), 4000))
    roster_two.add_player(Player('WR', 'Kacper8'.format(x), 4000))
    ntools.assert_equal(roster_one, roster_two)
    roster_one.players.pop()
    ntools.assert_false(roster_one == roster_two)
    roster_one.players.append(Player('WR', 'Kacper8'.format(x), 6000))
    ntools.assert_false(roster_one == roster_two)
Exemple #4
0
        def generate_player(pos, row):
            avg = float(row.get('AvgPointsPerGame', 0))
            player = Player(pos,
                            row['Name'],
                            row['Salary'],
                            possible_positions=row['Position'],
                            multi_position=('/' in row['Position']),
                            team=row['teamAbbrev'],
                            matchup=row['GameInfo'],
                            average_score=avg,
                            lock=(args.locked and row['Name'] in args.locked))
            if args.source == 'DK_AVG':
                player.proj = avg

            return player
def load_players():
    all_players = []
    with open('data/DKSalaries.csv', 'rb') as csvfile:
        csvdata = csv.reader(csvfile, skipinitialspace=True)
        for idx, row in enumerate(csvdata):
            if idx > 0:
                pname = row[5] + " " + row[1]
                pname = pname.replace(".", '').replace("-",
                                                       '').replace(" ",
                                                                   "").lower()
                all_players.append(
                    Player(row[0], row[1].strip(), row[2], row[3], row[5], 0,
                           0, pname))

    indexs = [i for i in range(len(all_players))]

    with open('data/FFA-CustomRankings.csv', 'rb') as csvfile:
        csvdata = csv.DictReader(csvfile)
        for row in csvdata:
            pname = row['team'].lower() + row['playername'].replace(
                ".", '').replace("-", '').replace(" ", "").lower()
            player = filter(lambda x: x.code in pname, all_players)
            try:
                players, id = zip(*filter(lambda (x, _): x.code in pname,
                                          zip(all_players, indexs)))
                if row['upper'] == '0':
                    del all_players[id[0]]
                    indexs.pop()
                    continue
                else:
                    points = int(repr(float(row['upper']) * 100).split('.')[0])

                if row['dropoff'] == 'null':
                    dropoff = 0
                else:
                    dropoff = int(repr(float(row['dropoff'])).split('.')[0])

                if row['risk'] == 'null':
                    risk = 0
                else:
                    risk = int(repr(float(row['risk']) * 100).split('.')[0])

                if '0.0' not in row['upper'] or player[0].cost != 0:
                    ppd = (float(row['upper']) * 100) / float(player[0].cost)
                else:
                    ppd = 0

                player[0].proj = points
                player[0].risk = risk
                player[0].marked = 'Y'
                player[0].dropoff = dropoff

            except Exception as e:
                pass
                #print(e,pname,player)

    check_missing_players(all_players, args.sp, args.mp)
    return all_players
Exemple #6
0
 def generate_player(pos, row):
     return Player(pos,
                   row['Name'],
                   row['Salary'],
                   possible_positions=row['Position'],
                   multi_position=('/' in row['Position']),
                   team=row['teamAbbrev'],
                   matchup=row['GameInfo'],
                   average_score=float(row.get('AvgPointsPerGame', 0)),
                   lock=(args.locked and row['Name'] in args.locked))
Exemple #7
0
            def generate_player(pos, row):
                # DK has inconsistent CSV formats
                avg = float(row.get('AvgPointsPerGame', 0))
                player = Player(
                    pos,
                    row['Name'],
                    row['Salary'],
                    possible_positions=row['Position'],
                    multi_position=('/' in row['Position']),
                    team=row.get('teamAbbrev') or row.get('TeamAbbrev'),
                    matchup=row.get('GameInfo') or row.get('Game Info'),
                    average_score=avg,
                    lock=(args.locked and row['Name'] in args.locked)
                )

                if args.source == _DK_AVG:
                    player.proj = avg

                return player
Exemple #8
0
def _add_player(s, name: str) -> Player:
    player = Player(name=name)
    s.add(player)
    s.commit()
    return player
def run(position_distribution, league, remove):
    solver = pywraplp.Solver('FD', 
                             pywraplp.Solver.CBC_MIXED_INTEGER_PROGRAMMING)

    all_players = []
    with open('data/dk-salaries-current-week.csv', 'rb') as csvfile:
        csvdata = csv.DictReader(csvfile)

        for idx, row in enumerate(csvdata):
            if idx > 0:
                player = Player(row['Position'], row['Name'], row['Salary'], 
                                matchup=row['GameInfo'])
                if args.l == 'NBA':
                    player.proj = float(row['AvgPointsPerGame'])
                    player.team = row['teamAbbrev']
                all_players.append(player)

    if league == 'NFL':
        with open('data/fan-pros.csv', 'rb') as csvfile:
            csvdata = csv.DictReader(csvfile)
            mass_hold = [['playername', 'points', 'cost', 'ppd']]

            for row in csvdata:
                holder = row
                player = filter(lambda x: x.name in row['playername'], all_players)
                if len(player) == 0:
                    continue

                player[0].proj = float(row['points'])
                player[0].marked = 'Y'
                player[0].team = row['playername'].split(' ')[-2]
                listify_holder = [
                    row['playername'],
                    row['points']
                ]
                if '0.0' not in row['points'] or player[0].cost != 0:
                    ppd = float(row['points']) / float(player[0].cost)
                else:
                    ppd = 0
                listify_holder.extend([player[0].cost,
                                       ppd * 100000])
                mass_hold.append(listify_holder)

        check = []
        with open('data/fan-pros.csv', 'rb') as csvdata:
            for row in csvdata:
                check = row
                break

        with open('data/fan-pros.csv', 'wb') as csvdata:        
            if len(check) == 4:
                pass
            else:
                writer = csv.writer(csvdata, lineterminator='\n')
                writer.writerows(mass_hold)

    if league == 'NFL':
        _check_missing_players(all_players, args.sp, args.mp)


    # filter based on criteria and previously optimized
    all_players = filter(lambda x: x.name not in remove and \
        x.proj >= int(args.lp) and \
        x.cost <= int(args.ms) and \
        x.team is not None, 
        all_players)

    variables, solution = run_solver(solver, 
                                     all_players, 
                                     position_distribution)

    if solution == solver.OPTIMAL:
        roster = RosterSelect().roster_gen(args.l)

        for i, player in enumerate(all_players):
            if variables[i].solution_value() == 1:
                roster.add_player(player)

        print "Optimal roster for: %s" % league
        print roster
        print
 
        return roster
    else:
      raise Exception('No solution error')
Exemple #10
0
def test_general_guard():
    pg = Player(name='A', cost=1, proj=1, pos='PG')
    ntools.assert_equal(pg.nba_general_position, 'G')
    sg = Player(name='A', cost=1, proj=1, pos='SG')
    ntools.assert_equal(sg.nba_general_position, 'G')
Exemple #11
0
def test_general_center():
    pg = Player(name='A', cost=1, proj=1, pos='C')
    ntools.assert_equal(pg.nba_general_position, 'C')
def run(position_distribution, league, remove, args, test_mode=False):
    csv_name = 'test' if test_mode else 'current'
    solver = pywraplp.Solver('FD',
                             pywraplp.Solver.CBC_MIXED_INTEGER_PROGRAMMING)

    all_players = []

    with open(fns.format(csv_name), 'rb') as csvfile:
        csvdata = csv.DictReader(csvfile)

        for row in csvdata:
            player = Player(row['Position'], row['Name'], row['Salary'],
                            team=row['teamAbbrev'],
                            matchup=row['GameInfo'],
                            lock=(args.locked and
                                  row['Name'] in args.locked))
            if args.l == 'NBA':
                player.proj = float(row['AvgPointsPerGame'])
                player.team = row['teamAbbrev']
            all_players.append(player)

    if args.w and args.season and args.historical == _YES:
        print('Fetching {} season data for all players...'
              .format(args.season))
        for p in all_players:
            p.set_historical(int(args.w), int(args.season))

    if league == 'NFL':
        if args.po_location and args.po:
            with open(args.po_location, 'rb') as csvfile:
                csvdata = csv.DictReader(csvfile)
                for row in csvdata:
                    player = filter(
                        lambda p: p.name in row['Name'],
                        all_players)
                    if player:
                        player[0].projected_ownership_pct = float(row['%'])

        with open(fnp.format(csv_name), 'rb') as csvfile:
            csvdata = csv.DictReader(csvfile)
            mass_hold = [['playername', 'points', 'cost', 'ppd']]

            # hack for weird defensive formatting
            def name_match(row):
                def match_fn(p):
                    if p.pos == 'DST':
                        return p.name.strip() in row['playername']
                    return p.name in row['playername']
                return match_fn

            for row in csvdata:
                player = filter(name_match(row), all_players)

                if len(player) == 0:
                    continue

                player[0].proj = float(row['points'])
                player[0].marked = 'Y'
                listify_holder = [
                    row['playername'],
                    row['points']
                ]
                if '0.0' not in row['points'] or player[0].cost != 0:
                    ppd = float(row['points']) / float(player[0].cost)
                else:
                    ppd = 0
                listify_holder.extend([player[0].cost,
                                       ppd * 100000])
                mass_hold.append(listify_holder)

        check = []
        with open(fns.format(csv_name), 'rb') as csvdata:
            for row in csvdata:
                check = row
                break

        with open(fnp.format(csv_name), 'wb') as csvdata:
            if len(check) == 4:
                pass
            else:
                writer = csv.writer(csvdata, lineterminator='\n')
                writer.writerows(mass_hold)

    if league == 'NFL':
        _check_missing_players(all_players, args.sp, args.mp)

    # filter based on criteria and previously optimized
    # do not include DST or TE projections in min point threshold.
    all_players = filter(
        qc.add_constraints(args, remove),
        all_players)

    if args.no_double_te == _YES:
        cons.POSITIONS['NFL'] = cons.get_nfl_positions(te_upper=1)

    variables, solution = run_solver(solver,
                                     all_players,
                                     position_distribution,
                                     args)

    if solution == solver.OPTIMAL:
        roster = RosterSelect().roster_gen(args.l)

        for i, player in enumerate(all_players):
            if variables[i].solution_value() == 1:
                roster.add_player(player)

        print "Optimal roster for: %s" % league
        print roster
        print

        return roster
    else:
        print("No solution found for command line query. " +
              "Try adjusting your query by taking away constraints.")
        return None
Exemple #13
0
def run(position_distribution, league, remove):
    solver = pywraplp.Solver('FD', 
                             pywraplp.Solver.CBC_MIXED_INTEGER_PROGRAMMING)

    all_players = []
    with open('dk/data/dkk.csv', 'rb') as csvfile:
        csvdata = csv.DictReader(csvfile)

        for idx, row in enumerate(csvdata):
            if idx > 0:
                player = Player(row['Position'], row['Name'], row['Salary'], 
                                matchup=row['GameInfo'])
                if args.l == 'NBA':
                    player.proj = float(row['AvgPointsPerGame'])
                    player.team = row['teamAbbrev']
                all_players.append(player)

    if league == 'NBA':
        with open('dk/data/fan-pros.csv', 'rb') as csvfile:
            csvdata = csv.DictReader(csvfile)
            mass_hold = [['player', 'projected', 'salary', 'cpp']]

            for row in csvdata:
                holder = row
                player = filter(lambda x: x.name in row['player'], all_players)
                if len(player) == 0: 
                    continue

                player[0].proj = float(row['projected'])
                player[0].marked = 'Y'
                player[0].team = row['playername'].split(' ')[-2]
                listify_holder = [
                    row['player'],
                    row['projected']
                ]
                if '0.0' not in row['projected'] or player[0].cost != 0:
                    ppd = float(row['projected']) / float(player[0].cost)
                else:
                    ppd = 0
                listify_holder.extend([player[0].cost,
                                       ppd * 100000])
                mass_hold.append(listify_holder)

        check = []
        with open('dk/data/fan-pros.csv', 'rb') as csvdata:
            for row in csvdata:
                check = row
                break

        with open('dk/data/fan-pros.csv', 'wb') as csvdata:        
            if len(check) == 4:
                pass
            else:
                writer = csv.writer(csvdata, lineterminator='\n')
                writer.writerows(mass_hold)

    if league == 'NFL':
        _check_missing_players(all_players, args.sp, args.mp)


    # filter based on criteria and previously optimized
    all_players = filter(lambda x: x.name not in remove and \
        x.proj >= int(args.lp) and \
        x.cost <= int(args.ms) and \
        x.team is not None, 
        all_players)

    variables, solution = run_solver(solver, 
                                     all_players, 
                                     position_distribution)

    if solution == solver.OPTIMAL:
        roster = RosterSelect().roster_gen(args.l)

        for i, player in enumerate(all_players):
            if variables[i].solution_value() == 1:
                roster.add_player(player)

        print "Optimal roster for: %s" % league
        print roster
        print
 
        return roster
    else:
      raise Exception('No solution error')
import os
import csv

from nose.tools import assert_equal
from csv_parse import nba_upload
from orm import NBARoster, Player

players = [
    Player(name='A', cost=1, proj=1, pos='SG'),
    Player(name='B', cost=1, proj=1, pos='PG'),
    Player(name='C', cost=1, proj=1, pos='SG'),
    Player(name='D', cost=1, proj=1, pos='SF'),
    Player(name='E', cost=1, proj=1, pos='PF'),
    Player(name='F', cost=1, proj=1, pos='SF'),
    Player(name='G', cost=1, proj=1, pos='C'),
    Player(name='H', cost=1, proj=1, pos='PF')
]

p_map = {}
for idx, p in enumerate(players):
    p.possible_positions = p.pos
    p_map['{} {}'.format(p.name, p.pos)] = idx


def test_upload():
    roster = NBARoster()
    for p in players:
        roster.add_player(p)

    nba_upload.create_upload_file()
    nba_upload.update_upload_csv(p_map, roster)
Exemple #15
0
def test_player_value():
    pg = Player(name='A', cost=5500, proj=55, pos='PG')
    ntools.assert_equal(pg.value, 10)
Exemple #16
0
def run(position_distribution, league, remove, args, test_mode=False):
    csv_name = 'test' if test_mode else 'current'
    solver = pywraplp.Solver('FD',
                             pywraplp.Solver.CBC_MIXED_INTEGER_PROGRAMMING)

    all_players = []

    with open(fns.format(csv_name), 'rb') as csvfile:
        csvdata = csv.DictReader(csvfile)

        for idx, row in enumerate(csvdata):
            if idx > 0:
                player = Player(row['Position'], row['Name'], row['Salary'],
                                matchup=row['GameInfo'])
                if args.l == 'NBA':
                    player.proj = float(row['AvgPointsPerGame'])
                    player.team = row['teamAbbrev']
                all_players.append(player)

    if league == 'NFL':
        with open(fnp.format(csv_name), 'rb') as csvfile:
            csvdata = csv.DictReader(csvfile)
            mass_hold = [['playername', 'points', 'cost', 'ppd']]

            for row in csvdata:
                player = filter(lambda x: x.name in row['playername'],
                                all_players)
                if len(player) == 0:
                    continue

                player[0].proj = float(row['points'])
                player[0].marked = 'Y'
                player[0].team = row['playername'].split(' ')[-2]
                listify_holder = [
                    row['playername'],
                    row['points']
                ]
                if '0.0' not in row['points'] or player[0].cost != 0:
                    ppd = float(row['points']) / float(player[0].cost)
                else:
                    ppd = 0
                listify_holder.extend([player[0].cost,
                                       ppd * 100000])
                mass_hold.append(listify_holder)

        check = []
        with open(fns.format(csv_name), 'rb') as csvdata:
            for row in csvdata:
                check = row
                break

        with open(fnp.format(csv_name), 'wb') as csvdata:
            if len(check) == 4:
                pass
            else:
                writer = csv.writer(csvdata, lineterminator='\n')
                writer.writerows(mass_hold)

    if league == 'NFL':
        _check_missing_players(all_players, args.sp, args.mp)

    # filter based on criteria and previously optimized
    # do not include DST or TE projections in min point threshold.
    if isinstance(args.teams, str):
        args.teams = args.teams.split(' ')

    all_players = filter(
        qc.add_constraints(args, remove),
        all_players)

    variables, solution = run_solver(solver,
                                     all_players,
                                     position_distribution)

    if solution == solver.OPTIMAL:
        roster = RosterSelect().roster_gen(args.l)

        for i, player in enumerate(all_players):
            if variables[i].solution_value() == 1:
                roster.add_player(player)

        print "Optimal roster for: %s" % league
        print roster
        print

        return roster
    else:
        print("No solution found for command line query. " +
              "Try adjusting your query by taking away constraints.")
        return None