Exemple #1
0
async def get_picks(team):
    """Returns a list of players with the necessary information to format the
    team's formation properly.
    """
    player_ids = [player["element"] for player in team]
    async with aiohttp.ClientSession() as session:
        fpl = FPL(session)
        players = await fpl.get_players(player_ids)

    for player_data in team:
        for player in players:
            if player_data["element"] != player.id:
                continue

            player.role = ""
            player.event_points = (player.event_points *
                                   player_data["multiplier"])
            player.team_position = player_data["position"]

            player.is_captain = player_data["is_captain"]
            if player.is_captain:
                player.role = " (C)"

            player.is_vice_captain = player_data["is_vice_captain"]
            if player.is_vice_captain:
                player.role = " (VC)"

            if player.status in ["d", "u"]:
                player.colour = "yellow"
            elif player.status in ["i"]:
                player.colour = "red"
            else:
                player.colour = None

    return players
async def main():
    async with aiohttp.ClientSession() as session:
        fpl = FPL(session)
        fdr = await fpl.FDR()

    fdr_table = PrettyTable()
    fdr_table.field_names = [
        "Team",
        "All (H)",
        "All (A)",
        "GK (H)",
        "GK (A)",
        "DEF (H)",
        "DEF (A)",
        "MID (H)",
        "MID (A)",
        "FWD (H)",
        "FWD (A)",
    ]

    for team, positions in fdr.items():
        row = [team]
        for difficulties in positions.values():
            for location in ["H", "A"]:
                if difficulties[location] == 5.0:
                    row.append(Fore.RED + "5.0" + Fore.RESET)
                elif difficulties[location] == 1.0:
                    row.append(Fore.GREEN + "1.0" + Fore.RESET)
                else:
                    row.append(f"{difficulties[location]:.2f}")

        fdr_table.add_row(row)

    fdr_table.align["Team"] = "l"
    print(fdr_table)
Exemple #3
0
async def get_scores(gameweek, team):
    async with aiohttp.ClientSession() as session:
        fpl = FPL(session)
        teams = await fpl.get_teams()
        team_dict = {i.short_name: i.code for i in teams}
        players = await fpl.get_players(None, True)

        lines = team.splitlines()
        score_map = {}
        for line in lines:
            p = re.split(' +', line)
            player_last_name = p[0]
            if player_last_name.lower() in player_name_replacement_map:
                player_last_name = player_name_replacement_map[
                    player_last_name.lower()]
            team_code = p[1].replace("(", "").replace(")",
                                                      "").replace("\n", "")

            player_details = get_player_details(player_last_name, team_code,
                                                players, team_dict)
            score = get_gameweek_score(player_details, gameweek)
            if len(p) > 2:
                captain = p[2].replace("(", "").replace(")",
                                                        "").replace("\n", "")
                if captain == 'c':
                    score = score * 2
                    player_last_name = player_last_name + " (c)"

            score_map[player_last_name] = score

        total_score = 0
        for i in score_map:
            total_score = total_score + score_map[i]
        score_map["Total"] = total_score
        return score_map
Exemple #4
0
    async def add_account(user_id, email, password):
        """Add a new account to the `accounts` table.

        :param int user_id: user's FPL ID
        :param string email: user's FPL email address
        :param string password: user's FPL password
        """
        if account_exists(user_id):
            raise ValueError("Account with user ID {} already exists!".format(
                user_id))

        async with aiohttp.ClientSession() as session:
            fpl = FPL(session)
            # Check if log in possible with provided email and password
            try:
                await fpl.login(email, password)
            except ValueError as error:
                click.echo(error)
                return

            # Use my_team function to determine if user ID is associated to email
            user = await fpl.get_user(user_id)
            try:
                await user.get_team()
            except ValueError as error:
                click.echo(error)
                return

        query = ("INSERT INTO accounts (user_id, email, password) "
                 "VALUES (?, ?, ?)", (user_id, email, password))
        cursor = connection.cursor()
        cursor.execute(*query)
        connection.commit()
Exemple #5
0
async def user():
    session = aiohttp.ClientSession()
    fpl = FPL(session)
    await fpl.login()
    user = await fpl.get_user(3808385)
    yield user
    await session.close()
Exemple #6
0
async def h2h_league():
    session = aiohttp.ClientSession()
    fpl = FPL(session)
    await fpl.login()
    h2h_league = await fpl.get_h2h_league(760869)
    yield h2h_league
    await session.close()
