Exemple #1
0
 def setUpClass(cls):
     cls.playerId = get_player('Tim', 'Duncan')
     cls.vs_playerId = get_player('Stephen', 'Curry')
     cls.teamId = ''
     cls.measureType = 'Base'
     cls.perMode = 'PerGame'
     cls.plusMinus = 'N'
     cls.paceAdjust = 'N'
     cls.rank = 'Y'
     cls.leagueId = '00'
     cls.season = '2015-16'
     cls.seasonType = 'Regular Season'
     cls.poRound = ''
     cls.outcome = ''
     cls.location = 'Home'
     cls.month = 0
     cls.sessionSegment = ''
     cls.dateFrom = ''
     cls.dateTo = ''
     cls.opponentTeamId = 0
     cls.vsConference = ''
     cls.vsDivision = ''
     cls.gameSegment = ''
     cls.period = 1
     cls.shotClockRange = ''
     cls.lastNGames = 0
Exemple #2
0
def test():
    team_id = TEAMS['ATL']['id']
    player_id = get_player('Lebron', 'James')
    assert team.TeamList()
    assert team.TeamSummary(team_id)
    team_details = team.TeamDetails(team_id)
    assert team_details
    assert team_details.background()
    assert team_details.history()
    assert team.TeamCommonRoster(team_id)
    assert team.TeamGeneralSplits(team_id)
    assert team.TeamOpponentSplits(team_id)
    assert team.TeamLastNGamesSplits(team_id)
    assert team.TeamInGameSplits(team_id)
    assert team.TeamClutchSplits(team_id)
    assert team.TeamShootingSplits(team_id)
    assert team.TeamPerformanceSplits(team_id)
    assert team.TeamLineups(team_id)
    assert team.TeamPlayers(team_id)
    assert team.TeamPlayerOnOffDetail(team_id)
    assert team.TeamPlayerOnOffSummary(team_id)
    assert team.TeamGameLogs(team_id)
    assert team.TeamShotTracking(team_id)
    assert team.TeamReboundTracking(team_id)
    assert team.TeamPassTracking(team_id)
    assert team.TeamVsPlayer(team_id, player_id)
def test():
    team_id = TEAMS['ATL']['id']
    player_id = get_player('Lebron', 'James')
    assert team.TeamList()
    assert team.TeamSummary(team_id)
    team_details = team.TeamDetails(team_id)
    assert team_details
    assert team_details.background()
    assert team_details.history()
    assert team.TeamCommonRoster(team_id)
    assert team.TeamGeneralSplits(team_id)
    assert team.TeamOpponentSplits(team_id)
    assert team.TeamLastNGamesSplits(team_id)
    assert team.TeamInGameSplits(team_id)
    assert team.TeamClutchSplits(team_id)
    assert team.TeamShootingSplits(team_id)
    assert team.TeamPerformanceSplits(team_id)
    assert team.TeamLineups(team_id)
    assert team.TeamPlayers(team_id)
    assert team.TeamPlayerOnOffDetail(team_id)
    assert team.TeamPlayerOnOffSummary(team_id)
    assert team.TeamGameLogs(team_id)
    assert team.TeamShotTracking(team_id)
    assert team.TeamReboundTracking(team_id)
    assert team.TeamPassTracking(team_id)
    assert team.TeamVsPlayer(team_id, player_id)
Exemple #4
0
def generate_shots_fromNBA(first, last, season):
    """ Takes first, last, and season as string,
    returns pandas structure of all shots
    """
    player_id = get_player(first, last)
    player = shotchart.ShotChart(player_id, season=season)
    shots = player.shot_chart()
    return shots
Exemple #5
0
def get_data():
    #Lebron is a place holder, first, last and year will be inputs int the future
    first = 'Lebron'
    last = 'James'
    year = '2012-13'
    player_id = get_player(first, last)
    #ShotChart creates a readable dictionary of all the data
    Lebron_James = shotchart.ShotChart(player_id, season=year)
    shots = Lebron_James.shot_chart()
    return shots
def get_playoff_stats(name):

    name_split = name.split()
    first = name_split[0]
    last = name_split[1]
    
    pid = player.get_player(first, last)
    stats = player.PlayerGameLogs(pid, season_type='Playoffs')
    
    return stats.info()
def get_playoff_stats(name):

    name_split = name.split()
    first = name_split[0]
    last = name_split[1]

    pid = player.get_player(first, last)
    stats = player.PlayerGameLogs(pid, season_type='Playoffs')

    return stats.info()
Exemple #8
0
def search():
    """Search post request when searching for a specific player or team.
    """
    name = request.form["searchname"]
    if name.upper() == "YAO MING":
        return redirect(url_for("players", playerid="2397"))

    team_id = ""
    split_name = name.split(" ", 1)
    if (len(split_name) == 1):
        try:
            get_player = player.get_player(split_name[0], just_id=False)
            get_team = False
        except:
            get_player = False
            if (split_name[0].upper() in TEAMS):
                team_id = TEAMS[split_name[0].upper()]["id"]
                team_summary = team.TeamSummary(team_id)
                get_team = team_summary.info()
            else:
                get_team = False
    else:
        try:
            get_player = player.get_player(split_name[0],
                                           last_name=split_name[1],
                                           just_id=False)
            get_team = False
        except:
            get_player = False
            if (name.lower() in TEAM_NAME_TO_ID):
                team_id = TEAM_NAME_TO_ID[name.lower()]["id"]
                team_summary = team.TeamSummary(team_id)
                get_team = team_summary.info()
            else:
                get_team = False

    if get_player:
        return redirect(url_for("players", playerid=get_player["PERSON_ID"]))
    elif get_team:
        return redirect(url_for("teams", teamid=team_id))
    else:
        return render_template("search.html")
