Exemplo n.º 1
0
def fill_ep(csv_filename, dbsession=session):
    """
    fill the database with FPLs ep_next prediction, and also
    write output to a csv.
    """
    if not os.path.exists(csv_filename):
        outfile = open(csv_filename, "w")
        outfile.write("player_id,gameweek,EP\n")
    else:
        outfile = open(csv_filename, "a")

    summary_data = fetcher.get_player_summary_data()
    gameweek = NEXT_GAMEWEEK
    for k, v in summary_data.items():
        player = get_player_from_api_id(k)
        player_id = player.player_id
        outfile.write("{},{},{}\n".format(player_id, gameweek, v["ep_next"]))
        pp = PlayerPrediction()
        pp.player_id = player_id
        pp.gameweek = gameweek
        pp.predicted_points = v["ep_next"]
        pp.method = "EP"
        dbsession.add(pp)
    dbsession.commit()
    outfile.close()
Exemplo n.º 2
0
def fill_initial_team(session,
                      season=CURRENT_SEASON,
                      tag="AIrsenal" + CURRENT_SEASON):
    """
    Fill the Transactions table in the database with the initial 15 players, and their costs,
    getting the information from the team history API endpoint (for the list of players in our team)
    and the player history API endpoint (for their price in gw1).
    """
    print("SQUAD Getting selected players for gameweek 1...")
    if NEXT_GAMEWEEK == 1:
        ### Season hasn't started yet - there won't be a team in the DB
        return True

    free_hit = free_hit_used_in_gameweek(1)
    init_players = get_players_for_gameweek(1)
    for pid in init_players:
        player_api_id = get_player(pid).fpl_api_id
        gw1_data = fetcher.get_gameweek_data_for_player(player_api_id, 1)

        if len(gw1_data) == 0:
            # Edge case where API doesn't have player data for gameweek 1, e.g. in 20/21
            # season where 4 teams didn't play gameweek 1. Calculate GW1 price from
            # API using current price and total price change.
            print(
                "Using current data to determine starting price for player {}".
                format(player_api_id))
            pdata = fetcher.get_player_summary_data()[player_api_id]
            price = pdata["now_cost"] - pdata["cost_change_start"]
        else:
            price = gw1_data[0]["value"]

        add_transaction(pid, 1, 1, price, season, tag, free_hit, session)
def fill_initial_squad(
    season=CURRENT_SEASON,
    tag="AIrsenal" + CURRENT_SEASON,
    fpl_team_id=None,
    dbsession=session,
):
    """
    Fill the Transactions table in the database with the initial 15 players, and their
    costs, getting the information from the team history API endpoint (for the list of
    players in our team) and the player history API endpoint (for their price in gw1).
    """

    if not fpl_team_id:
        fpl_team_id = fetcher.FPL_TEAM_ID
    print(
        "Getting initially selected players in squad {} for first gameweek...".
        format(fpl_team_id))
    if NEXT_GAMEWEEK == 1:
        # Season hasn't started yet - there won't be a team in the DB
        return True

    starting_gw = get_entry_start_gameweek(fpl_team_id)
    print(
        f"Got starting squad from gameweek {starting_gw}. Adding player data..."
    )

    init_players = get_players_for_gameweek(starting_gw, fpl_team_id)
    free_hit = free_hit_used_in_gameweek(starting_gw, fpl_team_id)
    time = fetcher.get_event_data()[starting_gw]["deadline"]
    for pid in init_players:
        player_api_id = get_player(pid).fpl_api_id
        first_gw_data = fetcher.get_gameweek_data_for_player(
            player_api_id, starting_gw)

        if len(first_gw_data) == 0:
            # Edge case where API doesn't have player data for gameweek 1, e.g. in 20/21
            # season where 4 teams didn't play gameweek 1. Calculate GW1 price from
            # API using current price and total price change.
            print(
                "Using current data to determine starting price for player {}".
                format(player_api_id))
            pdata = fetcher.get_player_summary_data()[player_api_id]
            price = pdata["now_cost"] - pdata["cost_change_start"]
        else:
            price = first_gw_data[0]["value"]

        add_transaction(
            pid,
            starting_gw,
            1,
            price,
            season,
            tag,
            free_hit,
            fpl_team_id,
            time,
            dbsession,
        )