async def update_players(engine):
    async with aiohttp.ClientSession() as session:
        fpl = FPL(session)
        players = await fpl.get_players(include_summary=True)

    for player in players:
        history = player.history
        history.reverse()

        history_len = min(len(history), 3)
        ict = [0] * 3
        minutes = [0] * 3
        value = [0] * 3

        for i in range(history_len):
            ict[i] += float(history[i]["ict_index"])
            minutes[i] += float(history[i]["minutes"])
            value[i] += float(history[i]["value"])

        ict_form = Models.setHistory(feat_name="player_ict", feat_list=ict)
        minutes_form = Models.setHistory(feat_name="player_minutes",
                                         feat_list=minutes)
        value_form = Models.setHistory(feat_name="player_value",
                                       feat_list=value)

        update_player(player, engine, ict_form, minutes_form, value_form)
Exemple #8
0
async def get_player_data():
    """Download all data from the Fantasy Premier League website"""
    # Connect to the sqlite3 DB
    conn, cursor = connect_to_db()
    summary_df = pd.DataFrame()

    async with aiohttp.ClientSession() as session:
        fpl = FPL(session)
        players = await fpl.get_players()
        i = 0
        for player in players:
            id = player.id
            i += 1
            print("Loading data for player {} of {}".format(i, len(players)))
            player_summary = await fpl.get_player_summary(id)
            player_history = pd.DataFrame(player_summary.history)
            player_history['web_name'] = player.web_name
            player_history['id'] = player.id
            player_history['team'] = player.team
            player_history['team_code'] = player.team_code
            summary_df = summary_df.append(player_history)

    # Upload the data to a table in the database
    run_query(cursor, 'DROP TABLE IF EXISTS player_data', return_data=False)
    summary_df.to_sql('player_data', conn)
Exemple #9
0
async def main():
    async with aiohttp.ClientSession() as session:
        fpl = FPL(session)
        Results_array = []
        Fixtures_array = []
        unconfirmed_fixrtures = [180, 286, 317]
        for i in range(1, 381):
            if (i in unconfirmed_fixrtures):
                pass
            else:
                fixture = await fpl.get_fixture(i)
                id = fixture.id
                team_a = fixture.team_a
                team_h = fixture.team_h
                if (fixture.finished):
                    team_a_score = fixture.team_a_score
                    team_h_score = fixture.team_h_score
                    result = [id, team_a, team_a_score, team_h, team_h_score]
                    Results_array.append(result)
                else:
                    fixtures = [id, team_a, team_h]
                    Fixtures_array.append(fixtures)
        data = pd.DataFrame.from_records(Results_array)
        data2 = pd.DataFrame.from_records(Fixtures_array)
        data.columns = [
            "ID", "Away Team", "Away Team Score", "Home Team",
            "Home Team Score"
        ]
        data2.columns = ["ID", "Away Team", "Home Team"]
        data.to_csv("Results.csv")
        data2.to_csv("Fixtures.csv")
Exemple #10
0
async def main():
      
      async with aiohttp.ClientSession() as session:
          linefig = go.Figure()
          fpl = FPL(session)
          await fpl.login(getID(),getPWD())
          classic_league = await fpl.get_classic_league(237300)
          standings = await classic_league.get_standings(1,1,1)
          print(standings['results'])
          listofids=[]
          for user in standings['results']:
              listofids.append(user['entry'])

          idtolostpoints = dict()
          for id in listofids:
           user = await fpl.get_user(id)
           print(str(user))
           history = await user.get_gameweek_history()
           points=[]
           gw=[]
           lostpoints = 0;
           for gwhistory in history:
            points.append(gwhistory['total_points'])
            gw.append(gwhistory['event'])
            lostpoints=lostpoints + gwhistory['points_on_bench']
           
           linefig.add_trace(go.Scatter(x=gw, y=points, name=str(user),  mode='lines',
                         line=dict(width=2)))
           idtolostpoints[str(user)]=lostpoints
          
          for key in idtolostpoints:
           print(key + ":" + str(idtolostpoints[key]))
          linefig.update_layout(title_text="Melawatians Total Points Every Game Week")
          linefig.show()
