Beispiel #1
0
def update_players(path):
    print("Updating players.")
    p = Players()
    players = p.get_all_players()
    # resp_data = json.loads(resp.json())
    with open(path, 'w') as outfile:
        json.dump(players, outfile, indent=2)
    return players
Beispiel #2
0
def get_negative_starters(league_id):
    """
    Finds all of the players that scores negative points in standard and
    :param league_id: Int league_id
    :return: Dict {"owner_name":[("player_name", std_score), ...], "owner_name":...}
    """
    week = get_current_week()

    league = League(league_id)
    users = league.get_users()
    matchups = league.get_matchups(week)

    stats = Stats()
    # WEEK STATS NEED TO BE FIXED
    week_stats = stats.get_week_stats("regular", STARTING_YEAR, week)

    players = Players()
    players_dict = players.get_all_players()
    owner_id_to_team_dict = map_users_to_team_name(users)
    roster_id_to_owner_id_dict = map_roster_id_to_owner_id(league_id)

    result_dict = {}

    for i, matchup in enumerate(matchups):
        starters = matchup["starters"]
        negative_players = []
        for starter_id in starters:
            try:
                std_pts = week_stats[str(starter_id)]["pts_std"]
            except KeyError:
                std_pts = 0
            if std_pts < 0:
                player_info = players_dict[starter_id]
                player_name = "{} {}".format(player_info["first_name"],
                                             player_info["last_name"])
                negative_players.append((player_name, std_pts))

        if len(negative_players) > 0:
            owner_id = roster_id_to_owner_id_dict[matchup["roster_id"]]

            if owner_id is None:
                team_name = "Team name not available" + str(i)
            else:
                team_name = owner_id_to_team_dict[owner_id]
            result_dict[team_name] = negative_players
    return result_dict
Beispiel #3
0
def main(argv):
    args = parse_user_provided_flags()
    user = args.username
    year = args.year
    league_regex = re.compile(args.league_regex)
    week = args.week
    include_covid = args.include_covid
    include_missing = args.include_missing

    # Retrieve the list of all inactive players
    nfl_players = Players()
    inactive_players = find_all_inactive_players_for_week(
        nfl_players.get_all_players(), week, include_covid)

    if include_missing:
        # Empty starting slots fill in as id 0, so add an entry for that
        # 0th player in order to report the empty spot
        inactive_players.append(
            Player("Missing Player", "0", "None", "MISSING", "NONE"))

    # Retrieve all of the leagues
    admin_user = User(user)
    all_leagues = admin_user.get_all_leagues("nfl", year)
    user_store = UserStore()

    inactive_rosters = []

    # Iterate through each league to find the inactive owners in each
    for league_object in all_leagues:
        league = League(league_object.get("league_id"))
        league_name = league.get_league().get("name")

        # Only look at leagues that match the provided regex
        if league_regex.match(league_name):
            user_store.store_users_for_league(league)

            inactive_rosters.extend(
                find_inactive_starters_for_league_and_week(
                    league, week, inactive_players, user_store))

    # Print out the final inactive rosters
    print("")
    for roster in inactive_rosters:
        print(roster)
Beispiel #4
0
}
owners_sorted = list(roster_to_owner_sorted.values())

#standings = league.get_standings(rosters, users)

# A number of arrays will be created where the row specifies the owner and the
# column specifies the week

points_arr = np.zeros((len(owner_roster_list), 17))
matchup_arr = np.zeros((len(owner_roster_list), 17))
win_arr = np.zeros((len(owner_roster_list), 17))
overall_win_arr = np.zeros((len(owner_roster_list), 17))
potential_points_arr = np.zeros((len(owner_roster_list), 17))
sleeper_points_arr = np.zeros((len(owner_roster_list), 17))

all_players = players.get_all_players()
# print('test')
weekly_matchup_list = np.array([])
weeks = 16
for week in range(weeks):
    weekly_matchup = league.get_matchups(week)
    week_stats = stats.get_week_stats('regular', 2019, week)

    # Using
    weekly_scores = []
    weekly_wins = []

    for team in weekly_matchup:
        sleeper_points = team['points']
        sleeper_points_arr[team['roster_id'] - 1, week - 1] = sleeper_points
