Example #1
0
def print_strat(strat):
    """
    nicely formated printout as output of optimization.
    """

    gameweeks_as_str = strat["points_per_gw"].keys()
    gameweeks_as_int = sorted([int(gw) for gw in gameweeks_as_str])
    print(" ===============================================")
    print(" ========= Optimum strategy ====================")
    print(" ===============================================")
    for gw in gameweeks_as_int:
        print("\n =========== Gameweek {} ================\n".format(gw))
        print("Chips played:  {}\n".format(strat["chips_played"][str(gw)]))
        print("Players in:\t\t\tPlayers out:")
        print("-----------\t\t\t------------")
        for i in range(len(strat["players_in"][str(gw)])):
            pin = get_player_name(strat["players_in"][str(gw)][i])
            pout = get_player_name(strat["players_out"][str(gw)][i])
            if len(pin) < 20:
                subs = "{}\t\t\t{}".format(pin, pout)
            else:
                subs = "{}\t\t{}".format(pin, pout)
            print(subs)
    print("\n==========================")
    print(" Total score: {} \n".format(int(strat["total_score"])))
Example #2
0
def discord_payload(strat, lineup):
    """
    json formated discord webhook contentent.
    """
    gameweeks_as_str = strat["points_per_gw"].keys()
    gameweeks_as_int = sorted([int(gw) for gw in gameweeks_as_str])
    discord_embed = {
        "title":
        "AIrsenal webhook",
        "description":
        "Optimum strategy for gameweek(S)"
        " {}:".format(",".join(str(x) for x in gameweeks_as_int)),
        "color":
        0x35A800,
        "fields": [],
    }
    for gw in gameweeks_as_int:
        discord_embed["fields"].append({
            "name":
            "GW{} chips:".format(gw),
            "value":
            "Chips played:  {}\n".format(strat["chips_played"][str(gw)]),
            "inline":
            False,
        })
        pin = [get_player_name(p) for p in strat["players_in"][str(gw)]]
        pout = [get_player_name(p) for p in strat["players_out"][str(gw)]]
        discord_embed["fields"].extend([
            {
                "name": "GW{} transfers out:".format(gw),
                "value": "{}".format("\n".join(pout)),
                "inline": True,
            },
            {
                "name": "GW{} transfers in:".format(gw),
                "value": "{}".format("\n".join(pin)),
                "inline": True,
            },
        ])
    payload = {
        "content": "\n".join(lineup),
        "username": "******",
        "embeds": [discord_embed],
    }
    return payload
def build_strategy_string(rows):
    output_string = "Suggested transfer strategy: \n"
    current_gw = 0
    for row in rows:
        if row.gameweek != current_gw:
            output_string += " gameweek {}: ".format(row.gameweek)
            current_gw = row.gameweek
        output_string += " sell " if row.in_or_out < 0 else " buy "
        output_string += get_player_name(row.player_id) + ","
    output_string += " for a total gain of {} points.".format(rows[0].points_gain)
    return output_string
Example #4
0
def print_output(
    team_id, current_gw, priced_transfers, pre_bank, post_bank, points_cost="TODO"
):

    print("\n")
    header = f"Transfers to apply for fpl_team_id: {team_id} for gameweek: {current_gw}"
    line = "=" * len(header)
    print(f"{header} \n {line} \n")

    print(f"Bank Balance Before transfers is: £{pre_bank/10}")

    t = PrettyTable(["Status", "Name", "Price"])
    for transfer in priced_transfers:
        t.add_row(["OUT", get_player_name(transfer[0][0]), f"£{transfer[0][1]/10}"])
        t.add_row(["IN", get_player_name(transfer[1][0]), f"£{transfer[1][1]/10}"])

    print(t)

    print(f"Bank Balance After transfers is: £{post_bank/10}")
    # print(f"Points Cost of Transfers: {points_cost}")
    print("\n")
def get_player_history_table(position="all"):
    """
    Query the player_score table.
    """
    with open("player_history_{}.csv".format(position), "w") as output_file:
        output_file.write(
            "player_id,player_name,match_id,goals,assists,minutes,team_goals\n"
        )
        player_ids = list_players(position)
        for pid in player_ids:
            player_name = get_player_name(pid)
            results = session.query(PlayerScore).filter_by(player_id=pid).all()
            row_count = 0
            for row in results:
                minutes = row.minutes
                match_id = row.match_id
                goals = row.goals
                assists = row.assists
                # find the match, in order to get team goals
                Match = None  # TODO: Placeholder for missing (deprecated?) Match class
                match = session.query(Match).filter_by(
                    match_id=row.match_id).first()
                if match.home_team == row.opponent:
                    team_goals = match.away_score
                elif match.away_team == row.opponent:
                    team_goals = match.home_score
                else:
                    print("Unknown opponent!")
                    team_goals = -1
                output_file.write("{},{},{},{},{},{},{}\n".format(
                    pid, player_name, match_id, goals, assists, minutes,
                    team_goals))
                row_count += 1
            if row_count < 38 * 3:
                for _ in range(row_count, 38 * 3):
                    output_file.write("{},{},0,0,0,0,0\n".format(
                        pid, player_name))
#!/usr/bin/env python
"""
query the transfer_suggestion table.  Each row of the table
will be in individual player in-or-out in a gameweek - we
therefore need to group together all the rows that correspond
to the same transfer strategy.  We do this using the "timestamp".
"""

from airsenal.framework.schema import TransferSuggestion
from airsenal.framework.utils import session, get_player_name

if __name__ == "__main__":
    all_rows = session.query(TransferSuggestion).all()
    last_timestamp = all_rows[-1].timestamp
    rows = (session.query(TransferSuggestion).filter_by(
        timestamp=last_timestamp).order_by(TransferSuggestion.gameweek).all())
    output_string = "Suggested transfer strategy: \n"
    current_gw = 0
    for row in rows:
        if row.gameweek != current_gw:
            output_string += " gameweek {}: ".format(row.gameweek)
            current_gw = row.gameweek
        if row.in_or_out < 0:
            output_string += " sell "
        else:
            output_string += " buy "
        output_string += get_player_name(row.player_id) + ","
    output_string += " for a total gain of {} points.".format(
        rows[0].points_gain)
    print(output_string)
Example #7
0
def test_get_player_name(fill_players):
    """
    Should be able to find a player with integer argument
    """
    with test_session_scope() as tsession:
        assert get_player_name(1, tsession) == "Bob"