Certainly! I can help you enhance your script by adding the functionality you described. Here's the modified script with the requested features:
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
# 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",
"Accept": "application/json",
"X-Sportsbook-Region": "NJ",
"Origin": "https://sportsbook.fanduel.com",
}
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 find_max_fanduel_available(player_name, stat_search_term, max_N):
"""
Finds the maximum N up to max_N such that check_fanduel_search(player_name N stat_search_term) returns True.
"""
low = 1
high = int(max_N)
result = None
while low <= high:
mid = (low + high) // 2
search_term = f"{player_name} {mid} {stat_search_term}"
if check_fanduel_search(search_term):
result = mid
low = mid + 1
else:
high = mid - 1
return result
def get_top_players_for_selected_teams(selected_teams, selected_stat, consistency_threshold, apply_consistency_filter, use_lowest_score, use_average_and_lowest_score):
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
all_player_stats.append((team_name, player_name, season, stat_value, std_dev, games_played))
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_value, max_players, consistency_threshold, apply_consistency_filter, use_lowest_score, use_average_and_lowest_score):
start_time = time.time()
result = get_top_players_for_selected_teams(
selected_teams, selected_stat_value, consistency_threshold,
apply_consistency_filter, use_lowest_score, use_average_and_lowest_score
)
if check_fanduel_var.get() and isinstance(result, list):
stat_search_term_map = {
'PPG': 'points',
'REB': 'rebounds',
'AST': 'assists',
'3PM': 'Made Threes'
}
stat_search_term = stat_search_term_map.get(selected_stat_value, 'points')
for idx, (team, player, season, stat_value, std_dev, games_played) in enumerate(result):
max_N = int(stat_value)
fanduel_N = find_max_fanduel_available(player, stat_search_term, max_N)
if fanduel_N is not None:
result[idx] = (team, player, season, fanduel_N, std_dev, games_played)
else:
# If not available at any point, set to None or keep original stat_value
pass # You can decide how to handle this case
end_time = time.time()
root.after(0, update_ui, result, start_time, end_time, selected_stat_value, max_players)
def update_ui(result, start_time, end_time, selected_stat_value, max_players):
result_area.delete("1.0", tk.END)
if isinstance(result, str):
result_label.config(text=result)
return
top_players = result[:max_players]
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_value, '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):
stat_line = f"{i}. {player} - {stat_value:.2f} {stat_label_text} (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()
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))
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("800x600") # Set a default window size
# 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)
# 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")
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")
check_fanduel_var = tk.BooleanVar(value=False)
check_fanduel_toggle = ttk.Checkbutton(filter_frame, text="Check FanDuel Availability", variable=check_fanduel_var)
check_fanduel_toggle.grid(row=4, column=0, columnspan=2, sticky="w")
# Section 4: Buttons
button_frame = ttk.Frame(main_frame)
button_frame.grid(row=4, 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 5: Results
result_label = ttk.Label(main_frame, text="", wraplength=780) # Set a fixed wraplength
result_label.grid(row=5, column=0, sticky="ew", pady=(0,5))
result_area = tk.Text(main_frame, wrap="word", height=15, state="normal") # Allow text editing temporarily
result_area.grid(row=6, column=0, sticky="nsew")
scrollbar = ttk.Scrollbar(main_frame, orient="vertical", command=result_area.yview)
scrollbar.grid(row=6, column=1, sticky="ns")
result_area.configure(yscrollcommand=scrollbar.set)
root.mainloop()
Explanation of Changes:
-
Added the FanDuel Check Toggle:
- Introduced a new
BooleanVar named check_fanduel_var.
- Added a
Checkbutton to the GUI to allow users to toggle the FanDuel availability check.
-
Included check_fanduel_search Function:
- Added the
check_fanduel_search function to perform the FanDuel API search.
- Adjusted headers and parameters as needed.
-
Implemented find_max_fanduel_available Function:
- Created a function that performs a binary search to find the highest number up to the player's average stat where the player is available on FanDuel.
- This function reduces the number of API calls by not checking every single number sequentially.
-
Modified Data Fetching to Include FanDuel Check:
- In the
fetch_data_and_update_ui function, after fetching the player stats, it checks if the FanDuel toggle is enabled.
- If enabled, it loops through each player and updates their
stat_value to the highest available number on FanDuel using the find_max_fanduel_available function.
-
Adjusted the Display in the UI:
- In the
update_ui function, since stat_value might have been modified to reflect the FanDuel availability, it displays the updated stat_value in the results area.
- The rest of the UI remains consistent.
-
Ensured Thread Safety and UI Responsiveness:
- Kept the data fetching and processing within a separate thread to prevent the GUI from freezing during network operations.
Note:
- The FanDuel API endpoint and parameters may need to be updated based on any changes in their API.
- The script assumes that the player names and search terms are correctly formatted for the FanDuel search.
- Error handling is included to ensure that network issues or API errors do not crash the application.
This enhanced script should now allow you to toggle the FanDuel availability check and adjust the displayed player stats accordingly.