def all_games_of_one_team(teamA):
    nba_teams = teams.get_teams()
    teamA = [team for team in nba_teams if team['abbreviation'] == teamA][0]
    teamA_Id = teamA['id']
    gamefinder = leaguegamefinder.LeagueGameFinder(team_id_nullable=teamA_Id)
    games = gamefinder.get_data_frames()[0]
    return games
示例#2
0
    def _today_matchups(self) -> pd.DataFrame:
        gamefinder = leaguegamefinder.LeagueGameFinder(
            league_id_nullable='00',
            date_from_nullable=self._date_nba_api_format)
        today_games = gamefinder.get_data_frames()[0]

        return today_games
def getTeamBoxScoreForYear(teamName, season):
    teamNameId = getTeamIdFromName(teamName)
    # this should find all games where celtics were playing
    time.sleep(5)
    gamefinder = leaguegamefinder.LeagueGameFinder(team_id_nullable=teamNameId)
    games = gamefinder.get_data_frames()[0]

    #filter to the season required
    games_in_season = games[games.SEASON_ID.str[-4:] == season[:4]]

    games_in_season = games_in_season.sort_values(
        "GAME_DATE", ascending=True)  # sorting the games by game_date

    # iterate over the games in the dataframe and add number of wins and number of losses at every log
    num_wins = 0
    num_losses = 0
    for index, row in games_in_season.iterrows():
        winloss = games_in_season.at[index, "WL"]
        if winloss == 'W':
            num_wins += 1
        else:
            num_losses += 1

        games_in_season.at[index, "NUM_WINS"] = num_wins
        games_in_season.at[index, "NUM_LOSSES"] = num_losses

    return games_in_season
示例#4
0
def get_previous_games(n=5):
    gamelog = leaguegamefinder.LeagueGameFinder(
        season_nullable='2019-20', timeout=60).get_dict()['resultSets'][0]

    games = gamelog['rowSet']
    headers = gamelog['headers']

    df = pd.DataFrame(games, columns=headers)
    df = df[['TEAM_ID', 'GAME_DATE', 'MATCHUP', 'PTS', 'PLUS_MINUS', 'WL']]

    previous_games = {}

    for team in team_ids.keys():
        team_previous_games = []
        team_last_games_df = df[df['TEAM_ID'] == team_ids[team]['id']][:n]
        team_last_games_df['OPP_PTS'] = team_last_games_df[
            'PTS'] - team_last_games_df['PLUS_MINUS']
        team_last_games_df = team_last_games_df.astype({'OPP_PTS': int})
        for index, row in team_last_games_df.iterrows():
            team_previous_games.append('{} | {} | {}-{} ({})'.format(
                row['GAME_DATE'], row['MATCHUP'], row['PTS'], row['OPP_PTS'],
                row['WL']))
        previous_games[team] = team_previous_games

    return previous_games
示例#5
0
    def __init__(self, team_id):

        self.stats = leaguegamefinder.LeagueGameFinder(
            team_id_nullable=team_id,
            season_nullable="2019-20",
            date_to_nullable="02/04/2020").get_normalized_dict(
            )["LeagueGameFinderResults"]
        self.get_average_atr()
示例#6
0
def getSchedule(dateFrom, dateTo):
	lgf = leaguegamefinder.LeagueGameFinder(date_to_nullable=dateTo, date_from_nullable=dateFrom)
	gameDict = lgf.get_dict()["resultSets"][0]["rowSet"]
	gameList = []
	for i in gameDict:
		if isGameRegularSeason(i[4]):
			gameList.insert(0, i[4])
	gameList = sorted(list(set(gameList)))
	return gameList
示例#7
0
def pullgameids(
        team,
        season):  ##takes two strings for team and season returns all game ids
    team = teams.find_teams_by_full_name(team)
    team = team[0]
    gamefinder = leaguegamefinder.LeagueGameFinder(
        team_id_nullable=team.get("id"))
    games = (gamefinder.get_data_frames())[0]
    seasongame = games[games.SEASON_ID.str[-4:] == season]
    return seasongame['GAME_ID']