Exemple #9
0
def search():
    """Search for the player name"""
    if not request.form.get("q"):
        error = 'Please input name'
    else:
        name = request.form.get("q").split()
        if len(name) > 1:
            first = name[0]
            last = name[1]
        else:
            first = name[0]
            last = None
        #Use nba_py api to get summary of player
        playerid = get_player(first, last, just_id=True)
        session["playerid"] = playerid
        summary = PlayerSummary(playerid)
        sum = summary.info()[0]
        stats = summary.headline_stats()[0]
        p = sum["DISPLAY_FIRST_LAST"]
        #wikipedia summary
        wiki = requests.get(
            "https://en.wikipedia.org/api/rest_v1/page/summary/%s" % p)
        wiki = wiki.json()
        #picture headshot
        pic = (
            "https://ak-static.cms.nba.com/wp-content/uploads/headshots/nba/latest/260x190/%s"
            % playerid) + ".png"
        #picture logo
        tabv = summary.info()[0]["TEAM_ABBREVIATION"]
        logo = ("https://stats.nba.com/media/img/teams/logos/%s" %
                tabv) + "_logo.svg"
        #Datetime to date only
        date = summary.info()[0]["BIRTHDATE"]
        date = date[:10]
        #convert to datetime type
        dob = datetime.datetime.strptime(date, "%Y-%m-%d").date()
        #calculate age
        age = calculate_age(dob)
        #convert PIE
        if "PIE" in stats:
            pie = float((stats["PIE"]) * 100)
        else:
            pie = '-'
        return render_template("id.html",
                               sum=sum,
                               stats=stats,
                               wiki=wiki,
                               pic=pic,
                               logo=logo,
                               age=age,
                               dob=dob,
                               pie=pie)
Exemple #10
0
def shooting_splits():
    player_name = request.args.get('player')
    if not player_name:
        return bad_request(ERRORS["NoPlayerParam"])
    name_tokens = player_name.split()
    try:
        player_id = get_player(name_tokens[0],
                               last_name=name_tokens[1],
                               just_id=True)
    except (PlayerNotFoundException, IndexError):
        return bad_request(ERRORS["PlayerNotFound"])
    res = get_data("shootingsplits", player_id, season="2017-18")
    return jsonify(res)
Exemple #11
0
def player_summary():
    player_name = request.args.get('player')
    if not player_name:
        return bad_request(ERRORS["NoPlayerParam"])
    name_tokens = player_name.split()
    try:
        player_id = get_player(name_tokens[0],
                               last_name=name_tokens[1],
                               just_id=True)
    except (PlayerNotFoundException, IndexError):
        return bad_request(ERRORS["PlayerNotFound"])
    player_summary = get_data("playersummary", player_id)
    return jsonify(player_summary)
Exemple #12
0
 def __init__(self, pid=-1, f_name='', l_name='', season=''):
     self.season = season
     if pid == -1:
         self.f_name = f_name
         self.l_name = l_name
         self.p_id = player.get_player(f_name, l_name).values[0]
         self.desc = self.get_desc()
     else:
         self.p_id = pid
         self.desc = self.get_desc()
         self.f_name = self.desc.ix[0, 'FIRST_NAME']
         self.l_name = self.desc.ix[0, 'LAST_NAME']
     self.game_logs = self.get_game_logs()
     self.model_list = {}
Exemple #13
0
def test():
    pid = get_player('Tim', 'Duncan')
    vs_pid = get_player('Stephen', 'Curry')
    assert player.PlayerList()
    assert player.PlayerSummary(pid)
    # assert player.PlayerGeneralSplits(pid)
    # assert player.PlayerOpponentSplits(pid)
    assert player.PlayerLastNGamesSplits(pid)
    assert player.PlayerInGameSplits(pid)
    assert player.PlayerClutchSplits(pid)
    # assert player.PlayerShootingSplits(pid)
    assert player.PlayerPerformanceSplits(pid)
    assert player.PlayerYearOverYearSplits(pid)
    assert player.PlayerCareer(pid)
    assert player.PlayerProfile(pid)
    assert player.PlayerGameLogs(pid)
    assert player.PlayerShotTracking(pid)
    assert player.PlayerReboundTracking(pid)
    assert player.PlayerPassTracking(pid)
    assert player.PlayerDefenseTracking(pid)
    # assert player.PlayerShotLogTracking(pid)
    # assert player.PlayerReboundLogTracking(pid)
    assert player.PlayerVsPlayer(pid, vs_pid)
Exemple #14
0
def player_stats():
    player_name = request.args.get('player')
    if not player_name:
        return bad_request(ERRORS["NoPlayerParam"])
    name_tokens = player_name.split()
    try:
        player_id = get_player(name_tokens[0],
                               last_name=name_tokens[1],
                               just_id=True)
    except (PlayerNotFoundException, IndexError):
        return bad_request(ERRORS["PlayerNotFound"])
    all_data = get_data("gamelogs",
                        player_id,
                        season="ALL",
                        season_type="Regular Season")
    return jsonify(all_data)