Exemple #11
0
async def get_current_squad(player_feature_names,
                            team_feature_names,
                            num_players=580):
    """function gets player lists for players in squad and out of squad

    Args:
        player_feature_names (list): names of player related features
        team_feature_names (list): names of team related features
        num_players (int, optional): max number of players to build dataset. Defaults to 580.

    Returns:
        current_squad, non_squad(list, list): players in squad, players out of squad
    """
    current_squad_players, non_squad_players = [], []
    players = await get_players(player_feature_names,
                                team_feature_names,
                                num_players=num_players)
    async with aiohttp.ClientSession() as session:
        fpl = FPL(session)
        await fpl.login(email=email, password=password)
        user = await fpl.get_user(user_id)
        bank = (await user.get_transfers_status())["bank"]
        squad = await user.get_team()
        for i, player_element in enumerate(squad):
            for player in players:
                if player.id == player_element["element"]:
                    player.in_current_squad = True
                    player.bank = bank
                    current_squad_players.append(player)

        for player in players:
            if not player.in_current_squad:
                non_squad_players.append(player)

        return current_squad_players, non_squad_players
Exemple #12
0
 async def main():
     async with aiohttp.ClientSession() as session:
         fpl = FPL(session)
         await fpl.login(email='jameshpalmer2000', password='******')
         player = await fpl.get_player(title, return_json=True)
         global price
         price = (player['now_cost'] / 10)
Exemple #13
0
async def find_fpl_captain():
    "Function to try and predict the optimal choice of fpl captain."
    session = aiohttp.ClientSession()
    fpl = FPL(session)

    #First get the top 5 players from all 20 teams in the epl.
    all_pl_teams = await fpl.get_teams()

    for team in all_pl_teams[:1]:
        players = await team.get_players(return_json=True)
        name_of_team = team.name

        print(name_of_team + '\n')

        #Create dataframe of the players.
        players_df_raw = pd.DataFrame(players)
        players_df_raw['goal_involvement'] = players_df_raw[
            'goals_scored'] + players_df_raw['assists']
        players_df = players_df_raw.sort_values(
            by=['goal_involvement', 'points_per_game', 'form', 'threat'],
            ascending=False)

        #print(players_df.columns)
        print(players_df[[
            'web_name', 'form', 'points_per_game', 'threat', 'goals_scored',
            'assists', 'goal_involvement', 'bonus', 'clean_sheets',
            'own_goals', 'penalties_order', 'now_cost'
        ]].head(3))

    await session.close()
Exemple #14
0
async def main(email, password, team_id):
    async with aiohttp.ClientSession() as session:
        fpl = FPL(session)
        await fpl.login(email, password)
        user = await fpl.get_user(3415098)
        team = await user.get_team()

        players = []
        for player in team:
            players.append(await fpl.get_player(player["element"]))

    form_table = PrettyTable()
    players.sort(key=lambda x: float(x.form), reverse=True)
    form_table.field_names = [
        "Player", "Form", "Total Points", "PP90", "ict_index"
    ]

    for player in players:
        row = [
            player.web_name,
            player.form,
            player.total_points,
            round(player.pp90, 2),
            player.ict_index,
        ]
        form_table.add_row(row)

    print(form_table)
async def get_fpl_teams():
    """Download upcoming fixture data from the Fantasy Premier League website"""
    # Connect to the sqlite3 DB
    conn, cursor = connect_to_db()
    df_teams = pd.DataFrame()
    i=0
    # Get all of the team IDs from the fpl_fixtures table
    teams = run_query(cursor, 'select distinct team_h from fpl_fixtures')
    n_teams = len(teams)
    assert n_teams == 20, 'The number of returned teams should be 20, ' \
                          'but is actually {}'.format(n_teams)
    async with aiohttp.ClientSession() as session:
        fpl = FPL(session)
        team_data = await fpl.get_teams(return_json=True)

    for team in team_data:
        df_teams = df_teams.append(pd.DataFrame(team, index=[i]))
        i += 1
    # Find the closest matching team names to the ones in our data
    matches = list(df_teams['name'].apply(lambda x: find_closest_match(x)))
    df_matches = pd.DataFrame()
    for match in matches:
        df_matches = df_matches.append(pd.DataFrame(match, index=[0]))
    df_teams = pd.concat([df_teams, df_matches.reset_index(drop=True)], axis=1)
    # Upload the data to a table in the database
    run_query(cursor, 'DROP TABLE IF EXISTS fpl_teams', return_data=False)
    df_teams.to_sql('fpl_teams', conn)
    conn.close()