def get_all_games_between_two_teams(teamA, teamB):
    nba_teams = teams.get_teams()
    teamA = [team for team in nba_teams if team['abbreviation'] == teamA][0]
    teamA_Id = teamA['id']
    gamefinder = leaguegamefinder.LeagueGameFinder(team_id_nullable=teamA_Id)
    games = gamefinder.get_data_frames()[0]
    games.head()
    games_1718 = games
    teamB_games_1718 = games_1718[games_1718.MATCHUP.str.contains(teamB)]
    return teamB_games_1718
def main():
    gamefinder = leaguegamefinder.LeagueGameFinder(
        league_id_nullable='00')  # nba id is '00'
    games = gamefinder.get_data_frames()[0]
    if not os.path.exists(PATH):
        os.mkdir(PATH)
    if not os.path.exists(os.path.join(PATH, FILENAME)):
        with open(os.path.join(PATH, FILENAME), 'w') as fp:
            pass
    games.to_csv(os.path.join(PATH, FILENAME))
示例#10
0
def game_search():
    gamefinder = leaguegamefinder.LeagueGameFinder()
    games = gamefinder.get_data_frames()[0]
    #games.head()
    game_id = games.at[0, 'GAME_ID']
    if game_id in recent_game_IDs:
        idle()
    else:
        recent_game_IDs = recent_game_IDs.append(game_id)
        tweetSummary()
示例#11
0
def get_game_info(team_id=None, season=None, season_type=None):
    # Define teams
    if team_id is None:
        team_info = get_team_info()
        team_ids = team_info['id']
    else:
        team_ids = team_id

    # Define season
    if season is None:
        season_code = Season.default
    else:
        season_code = '{}-{}'.format(season, str(season + 1)[2:])

    # Define Season Type
    if season_type is None:
        season_seg = SeasonType.regular
    elif season_type == 'Pre-Season':
        season_seg = SeasonType.preseason
    elif season_type == 'Regular':
        season_seg = SeasonType.regular
    elif season_type == 'Playoffs':
        season_seg = SeasonTypePlayoffs.playoffs

    for team in team_ids:
        gamefinder = leaguegamefinder.LeagueGameFinder(
            team_id_nullable=team,
            season_nullable=season_code,
            season_type_nullable=season_seg)
        game_info_dict0 = gamefinder.get_normalized_dict()
        game_info_dict1 = game_info_dict0['LeagueGameFinderResults']
        game_info_df = pd.DataFrame(game_info_dict1)
        game_info_dict[team] = game_info_df

    # collect dictionary keys into a list
    dict_keys = game_info_dict.keys()
    # Create list of game info dataframes
    frames = [game_info_dict[key] for key in dict_keys]
    # Union the dataframes in frames
    fin_game_info_df = pd.concat(frames, axis=0)

    # Convert dtypes
    fin_game_info_df['GAME_ID'] = fin_game_info_df['GAME_ID'].astype('str')
    fin_game_info_df['GAME_DATE'] = fin_game_info_df['GAME_DATE'].astype(
        'datetime64[ns]')
    fin_game_info_df['MATCHUP'] = fin_game_info_df['MATCHUP'].astype('str')
    fin_game_info_df['SEASON_ID'] = fin_game_info_df['SEASON_ID'].astype('str')
    fin_game_info_df['TEAM_ABBREVIATION'] = fin_game_info_df[
        'TEAM_ABBREVIATION'].astype('str')
    fin_game_info_df['TEAM_NAME'] = fin_game_info_df['TEAM_NAME'].astype('str')
    fin_game_info_df['WL'] = fin_game_info_df['WL'].astype('str')

    # return the finished data frame
    return (fin_game_info_df)
示例#12
0
def get_game_info(date, team_id, vs_team_id):
    # Search For Game
    gamefinder = leaguegamefinder.LeagueGameFinder(team_id_nullable=team_id, vs_team_id_nullable=vs_team_id, date_from_nullable=date,date_to_nullable=date)

    # Get dict based on games
    games_dict = gamefinder.get_normalized_dict()

    # Get the first game
    games = games_dict['LeagueGameFinderResults']
    game = games[0]
    
    # Return the game
    return game