def get_player_id(first_name, last_name=None):
    # print("first name is " + first_name)
    # print("last name is " + last_name)

    # if last_name is not None:
    try:
        player_id = player.get_player(first_name, last_name, just_id=True)
    except Exception as e:
        print(e)
        player_id = None

    # player.get_
    # else:
    #     player_id = player.get_player(first_name)

    # print(player_id)
    # print(type(player_id))
    return player_id
def main(argv=None):
    #acquiring player's information using get_player(NAME)
    #I want LBJ's points, reb, ast, stl, blk, to, 3pm
    #I want LBJ's last 10 games information
    #I want to calculate LBJ's DK points
    #I want to determine if LBJ's DK points exceeds/dissapoints salary * (multiplier)
    
    #input first name last name salary
    firstName = raw_input('input firstname: ')
    lastName = raw_input('input lastname: ')
    salary = raw_input('input salary: $')
    
    dfkPlayerList = player.PlayerList()
    
    #print dfkPlayerList.info()
    
    plyr = player.PlayerGameLogs(get_player(firstName,lastName)).info()
    
    #getting the player's name name
    plyrName = player.PlayerSummary(plyr.get('Player_ID')[0]).info().get('DISPLAY_FIRST_LAST')[0]

    plyrGameLog = playerGetGameLog(plyr)
    DFPKList = []

    # calculating DFK from GameLog
    for i in range(0,len(plyrGameLog)):
        DFPKList.append(calculate_DKFP(plyrGameLog[i][0],plyrGameLog[i][1],plyrGameLog[i][2],plyrGameLog[i][3],plyrGameLog[i][4],plyrGameLog[i][5],plyrGameLog[i][6]))

    #outputs
    
    print '\n__[%s]__ DFKpoints for the 2015-2016 season \n' % (plyrName)
    print DFPKList
    print exceeds_expectation(DFPKList, numpy.float(salary), 5.6)


    s = 'abcdefghijklmnop'
    temp = ''
    for letter in s:
        print letter
        temp = letter + temp
    print temp
Exemple #17
0
    def __init__(self):
        try:
            self.players = pickle.load(open(savedPlayerData, "rb"))
            print "Pickle file found! Loading..."
        except: 
            # When the saved file doesn't exist...
            players = getPlayerNames()
            self.players = []
            i = 1
            for player in players:
                try: 
                    last, first = "".join(player.split()).split(',', 1)
                except:
#                    print "Skipping over " + player
                    continue

                print "Found " + first + " " + last
                pID = p.get_player(first, last)
                new_player = Player(pID, player)
                if new_player.career:
                    self.players.append(new_player)
            pickle.dump(self.players, open(savedPlayerData, "wb"))
Exemple #18
0
    def __init__(self):
        try:
            self.players = pickle.load(open(savedPlayerData, "rb"))
            print "Pickle file found! Loading..."
        except:
            # When the saved file doesn't exist...
            players = getPlayerNames()
            self.players = []
            i = 1
            for player in players:
                try:
                    last, first = "".join(player.split()).split(',', 1)
                except:
                    #                    print "Skipping over " + player
                    continue

                print "Found " + first + " " + last
                pID = p.get_player(first, last)
                new_player = Player(pID, player)
                if new_player.career:
                    self.players.append(new_player)
            pickle.dump(self.players, open(savedPlayerData, "wb"))
Exemple #19
0
def add_ids(df):
	df.DraftYr = df.DraftYr.apply(create_season_string)
	players = df.Player.tolist()
	years = df.DraftYr.tolist()
	id_lists = []
	for player_name, year in zip(players, years):
		name_split = player_name.split()
		first = name_split[0]
		last = name_split[-1]
		year = year
		id_lists.append([first, last, year])
	
	ids = []
	for i in range(len(id_lists)):
		try:
			player_id = player.get_player(id_lists[i][0], last_name=id_lists[i][1], season=id_lists[i][2])
			ids.append(player_id)
		except player.PlayerNotFoundException:
			ids.append(0)
	rookie_ids = map(get_values, ids)
	rookie_series = pd.Series(rookie_ids)
	df['IDs'] = rookie_series.values
	return df
def get_fantasy_points_by_player(player_first_name, player_last_name):
    player_stats = None

    print("Loading: Getting Fantasy Point for " + player_first_name + " " +
          player_last_name)

    try:
        player_id = player.get_player(player_first_name, player_last_name,
                                      CURRENT_SEASON, 0, True)
        player_stats = player.PlayerYearOverYearSplits(
            player_id, 0, "Base", "PerGame", "N", "N", "N", League.Default,
            CURRENT_SEASON, 'Regular Season', "0", "", "", "0", "", '', '',
            '0', '', '', '', '0', '', '0').overall()[0]
    except StopIteration:
        print("Player not found")
    except IndexError:
        print(0)
        return 0

    fgm = player_stats["FGM"]
    fgmi = -0.5 * (player_stats["FGA"] - player_stats["FGM"])
    ftm = player_stats["FTM"]
    ftmi = -0.5 * (player_stats["FTA"] - player_stats["FTM"])
    fg3m = player_stats["FG3M"]
    reb = player_stats["REB"]
    ast = player_stats["AST"]
    stl = player_stats["STL"]
    blk = player_stats["BLK"]
    to = -0.25 * (player_stats["TOV"])
    pts = player_stats["PTS"]

    fantasy_points = round(
        fgm + fgmi + ftm + ftmi + fg3m + reb + ast + stl + blk + to + pts, 1)

    print(fantasy_points)

    return fantasy_points
from nba_py import player
from nba_py.player import get_player
import json