def main():
    with Halo("Setting up script details.", spinner="dots") as spinner:
        league_id = os.environ.get("SLEEPER_LEAGUE_ID", None)
        user_id = os.environ.get("SLEEPER_USER_ID", None)

        args = parser.parse_args()
        command_args = dict(vars(args))
        is_dry_run = command_args.pop("dry_run", None)
        keep_positions = tuple(command_args.pop("positions", None))
        spinner.succeed()

    Halo(f"Included positions are {', '.join(keep_positions)}",
         spinner="dots").succeed()
    league = League(league_id)
    players = Players()

    league_rosters = league.get_rosters()
    if is_dry_run:
        all_players = players.get_all_players()
        with open("./data/sleeper_players_current.json", "w") as outfile:
            json.dump(all_players, outfile)
    else:
        with open("./data/sleeper_players_current.json", "r") as infile:
            all_players = json.load(infile)

    own_team = [
        team for team in league_rosters if team["owner_id"] == user_id
    ].pop()
    own_players = own_team["players"]
    keep_players = {
        p_id: p_data
        for p_id, p_data in all_players.items()
        if p_data["position"] in keep_positions
    }
    # save keep_players for testing
    with open("./data/sleeper_players_keep.json", "w") as outfile:
        json.dump(keep_players, outfile)
    # ID free agents by comparing keep_players to rosters
    rostered_player_ids = [
        player for team in league_rosters for player in team["players"]
    ]
    with Halo("Separating players into rostered and FAs.",
              spinner="dots") as spinner:
        free_agents = {
            p_id: p_data
            for p_id, p_data in keep_players.items()
            if p_id not in rostered_player_ids
        }
        rostered_players = {
            p_id: p_data
            for p_id, p_data in keep_players.items()
            if p_id in rostered_player_ids
        }
        spinner.succeed()

    with Halo("Pulling Numberfire Projections", spinner="dots") as spinner:
        nfp = numberfireProjections("half_ppr")
        nfp.get_data("flex")
        nfp.convert_projections()
        spinner.succeed()

    nf_cleaned_names = {clean_name(x): x for x in nfp.projections.keys()}
    # add projections in to rosters
    for p_id, p_data in free_agents.items():
        if p_data["search_full_name"] in nf_cleaned_names.keys():
            p_data["numberfire_projections"] = nfp.projections[
                nf_cleaned_names[p_data["search_full_name"]]]
        else:
            p_data["numberfire_projections"] = 0

    for p_id, p_data in rostered_players.items():
        if p_data["search_full_name"] in nf_cleaned_names.keys():
            p_data["numberfire_projections"] = nfp.projections[
                nf_cleaned_names[p_data["search_full_name"]]]
        else:
            p_data["numberfire_projections"] = 0
    Halo("Added projections to FAs and rostered players.",
         spinner="dots").succeed()

    # comparison
    own_roster = {
        p_id: p_data
        for p_id, p_data in rostered_players.items() if p_id in own_players
    }
    waiver_players = dict()
    for p_id, p_data in own_roster.items():
        if p_data["status"] == "Injured Reserve":
            continue
        waiver_dict = {
            "drop_proj": p_data["numberfire_projections"],
            "players_to_add": list(),
        }
        for fa_id, fa_data in free_agents.items():
            if (fa_data["numberfire_projections"] >
                    p_data["numberfire_projections"]) and (
                        fa_data["position"] == p_data["position"]):
                fa_dict = {
                    "waiver_player": fa_data["search_full_name"],
                    "waiver_proj": fa_data["numberfire_projections"],
                }
                waiver_dict["players_to_add"].append(fa_dict)
        waiver_players[p_data["search_full_name"]] = waiver_dict
    Halo(
        "Compared FA projections to your roster. Returning players with better projections.",
        spinner="dots",
    ).succeed()

    pp = pprint.PrettyPrinter()
    pp.pprint(waiver_players)
Beispiel #6
0
# Define Inputs
league_id = 470314205950504960
players_file = 'sleeper_players.pkl'
team_num = 8

# Access API
league = League(league_id)
rosters = league.get_rosters()

# Not supposed to call this all the time because it is a large file (5MB)
if os.path.isfile(players_file):
    with open(players_file, 'rb') as f:
        players = pickle.load(f)