Exemple #16
0
async def head_to_head():
    league_id = 902521
    async with aiohttp.ClientSession() as session:
        fpl_session = FPL(session)
        await fpl_session.login(environ['EMAIL'], environ['FPL_PASSWORD'])
        league = await fpl_session.get_h2h_league(league_id)

        league_table = PrettyTable()
        league_table.field_names = [
            'Rank', 'Team', 'Played', 'Won', 'Drawn', 'Lost', 'FPL Points',
            'League Points'
        ]
        for entry in league.standings['results']:
            team = await fpl_session.get_user(entry['entry'], return_json=True)
            if entry['rank'] > entry['last_rank']:
                r = '-'
            elif entry['rank'] == entry['last_rank']:
                r = '='
            else:
                r = '+'
            league_table.add_row([
                f"{entry['rank']}. ({r})",
                f"{entry['player_name'].title()} ({entry['entry_name']})",
                entry['matches_played'],
                entry['matches_won'],
                entry['matches_drawn'],
                entry['matches_lost'],
                entry['points_for'],
                entry['matches_won'] * 2 + entry['matches_drawn'],
            ])
        league_table.sort_by = ('League Points', 'FPL Points')
        print(league_table)
        fixtures = await league.get_fixtures()
        print(fixtures)
Exemple #17
0
async def my_team(user_id):
    async with aiohttp.ClientSession() as session:
        fpl = FPL(session)
        await fpl.login(email="*****@*****.**", password="******")
        user = await fpl.get_user(user_id)
        team = await user.get_team()

    print(team)
Exemple #18
0
async def run_top_five_players():
    session = aiohttp.ClientSession()
    fpl = FPL(session)
    position = request.args.get('position')
    price = float(request.args.get('price')) * 10
    top_five_players = await get_top_five_players(position, price, fpl)
    await session.close()
    return jsonify(top_five_players)
async def main():
    async with aiohttp.ClientSession() as session:
        fpl = FPL(session)
        gameweeks = await fpl.get_gameweeks(return_json=True)

        for gameweek in gameweeks:
            if (gameweek["is_current"]):
                print(json.dumps(gameweek["id"]))
Exemple #20
0
async def get_form(inputted_player_tuple):
    session = aiohttp.ClientSession()
    fpl = FPL(session)
    player_one = await fpl.get_player(inputted_player_tuple[0])
    player_two = await fpl.get_player(inputted_player_tuple[1])
    player_form_tuple = (float(player_one.__dict__['form']), float(player_two.__dict__['form']))
    await session.close()
    return player_form_tuple
Exemple #21
0
async def get_fpl():
    """Get fpl session

    Returns:
        fpl (fpl): fpl object
    """
    async with aiohttp.ClientSession() as session:
        fpl = FPL(session)
        return fpl
Exemple #22
0
 def __init__(self, config, session):
     self.config = config
     self.database = client.fpl
     self.fpl = FPL(session)
     self.reddit = praw.Reddit(client_id=config.get("CLIENT_ID"),
                               client_secret=config.get("CLIENT_SECRET"),
                               password=config.get("PASSWORD"),
                               user_agent=config.get("USER_AGENT"),
                               username=config.get("USERNAME"))
     self.subreddit = self.reddit.subreddit(self.config.get("SUBREDDIT"))
Exemple #23
0
class H2HLeagueTest(unittest.TestCase):
    def setUp(self):
        self.fpl = FPL()
        self.fpl.login()
        self.h2h_league = self.fpl.get_h2h_league("760869")

    def test_h2h_league(self):
        self.assertEqual(
            self.h2h_league.__str__(), "League 760869 - 760869")

    def test__get_information(self):
        information = self.h2h_league._information
        self.assertIsInstance(information, dict)

    def test_get_standings(self):
        self.h2h_league.get_fixtures()
        fixtures = self.h2h_league.fixtures
        self.assertIsInstance(fixtures, list)
        self.assertEqual(fixtures[0]["event"], 1)
Exemple #24
0
class FPLTest(unittest.TestCase):
    def setUp(self):
        self.fpl = FPL()
        self.player = self.fpl.get_player(1)

    def test_games_played(self):
        pass

    def test_pp90(self):
        pass