mvp_name = [("James", "Harden"), ("Russell", "Westbrook"), ("Lebron", "James"),
            ("Kawhi", "Leonard"), ("Isaiah", "Thomas"), ("John", "Wall"),
            ("Kevin", "Durant"), ("Stephen", "Curry"), ("Chris", "Paul"),
            ("DeMar", "DeRozan")]
mvp_id = []
for name in mvp_name:
    first, last = name
    mvp_id.append(get_player(first, last_name=last))

print(mvp_id)
logs = None
for id in mvp_id:
    player_gamelog = player.PlayerGameLogs(id).info()
    if not logs:
        logs = player_gamelog
    else:
        logs += player_gamelog
print(logs)
with open('mvp_game.json', 'w') as f:
    json.dump(logs, f)

# players = player.PlayerList().info()
# print players
Exemple #22
0
from nba_py import team
from nba_py.player import get_player
from nba_py.constants import *

# What this will do is get the stats for:
# Spurs vs Tyson Chandler for the 2010-11 season
plyr = get_player('Tyson', 'Chandler', just_id=False)
tvp = team.TeamVsPlayer(team_id=TEAMS['SAS']['id'],
                        vs_player_id=plyr['PERSON_ID'],
                        season='2010-11')
sa_on = tvp.shot_area_on_court()

try:
    r_on = (i for i in sa_on
            if i["GROUP_VALUE"] == "Restricted Area").__next__()
except AttributeError:
    r_on = next(i for i in sa_on if i["GROUP_VALUE"] == "Restricted Area")
# rest_on = sa_on[sa_on.GROUP_VALUE == 'Restricted Area']
sa_off = tvp.shot_area_off_court()
try:
    r_off = (i for i in sa_off
             if i["GROUP_VALUE"] == "Restricted Area").__next__()
except AttributeError:
    r_off = next(i for i in sa_off if i["GROUP_VALUE"] == "Restricted Area")
# rest_off = sa_off[sa_off.GROUP_VALUE == 'Restricted Area']
print('Spurs stats vs Tyson Chandler (2010-11)')
print('On court:  {}'.format(float(r_on['FG_PCT'])))
print('Off court: {}'.format(float(r_off['FG_PCT'])))
def test():
    pid = get_player('Lebron', 'James')  #find errror handler for invalid name
    assert shotchart.ShotChart(
        pid)  #find any case-sensitive/player names including " - " , " ' "
Exemple #24
0
def print_player_information(first_name, last_name):
    print("What information about the player would you like to view?")
    print("1. Basic Info (Vitals)")
    print("2. View Season Averages")
    print("3. Compare to Another Player")
    print("9. Go back to main menu")
    choice = input("Pick a number from the list above.\n")

    # getting basic info
    if int(choice) == 1:
        first_name.strip()
        last_name.strip()
        id = player_functions.get_player_id(first_name, last_name) # the id of the player requested
        if id is None:
            print("The player was not found")
        else:
            # getting the basic player summary
            player_summary = player.PlayerSummary(id)
            vitals = player_summary.info()
            printer.pprint(vitals)
    # submenu for season averages
    elif int(choice) == 2:
        first_name.strip()
        last_name.strip()
        id = player_functions.get_player_id(first_name, last_name)  # the id of the player requested
        if id is None:
            print("The player was not found")
        else:
            print("1. View Headline Stats for this Season")
            print("2. View Regular Season Totals")
            print("3. View Career Regular Season Totals")
            print("4. View Post Season Totals")
            print("5. View Career Post Season Totals")
            print("6. View All Star Season Totals")
            print("7. View Career All Star Season Totals")
            print("8. View College Season Totals")
            print("9. View Career College Season Totals")
            player_career = player.PlayerCareer(id)
            choice = input("Pick a number from the list above.\n")
            num = int(choice)

            print()
            print()

            if num == 1:
                player_summary = player.PlayerSummary(id)
                printer.pprint(player_summary.headline_stats())
            elif num == 2:
                # view regular season totals
                printer.pprint(player_career.regular_season_totals())
            elif num == 3:
                printer.pprint(player_career.regular_season_career_totals())
            elif num == 4:
                printer.pprint(player_career.post_season_totals())
            elif num == 5:
                printer.pprint(player_career.post_season_career_totals())
            elif num == 6:
                printer.pprint(player_career.all_star_season_totals())
            elif num == 7:
                printer.pprint(player_career.career_all_star_season_totals())
            elif num == 8:
                printer.pprint(player_career.college_season_totals())
            elif num == 9:
                printer.pprint(player_career.college_season_career_totals())

            print()
            print()

    elif int(choice) == 3:
        vs_player_first_name = input("What is the first name of the player you'd like to compare against?\n")
        vs_player_last_name = input("What is their last name?\n")

        id = player_functions.get_player_id(first_name, last_name)
        vs_player_id = player_functions.get_player_id(vs_player_first_name, vs_player_last_name)  # the id of the player to be compared against
        printer.pprint(player.PlayerVsPlayer(id, vs_player_id, season='2017-18').overall())



    #tryna dip
    elif int(choice) == 9:
        return

    elif int(choice) == 100:
        printer.pprint(player.get_player(first_name, last_name, season='2017-18', just_id=False))
    else:
        print("Invalid menu choice")
		dkPlayerID = 1626162

	if dkPlayerLastName == 'Zimmerman Jr.':
		dkPlayerID = 1627757

	if dkPlayerLastName == 'Hernangomez':
		dkPlayerID = 1626195

	if dkPlayerLastName == 'Luwawu-Cabarrot':
		dkPlayerID = 1627789

	if dkPlayerLastName == 'Richard Mbah a Moute':
		dkPlayerID = 201601

	if dkPlayerID == 0:
		dkPlayerID = player.get_player(dkPlayerFirstName, dkPlayerLastName)

	print(dkPlayerID)

	gameLogs = player.PlayerGameLogs(dkPlayerID,'00','2016-17').info()
	# print(gameLogs)

	doubleDouble = False
	playerGames = []
	ceiling = 0
	floor = 100
	playerGameMinutes = 0
	lastFive = 0
	lastFiveGamePoints = 0
	lastFiveGamePointsPPD = 0
	lastFiveGameMin = 0
