Example #1
0
def show_current_team_picks(league_data, team_name, league_id):
    if not league_data:
        return "", ""
    if not team_name:
        return "", ""
    if not league_id:
        return "", ""

    if league_data and team_name:
        df_managers = pd.DataFrame(league_data)
        df_tmp = df_managers[df_managers["Team"] == team_name].copy()
        manager_id = df_tmp["entry_id"].unique().tolist()[0]
        df = query_manager_current_gw_picks(manager_id, league_id)
        team_points = (df["Points"] * df["multiplier"]).sum()
        expected_points = (df["xP"] * df["multiplier"]).sum()

        summary_section = html.Div(
            children=[
                html.P("Expected Points: {:.2f}".format(expected_points),
                       className='col-6'),
                html.P("Live Points: {}".format(team_points),
                       className='col-6'),
            ],
            className='row',
        )
        keep_cols = [
            "Player", "Team", "Position", "Top EO", "League EO", "xP", "Points"
        ]
        df = df[keep_cols].copy()
        table = make_table(df, page_size=11)
        return table, summary_section
Example #2
0
def make_league_standing_table(league_id):
    if not league_id:
        return "", None
    df = query_league_data(league_id)

    try:
        df = df.rename(
            columns={
                "entry_name": "Team",
                "manager_name": "Manager",
                "rank": "Rank",
                "score": "Points",
                "gw_points": "GW Score"
            })
        df["Rank Delta"] = (df["previous_rank"] - df["Rank"]).astype(int)
        df = df.sort_values(by="Points",
                            ascending=False).iloc[:100]  # keep top 100
        df_clean = df[["Team", "Manager", "Points", "GW Score",
                       "Rank Delta"]].copy()
        table = make_table(df_clean)
        return table, df.to_dict('records')
    except:
        return html.Div("Warning! This League Info Not Found!"), None
Example #3
0
def execute_transfer_suggestions(n_clicks, manager_id, num_transfers, gw_id,
                                 model_name):
    if not manager_id:
        msg = html.P("Please select manager...")
        return msg
    if not num_transfers:
        msg = html.P("Please select number of transfer to be made...")
        return msg
    if not gw_id:
        msg = html.P("Please select GW for scoring...")
        return msg
    if not model_name:
        msg = html.P("Please select ML Model...")
        return msg

    if n_clicks:
        tables = []
        n_suggestions = 5
        df_leads = load_leads(gw_id)

        for i in range(n_suggestions):
            try:
                df_transfer = transfer_optimizer(df_leads, manager_id,
                                                 num_transfers, model_name)
                tables.append(make_table(df_transfer))
                exclude_names = df_transfer["Transfer In"].unique().tolist()
                df_leads = df_leads[~df_leads["name"].isin(exclude_names
                                                           )].copy()
            except:
                pass

        output = html.Div(children=tables)

        return output

    return html.P("Button Not Clicked!")
