Sure! Below is the updated script that incorporates the functionality you requested:
- Added a toggle in the UI to enable or disable checking FanDuel availability.
- Integrated the
check_fanduel_search function to verify each player's availability on FanDuel up to their per-game statistic.
- Updated the UI display to show the highest available integer stat instead of the original decimal value when the toggle is enabled.
- Handled threading to ensure the UI remains responsive during the availability checks.
Updated Script
import tkinter as tk
from tkinter import ttk
from nba_api.stats.endpoints import leaguedashplayerstats, leaguegamelog, scoreboardv2
import time
import pandas as pd
from datetime import datetime
import threading
import requests
import json
import math
# Precomputed dictionary of team names to IDs
TEAM_IDS = {
"Atlanta Hawks": 1610612737, "Boston Celtics": 1610612738, "Brooklyn Nets": 1610612751,
"Charlotte Hornets": 1610612766, "Chicago Bulls": 1610612741, "Cleveland Cavaliers": 1610612739,
"Dallas Mavericks": 1610612742, "Denver Nuggets": 1610612743, "Detroit Pistons": 1610612765,
"Golden State Warriors": 1610612744, "Houston Rockets": 1610612745, "Indiana Pacers": 1610612754,
"LA Clippers": 1610612746, "Los Angeles Lakers": 1610612747, "Memphis Grizzlies": 1610612763,
"Miami Heat": 1610612748, "Milwaukee Bucks": 1610612749, "Minnesota Timberwolves": 1610612750,
"New Orleans Pelicans": 1610612740, "New York Knicks": 1610612752, "Oklahoma City Thunder": 1610612760,
"Orlando Magic": 1610612753, "Philadelphia 76ers": 1610612755, "Phoenix Suns": 1610612756,
"Portland Trail Blazers": 1610612757, "Sacramento Kings": 1610612758, "San Antonio Spurs": 1610612759,
"Toronto Raptors": 1610612761, "Utah Jazz": 1610612762, "Washington Wizards": 1610612764
}
def check_fanduel_search(search_term):
"""
Checks if a search term on FanDuel's sportsbook returns any results.
Args:
search_term: The term to search for.
Returns:
True if results are found, False otherwise.
"""
url = "https://search.sportsbook.fanduel.com/search/tabs"
headers = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:133.0) Gecko/20100101 Firefox/133.0",
"Accept": "application/json",
"Accept-Language": "en-US,en;q=0.5",
"Accept-Encoding": "gzip, deflate, br, zstd",
"X-Sportsbook-Region": "NJ",
"Origin": "https://sportsbook.fanduel.com",
"DNT": "1",
"Sec-GPC": "1",
"Connection": "keep-alive",
"Referer": "https://sportsbook.fanduel.com/",
"Sec-Fetch-Dest": "empty",
"Sec-Fetch-Mode": "cors",
"Sec-Fetch-Site": "same-site",
"TE": "trailers"
}
params = {
"q": search_term,
"startIndex": "0",
"_ak": "FhMFpcPWXMeyZxOx",
"isDesktop": "true",
"expandedEvents": "5",
"timezone": "America/New_York",
"withMarkets": "true",
"includeMarketResults": "true",
"includeMarketBlurbs": "false"
}
try:
response = requests.get(url, headers=headers, params=params, timeout=10)
response.raise_for_status() # Raise an exception for bad status codes
data = response.json()
if data and "response" in data and "header" in data["response"] and "found" in data["response"]["header"]:
return data["response"]["header"]["found"] > 0
else:
return False
except requests.exceptions.RequestException as e:
print(f"Error during request: {e}")
return False
except json.JSONDecodeError as e:
print(f"Error decoding JSON: {e}")
return False
def get_top_players_for_selected_teams(selected_teams, selected_stat, consistency_threshold, apply_consistency_filter, use_lowest_score, use_average_and_lowest_score, check_fanduel):
selected_team_ids = [TEAM_IDS[team] for team in selected_teams]
NBA_SEASON = '2024-25'
try:
player_stats = leaguedashplayerstats.LeagueDashPlayerStats(
season=NBA_SEASON,
per_mode_detailed='PerGame',
timeout=60
)
player_stats_df = player_stats.get_data_frames()[0]
except Exception as e:
return f"Failed to fetch league player stats: {e}"
filtered_players = player_stats_df[player_stats_df['TEAM_ID'].isin(selected_team_ids)]
team_id_to_name = {v: k for k, v in TEAM_IDS.items()}
stat_column_map = {'PPG': 'PTS', 'REB': 'REB', 'AST': 'AST', '3PM': 'FG3M'} # Added 3PM
stat_column = stat_column_map.get(selected_stat, 'PTS')
try:
league_gamelog = leaguegamelog.LeagueGameLog(
season=NBA_SEASON,
season_type_all_star='Regular Season',
player_or_team_abbreviation='P',
timeout=60
)
league_gamelog_df = league_gamelog.get_data_frames()[0]
except Exception as e:
return f"Failed to fetch league game logs: {e}"
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:
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'})
filtered_players = filtered_players.merge(player_stat_min, on='PLAYER_ID', how='left')
if use_average_and_lowest_score:
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'})
filtered_players = filtered_players.merge(player_stat_min, on='PLAYER_ID', how='left')
filtered_players['AVG_AND_LOWEST'] = (filtered_players[stat_column] + filtered_players['MIN_STAT']) / 2
if apply_consistency_filter:
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'})
filtered_players = filtered_players.merge(player_stat_std, on='PLAYER_ID', how='left')
filtered_players['STD_DEV'] = filtered_players['STD_DEV'].fillna(0)
filtered_players = filtered_players[filtered_players['STD_DEV'] <= consistency_threshold]
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']
if use_lowest_score:
stat_value = row['MIN_STAT']
elif use_average_and_lowest_score:
stat_value = row['AVG_AND_LOWEST']
else:
stat_value = row[stat_column]
std_dev = row['STD_DEV'] if apply_consistency_filter else None
# Check FanDuel Availability
if check_fanduel:
max_stat = math.floor(stat_value)
available_stat = 0
for stat in range(1, max_stat + 1):
search_term = f"{player_name} {stat} points"
if check_fanduel_search(search_term):
available_stat = stat
else:
break # Assuming higher stats won't be available if current is not
if available_stat == 0:
# Player not available at any stat, skip or handle accordingly
continue
else:
stat_to_display = available_stat
else:
stat_to_display = stat_value
all_player_stats.append((team_name, player_name, season, stat_to_display, std_dev, games_played))
# Remove players without availability if FanDuel check is enabled
if check_fanduel:
all_player_stats = [x for x in all_player_stats if x[3] > 0]
else:
all_player_stats = [x for x in all_player_stats if pd.notnull(x[3])]
return sorted(all_player_stats, key=lambda x: x[3], reverse=True)
def fetch_data_and_update_ui(selected_teams, selected_stat, max_players, consistency_threshold, apply_consistency_filter, use_lowest_score, use_average_and_lowest_score, check_fanduel):
start_time = time.time()
result = get_top_players_for_selected_teams(
selected_teams, selected_stat, consistency_threshold,
apply_consistency_filter, use_lowest_score, use_average_and_lowest_score, check_fanduel
)
end_time = time.time()
root.after(0, update_ui, result, start_time, end_time, selected_stat, max_players, check_fanduel)
def update_ui(result, start_time, end_time, selected_stat, max_players, check_fanduel):
result_area.delete("1.0", tk.END)
if isinstance(result, str):
result_label.config(text=result)
return
top_players = result[:max_players]
if check_fanduel:
result_label.config(text=f"Data fetched in {end_time - start_time:.2f} seconds! (FanDuel Availability Checked)")
else:
result_label.config(text=f"Data fetched in {end_time - start_time:.2f} seconds!")
stat_label_map = {'PPG': 'PPG', 'REB': 'RPG', 'AST': 'APG', '3PM': '3PM'} # Updated stat label
stat_label_text = stat_label_map.get(selected_stat, 'PPG')
if use_lowest_score_var.get():
result_area.insert(tk.END, f"Top {len(top_players)} players based on lowest {stat_label_text}:\n")
elif use_average_and_lowest_score_var.get():
result_area.insert(tk.END, f"Top {len(top_players)} players based on the average of the player's average and lowest {stat_label_text}:\n")
else:
result_area.insert(tk.END, f"Top {len(top_players)} players based on average {stat_label_text}:\n")
for i, (team, player, season, stat_value, std_dev, games_played) in enumerate(top_players, start=1):
if check_fanduel:
stat_display = f"{int(stat_value)} {stat_label_text}"
else:
stat_display = f"{stat_value:.2f} {stat_label_text}"
stat_line = f"{i}. {player} - {stat_display} (Games Played: {games_played})"
if apply_consistency_filter_var.get() and std_dev is not None:
stat_line += f" (Std Dev: {std_dev:.2f})"
stat_line += f" ({season} season) [{team}]"
result_area.insert(tk.END, stat_line + "\n")
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
apply_consistency_filter = apply_consistency_filter_var.get()
use_lowest_score = use_lowest_score_var.get()
use_average_and_lowest_score = use_average_and_lowest_score_var.get()
check_fanduel = check_fanduel_var.get()
if not selected_teams:
result_label.config(text="Please select at least one team.")
return
result_label.config(text="Fetching data...")
# Start the data fetching in a separate thread
thread = threading.Thread(target=fetch_data_and_update_ui, args=(
selected_teams, selected_stat_value, max_players,
consistency_threshold, apply_consistency_filter,
use_lowest_score, use_average_and_lowest_score, check_fanduel
))
thread.start()
def get_teams_playing_today():
team_listbox.selection_clear(0, tk.END)
try:
today_str = datetime.now().strftime("%m/%d/%Y")
sb = scoreboardv2.ScoreboardV2(game_date=today_str, timeout=30)
line_score_df = sb.line_score.get_data_frame()
todays_team_ids = line_score_df['TEAM_ID'].unique()
team_id_to_name = {v: k for k, v in TEAM_IDS.items()}
todays_teams = [team_id_to_name[tid] for tid in todays_team_ids if tid in team_id_to_name]
all_teams = list(TEAM_IDS.keys())
for team in todays_teams:
if team in all_teams:
index = all_teams.index(team)
team_listbox.selection_set(index)
if not todays_teams:
result_label.config(text="No games today or failed to fetch today's teams.")
else:
result_label.config(text="Teams playing today have been selected.")
except Exception as e:
result_label.config(text=f"Error fetching today's teams: {e}")
# UI Setup
root = tk.Tk()
root.title("NBA Player Comparison")
root.geometry("900x700") # Increased size to accommodate additional elements
# Use a style
style = ttk.Style()
style.theme_use('clam') # 'clam' is a good theme for modern look
# Main Frame
main_frame = ttk.Frame(root, padding="10")
main_frame.grid(row=0, column=0, sticky="nsew")
# Configure grid
root.columnconfigure(0, weight=1)
root.rowconfigure(0, weight=1)
main_frame.columnconfigure(0, weight=1)
main_frame.rowconfigure(0, weight=0)
main_frame.rowconfigure(1, weight=0)
main_frame.rowconfigure(2, weight=0)
main_frame.rowconfigure(3, weight=0)
main_frame.rowconfigure(4, weight=0)
main_frame.rowconfigure(5, weight=1)
main_frame.rowconfigure(6, weight=1)
# Section 1: Team Selection
team_label = ttk.Label(main_frame, text="Select Teams:")
team_label.grid(row=0, column=0, sticky="w", pady=(0,5))
team_listbox = tk.Listbox(main_frame, selectmode=tk.MULTIPLE, height=10, exportselection=False)
for team in TEAM_IDS:
team_listbox.insert(tk.END, team)
team_listbox.grid(row=1, column=0, sticky="ew", pady=(0,10))
# Section 2: Max Players and Stat Selection
options_frame = ttk.Frame(main_frame)
options_frame.grid(row=2, column=0, sticky="ew", pady=(0,10))
options_frame.columnconfigure(0, weight=1)
options_frame.columnconfigure(1, weight=1)
max_players_label = ttk.Label(options_frame, text="Max Players:")
max_players_label.grid(row=0, column=0, sticky="w")
max_players_entry = ttk.Entry(options_frame, width=5)
max_players_entry.insert(0, "5")
max_players_entry.grid(row=0, column=1, sticky="ew")
selected_stat = tk.StringVar(value='PPG')
stat_label = ttk.Label(options_frame, text="Select Stat:")
stat_label.grid(row=1, column=0, sticky="w")
stat_dropdown = ttk.Combobox(options_frame, textvariable=selected_stat, values=['PPG', 'REB', 'AST', '3PM'], state='readonly') # Added 3PM to dropdown
stat_dropdown.grid(row=1, column=1, sticky="ew")
# Section 3: Filters
filter_frame = ttk.Frame(main_frame)
filter_frame.grid(row=3, column=0, sticky="ew", pady=(0,10))
filter_frame.columnconfigure(0, weight=1)
filter_frame.columnconfigure(1, weight=1)
consistency_label = ttk.Label(filter_frame, text="Consistency Threshold (Max Std Dev):")
consistency_label.grid(row=0, column=0, sticky="w")
consistency_entry = ttk.Entry(filter_frame, width=5)
consistency_entry.insert(0, "5")
consistency_entry.grid(row=0, column=1, sticky="ew")
apply_consistency_filter_var = tk.BooleanVar(value=True)
consistency_toggle = ttk.Checkbutton(filter_frame, text="Apply Consistency Filter", variable=apply_consistency_filter_var)
consistency_toggle.grid(row=1, column=0, columnspan=2, sticky="w")
use_lowest_score_var = tk.BooleanVar(value=False)
lowest_score_toggle = ttk.Checkbutton(filter_frame, text="Use Player's Lowest Score", variable=use_lowest_score_var)
lowest_score_toggle.grid(row=2, column=0, columnspan=2, sticky="w")
# Add toggle for using the average of the average and lowest score
use_average_and_lowest_score_var = tk.BooleanVar(value=False)
average_and_lowest_score_toggle = ttk.Checkbutton(filter_frame, text="Use Average of Average and Lowest Score", variable=use_average_and_lowest_score_var)
average_and_lowest_score_toggle.grid(row=3, column=0, columnspan=2, sticky="w")
# Section 4: FanDuel Availability Toggle
fanduel_frame = ttk.Frame(main_frame)
fanduel_frame.grid(row=4, column=0, sticky="ew", pady=(0,10))
fanduel_frame.columnconfigure(0, weight=1)
fanduel_frame.columnconfigure(1, weight=1)
check_fanduel_var = tk.BooleanVar(value=False)
fanduel_toggle = ttk.Checkbutton(fanduel_frame, text="Check FanDuel Availability", variable=check_fanduel_var)
fanduel_toggle.grid(row=0, column=0, columnspan=2, sticky="w")
# Section 5: Buttons
button_frame = ttk.Frame(main_frame)
button_frame.grid(row=5, column=0, sticky="ew", pady=(0,10))
button_frame.columnconfigure(0, weight=1)
button_frame.columnconfigure(1, weight=1)
submit_button = ttk.Button(button_frame, text="Get Top Players", command=display_top_players, style="TButton")
submit_button.grid(row=0, column=0, sticky="ew", padx=(0,5))
today_teams_button = ttk.Button(button_frame, text="Get Today's Teams", command=get_teams_playing_today, style="TButton")
today_teams_button.grid(row=0, column=1, sticky="ew", padx=(5,0)))
# Section 6: Results
result_label = ttk.Label(main_frame, text="", wraplength=880) # Adjusted wraplength
result_label.grid(row=6, column=0, sticky="ew", pady=(0,5))
result_area = tk.Text(main_frame, wrap="word", height=20, state="normal") # Increased height
result_area.grid(row=7, column=0, sticky="nsew")
scrollbar = ttk.Scrollbar(main_frame, orient="vertical", command=result_area.yview)
scrollbar.grid(row=7, column=1, sticky="ns")
result_area.configure(yscrollcommand=scrollbar.set)
root.mainloop()
Explanation of Changes
-
FanDuel Availability Toggle:
- UI Element:
- Added a new checkbox in the
filter_frame to toggle FanDuel availability checking.
# Section 4: FanDuel Availability Toggle
fanduel_frame = ttk.Frame(main_frame)
fanduel_frame.grid(row=4, column=0, sticky="ew", pady=(0,10))
fanduel_frame.columnconfigure(0, weight=1)
fanduel_frame.columnconfigure(1, weight=1)
check_fanduel_var = tk.BooleanVar(value=False)
fanduel_toggle = ttk.Checkbutton(fanduel_frame, text="Check FanDuel Availability", variable=check_fanduel_var)
fanduel_toggle.grid(row=0, column=0, columnspan=2, sticky="w")
- Functionality:
- The state of this toggle (
check_fanduel_var) determines whether the script will perform FanDuel availability checks.
-
Integration of check_fanduel_search:
- Function Modification:
- The
get_top_players_for_selected_teams function now accepts an additional parameter check_fanduel to decide whether to perform the availability checks.
- If
check_fanduel is True, for each player, the script:
- Rounds down their per-game stat.
- Iteratively checks availability on FanDuel from
1 up to the rounded stat.
- Selects the highest available integer stat.
- If no availability is found, the player is skipped.
def get_top_players_for_selected_teams(..., check_fanduel):
...
if check_fanduel:
max_stat = math.floor(stat_value)
available_stat = 0
for stat in range(1, max_stat + 1):
search_term = f"{player_name} {stat} points"
if check_fanduel_search(search_term):
available_stat = stat
else:
break # Assuming higher stats won't be available if current is not
if available_stat == 0:
# Player not available at any stat, skip or handle accordingly
continue
else:
stat_to_display = available_stat
else:
stat_to_display = stat_value
...
- Threading Considerations:
- Since each FanDuel check involves a network request, performing this synchronously could freeze the UI. By handling data fetching in a separate thread, we ensure the UI remains responsive.
-
UI Update Adjustments:
Notes and Recommendations
- API Rate Limits: Be cautious of potential rate limits when making multiple requests to FanDuel's API. If you plan to scale this application or use it frequently, consider implementing delays or caching mechanisms.
- Asynchronous Requests: For improved performance, especially when checking FanDuel availability for many players, consider using asynchronous request libraries like
aiohttp instead of requests. This would allow multiple checks to be performed concurrently.
- User Experience: Depending on the number of players and checks, the data fetching process might take some time. You might want to add a progress bar or spinner to indicate ongoing processing.
- Data Storage: If you find that the FanDuel availability doesn't change frequently, you can cache the results to minimize repeated checks and improve performance.
This updated script should meet your requirements by allowing users to toggle FanDuel availability checks and displaying the highest available integer stat for each player accordingly. Feel free to further customize and optimize based on your specific needs!