def query_available_games(team1, team2, season):
    gamefinder = leaguegamefinder.LeagueGameFinder(team_id_nullable=team1,
                                                   vs_team_id_nullable=team2,
                                                   season_nullable=season)
    games = gamefinder.get_data_frames()[0]
    game_options = []
    for game in games.index:
        thedict = {
            'label':
            games['MATCHUP'][game] + " , " + str(games['GAME_DATE'][game]),
            'value': games['GAME_ID'][game]
        }
        game_options.append(thedict)
    return game_options
示例#14
0
def _get_games_for_team(team_id: str, date_from: datetime, date_to: datetime):
    gamefinder = leaguegamefinder.LeagueGameFinder(
        team_id_nullable=team_id,
        date_from_nullable=date_from,
        date_to_nullable=date_to,
        proxy=next(proxy_cycle))
    dfs = gamefinder.get_data_frames()
    if not dfs:
        logger.warning('Missing data for team with ID {}'.format(team_id))
        logger.warning('Missing data for team with ID {}'.format(team_id))
        return pd.DataFrame()
    if len(dfs) > 1:
        raise ValueError('Endpoint returned more than one DataFrame object')

    return dfs[0]
示例#15
0
def write_data_file_for_date(date_param):
    date_api_str = date_param.strftime("%m/%d/%Y")  # the only format the NBA API accepts for some reason

    gf = leaguegamefinder.LeagueGameFinder(
        date_from_nullable=date_api_str,
        date_to_nullable=date_api_str,
        player_or_team_abbreviation='P',  # per-player stats instead of per-team
        league_id_nullable='00'  # NBA only
    )
    frame = gf.get_data_frames()[0]
    """
    since my csv files are partitioned by date, season_id and game_date can be dropped
    also, 'MATCHUP' contains the team abbrev, and team names change infrequently enough that it's not worth storing for every game log
    I keep everything else passed back by the API though
    """
    frame.drop(['SEASON_ID', 'TEAM_NAME', 'TEAM_ABBREVIATION', 'GAME_DATE'], axis=1, inplace=True)
    write_dataframe_to_csv_on_s3(frame, "{}/game_logs/{}".format(data_path_prefix, date_param.strftime('%Y-%m-%d.csv')), bucket_path)
def get_data():
    # Se obtienen todos lo equipos de la NBA
    nba_teams = teams.get_teams()
    dataframes_list = []
    for team in nba_teams:
        # Se hace una petición a la API para obtener los partidos de cada equipo
        gamefinder = leaguegamefinder.LeagueGameFinder(
            team_id_nullable=team['id'])
        games = gamefinder.get_data_frames()[0]
        # Se almacenan los partidos de cada equipo por separado
        games.to_csv(r'.\datasets\by_team\\' + team['abbreviation'] + '.csv')
        dataframes_list.append(games)
    # Se almacenan los datos de todos los partidos en un mismo dataset
    games_dataframe = pd.concat(dataframes_list, axis=0, ignore_index=True)
    games_dataframe.to_csv(r'.\datasets\dataset.csv')

    return games_dataframe
    def get_stats(self, type='', stat=''):
        '''
        function that select stats and returns DataFrame with specified stats
        args:
        -type(string): type of stats, could be: players, games, teams
        -stat(string): specified stat, e.g. rebounds, points, etc.
        returns:
        -stats(dataFrame): selected stats
        '''

        types = ['players', 'games', 'teams']
        assert type not in types, 'Invalid type'
        if type == 'players':
            pass
        elif type == 'games':
            return leaguegamefinder.LeagueGameFinder(
                league_id_nullable='00').get_data_frames()[0]  # nba id is '00'
        elif type == 'teams':
            pass