Example #4
0
def execute_fastai_return_scoring(team_name, model_name, gw_id):
    if not gw_id:
        msg = html.P("Please select GW for scoring")
        return msg, msg, msg, msg

    if not model_name:
        msg = html.P("Please select Model")
        return msg, msg, msg, msg

    model_name_col_map = {
        "LGBM Point": "lgbm_point_pred",
        "LGBM Potential": "lgbm_potential_pred",
        "LGBM Return": "lgbm_return_pred",
        "Fast Point": "fastai_point_pred",
        "Fast Potential": "fastai_potential_pred",
        "Fast Return": "fastai_return_pred"
    }

    print("Leads for {} in gw {}".format(team_name, gw_id))
    data_maker = ModelDataMaker(CONFIG_2020)
    output_dir = "./data/model_outputs/"

    # load model predictions
    lgbm_point_path = os.path.join(
        output_dir, "lgbm_point_predictions_gw_{}.csv".format(gw_id))
    lgbm_potential_path = os.path.join(
        output_dir, "lgbm_potential_predictions_gw_{}.csv".format(gw_id))
    lgbm_return_path = os.path.join(
        output_dir, "lgbm_return_predictions_gw_{}.csv".format(gw_id))

    fastai_point_path = os.path.join(
        output_dir, "fastai_point_predictions_gw_{}.csv".format(gw_id))
    fastai_potential_path = os.path.join(
        output_dir, "fastai_potential_predictions_gw_{}.csv".format(gw_id))
    fastai_return_path = os.path.join(
        output_dir, "fastai_return_predictions_gw_{}.csv".format(gw_id))

    df_lgbm_point = load_dataframe(lgbm_point_path)
    df_lgbm_potential = load_dataframe(lgbm_potential_path)
    df_lgbm_return = load_dataframe(lgbm_return_path)
    df_fastai_point = load_dataframe(fastai_point_path)
    df_fastai_potential = load_dataframe(fastai_potential_path)
    df_fastai_return = load_dataframe(fastai_return_path)

    all_preds_df = [
        df_lgbm_point, df_lgbm_potential, df_lgbm_return, df_fastai_point,
        df_fastai_potential, df_fastai_return
    ]

    for df in all_preds_df:
        try:
            assert len(df) > 0
        except:
            msg = html.P("Run scoring for models before generating leads")
            return msg, msg, msg, msg

    # prepare prediction base dataframe
    XY_train, XY_test, XY_scoring, features_dict = load_data(gw_id)
    player_id_team_id_map = data_maker.get_player_id_team_id_map()
    player_id_player_name_map = data_maker.get_player_id_player_name_map()
    player_id_player_position_map = data_maker.get_player_id_player_position_map(
    )
    team_id_team_name_map = data_maker.get_team_id_team_name_map()
    player_id_cost_map = data_maker.get_player_id_cost_map()
    player_id_play_chance_map = data_maker.get_player_id_play_chance_map()
    player_id_selection_map = data_maker.get_player_id_selection_map()
    player_id_ave_points_map = data_maker.get_player_id_ave_points_map()

    df_leads = pd.DataFrame()
    df_leads["player_id"] = XY_scoring["player_id"].values
    df_leads["name"] = df_leads["player_id"].apply(
        lambda x: player_id_player_name_map.get(x, x))
    df_leads["team"] = df_leads["player_id"].apply(
        lambda x: team_id_team_name_map[player_id_team_id_map.get(x, x)])
    df_leads["next_opponent"] = XY_scoring["opp_team_id"].apply(
        lambda x: team_id_team_name_map.get(x, x))
    df_leads["position"] = df_leads["player_id"].apply(
        lambda x: player_id_player_position_map.get(x, x))
    df_leads["chance_of_play"] = df_leads["player_id"].apply(
        lambda x: player_id_play_chance_map.get(x, x))
    df_leads["cost"] = df_leads["player_id"].apply(
        lambda x: player_id_cost_map.get(x, x))
    df_leads["selection_pct"] = df_leads["player_id"].apply(
        lambda x: player_id_selection_map.get(x, x))
    df_leads["ave_pts"] = df_leads["player_id"].apply(
        lambda x: player_id_ave_points_map.get(x, x))
    df_leads["gw"] = gw_id
    df_leads = df_leads.drop_duplicates(subset=["player_id"])

    if team_name != "All":
        df_leads = df_leads[df_leads["team"] == team_name].copy()

    # merge predictions
    for df in all_preds_df:
        df = df.drop_duplicates()
        df_leads = pd.merge(df_leads, df, how='left', on=['player_id', 'gw'])
    # keep_cols = ["name", "cost", "position", "selection_pct", "next_opponent", "lgbm_point_pred", "lgbm_potential_pred"]
    # df_leads = df_leads[keep_cols].copy()
    # make tables
    df_leads["cost"] = df_leads["cost"] / 10
    model_col = model_name_col_map[model_name]
    df_leads = df_leads.sort_values(by=model_col, ascending=False)

    # column round up
    pred_cols = [
        "lgbm_point_pred", "lgbm_potential_pred", "lgbm_return_pred",
        "fastai_point_pred", "fastai_potential_pred", "fastai_return_pred"
    ]
    for col in pred_cols:
        df_leads[col] = df_leads[col].round(2)

    df_gk = df_leads[df_leads["position"] == "GK"].copy()
    df_def = df_leads[df_leads["position"] == "DEF"].copy()
    df_mid = df_leads[df_leads["position"] == "MID"].copy()
    df_fwd = df_leads[df_leads["position"] == "FWD"].copy()

    col_map = {
        "name": "Player",
        "cost": "Cost",
        "next_opponent": "Opponent",
        "selection_pct": "TSB"
    }
    base_cols = ["name", "cost", "selection_pct", "next_opponent", model_col]
    col_map[model_col] = model_name

    df_gk = df_gk[base_cols].copy()
    df_gk = df_gk.rename(columns=col_map)
    gk_table = make_table(df_gk)

    df_def = df_def[base_cols].copy()
    df_def = df_def.rename(columns=col_map)
    def_table = make_table(df_def)

    df_mid = df_mid[base_cols].copy()
    df_mid = df_mid.rename(columns=col_map)
    mid_table = make_table(df_mid)

    df_fwd = df_fwd[base_cols].copy()
    df_fwd = df_fwd.rename(columns=col_map)
    fwd_table = make_table(df_fwd)
    return gk_table, def_table, mid_table, fwd_table