def get_id(first_name, last_name):
    global player_id
    player_id =  player.get_player(first_name, last_name)
Exemple #27
0
def test():
    pid = get_player('Kevin', 'Durant')
    assert shotchart.ShotChart(pid)
		fdPlayerID = 1627789

	if fdPlayerLastName == 'Richard Mbah a Moute':
		fdPlayerID = 201601

	if fdPlayerLastName == 'Mbah a Moute':
		fdPlayerID = 201601

	if fdPlayerLastName == 'Tavares':
		fdPlayerID = 204002

	if fdPlayerLastName == 'Bembry':
		fdPlayerID = 1627761

	if fdPlayerID == 0:
		fdPlayerID = player.get_player(fdPlayerFirstName, fdPlayerLastName)

	foundSwishID = 'false'

	for swishPlayer in swishIds:
		if fdPlayerFullName == swishPlayer['name']:
			foundSwishID = 'true'
			fdPlayerSwishId = swishPlayer['swishID']
			break;

	if foundSwishID == 'false':
		print(fdPlayerFullName + " ERROR SWISH ID NOT FOUND")

	grindersProj = 0

	for grindersPlayer in grindersProjData:
Exemple #29
0
from nba_py import team
from nba_py.player import get_player
from nba_py.constants import *

# What this will do is get the stats for:
# Spurs vs Tyson Chandler for the 2010-11 season
plyr = get_player('Tyson', 'Chandler', just_id=False)
tvp = team.TeamVsPlayer(team_id=TEAMS['SAS']['id'],
                        vs_player_id=plyr['PERSON_ID'],
                        season='2010-11')
sa_on = tvp.shot_area_on_court()
rest_on = sa_on[sa_on.GROUP_VALUE == 'Restricted Area']
sa_off = tvp.shot_area_off_court()
rest_off = sa_off[sa_off.GROUP_VALUE == 'Restricted Area']
print 'Spurs stats vs Tyson Chandler (2010-11)'
print 'On court:  {}'.format(float(rest_on['FG_PCT']))
print 'Off court: {}'.format(float(rest_off['FG_PCT']))
Exemple #30
0
import nba_py
import json
import sys
import webbrowser
import os
from nba_py import team as team
from nba_py import player as p
from nba_py import constants as constants

firstName = sys.argv[1]
lastName = sys.argv[2]

print(firstName + " " + lastName + " " + "Stats")
pID = (p.get_player(firstName, lastName))

shootingSplits = p.PlayerShootingSplits(pID).shot_areas()
playerInfo = p.PlayerSummary(pID).info()
headlineStats = p.PlayerSummary(pID).headline_stats()

playerPhotoLink = "http://ak-static.cms.nba.com/wp-content/uploads/headshots/nba/latest/260x190/" + str(
    pID) + ".png"
linkJSON = {}
print(json.dumps(headlineStats, indent=4))
print(type(playerInfo))
playerInfo[0]["link"] = playerPhotoLink

twoMade = 0
twoAttempted = 0