示例#18
0
def check_and_post(player_name, city):
    """The following function gets the last nuggets game, checks if it's a new game, and posts Nikola Jokic's stats to twitter. Some code snippets were lifted and
    modified from the nba_api and Twitter API Python documentation"""
    global last_game_date
    # Get all teams
    nba_teams = teams.get_teams()

    # Select the dictionary for the selected player's team, which contains their team ID
    player_team = [team for team in nba_teams
                   if team['abbreviation'] == city][0]
    team_id = player_team['id']

    # Query for games where the Nuggets were playing
    gamefinder = leaguegamefinder.LeagueGameFinder(team_id_nullable=team_id)

    # The first DataFrame of those returned is what we want.
    games = gamefinder.get_data_frames()[0]
    last_team_game = games.sort_values('GAME_DATE').iloc[-1]
    current_game_date = last_team_game["GAME_DATE"]

    # Get the stats of the game
    game_stats = boxscoretraditionalv2.BoxScoreTraditionalV2(
        last_team_game["GAME_ID"])

    # Search for player, and build a string of his stats
    for player in game_stats.player_stats.get_dict()["data"]:
        if player_name in player:
            stats = "{0}'s stats for {1} {2}: points: {3}, rebounds: {4}, assists: {5}".format(
                player_name, last_team_game["GAME_DATE"],
                last_team_game["MATCHUP"], player[-2], player[-8], player[-7])

    # Make Twitter API
    api = twitter.Api(consumer_key=ck,
                      consumer_secret=cs,
                      access_token_key=atk,
                      access_token_secret=ats)
    try:
        status = api.PostUpdate(stats)
        print("{0} just posted: {1}".format(status.user.name, status.text))
    except UnicodeDecodeError:
        print("Failed to post to Twitter")
        sys.exit(2)
示例#19
0
    def get_teams(self):
        """
        method to get all nba teams using the NBA api and create data frame with box scores.
        """
        self.team_info = teams.get_teams()
        for team in self.team_info:
            # we have to sleep when making requests or we'll get booted.
            time.sleep(5)
            temp_frame = leaguegamefinder.LeagueGameFinder(
                team_id_nullable=team['id'],
                season_nullable=self.seasons).get_data_frames()[0]

            self.df = self.df.append(temp_frame, ignore_index=True)

        # drop the columns we don't need.
        self.df.drop(columns=[
            'FGM', 'FGA', 'MIN', 'FG3M', 'FG3A', 'FTM', 'FTA', 'PLUS_MINUS',
            'TEAM_NAME', 'REB'
        ],
                     inplace=True)
示例#20
0
def get_team_prev_games(team, n=5):
    gamelog = leaguegamefinder.LeagueGameFinder(
        team_id_nullable=team_ids[team]['id'],
        season_nullable='2019-20',
        timeout=60).get_dict()['resultSets'][0]

    games = gamelog['rowSet']
    headers = gamelog['headers']

    last_games = []

    for game in games[:n]:
        game_dict = dict(zip(headers, game))
        score = '{}-{}'.format(game_dict['PTS'],
                               int(game_dict['PTS'] - game_dict['PLUS_MINUS']))
        last_games.append('{} | {} | {} ({})'.format(game_dict['GAME_DATE'],
                                                     game_dict['MATCHUP'],
                                                     score, game_dict['WL']))

    return last_games
示例#21
0
def prepareTeamData(abb):
    print("Parsing data for " + abb)
    team = teams.find_team_by_abbreviation(abb)
    team_id = team['id']
    gamefinder = leaguegamefinder.LeagueGameFinder(team_id_nullable=team_id)
    games = gamefinder.get_data_frames()[0]
    games = games[games.SEASON_ID.str[-4:] == '2020']
    pts = 0
    fga = 0
    fgp = 0
    fg3a = 0
    fg3p = 0
    ftm = 0
    offr = 0
    defr = 0
    ass = 0
    stl = 0
    blk = 0
    tov = 0
    pts_a = 0
    for x in range(0, 5):
        game = games.iloc[x]
        pts += pts + game.PTS
        fga += game.FGA
        fgp += game.FG_PCT
        fg3a += game.FG3A
        fg3p += game.FG3_PCT
        ftm += game.FTM
        offr += game.OREB
        defr += game.DREB
        ass += game.AST
        stl += game.STL
        blk += game.BLK
        tov += game.TOV
        pts_a += game.PTS + (-1 * game.PLUS_MINUS)
    return [
        fga / 5, fgp / 5, fg3a / 5, fg3p / 5, ftm / 5, offr / 5, defr / 5,
        ass / 5, stl / 5, blk / 5, tov / 5, pts_a / 5, pts / 5
    ]
