File size: 5,160 Bytes
a22e862
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a7d59ca
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a22e862
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
import streamlit as st
import requests
import pandas as pd

st.set_page_config(page_title="MLB Prospect Pulse", layout="wide")

# Title and description
st.title("⚾ MLB Prospect Prediction Toolkit")
st.markdown("""
**Challenge 5 Solution**  
Predict prospect potential, compare players, and explore scenarios using MLB's GUMBO data.
""")

@st.cache_data
def get_schedule(season=2024):
    url = f"https://statsapi.mlb.com/api/v1/schedule?sportId=1&season={season}"
    return requests.get(url).json()

@st.cache_data
def get_roster(team_id=119, season=2024):  # Default: LA Dodgers
    url = f"https://statsapi.mlb.com/api/v1/teams/{team_id}/roster?season={season}"
    return requests.get(url).json()

@st.cache_data
def get_player_stats(player_id):
    url = f"https://statsapi.mlb.com/api/v1/people/{player_id}?hydrate=stats"
    return requests.get(url).json()


def prediction_section():
    st.header("🧠 Prospect Potential Prediction")
    
    try:
        # Get available teams with error handling
        schedule = get_schedule()
        teams = {}
        
        # Safely navigate through possible missing keys
        if 'dates' in schedule and len(schedule['dates']) > 0:
            for date in schedule['dates']:
                if 'games' in date:
                    for game in date['games']:
                        for team_type in ['home', 'away']:
                            team = game['teams'][team_type].get('team', {})
                            team_id = team.get('id')
                            team_name = team.get('name')
                            if team_id and team_name:
                                teams[team_id] = team_name
        
        if not teams:
            st.warning("No team data available. Using default teams.")
            teams = {119: "Los Angeles Dodgers"}  # Fallback
            
        col1, col2 = st.columns(2)
        with col1:
            team_id = st.selectbox("Select Team", options=teams.keys(), format_func=lambda x: teams[x])
        
        with col2:
            try:
                roster = get_roster(team_id).get('roster', [])
                players = {}
                for p in roster:
                    person = p.get('person', {})
                    players[person.get('id')] = person.get('fullName', 'Unknown Player')
                
                if not players:
                    st.error("No players found for this team")
                    return
                    
                player_id = st.selectbox("Select Prospect", options=players.keys(), format_func=lambda x: players[x])
            
            except Exception as e:
                st.error(f"Error loading roster: {str(e)}")
                return

        if st.button("Analyze Prospect"):
            try:
                stats = get_player_stats(player_id)
                # Add proper error handling for stats data
                if not stats:
                    st.error("No player stats available")
                    return
                
                # Placeholder for actual model prediction
                st.success(f"Predicted WAR in 3 years: 4.2 (Sample Output)")
                st.json(stats)  # Show raw data for inspection
                
            except Exception as e:
                st.error(f"Analysis failed: {str(e)}")

    except Exception as e:
        st.error(f"Failed to load schedule data: {str(e)}")


def comparison_tool():
    st.header("🔍 Player Comparison")
    
    # Get 2 players to compare
    roster = get_roster()['roster']
    players = {p['person']['id']: p['person']['fullName'] for p in roster}
    
    col1, col2 = st.columns(2)
    with col1:
        p1 = st.selectbox("Player 1", options=players.keys(), format_func=lambda x: players[x])
    with col2:
        p2 = st.selectbox("Player 2", options=players.keys(), format_func=lambda x: players[x])
    
    if p1 and p2:
        stats1 = get_player_stats(p1)
        stats2 = get_player_stats(p2)
        
        # Create comparison table (customize with actual metrics)
        comparison = pd.DataFrame({
            "Metric": ["Age", "BA", "HR", "SO"],
            players[p1]: [25, 0.285, 32, 110],  # Sample data
            players[p2]: [23, 0.265, 28, 95]
        }).set_index("Metric")
        
        st.dataframe(comparison, use_container_width=True)


def what_if_scenarios():
    st.header("🎮 What-If Analysis")
    
    # Interactive sliders
    col1, col2, col3 = st.columns(3)
    with col1:
        age = st.slider("Age", 18, 35, 22)
    with col2:
        ba = st.slider("Batting Average", 0.150, 0.400, 0.275)
    with col3:
        hr = st.slider("Projected HR", 0, 60, 25)
    
    # Add your model simulation here
    simulated_war = age * 0.1 + ba * 10 + hr * 0.2  # Example calculation
    st.metric("Simulated Future WAR", f"{simulated_war:.1f}")


def main():
    tabs = {
        "Prediction": prediction_section,
        "Comparison": comparison_tool,
        "What-If": what_if_scenarios
    }
    
    current_tab = st.sidebar.radio("Navigation", list(tabs.keys()))
    tabs[current_tab]()
    
if __name__ == "__main__":
    main()