Exemple #25
0
async def get_season_stats():
    "Function to obtain player's game by game stats and save to relevant files"
    session = aiohttp.ClientSession()
    fpl = FPL(session)

    players_data = await fpl.get_players(include_summary=True,
                                         return_json=True)

    #First update the player's history using data from FPL site.
    for player in players_data:

        player_name = player['first_name']
        player_surname = player['second_name']
        player_id = str(player['history'][0]['element'])

        fname = "/home/zwi/zwi_work/Fantasy-Premier-League/data/2021-22/players/" + player_name + "_" + player_surname + "_" + player_id + "/gw.csv"
        #stream_to_file = open(fname, "w+")
        player_df = pd.DataFrame(player['history'])
        try:
            player_df.to_csv(fname, index=None, mode="w+")

        except FileNotFoundError:
            #print(player_df.to_csv())
            continue

    #Next pull up the updated data and compute season's stats
    dataframe_collector = []
    for player in players_data:

        player_name = player['first_name']
        player_surname = player['second_name']
        player_id = str(player['history'][0]['element'])

        fname = "/home/zwi/zwi_work/Fantasy-Premier-League/data/2021-22/players/" + player_name + "_" + player_surname + "_" + player_id + "/gw.csv"

        try:
            player_rolling_stats = create_model_features(
                fname, True
            )  # This will give the player's rolling stats going into the next match.

        except FileNotFoundError:
            continue

        player_rolling_stats['player_id'] = player_id
        player_rolling_stats['player_name'] = player_name
        player_rolling_stats['player_surname'] = player_surname
        dataframe_collector.append(player_rolling_stats)
        #print(np.array(player_rolling_stats))
    consolidated_df = pd.concat(
        dataframe_collector)  #, columns=player_rolling_stats.columns)
    #consolidated_df.drop()

    await session.close()

    return consolidated_df
Exemple #26
0
async def fpl_login(email: str, password: str) -> int:
    """
    Login to FPL with given credentials
    :param: email - str
    :param: password - str
    """
    async with aiohttp.ClientSession() as session:
        fpl = FPL(session)
        await fpl.login(email, password)
        user = await fpl.get_user()
        return user.id
Exemple #27
0
async def check_update():
    async with aiohttp.ClientSession() as session:
        fpl = FPL(session)
        gw = await fpl.get_gameweeks(return_json=True)
        df = pd.DataFrame(gw)
        today = datetime.now()
        tomorrow = (today + timedelta(days=3)).timestamp()
        today = today.timestamp()
        df = df.loc[df.deadline_time_epoch > today]
        deadline = df.iloc[0].deadline_time_epoch
        return deadline < tomorrow
Exemple #28
0
async def get_gameweek_fixtures(gameweek_id):
    """
    Returns the fixtures for a given league and gameweek
    :param gameweek_id: the identifier for the gameweek to get fixtures for
    :return: fixtures for the gameweek
    """
    async with aiohttp.ClientSession() as session:
        fpl = FPL(session)
        await fpl.login(email=environ['FPL_EMAIL'],
                        password=environ['FPL_PASSWORD'])
        h2h_league = await fpl.get_h2h_league(environ['LEAGUE_ID'])
        return await h2h_league.get_fixtures(gameweek=gameweek_id)
Exemple #29
0
async def get_final_gameweek_fixture_date(gameweek_id):
    """
    Gets the date of the final fixture of a gameweek.
    :param gameweek_id: The id of a gameweek
    :return: the date of the last fixture
    """
    async with aiohttp.ClientSession() as session:
        fpl = FPL(session)
        await fpl.login(email=environ['FPL_EMAIL'],
                        password=environ['FPL_PASSWORD'])
        fixtures = await fpl.get_fixtures_by_gameweek(gameweek=gameweek_id)
        return fixtures[-1].kickoff_time
Exemple #30
0
async def get_current_fixtures():
    async with aiohttp.ClientSession() as session:
        fpl = FPL(session)
        current_gameweek = await utils.get_current_gameweek(session)
        fixtures = await fpl.get_fixtures_by_gameweek(current_gameweek)

    min_range = timedelta(minutes=2)
    return [
        fixture for fixture in fixtures
        if fixture.team_news_time.replace(tzinfo=None) - min_range < datetime.
        now() < fixture.team_news_time.replace(tzinfo=None) + min_range
    ]