示例#22
0
def get_stats(team_abbr):

	'''
	This function will return the last game stats of a particlar team.

	Parameters:
	team_abbr: pass a string with the abbreviation of a particular team

	example> get_stats('CHI')
	'''

	nba_teams = teams.get_teams()


	# Select the dictionary for the Pacers, which contains their team ID
	nba_team = [team for team in nba_teams if team['abbreviation'] == team_abbr][0]
	nba_team_id = nba_team['id']

	# Query for the last regular season game where the Pacers were playing

	gamefinder = leaguegamefinder.LeagueGameFinder(team_id_nullable=nba_team_id,
	                            season_nullable=Season.default,
	                            season_type_nullable=SeasonType.regular)  

	games_dict = gamefinder.get_normalized_dict()
	games = games_dict['LeagueGameFinderResults']
	game = games[0]
	game_id = game['GAME_ID']
	game_matchup = game['MATCHUP']

	print(f'Searching through {len(games)} game(s) for the game_id of {game_id} where {game_matchup}')

	# Query for the play by play of that most recent regular season game
	df = playbyplay.PlayByPlay(game_id).get_data_frames()[0]
	df.head() #just looking at the head of the data

	df.to_csv(team_abbr+'_'+str(game_id)+'.csv')

	return print('stats have been exported in the working folder!')
示例#23
0
def get_game_ids(team_id=None, season=None, season_type=None):
    # Define teams
    if team_id is None:
        team_info = get_team_info()
        team_ids = team_info['id']
    else:
        team_ids = team_id

    # Define season
    if season is None:
        season_code = Season.default
    else:
        season_code = '{}-{}'.format(season, str(season + 1)[2:])

    # Define Season Type
    if season_type is None:
        season_seg = SeasonType.regular
    elif season_type == 'Pre-Season':
        season_seg = SeasonType.preseason
    elif season_type == 'Regular':
        season_seg = SeasonType.regular
    elif season_type == 'Playoffs':
        season_seg = SeasonTypePlayoffs.playoffs

    for team in team_ids:
        gamefinder = leaguegamefinder.LeagueGameFinder(
            team_id_nullable=team,
            season_nullable=season_code,
            season_type_nullable=season_seg)
        game_info_dict0 = gamefinder.get_normalized_dict()
        game_info_dict1 = game_info_dict0['LeagueGameFinderResults']
        game_info_df = pd.DataFrame(game_info_dict1)
        game_id_list = list(game_info_df['GAME_ID'])
        game_id_dict[team] = game_id_list

    # extract unique dictionary values
    ll = list(game_id_dict.values())
    l = [item for sublist in ll for item in sublist]
    return (list(set(l)))
def get_games_list(get_games_bool):
    # function for gettting all games played in the NBA for a given season
    # inputs:
    #   get_games_bool: if True, get new game_id list, else get from pickle file
    
    print('    Getting list of game_ids...')
    if get_games_bool:
        print('        Getting new list of game_ids...')
        nba_teams = teams.get_teams()
        all_games = []
        
        # loop through each nba team to get all games
        for team in nba_teams:
            print('            Currently getting data for: {}'.format(team['full_name']))
            curr_team_id = team['id']
    
            gamefinder = leaguegamefinder.LeagueGameFinder(team_id_nullable=curr_team_id)
            games = gamefinder.get_data_frames()[0]
        
            # filter games only from the requested season
            curr_year_games = games[games.SEASON_ID.str[-4:] == CURR_YEAR]
            
            # add to overall games list        
            all_games.extend(curr_year_games.GAME_ID.unique().tolist())
        
        # after getting all game_ids for each team, get list of unique ids        
        all_games_unique = list(set(all_games))
        pickle.dump(all_games_unique, open("gameid_list.p", "wb"))
    
        # return all a list of all unique game ids
        return all_games_unique
    
    # else read game_id list from saved pickle file
    else:
        print('        Getting list of game_ids from pickle file...')
        all_games_unique = pickle.load(open("gameid_list.p", "rb") )
        return all_games_unique