else:
    P = Players()
    players = P.get_all_players()
    with open(players_file, 'wb') as f:
        pickle.dump(players, f)

my_team = rosters[team_num - 1]
my_dudes = [players[id] for id in my_team['players']]
my_pals = [
    dude['full_name'] for dude in my_dudes
    if not (('DEF' in dude['fantasy_positions']) or
            ('K' in dude['fantasy_positions']))
]

rostered_teams = [roster['players'] for roster in rosters]
rostered_players = sum(rostered_teams, [])
rostered_dudes = [players[id] for id in rostered_players]
rostered_pals = [
Beispiel #7
0
def get_dudes(my_league):

    starting_lineup = []

    if my_league['platform'] == 'ESPN':
        from ff_espn_api import League

        league_id = my_league['league_id']
        year = my_league['year']
        swid = my_league['swid']
        espn_s2 = my_league['espn_s2']
        team_num = my_league['team_num']

        league = League(league_id, year, espn_s2, swid)
        my_team = league.teams[team_num - 1]
        my_dudes = my_team.roster
        my_pals = [
            dude.name for dude in my_dudes
            if not ('D/ST' in dude.eligibleSlots or 'K' in dude.eligibleSlots)
        ]
        my_pos = [
            dude.position for dude in my_dudes
            if not ('D/ST' in dude.eligibleSlots or 'K' in dude.eligibleSlots)
        ]
        my_def = [
            dude.proTeam for dude in my_dudes if 'D/ST' in dude.eligibleSlots
        ]
        my_kick = [dude.name for dude in my_dudes if 'K' in dude.eligibleSlots]

        teams = league.teams
        rosters = [team.roster for team in teams]
        rostered_pals = []
        rostered_def = []
        rostered_kick = []
        for roster in rosters:
            dudes = [
                dude.name for dude in roster if not (
                    'D/ST' in dude.eligibleSlots or 'K' in dude.eligibleSlots)
            ]
            rostered_pals.extend(dudes)
            rostered_def.extend([
                dude.proTeam for dude in roster if 'D/ST' in dude.eligibleSlots
            ])
            rostered_kick.extend(
                [dude.name for dude in roster if 'K' in dude.eligibleSlots])

        team_name = my_team.team_name
        boxscores = league.box_scores()
        for boxscore in boxscores:
            if boxscore.away_team.team_name == team_name:
                my_guys = boxscore.away_lineup
            elif boxscore.home_team.team_name == team_name:
                my_guys = boxscore.home_lineup

        for guy in my_guys:
            if guy.slot_position not in ['D/ST', 'K', 'BE']:
                starting_lineup.append(guy.name)

    elif my_league['platform'] == 'YAHOO':
        from yahoo_oauth import OAuth2
        import yahoo_fantasy_api as yfa

        oauth_file = my_league['oauth_file']
        lg_number = my_league['lg_number']

        sc = OAuth2(None, None, from_file=oauth_file)
        gm = yfa.Game(sc, 'nfl')
        league = gm.to_league(lg_number)
        week = league.current_week()

        team_objs = league.teams()
        team_keys = [team['team_key'] for team in team_objs]
        teams = [league.to_team(key) for key in team_keys]
        rosters = [team.roster(week) for team in teams]
        rostered_pals = []
        rostered_def = []
        rostered_kick = []
        for roster in rosters:
            dudes = [
                dude['name'] for dude in roster
                if not ('K' in dude['eligible_positions']
                        or 'DEF' in dude['eligible_positions'])
            ]
            rostered_pals.extend(dudes)
            rostered_def.extend([
                dude['name'] for dude in roster
                if 'DEF' in dude['eligible_positions']
            ])
            rostered_kick.extend([
                dude['name'] for dude in roster
                if 'K' in dude['eligible_positions']
            ])

        my_team = league.to_team(league.team_key())
        my_roster = my_team.roster(week)
        my_pals = [
            dude['name'] for dude in my_roster
            if not ('K' in dude['eligible_positions']
                    or 'DEF' in dude['eligible_positions'])
        ]
        my_pos = [
            dude['eligible_positions'][0] for dude in my_roster
            if not ('K' in dude['eligible_positions']
                    or 'DEF' in dude['eligible_positions'])
        ]
        my_def = [
            dude['name'] for dude in my_roster
            if 'DEF' in dude['eligible_positions']
        ]
        my_kick = [
            dude['name'] for dude in my_roster
            if 'K' in dude['eligible_positions']
        ]
        starting_lineup = [
            dude['name'] for dude in my_roster
            if not dude['selected_position'] in ['BN', 'K', 'DEF']
        ]

        def_map = {  #This neglects the RAMS and the GIANTS because Yahoo is dumb and I don't want to figure out their player IDs.
            'New England': 'NE',
            'Chicago': 'CHI',
            'Tampa Bay': 'TB',
            'Tennessee': 'TEN',
            'San Francisco': 'SF',
            'New York': 'NYJ',
            'Green Bay': 'GB',
            'New Orleans': 'NO',
            'Pittsburgh': 'PIT',
            'Carolina': 'CAR',
            'Detroit': 'DET',
            'Seattle': 'SEA',
            'Cleveland': 'CLE',
            'Los Angeles': 'LAC',
            'Kansas City': 'KC',
            'Minnesota': 'MIN',
            'Buffalo': 'BUF',
            'Dallas': 'DAL',
            'Houston': 'HOU',
            'Jacksonville': 'JAX',
            'Indianapolis': 'IND',
            'Oakland': 'OAK',
            'Washington': 'WAS',
            'Baltimore': 'BAL',
            'Philadelphia': 'PHI',
            'Arizona': 'ARI',
            'Atlanta': 'ATL',
            'Cincinnati': 'CIN',
            'Denver': 'DEN',
            'Miami': 'MIA'
        }

        my_def = [def_map[d] for d in my_def]
        rostered_def = [def_map[d] for d in rostered_def]

    elif my_league['platform'] == 'SLEEPER':
        from sleeper_wrapper import League, Players
        import pickle
        import os.path

        league_id = my_league['league_id']
        players_file = my_league['players_file']
        team_num = my_league['team_num']

        league = League(league_id)
        rosters = league.get_rosters()

        # Not supposed to call this all the time because it is a large file (5MB)
        if os.path.isfile(players_file):
            with open(players_file, 'rb') as f:
                players = pickle.load(f)
        else:
            P = Players()
            players = P.get_all_players()
            with open(players_file, 'wb') as f:
                pickle.dump(players, f)

        my_team = rosters[team_num - 1]
        my_dudes = [players[id] for id in my_team['players']]
        my_pals = [
            dude['full_name'] for dude in my_dudes
            if not (('DEF' in dude['fantasy_positions']) or
                    ('K' in dude['fantasy_positions']))
        ]
        starting_dudes = [players[id] for id in my_team['starters']]
        starting_lineup = [
            dude['full_name'] for dude in starting_dudes
            if not (('DEF' in dude['fantasy_positions']) or
                    ('K' in dude['fantasy_positions']))
        ]
        my_pos = [
            dude['position'] for dude in my_dudes
            if not (('DEF' in dude['fantasy_positions']) or
                    ('K' in dude['fantasy_positions']))
        ]
        my_def = [
            dude['player_id'] for dude in my_dudes
            if 'DEF' in dude['fantasy_positions']
        ]
        my_kick = [
            dude['full_name'] for dude in my_dudes
            if 'K' in dude['fantasy_positions']
        ]

        rostered_teams = [roster['players'] for roster in rosters]
        rostered_players = sum(rostered_teams, [])
        rostered_dudes = [players[id] for id in rostered_players]
        rostered_pals = [
            dude['full_name'] for dude in rostered_dudes
            if not (('DEF' in dude['fantasy_positions']) or
                    ('K' in dude['fantasy_positions']))
        ]
        rostered_def = [
            dude['player_id'] for dude in rostered_dudes
            if 'DEF' in dude['fantasy_positions']
        ]
        rostered_kick = [
            dude['full_name'] for dude in rostered_dudes
            if 'K' in dude['fantasy_positions']
        ]

    else:
        raise ValueError('League platform ' + league.platform +
                         ' is not supported.')

    return my_pals, my_pos, rostered_pals, my_def, rostered_def, my_kick, rostered_kick, clean_names(
        starting_lineup)