Example #5
0
def execute_squad_optimization(n_clicks, gw_id, model_name, formation,
                               squad_val, bench_val, uncertain_flag):
    if not gw_id:
        msg = html.P("Please select GW for scoring")
        return msg, msg

    if not model_name:
        msg = html.P("Please select Model")
        return msg, msg

    if not formation:
        msg = html.P("Please select Formation")
        return msg, msg

    if not squad_val:
        msg = html.P("Please select Squad Value")
        return msg, msg

    if not bench_val:
        msg = html.P("Please select Bench Value")
        return msg, msg

    if not uncertain_flag:
        msg = html.P("Please select Uncertain Flag")
        return msg, msg
    df_leads = load_leads(gw_id)
    # pdb.set_trace()
    df_leads["name"] = df_leads["name"].apply(
        lambda x: str(x).encode('ascii', 'ignore'))
    print(df_leads.head())
    if n_clicks:
        df_squad_xi, sol_info_xi = squad_optimizer(df_leads,
                                                   formation=formation,
                                                   budget=squad_val -
                                                   bench_val,
                                                   optimise_on=model_name)
        xi_players = [int(i) for i in formation.split('-')]
        bench_players = [
            str(2 - xi_players[0]),
            str(5 - xi_players[1]),
            str(5 - xi_players[2]),
            str(3 - xi_players[3])
        ]
        bench_formation = "-".join(bench_players)
        xi_names = df_squad_xi["name"].unique().tolist()
        df_leads = df_leads[~df_leads["name"].isin(xi_names)].copy()
        df_squad_bench, sol_info_bench = squad_optimizer(
            df_leads,
            formation=bench_formation,
            budget=bench_val,
            optimise_on=model_name)

        df_squad_xi["name"] = df_squad_xi["name"].apply(
            lambda x: x.decode('utf-8'))
        df_squad_bench["name"] = df_squad_bench["name"].apply(
            lambda x: x.decode('utf-8'))
        # df_squad = df_squad[["position", "cost", "points"]].copy()
        df_squad_xi["points"] = df_squad_xi["points"].round(2)
        df_squad_bench["points"] = df_squad_bench["points"].round(2)
        col_map = {
            "name": "Player",
            "team": "Team",
            "cost": "Cost",
            "position": "Position",
            "points": model_name
        }
        df_squad_xi = df_squad_xi.rename(columns=col_map)
        df_squad_bench = df_squad_bench.rename(columns=col_map)
        position_map = {'GK': 1, 'DEF': 2, 'MID': 3, 'FWD': 4}

        df_squad_xi["pos_map"] = df_squad_xi["Position"].apply(
            lambda x: position_map[x])
        df_squad_bench["pos_map"] = df_squad_bench["Position"].apply(
            lambda x: position_map[x])
        df_squad_xi = df_squad_xi.sort_values(by=["pos_map"])
        df_squad_bench = df_squad_bench.sort_values(by=["pos_map"])
        df_squad_xi = df_squad_xi.drop(columns=["pos_map"])
        df_squad_bench = df_squad_bench.drop(columns=["pos_map"])
        table_xi, table_bench = make_table(
            df_squad_xi, page_size=11), make_table(df_squad_bench)

        return table_xi, table_bench
    else:
        return html.P("Button Not Clicked!")