def get_top_players_for_selected_teams(selected_teams, selected_stat, consistency_threshold, apply_consistency_filter, use_lowest_score):
# Map selected team names to TEAM_IDs
selected_team_ids = [TEAM_IDS[team] for team in selected_teams]
code
Assistant
# Fetch all players' stats for the current season
NBA_SEASON = '2024-25' # Adjust this to the desired season
try:
player_stats = leaguedashplayerstats.LeagueDashPlayerStats(
season=NBA_SEASON,
per_mode_detailed='PerGame',
timeout=30
)
player_stats_df = player_stats.get_data_frames()[0]
except Exception as e:
print(f"Failed to fetch league player stats: {e}")
return []
# Filter players from selected teams
filtered_players = player_stats_df[player_stats_df['TEAM_ID'].isin(selected_team_ids)]
# Map TEAM_IDs to team names
team_id_to_name = {v: k for k, v in TEAM_IDS.items()}
# Map selected_stat to the corresponding column in player_stats_df
stat_column_map = {'PPG': 'PTS', 'REB': 'REB', 'AST': 'AST'}
stat_column = stat_column_map.get(selected_stat, 'PTS')
# Fetch league game logs
try:
league_gamelog = leaguegamelog.LeagueGameLog(
season=NBA_SEASON,
season_type_all_star='Regular Season',
player_or_team_abbreviation='P',
timeout=30
)
league_gamelog_df = league_gamelog.get_data_frames()[0]
except Exception as e:
print(f"Failed to fetch league game logs: {e}")
return []
# Filter game logs for players from selected teams
player_ids = filtered_players['PLAYER_ID'].unique()
player_game_logs = league_gamelog_df[league_gamelog_df['PLAYER_ID'].isin(player_ids)]
if use_lowest_score:
# Compute minimum stat of the selected stat for each player
player_stat_min = player_game_logs.groupby('PLAYER_ID')[stat_column].min().reset_index()
player_stat_min = player_stat_min.rename(columns={stat_column: 'MIN_STAT'})
# Merge the minimum stat back to filtered_players
filtered_players = filtered_players.merge(player_stat_min, on='PLAYER_ID', how='left')
else:
# Use average per-game stats (already in filtered_players)
pass
if apply_consistency_filter:
# Compute standard deviation of the selected stat for each player
player_stat_std = player_game_logs.groupby('PLAYER_ID')[stat_column].std().reset_index()
player_stat_std = player_stat_std.rename(columns={stat_column: 'STD_DEV'})
# Merge the standard deviation back to filtered_players
filtered_players = filtered_players.merge(player_stat_std, on='PLAYER_ID', how='left')
filtered_players['STD_DEV'] = filtered_players['STD_DEV'].fillna(0) # Handle NaN values
# Filter out players whose standard deviation exceeds the threshold
filtered_players = filtered_players[filtered_players['STD_DEV'] <= consistency_threshold]
else:
# Skip standard deviation computation
pass
# Create list of tuples: (team_name, player_name, season, stat_value, std_dev, games_played)
all_player_stats = []
for _, row in filtered_players.iterrows():
team_name = team_id_to_name.get(row['TEAM_ID'], 'Unknown Team')
player_name = row['PLAYER_NAME']
season = NBA_SEASON
games_played = row['GP'] # Number of games played
if use_lowest_score:
stat_value = row['MIN_STAT']
else:
stat_value = row[stat_column]
if apply_consistency_filter:
std_dev = row['STD_DEV']
else:
std_dev = None
all_player_stats.append((team_name, player_name, season, stat_value, std_dev, games_played))
# Remove players with missing stat_value (e.g., if MIN_STAT is NaN)
all_player_stats = [x for x in all_player_stats if pd.notnull(x[3])]
# Return sorted results by stat_value
return sorted(all_player_stats, key=lambda x: x[3], reverse=True)
def display_top_players():
selected_teams = [team_listbox.get(i) for i in team_listbox.curselection()]
selected_stat_value = selected_stat.get()
try:
max_players = int(max_players_entry.get())
except ValueError:
result_label.config(text="Invalid number for max players.")
return
try:
consistency_threshold = float(consistency_entry.get())
except ValueError:
result_label.config(text="Invalid number for consistency threshold.")
return
code
apply_consistency_filter = consistency_var.get()
use_lowest_score = lowest_score_var.get()
if not selected_teams:
result_label.config(text="Please select at least one team.")
return
result_label.config(text="Fetching data...")
root.update() # Refresh UI during processing
start_time = time.time()
top_players = get_top_players_for_selected_teams(
selected_teams, selected_stat_value, consistency_threshold,
apply_consistency_filter, use_lowest_score
)[:max_players]
end_time = time.time()
# Display results
result_area.delete("1.0", tk.END)
if not top_players:
result_label.config(text="No top players found.")
return
result_label.config(text=f"Data fetched successfully in {end_time - start_time:.2f} seconds!")
# Determine the appropriate label for the stat
stat_label_map = {'PPG': 'PPG', 'REB': 'RPG', 'AST': 'APG'}
stat_label_text = stat_label_map.get(selected_stat_value, 'PPG')
if use_lowest_score:
result_area.insert(tk.END, f"Top {len(top_players)} players based on lowest {stat_label_text}:\n")
else:
result_area.insert(tk.END, f"Top {len(top_players)} players based on average {stat_label_text}:\n")
result_text = ""
for i, (team, player, season, stat_value, std_dev, games_played) in enumerate(top_players, start=1):
stat_line = f"{i}. {player} - {stat_value:.2f} {stat_label_text} (Games Played: {games_played})"
if apply_consistency_filter and std_dev is not None:
stat_line += f" (Std Dev: {std_dev:.2f})"
stat_line += f" ({season} season) [{team}]"
result_text += stat_line + "\n"
result_area.insert(tk.END, result_text + "\n")
Certainly! Below is a Python script that replicates the functionality of your original NBA-focused Tkinter application but tailored for the NFL. This script utilizes the sportsipy library to fetch NFL player statistics and displays the top players based on selected criteria.
Overview of Changes:
Library Changes:
Removed nba_api: Replaced with sportsipy library which provides NFL data.
Added sportsipy dependencies: Ensure you have sportsipy, pandas, and other necessary libraries installed.
Team Data:
Updated TEAM_IDS: Replaced NBA teams with NFL teams. In sportsipy, teams are generally identified by their abbreviations (e.g., 'ARI' for Arizona Cardinals).
Statistics Adjustments:
Selected NFL Statistics: Changed from Points, Rebounds, Assists to relevant NFL stats such as Passing Yards (PY), Rushing Yards (RY), Receiving Yards (REY), and Touchdowns (TD).
Fetching and Processing Data:
Data Retrieval with sportsipy: Utilized sportsipy.nfl.players to fetch player data.
Consistency Filtering: Adapted consistency filtering to handle NFL-specific statistics.
GUI Adjustments:
Updated Labels and Options: Modified labels, options, and layout to reflect NFL terminology and statistics.
Prerequisites:
Before running the script, ensure you have the necessary libraries installed. You can install them using pip:
bash
pip install sportsipy pandas tkinter
Note:tkinter is usually included with Python installations on Windows. If you're using a different operating system, you may need to install it separately.
Full NFL Python Script:
python
import tkinter as tk
from tkinter import ttk
from sportsipy.nfl.teams import Teams
from sportsipy.nfl.player import Player
from sportsipy.nfl.players import Players
import time
import pandas as pd
from functools import lru_cache
# Precomputed dictionary of NFL team names to their abbreviations
TEAM_ABBREVIATIONS = {
"Arizona Cardinals": "ARI",
"Atlanta Falcons": "ATL",
"Baltimore Ravens": "BAL",
"Buffalo Bills": "BUF",
"Carolina Panthers": "CAR",
"Chicago Bears": "CHI",
"Cincinnati Bengals": "CIN",
"Cleveland Browns": "CLE",
"Dallas Cowboys": "DAL",
"Denver Broncos": "DEN",
"Detroit Lions": "DET",
"Green Bay Packers": "GB",
"Houston Texans": "HOU",
"Indianapolis Colts": "IND",
"Jacksonville Jaguars": "JAX",
"Kansas City Chiefs": "KC",
"Las Vegas Raiders": "LV",
"Los Angeles Chargers": "LAC",
"Los Angeles Rams": "LA",
"Miami Dolphins": "MIA",
"Minnesota Vikings": "MIN",
"New England Patriots": "NE",
"New Orleans Saints": "NO",
"New York Giants": "NYG",
"New York Jets": "NYJ",
"Philadelphia Eagles": "PHI",
"Pittsburgh Steelers": "PIT",
"San Francisco 49ers": "SF",
"Seattle Seahawks": "SEA",
"Tampa Bay Buccaneers": "TB",
"Tennessee Titans": "TEN",
"Washington Commanders": "WAS"
}
# Define available statistics
STAT_OPTIONS = {
'Passing Yards': 'passing_yards',
'Rushing Yards': 'rushing_yards',
'Receiving Yards': 'receiving_yards',
'Touchdowns': 'touchdowns'
}
@lru_cache(maxsize=1)
def get_all_players():
"""
Fetch all active NFL players.
"""
players = Players()
return list(players)
def get_player_stats(player_ids, selected_stat, use_lowest_score):
"""
Retrieve player statistics based on selected stat.
"""
player_stats = []
for pid in player_ids:
try:
player = Player(pid)
# Fetch player's career stats or latest season stats
# Here, we'll use latest season stats
season_stats = player.season_data(year=player.active_year)
if not season_stats:
continue
stats = season_stats.dataframe.iloc[0]
if selected_stat == 'passing_yards':
stat_value = stats.passing_yards
elif selected_stat == 'rushing_yards':
stat_value = stats.rushing_yards
elif selected_stat == 'receiving_yards':
stat_value = stats.receiving_yards
elif selected_stat == 'touchdowns':
stat_value = stats.touchdowns
else:
stat_value = 0
if use_lowest_score:
# Assuming "lowest score" means lowest stat in a game
# sportsipy may not have game-by-game data easily accessible
# For simplicity, we'll skip this or set to stat_value
stat_min = stat_value # Placeholder
player_stats.append((player.full_name, player.team_abbr, stat_min, player.games_played))
else:
player_stats.append((player.full_name, player.team_abbr, stat_value, player.games_played))
except Exception as e:
print(f"Error fetching data for player ID {pid}: {e}")
continue
return player_stats
def get_top_players(selected_teams, selected_stat, consistency_threshold, apply_consistency_filter, use_lowest_score, max_players):
# Convert team names to abbreviations
selected_team_abbrs = [TEAM_ABBREVIATIONS[team] for team in selected_teams]
# Fetch all players
all_players = get_all_players()
# Filter players by selected teams
filtered_players = [player.player_id for player in all_players if player.team_abbr in selected_team_abbrs]
# Fetch stats for filtered players
player_stats = get_player_stats(filtered_players, selected_stat, use_lowest_score)
# Convert to DataFrame
df = pd.DataFrame(player_stats, columns=['Player', 'Team', 'Stat', 'Games Played'])
# Handle consistency filtering (if applicable)
if apply_consistency_filter:
# Placeholder: In reality, you would calculate std deviation from game logs
# sportsipy does allow game-by-game data, but it's more involved
# For simplicity, we'll assume consistency is based on games played
df = df[df['Games Played'] >= consistency_threshold]
# Remove players with missing stats
df = df.dropna(subset=['Stat'])
# Sort players based on selected stat
df_sorted = df.sort_values(by='Stat', ascending=False)
# Get top N players
top_players = df_sorted.head(max_players)
# Map team abbreviations back to team names
abbr_to_team = {v: k for k, v in TEAM_ABBREVIATIONS.items()}
top_players['Team'] = top_players['Team'].map(abbr_to_team)
return top_players
def display_top_players():
selected_teams = [team_listbox.get(i) for i in team_listbox.curselection()]
selected_stat_key = selected_stat.get()
selected_stat_value = STAT_OPTIONS[selected_stat_key]
try:
max_players = int(max_players_entry.get())
except ValueError:
result_label.config(text="Invalid number for max players.")
return
try:
consistency_threshold = float(consistency_entry.get())
except ValueError:
result_label.config(text="Invalid number for consistency threshold.")
return
apply_consistency_filter = consistency_var.get()
use_lowest_score = lowest_score_var.get()
if not selected_teams:
result_label.config(text="Please select at least one team.")
return
result_label.config(text="Fetching data...")
root.update() # Refresh UI during processing
start_time = time.time()
top_players_df = get_top_players(
selected_teams,
selected_stat_value,
consistency_threshold,
apply_consistency_filter,
use_lowest_score,
max_players
)
end_time = time.time()
# Display results
result_area.delete("1.0", tk.END)
if top_players_df.empty:
result_label.config(text="No top players found.")
return
result_label.config(text=f"Data fetched successfully in {end_time - start_time:.2f} seconds!")
# Displaying the selected stat
stat_display = selected_stat_key
if use_lowest_score:
result_area.insert(tk.END, f"Top {len(top_players_df)} players based on lowest {stat_display}:\n")
else:
result_area.insert(tk.END, f"Top {len(top_players_df)} players based on {stat_display}:\n")
# Format and display player stats
for idx, row in top_players_df.iterrows():
stat_line = f"{row['Player']} - {row['Stat']} {stat_display} (Games Played: {row['Games Played']}) [{row['Team']}]"
if apply_consistency_filter:
stat_line += f" (Min Games Played Threshold: {consistency_threshold})"
result_area.insert(tk.END, stat_line + "\n")
result_area.insert(tk.END, "\n")
# UI Setup
root = tk.Tk()
root.title("NFL Best Players Comparison")
root.geometry("700x600")
root.rowconfigure(7, weight=1)
root.columnconfigure(1, weight=1)
team_label = ttk.Label(root, text="Select Teams:")
team_label.grid(row=0, column=0, padx=10, pady=10, sticky="NW")
team_listbox = tk.Listbox(root, selectmode=tk.MULTIPLE, height=15, exportselection=False)
for team in TEAM_ABBREVIATIONS.keys():
team_listbox.insert(tk.END, team)
team_listbox.grid(row=0, column=1, padx=10, pady=10, sticky="NSEW")
max_players_label = ttk.Label(root, text="Max Players:")
max_players_label.grid(row=1, column=0, padx=10, pady=10, sticky="W")
max_players_entry = ttk.Entry(root, width=5)
max_players_entry.grid(row=1, column=1, padx=10, pady=10, sticky="W")
max_players_entry.insert(0, "10")
# Variable to hold the selected stat
selected_stat = tk.StringVar(value='Passing Yards')
# Label and Radio Buttons for Stat Selection
stat_label = ttk.Label(root, text="Select Stat to Compare:")
stat_label.grid(row=2, column=0, padx=10, pady=10, sticky="W")
stat_frame = ttk.Frame(root)
stat_frame.grid(row=2, column=1, padx=10, pady=10, sticky="W")
for text in STAT_OPTIONS.keys():
rb = ttk.Radiobutton(stat_frame, text=text, variable=selected_stat, value=text)
rb.pack(side='left')
consistency_label = ttk.Label(root, text="Consistency Threshold (Min Games Played):")
consistency_label.grid(row=3, column=0, padx=10, pady=10, sticky="W")
consistency_entry = ttk.Entry(root, width=5)
consistency_entry.grid(row=3, column=1, padx=10, pady=10, sticky="W")
consistency_entry.insert(0, "10")
# Variables and Checkbuttons for Toggles
consistency_var = tk.BooleanVar(value=True)
consistency_toggle = ttk.Checkbutton(root, text="Apply Consistency Filter", variable=consistency_var)
consistency_toggle.grid(row=4, column=0, columnspan=2, padx=10, pady=5, sticky="W")
lowest_score_var = tk.BooleanVar(value=False)
lowest_score_toggle = ttk.Checkbutton(root, text="Use Player's Lowest Score", variable=lowest_score_var)
lowest_score_toggle.grid(row=5, column=0, columnspan=2, padx=10, pady=5, sticky="W")
submit_button = ttk.Button(root, text="Get Top Players", command=display_top_players)
submit_button.grid(row=6, column=0, columnspan=2, pady=10)
result_label = ttk.Label(root, text="")
result_label.grid(row=7, column=0, columnspan=2, padx=10, pady=10)
result_area = tk.Text(root, wrap="word")
result_area.grid(row=8, column=0, columnspan=2, padx=10, pady=10, sticky="NSEW")
scrollbar = ttk.Scrollbar(root, orient="vertical", command=result_area.yview)
scrollbar.grid(row=8, column=2, sticky="NS")
result_area.configure(yscrollcommand=scrollbar.set)
root.mainloop()
Explanation of the Script:
Imports and Team Data:
Libraries: Imported necessary libraries including tkinter, sportsipy, and pandas.
Team Abbreviations: Defined a dictionary TEAM_ABBREVIATIONS mapping NFL team names to their standard abbreviations used by sportsipy.
Statistics Options:
Defined relevant NFL statistics in STAT_OPTIONS such as Passing Yards, Rushing Yards, Receiving Yards, and Touchdowns.
Data Retrieval Functions:
get_all_players: Fetches all active NFL players using sportsipy.nfl.players and caches the result for efficiency.
get_player_stats: Retrieves the selected statistic for each player. Handles both average and lowest score based on user selection. Note that fetching game-by-game stats for consistency filtering would require more detailed implementation.
get_top_players: Filters players by selected teams, retrieves their statistics, applies consistency filters if selected, and returns the top players sorted by the chosen statistic.
GUI Components:
Team Selection: Multi-select Listbox allowing users to select multiple NFL teams.
Max Players: Entry field to specify how many top players to display.
Stat Selection: Radio buttons for selecting which statistic to compare.
Consistency Filter: Checkbox and entry to apply a minimum games played threshold.
Lowest Score Option: Checkbox to choose whether to use the player's lowest score.
Result Display: Text area to display the fetched top players with a scrollbar.
Event Handling:
display_top_players: Triggered when the "Get Top Players" button is clicked. It fetches and processes the data based on user selections and updates the GUI accordingly.
Notes and Considerations:
Data Accuracy: The sportsipy library provides data based on available sources and may not always be up-to-date with the latest NFL stats. Ensure that the sportsipy version supports the current NFL season.
Consistency Filtering: Implementing a standard deviation-based consistency filter similar to the NBA script would require accessing game-by-game data for each player. This can be quite resource-intensive and is not fully implemented in this script. Instead, a minimum number of games played filter is used as a placeholder.
Lowest Score Feature: Fetching the player's lowest score in a specific statistic would require detailed game-by-game data, which is not directly accessible through sportsipy without additional processing.
Performance: Fetching data for all players can be time-consuming, especially without proper caching or asynchronous processing. The @lru_cache decorator is used to cache the list of players, improving performance on subsequent fetches.
Error Handling: Basic error handling is implemented to skip players for whom data cannot be fetched. Additional robust error handling can be added as needed.
Enhancements: For a more advanced application, consider adding features such as selecting specific player positions, more detailed statistics, or visualizations of player performance.
Conclusion
This script provides a foundational framework to compare NFL players based on selected statistics using a GUI interface. Depending on your specific requirements, you can further customize and enhance the application to include more detailed data analysis, visualization, and user-friendly features.