Exemplo n.º 4
0
def update_players(season, dbsession):
    """
    See if any new players have been added to FPL since we last filled the 'player'
    table in the db.  If so, add them.
    """
    players_from_db = list_players(
        position="all", team="all", season=season, dbsession=dbsession
    )
    player_data_from_api = fetcher.get_player_summary_data()
    players_from_api = list(player_data_from_api.keys())

    if len(players_from_db) == len(players_from_api):
        print("Player table already up-to-date.")
        return 0
    elif len(players_from_db) > len(players_from_api):
        raise RuntimeError(
            "Something strange has happened - more players in DB than API"
        )
    else:
        print("Updating player table...")
        # find the new player(s) from the API
        api_ids_from_db = [p.fpl_api_id for p in players_from_db]
        new_players = [p for p in players_from_api if p not in api_ids_from_db]
        for player_api_id in new_players:
            first_name = player_data_from_api[player_api_id]["first_name"]
            second_name = player_data_from_api[player_api_id]["second_name"]
            name = "{} {}".format(first_name, second_name)
            # check whether we alreeady have this player in the database -
            # if yes update that player's data, if no create a new player
            p = get_player(name, dbsession=dbsession)
            if p is None:
                print("Adding player {}".format(name))
                p = Player()
                update = False
            elif p.fpl_api_id is None:
                print("Updating player {}".format(name))
                update = True
            else:
                update = True
            p.fpl_api_id = player_api_id
            p.name = name
            if not update:
                dbsession.add(p)
        dbsession.commit()
        return len(new_players)
Exemplo n.º 5
0
def is_injured_or_suspended(player_api_id, gameweek, season, session):
    """
    Query the API for 'chance of playing next round', and if this
    is <=50%, see if we can find a return date.
    """
    if season != CURRENT_SEASON:  # no API info for past seasons
        return False
    ## check if a player is injured or suspended
    pdata = fetcher.get_player_summary_data()[player_api_id]
    if ("chance_of_playing_next_round" in pdata.keys()
            and pdata["chance_of_playing_next_round"] is not None
            and pdata["chance_of_playing_next_round"] <= 50):
        ## check if we have a return date
        return_gameweek = get_return_gameweek_for_player(
            player_api_id, session)
        if return_gameweek is None or return_gameweek > gameweek:
            return True
    return False
Exemplo n.º 6
0
    def get_sell_price_for_player(
        self,
        player,
        use_api=False,
        season=CURRENT_SEASON,
        gameweek=NEXT_GAMEWEEK,
        dbsession=None,
    ):
        """Get sale price for player (a player in self.players) in the current
        gameweek of the current season.
        """
        price_bought = player.purchase_price
        player_id = player.player_id
        price_now = None
        if use_api and season == CURRENT_SEASON and gameweek >= NEXT_GAMEWEEK:
            try:
                # first try getting the price for the player from the API
                player_db = get_player(player_id)
                price_now = fetcher.get_player_summary_data()[
                    player_db.fpl_api_id]["now_cost"]
            except:
                pass

        if not price_now:
            player_db = get_player(player_id, dbsession=dbsession)

            if player_db:
                price_now = player_db.price(season, gameweek)
        if not price_now:
            # if all else fails just use the purchase price as the sale
            # price for this player.
            print(
                "Using purchase price as sale price for",
                player.player_id,
                player.name,
            )
            price_now = price_bought

        if price_now > price_bought:
            price_sell = (price_now + price_bought) // 2
        else:
            price_sell = price_now
        return price_sell
Exemplo n.º 7
0
def update_players(season, dbsession):
    """
    See if any new players have been added to FPL since we last filled the 'player'
    table in the db.  If so, add them.
    """
    players_from_db = list_players(position="all",
                                   team="all",
                                   season=season,
                                   dbsession=dbsession)
    player_data_from_api = fetcher.get_player_summary_data()
    players_from_api = list(player_data_from_api.keys())

    if len(players_from_db) == len(players_from_api):
        print("Player table already up-to-date.")
        return 0
    elif len(players_from_db) > len(players_from_api):
        raise RuntimeError(
            "Something strange has happened - more players in DB than API")
    else:
        return add_players_to_db(players_from_db, players_from_api,
                                 player_data_from_api, dbsession)