def getNbaScore():
    nba_teams = teams.get_teams()
    raptors = [team for team in nba_teams if team['abbreviation'] == 'TOR'][0]
    raptors_id = raptors['id']

    rapsGames = teamgamelog.TeamGameLog(team_id=raptors_id,
                                        season_all="2018-19",
                                        season_type_all_star='Regular Season')
    mostRecentGame = pd.DataFrame(rapsGames.get_data_frames()[0]).iloc[0]
    gameId = mostRecentGame['Game_ID']
    matchup = mostRecentGame['MATCHUP']
    win = mostRecentGame['WL']
    wins = mostRecentGame['W']
    losses = mostRecentGame['L']
    torScore = mostRecentGame['PTS']

    gamesResult = leaguegamefinder.LeagueGameFinder()
    all_games = gamesResult.get_data_frames()[0]
    opponentGame = all_games[all_games.GAME_ID == gameId]
    opponentGame = opponentGame[
        opponentGame['TEAM_ABBREVIATION'] != 'TOR'].iloc[0]
    opponentScore = opponentGame['PTS']
    gameDate = getDay(opponentGame['GAME_DATE'])

    statsResult = teamplayerdashboard.TeamPlayerDashboard(team_id=raptors_id,
                                                          last_n_games=1)
    playerStats = pd.DataFrame(statsResult.get_data_frames()[1])
    key_player = playerStats.sort_values(by=['PTS'], ascending=False).iloc[0]
    key_player_name = key_player['PLAYER_NAME']
    key_player_pts = key_player['PTS']
    key_player_ast = key_player['AST']
    key_player_reb = key_player['REB']

    return "Latest Game from {}: {}\nThe Raps took a {} making their record {}W / {}L \nScore: {} : {}\nKey Player: {}\nStats:\n\tPoints: {}\n\tAssists: {}\n\tRebounds: {}".format(
        gameDate, matchup, win, wins, losses, torScore, opponentScore,
        key_player_name, key_player_pts, key_player_ast, key_player_reb)
示例#26
0
headers = {
    'x-rapidapi-host': "api-nba-v1.p.rapidapi.com",
    'x-rapidapi-key': "acca717e1fmshd937604fdb1e291p148866jsn0e6ec8ccd90e"
}

# API Call
response = requests.request("GET", url, headers=headers)

# API Response as JSON
team_json = response.json()

# Find Stats
team_name = team_json['api']['teams'][0]['fullName']
nba_teams = teams.find_teams_by_full_name(team_name)
team_id = nba_teams[0]['id']
game_finder = leaguegamefinder.LeagueGameFinder(team_id_nullable=team_id)
games = game_finder.get_data_frames()[0]

# Narrow down list of stats and to latest season
games_1819 = games[games.SEASON_ID.str[-4:] == '2018']
cols = [
    'TEAM_NAME', 'GAME_ID', 'GAME_DATE', 'MATCHUP', 'WL', 'MIN', 'PTS', 'FGM',
    'FGA', 'FG_PCT', 'FG3M', 'FG3A', 'FG3_PCT', 'FTM', 'FTA', 'FT_PCT', 'OREB',
    'DREB', 'REB', 'AST', 'STL', 'BLK', 'TOV', 'PF', 'PLUS_MINUS'
]
games_1819 = games_1819[cols]
team_stats = games_1819.mean()
team_name = games_1819['TEAM_NAME'].to_list()[0]

# Twilio access tokens used to send SMS
# ADD AUTHENTICATION
示例#27
0
def get_last_game():
    gamefinder = leaguegamefinder.LeagueGameFinder(team_id_nullable=get_team_id(i))
