File size: 3,976 Bytes
fb7f2c1
7cf6c15
 
fb7f2c1
 
7cf6c15
fb7f2c1
7cf6c15
fb7f2c1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f413cfe
 
 
 
 
 
 
f4b177d
7cf6c15
4d4b05d
7cf6c15
 
 
 
 
 
 
dd56812
 
4d4b05d
 
 
7cf6c15
fb7f2c1
 
 
 
 
 
 
 
 
99353b8
fb7f2c1
 
 
 
 
 
 
 
 
f413cfe
 
 
 
 
 
fb7f2c1
 
 
 
 
 
f4b177d
fb7f2c1
f413cfe
fb7f2c1
7cf6c15
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
import pandas as pd
import streamlit as st

from config import DEFAULT_ICON, SEASON
from login_component import is_token_in_session
from shared_page import common_page_config
from simulate import create_simulate_summary, run_simulations


@st.cache_resource(ttl=60 * 60 * 24)
def get_all_league_settings_with_cache(season: int):
    return st.session_state.yahoo_client.get_all_logged_in_user_league_settings(season=season)


@st.cache_resource(ttl=60 * 60 * 24)
def get_schedule_with_cache(league_key):
    return st.session_state.yahoo_client.full_schedule_dataframe(league_key)


def clear_all():
    for session_key in st.session_state.keys():
        if session_key[:13] == "match-filter-":
            st.session_state[session_key] = None
    return


def show_week_matches(schedule: pd.DataFrame, week: int | str):
    df_week = schedule[schedule.week == week]
    columns = st.columns(df_week.match_index.nunique())
    match_filter_map = {}
    for match_col, (match_index, df) in zip(columns, df_week.groupby("match_index")):
        with match_col:
            match_winner = st.radio(
                "Set winner",
                key=f"match-filter-{match_index}",
                options=df.team_name.tolist(),
                index=None,
            )
            if match_winner:
                match_filter_map[match_index] = match_winner
    return match_filter_map


def get_sim_with_file_cache(league_key, schedule: pd.DataFrame, complete_weeks: int, n_sims: int, n_playoff: int):
    file_name = f"sims_{league_key}_{complete_weeks}.parquet"
    try:
        return pd.read_parquet(file_name)
    except Exception:
        df = run_simulations(schedule, complete_weeks, n_sims, n_playoff)
        df.to_parquet(file_name)
        return pd.read_parquet(file_name)


def get_page():
    page_title = "Yahoo FF League Simulation"
    st.set_page_config(page_title=page_title, page_icon=DEFAULT_ICON, layout="wide")
    common_page_config()
    st.title(page_title)

    if not is_token_in_session():
        st.write(
            "You must authorize the application to access your account in order to use this feature."
            " Please click Login button above."
        )

    else:
        selected_season = st.selectbox("Select Season", list(range(SEASON, 2012, -1)))
        user_leagues = get_all_league_settings_with_cache(season=selected_season)
        selected_league = st.selectbox("Select league", user_leagues, format_func=lambda x: x.name)
        st.header(f"{selected_league.name} - {selected_league.season}")

        df_schedule = get_schedule_with_cache(selected_league.league_key)
        # st.dataframe(df_schedule)
        st.write(f"Current Week: {selected_league.current_week}")
        sim_result = pd.DataFrame()
        n_sims = 10000

        st.header("Match Scenarios")
        st.write("Select match winners to filter simulation scenarios")
        all_match_filters = {}
        st.button("Reset", on_click=clear_all)
        for week in range(selected_league.current_week, selected_league.playoff_start_week):
            with st.expander(f"Week {week}"):
                all_match_filters[week] = show_week_matches(df_schedule, week)

        sim_result = get_sim_with_file_cache(
            selected_league.league_key,
            df_schedule,
            selected_league.current_week - 1,
            n_sims,
            selected_league.num_playoff_teams,
        )

        if len(sim_result):
            filtered_sims = sim_result.copy()
            for week, filtered_match_dict in all_match_filters.items():
                for match_index, match_winner in filtered_match_dict.items():
                    filtered_sims = filtered_sims[filtered_sims[str(float(week))][str(match_index)] == match_winner]

            st.write(f"Number of Scenarios included in filter: {len(filtered_sims)} / {n_sims}")
            st.dataframe(create_simulate_summary(filtered_sims))


if __name__ == "__main__":
    get_page()