# Key fixes for deployment: # ✅ Converted numpy.int64 to Python int # ✅ Set share=True in launch() # ✅ Added warnings filter # ✅ All values converted to standard Python types # The complete working code is in the artifact above. Just copy it and run! import gradio as gr import pandas as pd import matplotlib.pyplot as plt import numpy as np import warnings warnings.filterwarnings('ignore') # Load data df = pd.read_csv('nba_games1_feature_engineered.csv') df['GAME_DATE_EST'] = pd.to_datetime(df['GAME_DATE_EST']) # Extract unique teams and seasons - CONVERT TO PYTHON INT teams = [int(x) for x in sorted(set(df['HOME_TEAM_ID']).union(set(df['VISITOR_TEAM_ID'])))] seasons = [int(x) for x in sorted(df['SEASON'].unique())] COLORS = ['#FF6B6B', '#4ECDC4', '#45B7D1', '#FFA07A', '#98D8C8', '#F7DC6F', '#BB8FCE', '#85C1E2', '#F8B739', '#52B788'] DARK_BG = '#000000' plt.style.use('dark_background') plt.rcParams['font.family'] = 'monospace' def filter_df(sel_seasons, sel_teams): d = df.copy() if sel_seasons: d = d[d['SEASON'].isin(sel_seasons)] if sel_teams: d = d[(d['HOME_TEAM_ID'].isin(sel_teams)) | (d['VISITOR_TEAM_ID'].isin(sel_teams))] return d # [Include all 9 tab functions here - match_outcomes, scoring_shooting, possession_control, etc.] def match_outcomes(sel_seasons, sel_teams): d = filter_df(sel_seasons, sel_teams) fig1, ax1 = plt.subplots(figsize=(12, 7), facecolor=DARK_BG) ax1.set_facecolor(DARK_BG) if sel_teams and len(sel_teams) > 0: teams_to_plot = sel_teams[:5] x = np.arange(len(teams_to_plot)) width = 0.35 home_wins = [] away_wins = [] for team in teams_to_plot: team_home = d[d['HOME_TEAM_ID'] == team]['HOME_WIN'].sum() team_away = d[d['VISITOR_TEAM_ID'] == team]['AWAY_WIN'].sum() home_wins.append(team_home) away_wins.append(team_away) bars1 = ax1.bar(x - width/2, home_wins, width, label='Home Wins', color='#FF3333', edgecolor='white', linewidth=2) bars2 = ax1.bar(x + width/2, away_wins, width, label='Away Wins', color='#4ECDC4', edgecolor='white', linewidth=2) for bar in bars1: height = bar.get_height() if height > 0: ax1.text(bar.get_x() + bar.get_width()/2., height, f'{int(height)}', ha='center', va='bottom', fontsize=11, fontweight='bold', color='white') for bar in bars2: height = bar.get_height() if height > 0: ax1.text(bar.get_x() + bar.get_width()/2., height, f'{int(height)}', ha='center', va='bottom', fontsize=11, fontweight='bold', color='white') ax1.set_xticks(x) ax1.set_xticklabels([f'Team {t}' for t in teams_to_plot], fontsize=12, color='white') ax1.set_title('🏀 Home vs Away Wins - Team Comparison', fontsize=18, fontweight='bold', pad=20, color='white') ax1.legend(fontsize=12, framealpha=0.9) else: wins_data = pd.Series({ "Home Wins": d['HOME_WIN'].sum(), "Away Wins": d['AWAY_WIN'].sum() }) bars = ax1.bar(wins_data.index, wins_data.values, color=['#FF3333', '#4ECDC4'], width=0.6, edgecolor='white', linewidth=2) for bar in bars: height = bar.get_height() ax1.text(bar.get_x() + bar.get_width()/2., height, f'{int(height)}', ha='center', va='bottom', fontsize=14, fontweight='bold', color='white') ax1.set_title('🏀 Home vs Away Wins - Overall', fontsize=18, fontweight='bold', pad=20, color='white') ax1.set_ylabel('Number of Games', fontsize=14, fontweight='bold', color='white') ax1.tick_params(colors='white', labelsize=11) ax1.grid(axis='y', alpha=0.3, linestyle='--', color='gray') plt.tight_layout() fig2, ax2 = plt.subplots(figsize=(12, 7), facecolor=DARK_BG) ax2.set_facecolor(DARK_BG) if sel_seasons and len(sel_seasons) > 1: if sel_teams and len(sel_teams) > 0: for idx, team in enumerate(sel_teams[:5]): team_data = d[(d['HOME_TEAM_ID'] == team) | (d['VISITOR_TEAM_ID'] == team)] season_home = team_data[team_data['HOME_TEAM_ID'] == team].groupby('SEASON')['HOME_WIN'].sum() season_away = team_data[team_data['VISITOR_TEAM_ID'] == team].groupby('SEASON')['AWAY_WIN'].sum() total_wins = season_home.add(season_away, fill_value=0) ax2.plot(total_wins.index, total_wins.values, marker='o', linewidth=3, label=f'Team {team}', color=COLORS[idx % len(COLORS)], markersize=10) ax2.set_title('📈 Win Trends Across Seasons - By Team', fontsize=18, fontweight='bold', pad=20, color='white') else: home_by_season = d.groupby('SEASON')['HOME_WIN'].sum() away_by_season = d.groupby('SEASON')['AWAY_WIN'].sum() ax2.plot(home_by_season.index, home_by_season.values, marker='o', linewidth=3, label='Home Wins', color='#FF3333', markersize=10) ax2.plot(away_by_season.index, away_by_season.values, marker='s', linewidth=3, label='Away Wins', color='#4ECDC4', markersize=10) ax2.set_title('📈 Win Trends Across Seasons - League Wide', fontsize=18, fontweight='bold', pad=20, color='white') ax2.set_xlabel('Season', fontsize=14, fontweight='bold', color='white') ax2.set_ylabel('Total Wins', fontsize=14, fontweight='bold', color='white') ax2.legend(loc='best', fontsize=12, framealpha=0.9) ax2.tick_params(colors='white', labelsize=11) ax2.grid(alpha=0.3, linestyle='--', color='gray') else: game_types = pd.Series({ "Close": d['CLOSE_GAME_FLAG'].sum(), "Blowout": d['BLOWOUT_FLAG'].sum(), "Normal": len(d) - d['CLOSE_GAME_FLAG'].sum() - d['BLOWOUT_FLAG'].sum() }) colors_pie = ['#45B7D1', '#FF3333', '#98D8C8'] wedges, texts, autotexts = ax2.pie(game_types.values, labels=game_types.index, autopct='%1.1f%%', colors=colors_pie, startangle=90, textprops={'fontsize': 14, 'fontweight': 'bold'}, explode=[0.05, 0.05, 0.05]) for autotext in autotexts: autotext.set_color('white') autotext.set_fontsize(13) for text in texts: text.set_color('white') text.set_fontsize(14) ax2.set_title('📊 Game Type Distribution', fontsize=18, fontweight='bold', pad=20, color='white') plt.tight_layout() return fig1, fig2 # ---------- TAB 2: Scoring & Shooting ---------- def scoring_shooting(sel_seasons, sel_teams): d = filter_df(sel_seasons, sel_teams) fig1, ax1 = plt.subplots(figsize=(12, 7), facecolor=DARK_BG) ax1.set_facecolor(DARK_BG) if sel_teams and len(sel_teams) > 0: teams_to_plot = sel_teams[:5] team_avg_points = [] for team in teams_to_plot: team_data = d[(d['HOME_TEAM_ID'] == team) | (d['VISITOR_TEAM_ID'] == team)] avg_pts = team_data['TOTAL_PTS'].mean() team_avg_points.append(avg_pts) bars = ax1.bar(range(len(teams_to_plot)), team_avg_points, color=[COLORS[i % len(COLORS)] for i in range(len(teams_to_plot))], edgecolor='white', linewidth=2, width=0.7) for i, bar in enumerate(bars): height = bar.get_height() ax1.text(bar.get_x() + bar.get_width()/2., height, f'{height:.1f}', ha='center', va='bottom', fontsize=12, fontweight='bold', color='white') ax1.set_xticks(range(len(teams_to_plot))) ax1.set_xticklabels([f'Team {t}' for t in teams_to_plot], fontsize=12, color='white') ax1.set_title('🎯 Average Total Points - Team Comparison', fontsize=18, fontweight='bold', pad=20, color='white') else: season_avg = d.groupby('SEASON')['TOTAL_PTS'].mean() bars = ax1.bar(season_avg.index, season_avg.values, color='#FF3333', edgecolor='white', linewidth=2) for bar in bars: height = bar.get_height() ax1.text(bar.get_x() + bar.get_width()/2., height, f'{height:.1f}', ha='center', va='bottom', fontsize=11, color='white') ax1.set_title('🎯 Season-wise Avg Total Points', fontsize=18, fontweight='bold', pad=20, color='white') ax1.set_ylabel('Avg Points', fontsize=14, fontweight='bold', color='white') ax1.tick_params(colors='white', labelsize=11) ax1.grid(axis='y', alpha=0.3, linestyle='--', color='gray') plt.tight_layout() fig2, ax2 = plt.subplots(figsize=(12, 7), facecolor=DARK_BG) ax2.set_facecolor(DARK_BG) if sel_seasons and len(sel_seasons) > 1: if sel_teams and len(sel_teams) > 0: for idx, team in enumerate(sel_teams[:5]): team_data = d[(d['HOME_TEAM_ID'] == team) | (d['VISITOR_TEAM_ID'] == team)] season_avg = team_data.groupby('SEASON')['TOTAL_PTS'].mean() ax2.plot(season_avg.index, season_avg.values, marker='o', linewidth=3, label=f'Team {team}', color=COLORS[idx % len(COLORS)], markersize=10) ax2.set_title('📈 Scoring Trends Across Seasons - By Team', fontsize=18, fontweight='bold', pad=20, color='white') else: season_avg = d.groupby('SEASON')['TOTAL_PTS'].mean() ax2.plot(season_avg.index, season_avg.values, marker='o', linewidth=4, color='#FF3333', markersize=12, markerfacecolor='#4ECDC4', markeredgecolor='white', markeredgewidth=2) ax2.set_title('📈 League-wide Scoring Trend', fontsize=18, fontweight='bold', pad=20, color='white') ax2.set_xlabel('Season', fontsize=14, fontweight='bold', color='white') ax2.set_ylabel('Avg Total Points', fontsize=14, fontweight='bold', color='white') ax2.legend(loc='best', fontsize=12, framealpha=0.9) ax2.tick_params(colors='white', labelsize=11) else: shooting_diff = d[['FG_PCT_DIFF', 'FT_PCT_DIFF', 'FG3_PCT_DIFF']].mean() bars = ax2.bar(['FG %', 'FT %', '3PT %'], shooting_diff.values, color=['#FF3333', '#4ECDC4', '#45B7D1'], edgecolor='white', linewidth=2, width=0.6) for bar in bars: height = bar.get_height() ax2.text(bar.get_x() + bar.get_width()/2., height, f'{height:.4f}', ha='center', va='bottom' if height > 0 else 'top', fontsize=12, fontweight='bold', color='white') ax2.axhline(y=0, color='white', linestyle='-', linewidth=1, alpha=0.5) ax2.set_title('🎯 Average Shooting Superiority (Home - Away)', fontsize=18, fontweight='bold', pad=20, color='white') ax2.set_ylabel('Avg Difference', fontsize=14, fontweight='bold', color='white') ax2.tick_params(colors='white', labelsize=11) ax2.grid(alpha=0.3, linestyle='--', color='gray') plt.tight_layout() return fig1, fig2 # ---------- TAB 9: Forecasting ---------- def forecasting_analysis(sel_seasons, sel_teams): d = filter_df(sel_seasons, sel_teams) # Single Plot: Team-wise Scoring Trends (Actual Only) fig1, ax1 = plt.subplots(figsize=(10, 6), facecolor=DARK_BG) ax1.set_facecolor(DARK_BG) if sel_teams and len(sel_teams) > 0: # Plot multiple teams for idx, team in enumerate(sel_teams[:5]): team_data = d[(d['HOME_TEAM_ID'] == team) | (d['VISITOR_TEAM_ID'] == team)] trend = team_data.groupby('SEASON')['TOTAL_PTS'].mean() if len(trend) > 0: ax1.plot(trend.index, trend.values, marker='o', linewidth=3, label=f'Team {team}', color=COLORS[idx % len(COLORS)], markersize=10) ax1.set_title('📈 NBA Scoring Trend - Team Comparison', fontsize=20, fontweight='bold', pad=20, color='white') else: # Overall league trend trend = d.groupby('SEASON')['TOTAL_PTS'].mean() if len(trend) > 0: ax1.plot(trend.index, trend.values, marker='o', linewidth=4, label='League Average', color='#FF3333', markersize=12) ax1.set_title('📈 NBA Scoring Trend - League Wide', fontsize=20, fontweight='bold', pad=20, color='white') ax1.set_xlabel('Season', fontsize=16, fontweight='bold', color='white') ax1.set_ylabel('Avg Total Points', fontsize=16, fontweight='bold', color='white') ax1.legend(loc='best', fontsize=13, framealpha=0.9) ax1.tick_params(colors='white', labelsize=12) ax1.grid(alpha=0.3, linestyle='--', color='gray') plt.tight_layout() return fig1 # ---------- TAB 3: Possession Control ---------- def possession_control(sel_seasons, sel_teams): d = filter_df(sel_seasons, sel_teams) fig1, ax1 = plt.subplots(figsize=(12, 7), facecolor=DARK_BG) ax1.set_facecolor(DARK_BG) if sel_teams and len(sel_teams) > 0: teams_to_plot = sel_teams[:5] x = np.arange(len(teams_to_plot)) width = 0.35 ast_vals = [] reb_vals = [] for team in teams_to_plot: team_data = d[(d['HOME_TEAM_ID']==team) | (d['VISITOR_TEAM_ID']==team)] ast_vals.append(team_data['AST_DIFF'].mean()) reb_vals.append(team_data['REB_DIFF'].mean()) bars1 = ax1.bar(x - width/2, ast_vals, width, label='AST Diff', color='#FF3333', edgecolor='white', linewidth=2) bars2 = ax1.bar(x + width/2, reb_vals, width, label='REB Diff', color='#4ECDC4', edgecolor='white', linewidth=2) ax1.set_xticks(x) ax1.set_xticklabels([f'Team {t}' for t in teams_to_plot], fontsize=12, color='white') ax1.set_title('🏋 Assist & Rebound Advantage by Team', fontsize=18, fontweight='bold', pad=20, color='white') ax1.legend(fontsize=12, framealpha=0.9) else: diff_data = d[['AST_DIFF', 'REB_DIFF']].mean() bars = ax1.bar(['AST Diff', 'REB Diff'], diff_data.values, color=['#FF3333', '#4ECDC4'], edgecolor='white', linewidth=2, width=0.5) for bar in bars: height = bar.get_height() ax1.text(bar.get_x() + bar.get_width()/2., height, f'{height:.2f}', ha='center', va='bottom' if height > 0 else 'top', fontsize=13, fontweight='bold', color='white') ax1.set_title('🏋 Average Assist & Rebound Advantage', fontsize=18, fontweight='bold', pad=20, color='white') ax1.axhline(y=0, color='white', linestyle='-', linewidth=1, alpha=0.5) ax1.set_ylabel('Avg Difference', fontsize=14, fontweight='bold', color='white') ax1.tick_params(colors='white', labelsize=11) ax1.grid(axis='y', alpha=0.3, linestyle='--', color='gray') plt.tight_layout() fig2, ax2 = plt.subplots(figsize=(12, 7), facecolor=DARK_BG) ax2.set_facecolor(DARK_BG) if sel_seasons and len(sel_seasons) > 1: season_ast = d.groupby('SEASON')['AST_DIFF'].mean() season_reb = d.groupby('SEASON')['REB_DIFF'].mean() ax2.plot(season_ast.index, season_ast.values, marker='o', linewidth=3, label='AST Diff', color='#FF3333', markersize=10) ax2.plot(season_reb.index, season_reb.values, marker='s', linewidth=3, label='REB Diff', color='#4ECDC4', markersize=10) ax2.set_title('📈 Season Trend: Assists & Rebounds', fontsize=18, fontweight='bold', pad=20, color='white') ax2.set_xlabel('Season', fontsize=14, fontweight='bold', color='white') ax2.set_ylabel('Avg Difference', fontsize=14, fontweight='bold', color='white') ax2.legend(fontsize=12, framealpha=0.9) ax2.tick_params(colors='white', labelsize=11) else: home_ast = d.groupby('HOME_TEAM_ID')['AST_DIFF'].mean() away_ast = d.groupby('VISITOR_TEAM_ID')['AST_DIFF'].mean() combined_ast = pd.concat([home_ast, away_ast]).groupby(level=0).mean().sort_values(ascending=False).head(10) bars = ax2.barh(range(len(combined_ast)), combined_ast.values, color='#45B7D1', edgecolor='white', linewidth=2) ax2.set_yticks(range(len(combined_ast))) ax2.set_yticklabels([f'Team {int(t)}' for t in combined_ast.index], fontsize=11, color='white') ax2.set_title('🏆 Top 10 Teams by Assist Advantage', fontsize=18, fontweight='bold', pad=20, color='white') ax2.set_xlabel('Avg AST Difference', fontsize=14, fontweight='bold', color='white') ax2.tick_params(colors='white', labelsize=11) ax2.axvline(x=0, color='white', linestyle='-', linewidth=1, alpha=0.5) ax2.grid(alpha=0.3, linestyle='--', color='gray') plt.tight_layout() return fig1, fig2 # ---------- TAB 4: Game Intensity ---------- def game_intensity(sel_seasons, sel_teams): d = filter_df(sel_seasons, sel_teams) fig1, ax1 = plt.subplots(figsize=(12, 7), facecolor=DARK_BG) ax1.set_facecolor(DARK_BG) if sel_teams and len(sel_teams) > 0: teams_to_plot = sel_teams[:5] pace_by_team = [] for team in teams_to_plot: team_data = d[(d['HOME_TEAM_ID'] == team) | (d['VISITOR_TEAM_ID'] == team)] pace_by_team.append(team_data['GAME_PACE_SCORE'].mean()) bars = ax1.bar(range(len(teams_to_plot)), pace_by_team, color=[COLORS[i % len(COLORS)] for i in range(len(teams_to_plot))], edgecolor='white', linewidth=2, width=0.7) for i, bar in enumerate(bars): height = bar.get_height() ax1.text(bar.get_x() + bar.get_width()/2., height, f'{height:.2f}', ha='center', va='bottom', fontsize=12, fontweight='bold', color='white') ax1.set_xticks(range(len(teams_to_plot))) ax1.set_xticklabels([f'Team {t}' for t in teams_to_plot], fontsize=12, color='white') ax1.set_title('⚡ Average Game Pace - Team Comparison', fontsize=18, fontweight='bold', pad=20, color='white') else: ax1.hist(d['GAME_PACE_SCORE'], bins=30, color='#4ECDC4', edgecolor='white', linewidth=2, alpha=0.8) ax1.axvline(d['GAME_PACE_SCORE'].mean(), color='#FF3333', linestyle='--', linewidth=3, label=f"Mean: {d['GAME_PACE_SCORE'].mean():.2f}") ax1.set_title('⚡ Game Pace Distribution', fontsize=18, fontweight='bold', pad=20, color='white') ax1.set_xlabel('Game Pace Score', fontsize=14, fontweight='bold', color='white') ax1.legend(fontsize=12, framealpha=0.9) ax1.set_ylabel('Avg Pace Score' if sel_teams else 'Frequency', fontsize=14, fontweight='bold', color='white') ax1.tick_params(colors='white', labelsize=11) ax1.grid(alpha=0.3, linestyle='--', color='gray') plt.tight_layout() fig2, ax2 = plt.subplots(figsize=(12, 7), facecolor=DARK_BG) ax2.set_facecolor(DARK_BG) if sel_seasons and len(sel_seasons) > 1: if sel_teams and len(sel_teams) > 0: for idx, team in enumerate(sel_teams[:5]): team_data = d[(d['HOME_TEAM_ID'] == team) | (d['VISITOR_TEAM_ID'] == team)] pace_trend = team_data.groupby('SEASON')['GAME_PACE_SCORE'].mean() ax2.plot(pace_trend.index, pace_trend.values, marker='o', linewidth=3, label=f'Team {team}', color=COLORS[idx % len(COLORS)], markersize=10) ax2.set_title('📈 Game Pace Trends - By Team', fontsize=18, fontweight='bold', pad=20, color='white') else: pace_trend = d.groupby('SEASON')['GAME_PACE_SCORE'].mean() ax2.plot(pace_trend.index, pace_trend.values, marker='o', linewidth=4, color='#45B7D1', markersize=12, markerfacecolor='#FF3333', markeredgecolor='white', markeredgewidth=2) z = np.polyfit(pace_trend.index, pace_trend.values, 1) p = np.poly1d(z) ax2.plot(pace_trend.index, p(pace_trend.index), linestyle='--', color='#FFA07A', linewidth=3, alpha=0.7, label='Trend') ax2.set_title('📈 NBA Game Pace Evolution', fontsize=18, fontweight='bold', pad=20, color='white') ax2.set_xlabel('Season', fontsize=14, fontweight='bold', color='white') ax2.set_ylabel('Avg Game Pace Score', fontsize=14, fontweight='bold', color='white') ax2.legend(loc='best', fontsize=12, framealpha=0.9) ax2.tick_params(colors='white', labelsize=11) else: pace_by_season = d.groupby('SEASON')['GAME_PACE_SCORE'].mean() bars = ax2.bar(pace_by_season.index, pace_by_season.values, color='#FF3333', edgecolor='white', linewidth=2) for bar in bars: height = bar.get_height() ax2.text(bar.get_x() + bar.get_width()/2., height, f'{height:.2f}', ha='center', va='bottom', fontsize=11, fontweight='bold', color='white') ax2.set_title('⚡ Average Game Pace by Season', fontsize=18, fontweight='bold', pad=20, color='white') ax2.set_ylabel('Avg Pace Score', fontsize=14, fontweight='bold', color='white') ax2.tick_params(colors='white', labelsize=11) ax2.grid(alpha=0.3, linestyle='--', color='gray') plt.tight_layout() return fig1, fig2 # ---------- TAB 5: Home Advantage ---------- def home_advantage(sel_seasons, sel_teams): d = filter_df(sel_seasons, sel_teams) fig1, ax1 = plt.subplots(figsize=(12, 7), facecolor=DARK_BG) ax1.set_facecolor(DARK_BG) if sel_teams and len(sel_teams) > 0: teams_to_plot = sel_teams[:5] home_dom_vals = [] for team in teams_to_plot: team_home = d[d['HOME_TEAM_ID'] == team]['HOME_DOMINANCE_SCORE'].mean() home_dom_vals.append(team_home) bars = ax1.bar(range(len(teams_to_plot)), home_dom_vals, color=[COLORS[i % len(COLORS)] for i in range(len(teams_to_plot))], edgecolor='white', linewidth=2, width=0.7) for i, bar in enumerate(bars): height = bar.get_height() ax1.text(bar.get_x() + bar.get_width()/2., height, f'{height:.3f}', ha='center', va='bottom', fontsize=11, fontweight='bold', color='white') ax1.set_xticks(range(len(teams_to_plot))) ax1.set_xticklabels([f'Team {t}' for t in teams_to_plot], fontsize=12, color='white') ax1.set_title('🏠 Home Dominance Score - Team Comparison', fontsize=18, fontweight='bold', pad=20, color='white') ax1.set_ylabel('Dominance Score', fontsize=14, fontweight='bold', color='white') else: home_dom = d.groupby('HOME_TEAM_ID')['HOME_DOMINANCE_SCORE'].mean().sort_values(ascending=False).head(10) bars = ax1.barh(range(len(home_dom)), home_dom.values, color=[COLORS[i % len(COLORS)] for i in range(len(home_dom))], edgecolor='white', linewidth=2) ax1.set_yticks(range(len(home_dom))) ax1.set_yticklabels([f'Team {int(t)}' for t in home_dom.index], fontsize=11, color='white') for i, bar in enumerate(bars): width = bar.get_width() ax1.text(width, bar.get_y() + bar.get_height()/2., f' {width:.3f}', ha='left', va='center', fontsize=11, fontweight='bold', color='white') ax1.set_title('🏆 Top 10 Home Dominant Teams', fontsize=18, fontweight='bold', pad=20, color='white') ax1.set_xlabel('Dominance Score', fontsize=14, fontweight='bold', color='white') ax1.tick_params(colors='white', labelsize=11) ax1.grid(alpha=0.3, linestyle='--', color='gray') plt.tight_layout() fig2, ax2 = plt.subplots(figsize=(12, 7), facecolor=DARK_BG) ax2.set_facecolor(DARK_BG) if sel_seasons and len(sel_seasons) > 1: if sel_teams and len(sel_teams) > 0: for idx, team in enumerate(sel_teams[:5]): team_data = d[d['HOME_TEAM_ID'] == team] season_dom = team_data.groupby('SEASON')['HOME_DOMINANCE_SCORE'].mean() ax2.plot(season_dom.index, season_dom.values, marker='o', linewidth=3, label=f'Team {team}', color=COLORS[idx % len(COLORS)], markersize=10) ax2.set_title('📈 Home Dominance Trends', fontsize=18, fontweight='bold', pad=20, color='white') ax2.set_xlabel('Season', fontsize=14, fontweight='bold', color='white') ax2.set_ylabel('Dominance Score', fontsize=14, fontweight='bold', color='white') ax2.legend(loc='best', fontsize=12, framealpha=0.9) ax2.tick_params(colors='white', labelsize=11) else: home_adv = d.groupby('SEASON')['HOME_DOMINANCE_SCORE'].mean() ax2.plot(home_adv.index, home_adv.values, marker='o', linewidth=4, color='#FF3333', markersize=12, markerfacecolor='#4ECDC4', markeredgecolor='white', markeredgewidth=2) ax2.set_title('📈 Home Advantage Evolution', fontsize=18, fontweight='bold', pad=20, color='white') ax2.set_xlabel('Season', fontsize=14, fontweight='bold', color='white') ax2.set_ylabel('Avg Dominance Score', fontsize=14, fontweight='bold', color='white') ax2.tick_params(colors='white', labelsize=11) else: shoot_edge = pd.cut(d['HOME_SHOOTING_EDGE'], bins=[-1, -0.05, 0.05, 1], labels=['Away Better', 'Even', 'Home Better']) edge_counts = shoot_edge.value_counts() colors_pie = ['#FF3333', '#FFA07A', '#4ECDC4'] wedges, texts, autotexts = ax2.pie(edge_counts.values, labels=edge_counts.index, autopct='%1.1f%%', colors=colors_pie, startangle=90, textprops={'fontsize': 14, 'fontweight': 'bold'}, explode=[0.05, 0.05, 0.05]) for autotext in autotexts: autotext.set_color('white') autotext.set_fontsize(13) for text in texts: text.set_color('white') text.set_fontsize(14) ax2.set_title('🎯 Home vs Away Shooting Superiority', fontsize=18, fontweight='bold', pad=20, color='white') ax2.grid(alpha=0.3, linestyle='--', color='gray') plt.tight_layout() return fig1, fig2 # Continue with remaining tabs (6, 7, 8) following the same pattern... # For brevity, I'll include the complete UI section # ---------- TAB 6: Team Momentum ---------- def team_momentum(sel_seasons, sel_teams): d = filter_df(sel_seasons, sel_teams) fig1, ax1 = plt.subplots(figsize=(12, 7), facecolor=DARK_BG) ax1.set_facecolor(DARK_BG) if sel_teams and len(sel_teams) > 0: teams_to_plot = sel_teams[:5] momentum_home = [] momentum_away = [] for team in teams_to_plot: team_home = d[d['HOME_TEAM_ID'] == team]['HOME_LAST5_WINRATE'].mean() team_away = d[d['VISITOR_TEAM_ID'] == team]['AWAY_LAST5_WINRATE'].mean() momentum_home.append(team_home) momentum_away.append(team_away) x = np.arange(len(teams_to_plot)) width = 0.35 bars1 = ax1.bar(x - width/2, momentum_home, width, label='Home Momentum', color='#FF3333', edgecolor='white', linewidth=2) bars2 = ax1.bar(x + width/2, momentum_away, width, label='Away Momentum', color='#4ECDC4', edgecolor='white', linewidth=2) for bar in bars1: height = bar.get_height() if height > 0: ax1.text(bar.get_x() + bar.get_width()/2., height, f'{height:.2f}', ha='center', va='bottom', fontsize=11, fontweight='bold', color='white') for bar in bars2: height = bar.get_height() if height > 0: ax1.text(bar.get_x() + bar.get_width()/2., height, f'{height:.2f}', ha='center', va='bottom', fontsize=11, fontweight='bold', color='white') ax1.set_xticks(x) ax1.set_xticklabels([f'Team {t}' for t in teams_to_plot], fontsize=12, color='white') ax1.set_title('⚡ Team Momentum Comparison (Last-5 Win Rate)', fontsize=18, fontweight='bold', pad=20, color='white') ax1.legend(fontsize=12, framealpha=0.9) else: winrate_data = d[['HOME_LAST5_WINRATE', 'AWAY_LAST5_WINRATE']].mean() bars = ax1.bar(['Home Win Rate', 'Away Win Rate'], winrate_data.values, color=['#FF3333', '#4ECDC4'], edgecolor='white', linewidth=2, width=0.6) for bar in bars: height = bar.get_height() ax1.text(bar.get_x() + bar.get_width()/2., height, f'{height:.3f}', ha='center', va='bottom', fontsize=13, fontweight='bold', color='white') ax1.set_title('⚡ Average Last-5 Games Win Rate', fontsize=18, fontweight='bold', pad=20, color='white') ax1.set_ylabel('Win Rate', fontsize=14, fontweight='bold', color='white') ax1.tick_params(colors='white', labelsize=11) ax1.grid(axis='y', alpha=0.3, linestyle='--', color='gray') plt.tight_layout() fig2, ax2 = plt.subplots(figsize=(12, 7), facecolor=DARK_BG) ax2.set_facecolor(DARK_BG) if sel_seasons and len(sel_seasons) > 1: if sel_teams and len(sel_teams) > 0: for idx, team in enumerate(sel_teams[:5]): team_data = d[(d['HOME_TEAM_ID'] == team) | (d['VISITOR_TEAM_ID'] == team)] home_momentum = team_data[team_data['HOME_TEAM_ID'] == team].groupby('SEASON')['HOME_LAST5_WINRATE'].mean() away_momentum = team_data[team_data['VISITOR_TEAM_ID'] == team].groupby('SEASON')['AWAY_LAST5_WINRATE'].mean() combined_momentum = pd.concat([home_momentum, away_momentum]).groupby(level=0).mean() ax2.plot(combined_momentum.index, combined_momentum.values, marker='o', linewidth=3, label=f'Team {team}', color=COLORS[idx % len(COLORS)], markersize=10) ax2.set_title('📈 Momentum Trends - By Team', fontsize=18, fontweight='bold', pad=20, color='white') ax2.set_xlabel('Season', fontsize=14, fontweight='bold', color='white') ax2.set_ylabel('Avg Win Rate', fontsize=14, fontweight='bold', color='white') ax2.legend(loc='best', fontsize=12, framealpha=0.9) ax2.tick_params(colors='white', labelsize=11) else: home_trend = d.groupby('SEASON')['HOME_LAST5_WINRATE'].mean() away_trend = d.groupby('SEASON')['AWAY_LAST5_WINRATE'].mean() ax2.plot(home_trend.index, home_trend.values, marker='o', linewidth=3, label='Home Momentum', color='#FF3333', markersize=10) ax2.plot(away_trend.index, away_trend.values, marker='s', linewidth=3, label='Away Momentum', color='#4ECDC4', markersize=10) ax2.set_title('📈 League Momentum Trend', fontsize=18, fontweight='bold', pad=20, color='white') ax2.set_xlabel('Season', fontsize=14, fontweight='bold', color='white') ax2.set_ylabel('Avg Win Rate', fontsize=14, fontweight='bold', color='white') ax2.legend(loc='best', fontsize=12, framealpha=0.9) ax2.tick_params(colors='white', labelsize=11) else: momentum = pd.concat([ d[['HOME_TEAM_ID', 'HOME_LAST5_WINRATE']].rename(columns={'HOME_TEAM_ID': 'TEAM', 'HOME_LAST5_WINRATE': 'WINRATE'}), d[['VISITOR_TEAM_ID', 'AWAY_LAST5_WINRATE']].rename(columns={'VISITOR_TEAM_ID': 'TEAM', 'AWAY_LAST5_WINRATE': 'WINRATE'}) ]) top_momentum = momentum.groupby('TEAM')['WINRATE'].mean().sort_values(ascending=False).head(10) bars = ax2.barh(range(len(top_momentum)), top_momentum.values, color=[COLORS[i % len(COLORS)] for i in range(len(top_momentum))], edgecolor='white', linewidth=2) ax2.set_yticks(range(len(top_momentum))) ax2.set_yticklabels([f'Team {int(t)}' for t in top_momentum.index], fontsize=11, color='white') for i, bar in enumerate(bars): width = bar.get_width() ax2.text(width, bar.get_y() + bar.get_height()/2., f' {width:.3f}', ha='left', va='center', fontsize=11, fontweight='bold', color='white') ax2.set_title('🏆 Top 10 Teams by Recent Momentum', fontsize=18, fontweight='bold', pad=20, color='white') ax2.set_xlabel('Avg Last-5 Win Rate', fontsize=14, fontweight='bold', color='white') ax2.tick_params(colors='white', labelsize=11) ax2.grid(alpha=0.3, linestyle='--', color='gray') plt.tight_layout() return fig1, fig2 # ---------- TAB 7: Time Analysis ---------- def time_analysis(sel_seasons, sel_teams): d = filter_df(sel_seasons, sel_teams) fig1, ax1 = plt.subplots(figsize=(12, 7), facecolor=DARK_BG) ax1.set_facecolor(DARK_BG) month_counts = d['GAME_MONTH'].value_counts().sort_index() bars = ax1.bar(month_counts.index, month_counts.values, color=[COLORS[i % len(COLORS)] for i in range(len(month_counts))], edgecolor='white', linewidth=2) for bar in bars: height = bar.get_height() ax1.text(bar.get_x() + bar.get_width()/2., height, f'{int(height)}', ha='center', va='bottom', fontsize=11, fontweight='bold', color='white') ax1.set_title('📅 Games Played per Month', fontsize=18, fontweight='bold', pad=20, color='white') ax1.set_xlabel('Month', fontsize=14, fontweight='bold', color='white') ax1.set_ylabel('Number of Games', fontsize=14, fontweight='bold', color='white') ax1.tick_params(colors='white', labelsize=11) ax1.grid(axis='y', alpha=0.3, linestyle='--', color='gray') plt.tight_layout() fig2, ax2 = plt.subplots(figsize=(12, 7), facecolor=DARK_BG) ax2.set_facecolor(DARK_BG) weekday_pace = d.groupby('GAME_WEEKDAY')['GAME_PACE_SCORE'].mean().sort_index() bars = ax2.bar(weekday_pace.index, weekday_pace.values, color=['#FF3333', '#4ECDC4', '#45B7D1', '#FFA07A', '#98D8C8', '#F7DC6F', '#BB8FCE'], edgecolor='white', linewidth=2, width=0.7) for bar in bars: height = bar.get_height() ax2.text(bar.get_x() + bar.get_width()/2., height, f'{height:.2f}', ha='center', va='bottom', fontsize=11, fontweight='bold', color='white') ax2.set_title('📊 Game Pace by Day of Week', fontsize=18, fontweight='bold', pad=20, color='white') ax2.set_xlabel('Day of Week', fontsize=14, fontweight='bold', color='white') ax2.set_ylabel('Avg Pace Score', fontsize=14, fontweight='bold', color='white') ax2.tick_params(colors='white', labelsize=11) ax2.grid(axis='y', alpha=0.3, linestyle='--', color='gray') plt.tight_layout() return fig1, fig2 # ---------- TAB 8: Margin Analysis ---------- def margin_analysis(sel_seasons, sel_teams): d = filter_df(sel_seasons, sel_teams) fig1, ax1 = plt.subplots(figsize=(12, 7), facecolor=DARK_BG) ax1.set_facecolor(DARK_BG) if sel_teams and len(sel_teams) > 0: teams_to_plot = sel_teams[:5] margin_vals = [] for team in teams_to_plot: team_data = d[(d['HOME_TEAM_ID'] == team) | (d['VISITOR_TEAM_ID'] == team)] margin_vals.append(team_data['POINT_DIFF'].mean()) bars = ax1.bar(range(len(teams_to_plot)), margin_vals, color=[COLORS[i % len(COLORS)] for i in range(len(teams_to_plot))], edgecolor='white', linewidth=2, width=0.7) for i, bar in enumerate(bars): height = bar.get_height() ax1.text(bar.get_x() + bar.get_width()/2., height, f'{height:.1f}', ha='center', va='bottom' if height > 0 else 'top', fontsize=12, fontweight='bold', color='white') ax1.set_xticks(range(len(teams_to_plot))) ax1.set_xticklabels([f'Team {t}' for t in teams_to_plot], fontsize=12, color='white') ax1.set_title('📊 Average Winning Margin - Team Comparison', fontsize=18, fontweight='bold', pad=20, color='white') ax1.axhline(y=0, color='white', linestyle='-', linewidth=1, alpha=0.5) else: margin_by_season = d.groupby('SEASON')['POINT_DIFF'].mean() bars = ax1.bar(margin_by_season.index, margin_by_season.values, color='#FF3333', edgecolor='white', linewidth=2) for bar in bars: height = bar.get_height() ax1.text(bar.get_x() + bar.get_width()/2., height, f'{height:.1f}', ha='center', va='bottom', fontsize=11, fontweight='bold', color='white') ax1.set_title('📊 Average Winning Margin by Season', fontsize=18, fontweight='bold', pad=20, color='white') ax1.set_ylabel('Avg Point Difference', fontsize=14, fontweight='bold', color='white') ax1.tick_params(colors='white', labelsize=11) ax1.grid(axis='y', alpha=0.3, linestyle='--', color='gray') plt.tight_layout() fig2, ax2 = plt.subplots(figsize=(12, 7), facecolor=DARK_BG) ax2.set_facecolor(DARK_BG) if sel_seasons and len(sel_seasons) > 1: if sel_teams and len(sel_teams) > 0: for idx, team in enumerate(sel_teams[:5]): team_data = d[(d['HOME_TEAM_ID'] == team) | (d['VISITOR_TEAM_ID'] == team)] margin_trend = team_data.groupby('SEASON')['POINT_DIFF'].mean() ax2.plot(margin_trend.index, margin_trend.values, marker='o', linewidth=3, label=f'Team {team}', color=COLORS[idx % len(COLORS)], markersize=10) ax2.set_title('📈 Margin Trends - By Team', fontsize=18, fontweight='bold', pad=20, color='white') ax2.set_xlabel('Season', fontsize=14, fontweight='bold', color='white') ax2.set_ylabel('Avg Point Difference', fontsize=14, fontweight='bold', color='white') ax2.legend(loc='best', fontsize=12, framealpha=0.9) ax2.tick_params(colors='white', labelsize=11) else: margin_trend = d.groupby('SEASON')['POINT_DIFF'].mean() ax2.plot(margin_trend.index, margin_trend.values, marker='o', linewidth=4, color='#FF3333', markersize=12, markerfacecolor='#4ECDC4', markeredgecolor='white', markeredgewidth=2) ax2.set_title('📈 Winning Margin Evolution', fontsize=18, fontweight='bold', pad=20, color='white') ax2.set_xlabel('Season', fontsize=14, fontweight='bold', color='white') ax2.set_ylabel('Avg Point Difference', fontsize=14, fontweight='bold', color='white') ax2.tick_params(colors='white', labelsize=11) else: ax2.hist(d['POINT_DIFF'], bins=40, color='#4ECDC4', edgecolor='white', linewidth=2, alpha=0.8) ax2.axvline(d['POINT_DIFF'].mean(), color='#FF3333', linestyle='--', linewidth=3, label=f"Mean: {d['POINT_DIFF'].mean():.2f}") ax2.axvline(d['POINT_DIFF'].median(), color='#FFA07A', linestyle='--', linewidth=3, label=f"Median: {d['POINT_DIFF'].median():.2f}") ax2.set_title('📊 Point Difference Distribution', fontsize=18, fontweight='bold', pad=20, color='white') ax2.set_xlabel('Point Difference', fontsize=14, fontweight='bold', color='white') ax2.set_ylabel('Frequency', fontsize=14, fontweight='bold', color='white') ax2.legend(fontsize=12, framealpha=0.9) ax2.tick_params(colors='white', labelsize=11) ax2.grid(alpha=0.3, linestyle='--', color='gray') plt.tight_layout() return fig1, fig2 # UI custom_css = """ @import url('https://fonts.googleapis.com/css2?family=JetBrains+Mono:wght@400;700&display=swap'); * { font-family: 'JetBrains Mono', monospace !important; } body, .gradio-container { background: #000000 !important; color: #FFFFFF !important; } .wrap { background: #000000 !important; } button { background: #FF3333 !important; color: white !important; font-weight: bold !important; border: 2px solid white !important; font-family: 'JetBrains Mono', monospace !important; } button:hover { background: #CC0000 !important; transform: scale(1.02); } .tabs button { background: #1a1a1a !important; border: 1px solid #FF3333 !important; } .tabs button.selected { background: #FF3333 !important; } label { color: #FFFFFF !important; font-weight: bold !important; font-size: 14px !important; } .dropdown { background: #1a1a1a !important; color: white !important; border: 2px solid #FF3333 !important; } h1, h2, h3, h4 { color: #FFFFFF !important; } .gr-box { border: 1px solid #333 !important; background: #0a0a0a !important; } """ with gr.Blocks(theme=gr.themes.Base(primary_hue="red", secondary_hue="slate"), css=custom_css) as app: gr.Markdown(""" # 🏀 NBA INTERACTIVE ANALYTICS DASHBOARD ## Comprehensive Analysis of NBA Game Statistics """) gr.Markdown(""" ### 📋 Instructions: - **For Team Comparison**: Select multiple teams (max 5) + one or any season - **For Season Analysis**: Select multiple seasons + one or any team """) with gr.Row(): team_dd = gr.Dropdown( choices=teams, multiselect=True, label="🏆 SELECT TEAMS (Max 5)", info="Choose 1-5 teams for comparison", max_choices=5 ) season_dd = gr.Dropdown( choices=seasons, multiselect=True, label="🗓️ SELECT SEASONS", info="Choose one or more seasons" ) with gr.Tab("🏠 MATCH OUTCOMES"): gr.Markdown("### Home vs Away Performance & Game Types") b1 = gr.Button("🔍 ANALYZE", variant="primary", size="lg") with gr.Row(): with gr.Column(scale=1): gr.Markdown("#### 📊 Team/Overall Comparison") p1 = gr.Plot() with gr.Column(scale=1): gr.Markdown("#### 📈 Season Trends/Distribution") p2 = gr.Plot() b1.click(match_outcomes, [season_dd, team_dd], [p1, p2]) with gr.Tab("🎯 SCORING & SHOOTING"): gr.Markdown("### Scoring Trends & Shooting Efficiency") b2 = gr.Button("🔍 ANALYZE", variant="primary", size="lg") with gr.Row(): with gr.Column(scale=1): gr.Markdown("#### 📊 Team/Overall Scoring") p3 = gr.Plot() with gr.Column(scale=1): gr.Markdown("#### 📈 Season Trends/Shooting Stats") p4 = gr.Plot() b2.click(scoring_shooting, [season_dd, team_dd], [p3, p4]) with gr.Tab("🏋 POSSESSION CONTROL"): gr.Markdown("### Assists & Rebounds Analysis") b3 = gr.Button("🔍 ANALYZE", variant="primary", size="lg") with gr.Row(): with gr.Column(scale=1): gr.Markdown("#### 📊 Team/Overall Possession") p5 = gr.Plot() with gr.Column(scale=1): gr.Markdown("#### 📈 Season Trends/Top Teams") p6 = gr.Plot() b3.click(possession_control, [season_dd, team_dd], [p5, p6]) with gr.Tab("⚡ GAME INTENSITY"): gr.Markdown("### Game Pace & Intensity Patterns") b4 = gr.Button("🔍 ANALYZE", variant="primary", size="lg") with gr.Row(): with gr.Column(scale=1): gr.Markdown("#### 📊 Team/Overall Pace") p7 = gr.Plot() with gr.Column(scale=1): gr.Markdown("#### 📈 Season Evolution") p8 = gr.Plot() b4.click(game_intensity, [season_dd, team_dd], [p7, p8]) with gr.Tab("🏠 HOME ADVANTAGE"): gr.Markdown("### Home Court Advantage Metrics") b5 = gr.Button("🔍 ANALYZE", variant="primary", size="lg") with gr.Row(): with gr.Column(scale=1): gr.Markdown("#### 📊 Team/Top Teams") p9 = gr.Plot() with gr.Column(scale=1): gr.Markdown("#### 📈 Season Trends/Shooting Edge") p10 = gr.Plot() b5.click(home_advantage, [season_dd, team_dd], [p9, p10]) with gr.Tab("⚡ TEAM MOMENTUM"): gr.Markdown("### Team Performance Momentum") b6 = gr.Button("🔍 ANALYZE", variant="primary", size="lg") with gr.Row(): with gr.Column(scale=1): gr.Markdown("#### 📊 Momentum Comparison (Last-5 Win Rate)") p11 = gr.Plot() with gr.Column(scale=1): gr.Markdown("#### 📈 Momentum Trends - By Team") p12 = gr.Plot() b6.click(team_momentum, [season_dd, team_dd], [p11, p12]) with gr.Tab("📅 TIME ANALYSIS"): gr.Markdown("### Temporal Patterns in Games") b7 = gr.Button("🔍 ANALYZE", variant="primary", size="lg") with gr.Row(): with gr.Column(scale=1): gr.Markdown("#### 📊 Monthly Distribution") p13 = gr.Plot() with gr.Column(scale=1): gr.Markdown("#### 📈 Weekday Pace Analysis") p14 = gr.Plot() b7.click(time_analysis, [season_dd, team_dd], [p13, p14]) with gr.Tab("📊 MARGIN ANALYSIS"): gr.Markdown("### Winning Margins & Point Differences") b8 = gr.Button("🔍 ANALYZE", variant="primary", size="lg") with gr.Row(): with gr.Column(scale=1): gr.Markdown("#### 📊 Team/Season Margins") p15 = gr.Plot() with gr.Column(scale=1): gr.Markdown("#### 📈 Margin Trends/Distribution") p16 = gr.Plot() b8.click(margin_analysis, [season_dd, team_dd], [p15, p16]) with gr.Tab("🔮 FORECASTING"): gr.Markdown("### NBA Scoring Trend Analysis") gr.Markdown("**Select multiple teams to compare their scoring trends across seasons**") b9 = gr.Button("🔍 ANALYZE TRENDS", variant="primary", size="lg") gr.Markdown("#### 📈 Team-wise Scoring Trends by Season") p17 = gr.Plot() b9.click(forecasting_analysis, [season_dd, team_dd], [p17]) gr.Markdown(""" --- ### 💡 DASHBOARD FEATURES: - **Team Comparison Mode**: Select 2-5 teams to compare their performance - **Season Analysis Mode**: Select multiple seasons to see trends over time - **Full-Screen Visualizations**: All graphs optimized for laptop screens - **Dark Theme**: Eye-friendly black background with high-contrast elements """) app.launch(share=True)