示例#28
0
    def handle(self, *args, **kwargs):
        db_teams = Team.objects.all()
        for team in db_teams:
            ## THE PORTLAND TRAILBLAZERS REFUSE TO COMFORM TO THIS API, THEY REQUIRE HARD CODED CHANGING FOR LEAGUE STANDING

            # update team rankings
            s = leaguestandingsv3.LeagueStandingsV3(
                season="2020")  # hard coded season value
            standings = s.get_data_frames()[0]

            team_name = str(team.full_name).split(" ")[-1]
            #logging.debug(team_name)
            curTeam = standings.loc[standings["TeamName"] == team_name]

            # check if empty
            if curTeam.empty:
                pass
            else:
                team.league_standing = curTeam.PlayoffRank.values[0]
                team.conference = curTeam.Conference.values[0]
                team.save()

            # ''' INITIAL EVALUTAION ''' (uncomment if you need to reset team values)
            '''
            team.market_price = (50 - (2 * team.league_standing))
            team.save()
            '''

            # ''' EVALUTAION '''

            api_team = [
                t for t in teams.get_teams()
                if t['abbreviation'] == str(team.slug)
            ][0]
            team_id = api_team['id']

            today = str(datetime.datetime.today().strftime('%m/%d/%Y'))
            yesterday = str((datetime.datetime.today() -
                             datetime.timedelta(days=1)).strftime('%m/%d/%Y'))

            # find the game
            gamefinder = leaguegamefinder.LeagueGameFinder(
                team_id_nullable=team_id,
                date_from_nullable=yesterday,
                date_to_nullable=today)
            game = gamefinder.get_data_frames()[0]
            game_id = game["GAME_ID"]

            # find proability of winning

            # team did not have a game today
            if game.empty:
                continue

            # Win Lose Evaluation
            win_value = 1.5
            temp_odds = 1.5
            net_value = 0
            logging.debug(game)

            # Find opposing team's standing
            at_team_slug = str(game['MATCHUP'].values[0])[-3:]
            at_team = Team.objects.get(slug=at_team_slug)
            at_team_standing = at_team.league_standing

            win_lose = game['WL'][0]

            if win_lose == 'W':
                net_value += (
                    (team.league_standing / 7.5) * win_value) * temp_odds
            else:
                net_value -= ((at_team_standing / 7.5) * win_value) * temp_odds

            team.market_price += net_value
            team.save()
            logging.debug('Team Updated:' + team.full_name + ' Net value:' +
                          str(net_value))

            sleep(10)
示例#29
0
nba_teams[0]['city']
dict_nba = one_dict(nba_teams)
df_teams = pd.DataFrame(dict_nba)
df_teams.head()

df_warriors = df_teams[df_teams['nickname'] == 'Warriors']
df_warriors

type(df_warriors[['id']])
id_warriors = df_warriors[['id']].values[0][0]

from nba_api.stats.endpoints import leaguegamefinder

# Since https://stats.nba.com does lot allow api calls from Cloud IPs and Skills Network Labs uses a Cloud IP.
# The following code is comment out, you can run it on jupyter labs on your own computer.
gamefinder = leaguegamefinder.LeagueGameFinder(team_id_nullable=id_warriors)
gamefinder.get_json()

games = gamefinder.get_data_frames()[0]
games.head()

games_home = games[games['MATCHUP'] == 'GSW vs. TOR']
games_away = games[games['MATCHUP'] == 'GSW @ TOR']

games_home.mean()['PLUS_MINUS']
games_away.mean()['PLUS_MINUS']

fig, ax = plt.subplots()
games_away.plot(x='GAME_DATE', y='PLUS_MINUS', ax=ax)
games_home.plot(x='GAME_DATE', y='PLUS_MINUS', ax=ax)
ax.legend(["away", "home"])
示例#30
0
import time

pd.set_option('display.max_columns', None)

# pd.set_option('display.max_rows', None)
# pd.reset_option('display.max_rows', None)

### GET GSW TEAM ID
# nba_teams = teams.get_teams()
# gsw = [team for team in nba_teams if team['abbreviation'] == 'GSW'][0]
# gsw_id = gsw['id']
# curry_id = 201939

### FIND GameID

gamefinder = leaguegamefinder.LeagueGameFinder()
games = gamefinder.get_data_frames()[0]
#games.head()
game_id = games.at[0, 'GAME_ID']

### HEADER

custom_headers = {
    'Host': 'stats.nba.com',
    'Connection': 'keep-alive',
    'Cache-Control': 'max-age=0',
    'Upgrade-Insecure-Requests': '1',
    'User-Agent':
    'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.86 Safari/537.36',
    'Accept':
    'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3',