threeMade = 0
threeAttempted = 0
Exemple #31
0
def _get_query_results(params={}, flatten_keys=False):
    if 'module' not in params or 'sub_module' not in params or 'function' not in params:
        return []
    if not flatten_keys and 'value_query' not in params:
        return []
    if params['module'] == 'player':
        if 'first_name' not in params:
            return []
        first = params['first_name']
        last = params['last_name'] if 'last_name' in params else None
        team_id = params['team_id'] if 'team_id' in params else 0
        measure_type = params[
            'measure_type'] if 'measure_type' in params else 'Base'
        per_mode = params['per_mode'] if 'per_mode' in params else 'PerGame'
        plus_minus = params['plus_minus'] if 'plus_minus' in params else 'N'
        pace_adjust = params['pace_adjust'] if 'pace_adjust' in params else 'N'
        rank = params['rank'] if 'rank' in params else 'N'
        league_id = params['league_id'] if 'league_id' in params else '00'
        season = params['season'] if 'season' in params else '2016-17'
        season_type = params[
            'season_type'] if 'season_type' in params else 'Regular Season'
        po_round = params['po_round'] if 'po_round' in params else '0'
        outcome = params['outcome'] if 'outcome' in params else ''
        location = params['location'] if 'location' in params else ''
        month = params['month'] if 'month' in params else '0'
        season_segment = params[
            'season_segment'] if 'season_segment' in params else ''
        date_from = params['date_from'] if 'date_from' in params else ''
        date_to = params['date_to'] if 'date_to' in params else ''
        opponent_team_id = params[
            'opponent_team_id'] if 'opponent_team_id' in params else '0'
        vs_conference = params[
            'vs_conference'] if 'vs_conference' in params else ''
        vs_division = params['vs_division'] if 'vs_division' in params else ''
        game_segment = params[
            'game_segment'] if 'game_segment' in params else ''
        period = params['period'] if 'period' in params else '0'
        shot_clock_range = params[
            'shot_clock_range'] if 'shot_clock_range' in params else ''
        last_n_games = params[
            'last_n_games'] if 'last_n_games' in params else '0'
        only_current = params['only_current'] if 'only_current' in params else 0
        just_id = params['just_id'] if 'just_id' in params else True
        player_id = player.get_player(first,
                                      last_name=last,
                                      season=season,
                                      only_current=only_current,
                                      just_id=just_id)
        if params['sub_module'] == 'player_career':
            career = player.PlayerCareer(player_id)
            if params['function'] == 'all_star_season_totals':
                temp = career.all_star_season_totals()
            elif params['function'] == 'career_all_star_season_totals':
                temp = career.career_all_star_season_totals()
            elif params['function'] == 'college_season_career_totals':
                temp = career.college_season_career_totals()
            elif params['function'] == 'college_season_totals':
                temp = career.college_season_totals()
            elif params['function'] == 'post_season_career_totals':
                temp = career.post_season_career_totals()
            elif params['function'] == 'post_season_rankings':
                temp = career.post_season_rankings()
            elif params['function'] == 'post_season_totals':
                temp = career.post_season_totals()
            elif params['function'] == 'preseason_career_totals':
                temp = career.preseason_career_totals()
            elif params['function'] == 'preseason_season_totals':
                temp = career.preseason_season_totals()
            elif params['function'] == 'regular_season_career_totals':
                temp = career.regular_season_career_totals()
            elif params['function'] == 'regular_season_rankings':
                temp = career.regular_season_rankings()
            elif params['function'] == 'regular_season_totals':
                temp = career.regular_season_totals()
            else:
                return []
        elif params['sub_module'] == 'player_clutch_splits':
            clutch = player.PlayerClutchSplits(player_id, team_id=team_id, measure_type=measure_type, per_mode=per_mode, plus_minus=plus_minus, \
                pace_adjust=pace_adjust, rank=rank, league_id=league_id, season=season, season_type=season_type, po_round=po_round, outcome=outcome, \
                location=location, month=month, season_segment=season_segment, date_from=date_from, date_to=date_to, opponent_team_id=opponent_team_id, \
                vs_conference=vs_conference, vs_division=vs_division, game_segment=game_segment, period=period, shot_clock_range=shot_clock_range, \
                last_n_games=last_n_games
            )
            if params['function'] == 'last10sec_deficit_3point':
                temp = clutch.last10sec_deficit_3point()
            elif params['function'] == 'last1min_deficit_5point':
                temp = clutch.last1min_deficit_5point()
            elif params['function'] == 'last1min_plusminus_5point':
                temp = clutch.last1min_plusminus_5point()
            elif params['function'] == 'last30sec_deficit_3point':
                temp = clutch.last30sec_deficit_3point()
            elif params['function'] == 'last30sec_plusminus_5point':
                temp = clutch.last30sec_plusminus_5point()
            elif params['function'] == 'last3min_deficit_5point':
                temp = clutch.last3min_deficit_5point()
            elif params['function'] == 'last3min_plusminus_5point':
                temp = clutch.last3min_plusminus_5point()
            elif params['function'] == 'last5min_deficit_5point':
                temp = clutch.last5min_deficit_5point()
            elif params['function'] == 'last5min_plusminus_5point':
                temp = clutch.last5min_plusminus_5point()
            else:
                return []
        elif params['sub_module'] == 'player_defense_tracking':
            temp = player.PlayerDefenseTracking(player_id, team_id=team_id, measure_type=measure_type, per_mode=per_mode, plus_minus=plus_minus, \
                pace_adjust=pace_adjust, rank=rank, league_id=league_id, season=season, season_type=season_type, po_round=po_round, outcome=outcome, \
                location=location, month=month, season_segment=season_segment, date_from=date_from, date_to=date_to, opponent_team_id=opponent_team_id, \
                vs_conference=vs_conference, vs_division=vs_division, game_segment=game_segment, period=period, shot_clock_range=shot_clock_range, \
                last_n_games=last_n_games
            )
        elif params['sub_module'] == 'player_game_logs':
            if params['function'] == 'info':
                temp = player.PlayerGameLogs(player_id,
                                             league_id=league_id,
                                             season=season,
                                             season_type=season_type)
            else:
                return []
        elif params['sub_module'] == 'player_general_splits':
            splits = player.PlayerGeneralSplits(player_id, team_id=team_id, measure_type=measure_type, per_mode=per_mode, plus_minus=plus_minus, \
                pace_adjust=pace_adjust, rank=rank, league_id=league_id, season=season, season_type=season_type, po_round=po_round, outcome=outcome, \
                location=location, month=month, season_segment=season_segment, date_from=date_from, date_to=date_to, opponent_team_id=opponent_team_id, \
                vs_conference=vs_conference, vs_division=vs_division, game_segment=game_segment, period=period, shot_clock_range=shot_clock_range, \
                last_n_games=last_n_games
            )
            if params['function'] == 'days_rest':
                temp = splits.days_rest()
            elif params['function'] == 'location':
                temp = splits.location()
            elif params['function'] == 'month':
                temp = splits.month()
            elif params['function'] == 'pre_post_all_star':
                temp = splits.pre_post_all_star()
            elif params['function'] == 'starting_position':
                temp = splits.starting_position()
            elif params['function'] == 'win_losses':
                temp = splits.win_losses()
            else:
                return []
        elif params['sub_module'] == 'player_in_game_splits':
            if params['function'] == 'by_actual_margin':
                temp = splits.by_actual_margin()
            elif params['function'] == 'by_half':
                temp = splits.by_half()
            elif params['function'] == 'by_period':
                temp = splits.by_period()
            elif params['function'] == 'by_score_margin':
                temp = splits.by_score_margin()
            else:
                return []
        elif params['sub_module'] == 'player_last_n_games_splits':
            n_splits = player.PlayerLastNGamesSplits(player_id, team_id=team_id, measure_type=measure_type, per_mode=per_mode, plus_minus=plus_minus, \
                pace_adjust=pace_adjust, rank=rank, league_id=league_id, season=season, season_type=season_type, po_round=po_round, outcome=outcome, \
                location=location, month=month, season_segment=season_segment, date_from=date_from, date_to=date_to, opponent_team_id=opponent_team_id, \
                vs_conference=vs_conference, vs_division=vs_division, game_segment=game_segment, period=period, shot_clock_range=shot_clock_range, \
                last_n_games=last_n_games
            )
            if params['function'] == 'game_number':
                temp = n_splits.gamenumber()
            elif params['function'] == 'last10':
                temp = n_splits.last10()
            elif params['function'] == 'last15':
                temp = n_splits.last15()
            elif params['function'] == 'last20':
                temp = n_splits.last20()
            elif params['function'] == 'last5':
                temp = n_splits.last5()
            else:
                return []
        elif params['sub_module'] == 'player_list':
            player_list = player.PlayerList(league_id=league_id,
                                            season=season,
                                            only_current=only_current)
            if params['function'] == 'info':
                temp = player_list.info()
            else:
                return []
        elif params['sub_module'] == 'player_opponent_splits':
            op_splits = player.PlayerOpponentSplits(player_id, team_id=team_id, measure_type=measure_type, per_mode=per_mode, plus_minus=plus_minus, \
                pace_adjust=pace_adjust, rank=rank, league_id=league_id, season=season, season_type=season_type, po_round=po_round, outcome=outcome, \
                location=location, month=month, season_segment=season_segment, date_from=date_from, date_to=date_to, opponent_team_id=opponent_team_id, \
                vs_conference=vs_conference, vs_division=vs_division, game_segment=game_segment, period=period, shot_clock_range=shot_clock_range, \
                last_n_games=last_n_games
            )
            if params['function'] == 'by_conference':
                temp = op_splits.by_conference()
            elif params['function'] == 'by_division':
                temp = op_splits.by_division()
            elif params['function'] == 'by_opponent':
                temp = op_splits.by_opponent()
            else:
                return []
        elif params['sub_module'] == 'player_pass_tracking':
            pass_tracking = player.PlayerPassTracking(player_id, team_id=team_id, measure_type=measure_type, per_mode=per_mode, plus_minus=plus_minus, \
                pace_adjust=pace_adjust, rank=rank, league_id=league_id, season=season, season_type=season_type, po_round=po_round, outcome=outcome, \
                location=location, month=month, season_segment=season_segment, date_from=date_from, date_to=date_to, opponent_team_id=opponent_team_id, \
                vs_conference=vs_conference, vs_division=vs_division, game_segment=game_segment, period=period, shot_clock_range=shot_clock_range, \
                last_n_games=last_n_games
            )
            if params['function'] == 'passes_made':
                temp = pass_tracking.passes_made()
            elif params['function'] == 'passes_received':
                temp = pass_tracking.passes_received()
            else:
                return []
        elif params['sub_module'] == 'player_performance_splits':
            performance_splits = player.PlayerPerformanceSplits(player_id, team_id=team_id, measure_type=measure_type, per_mode=per_mode, plus_minus=plus_minus, \
                pace_adjust=pace_adjust, rank=rank, league_id=league_id, season=season, season_type=season_type, po_round=po_round, outcome=outcome, \
                location=location, month=month, season_segment=season_segment, date_from=date_from, date_to=date_to, opponent_team_id=opponent_team_id, \
                vs_conference=vs_conference, vs_division=vs_division, game_segment=game_segment, period=period, shot_clock_range=shot_clock_range, \
                last_n_games=last_n_games
            )
            if params['function'] == 'points_against':
                temp = performance_splits.points_against()
            elif params['function'] == 'points_scored':
                temp = performance_splits.points_scored()
            elif params['function'] == 'score_differential':
                temp = performance_splits.score_differential()
            else:
                return []
        elif params['sub_module'] == 'player_profile':
            prof = player.PlayerProfile(per_mode=per_mode, league_id=league_id)
            if params['function'] == 'career_highs':
                temp = prof.career_highs()
            elif params['function'] == 'next_game':
                temp = prof.next_game()
            elif params['function'] == 'season_highs':
                temp = prof.season_highs()
            else:
                return []
        elif params['sub_module'] == 'player_rebound_log_tracking':
            temp = player.PlayerReboundLogTracking(player_id, team_id=team_id, measure_type=measure_type, per_mode=per_mode, plus_minus=plus_minus, \
                pace_adjust=pace_adjust, rank=rank, league_id=league_id, season=season, season_type=season_type, po_round=po_round, outcome=outcome, \
                location=location, month=month, season_segment=season_segment, date_from=date_from, date_to=date_to, opponent_team_id=opponent_team_id, \
                vs_conference=vs_conference, vs_division=vs_division, game_segment=game_segment, period=period, shot_clock_range=shot_clock_range, \
                last_n_games=last_n_games
            )
        elif params['sub_module'] == 'player_rebound_tracking':
            rb_tracking = player.PlayerReboundTracking(player_id, team_id=team_id, measure_type=measure_type, per_mode=per_mode, plus_minus=plus_minus, \
                pace_adjust=pace_adjust, rank=rank, league_id=league_id, season=season, season_type=season_type, po_round=po_round, outcome=outcome, \
                location=location, month=month, season_segment=season_segment, date_from=date_from, date_to=date_to, opponent_team_id=opponent_team_id, \
                vs_conference=vs_conference, vs_division=vs_division, game_segment=game_segment, period=period, shot_clock_range=shot_clock_range, \
                last_n_games=last_n_games
            )
            if params['function'] == 'num_contested_rebounding':
                temp = rb_tracking.num_contested_rebounding()
            elif params['function'] == 'rebound_distance_rebounding':
                temp = rb_tracking.rebound_distance_rebounding()
            elif params['function'] == 'shot_distance_rebounding':
                temp = rb_tracking.shot_distance_rebounding()
            elif params['function'] == 'shot_type_rebounding':
                temp = rb_tracking.shot_type_rebounding()
            else:
                return []
        elif params['sub_module'] == 'player_shooting_splits':
            if params['function'] == 'assisted_by':
                temp = rb_tracking.assisted_by()
            elif params['function'] == 'assisted_shots':
                temp = rb_tracking.assisted_shots()
            elif params['function'] == 'shot_5ft':
                temp = rb_tracking.shot_5ft()
            elif params['function'] == 'shot_8ft':
                temp = rb_tracking.shot_8ft()
            elif params['function'] == 'shot_areas':
                temp = rb_tracking.shot_areas()
            elif params['function'] == 'shot_types_detail':
                temp = rb_tracking.shot_types_detail()
            elif params['function'] == 'shot_types_summary':
                temp = rb_tracking.shot_types_summary()
            else:
                return []
        elif params['sub_module'] == 'player_shot_log_tracking':
            temp = player.PlayerShotLogTracking(player_id, team_id=team_id, measure_type=measure_type, per_mode=per_mode, plus_minus=plus_minus, \
                pace_adjust=pace_adjust, rank=rank, league_id=league_id, season=season, season_type=season_type, po_round=po_round, outcome=outcome, \
                location=location, month=month, season_segment=season_segment, date_from=date_from, date_to=date_to, opponent_team_id=opponent_team_id, \
                vs_conference=vs_conference, vs_division=vs_division, game_segment=game_segment, period=period, shot_clock_range=shot_clock_range, \
                last_n_games=last_n_games
            )
            if params['function'] == 'closest_defender_shooting':
                temp = rb_tracking.closest_defender_shooting()
            elif params['function'] == 'closest_defender_shooting_long':
                temp = rb_tracking.closest_defender_shooting_long()
            elif params['function'] == 'dribble_shooting':
                temp = rb_tracking.dribble_shooting()
            elif params['function'] == 'general_shooting':
                temp = rb_tracking.general_shooting()
            elif params['function'] == 'shot_clock_shooting':
                temp = rb_tracking.shot_clock_shooting()
            elif params['function'] == 'touch_time_shooting':
                temp = rb_tracking.touch_time_shooting()
            else:
                return []
        # elif params['sub_module'] == 'player_shot_tracking':
        # elif params['sub_module'] == 'player_summary':
        # elif params['sub_module'] == 'player_vs_player':
        # elif params['sub_module'] == 'player_year_over_year_splits':
    elif params['module'] == 'game':
        pass
    elif params['module'] == 'team':
        pass
    else:
        # Failure case.
        pass
    if flatten_keys:
        return [
            l for l in list(set([el for o in temp for el in o.keys()]))
            if l not in to_remove
        ]
    else:
        return {
            'data': [o[params['value_query']] for o in temp],
            'labels': [o[get_x_axis_key(params['function'])] for o in temp]
        }
Exemple #32
0
	
		collection.insert({'firstname'    : firstname,
                           'lastname'   : lastname,
                           'name': player_name,
                           'height'   : height,
                           'weight'   : weight,
                           'positions' : positions,
                           'overview_url': overview_url,
                          })

	'''

    #print len(players.keys())

    try:
        get_player = player.get_player(firstname, last_name=lastname)
        #print get_player

        player_id = get_player.values[0]
        #print player_id
        player_summary = player.PlayerSummary(player_id)
        team_name = player_summary.info(
        )["TEAM_CITY"][0] + ' ' + player_summary.info()["TEAM_NAME"][0]

        print i, firstname, lastname + ':', team_name
        birthday = player_summary.info()["BIRTHDATE"][0].split('T')[0]
        from_year = player_summary.info()["FROM_YEAR"][0]
        jersey = player_summary.info()["JERSEY"][0]
        school = player_summary.info()["SCHOOL"][0]

        userRecord = collection.find_one({
 def setUpClass(cls):
     cls.teamId = TEAMS['ATL']['id']
     cls.playerId = get_player('Lebron', 'James')
def test():
    pid = get_player("Kevin", "Durant")
    assert shotchart.ShotChart(pid)
Exemple #35
0
def get_player_id(first, last):
  try:
    return int(get_player(first, last).values[0])
  except PlayerNotFoundException:
    print (first + " " + last + " doesnt exist...")
    return None