示例#1
0
def get_games_on_day(datetime_instance):
    #create scoreboard
    YESTERDAY = datetime_instance

    a = Scoreboard(
                 month=YESTERDAY.month,
                 day=YESTERDAY.day,
                 year=YESTERDAY.year,
                 )
    listgames = a.available().get_values()

    for l in listgames:
        bss = game.BoxscoreScoring(l)

        awayscore = bss.json['resultSets'][1]['rowSet'][-1][-1] #home team score
        homescore = bss.json['resultSets'][1]['rowSet'][0][-1] #AWAY team score
        hometeam  = bss.json['resultSets'][3]['rowSet'][0][4]+" "+bss.json['resultSets'][3]['rowSet'][0][5]
        homekurz = bss.json['resultSets'][3]['rowSet'][0][6]
        awayteam  = bss.json['resultSets'][3]['rowSet'][0][-4]+" "+bss.json['resultSets'][3]['rowSet'][0][-3]
        awaykurz = bss.json['resultSets'][3]['rowSet'][0][-2]

        print "Home team %s Home score %d" %(hometeam, homescore)
        print "Away team %s Away score %d" %(awayteam, awayscore)
        print ""

        diff = abs(homescore-awayscore)
    #Match games that were last night


    return "oi"
def get_yesterdays_games():
    today = datetime.now()

    try:
        day = today.day - 1
        month = today.month
        year = today.year
    except:
        print("Error: Is it a new month or new year?")

    ex = Scoreboard(month=month, day=day, year=year)
    yesterdays_games = ex.line_score()[['TEAM_ABBREVIATION', 'PTS', 'GAME_ID']]
    teams = []
    scores = []
    for i, game in enumerate(yesterdays_games.values):
        teams.append(game[0])
        scores.append(game[1])
    road_teams = teams[0::2]
    home_teams = teams[1::2]
    road_scores = scores[0::2]
    home_scores = scores[1::2]
    f = open("output.txt", "a")
    f.write('\n')
    f.write("Winners from " + str(month) + '/' + str(day) + '/' + str(year) +
            '\n')

    for i in range(len(road_teams)):

        if road_scores[i] > home_scores[i]:
            f.write(road_teams[i] + '\n')
        else:
            f.write(home_teams[i] + '\n')
    print("Done!")

    return
示例#3
0
 def get_standing_data(self) -> pd.DataFrame:
     """Retrieve season standing data using API.
     """
     self.logger.info('Retrieving standing data')
     year = int(f'20{self.season.split("-")[1]}')
     data = pd.DataFrame()
     data = data.append(Scoreboard(month=6, day=1, year=year).east_conf_standings_by_day(), ignore_index=True)
     data = data.append(Scoreboard(month=6, day=1, year=year).west_conf_standings_by_day(), ignore_index=True)
     return data
示例#4
0
def get_todays_games():
    """
    Get the game's going on today. 
    
    Parameters:
    -----------
    
    None
    
    
    Returns 
    -------
    
    matchups : arr
        array of all the matchups today. Note I skip the first element since it just denotes road, or home which is known
        now. 
        
        
    
    """

    today = datetime.now()
    day = today.day
    month = today.month
    year = today.year

    ex = Scoreboard(month=month, day=day, year=year)
    games = ex.game_header()['GAMECODE']
    matchups = []
    matchups.append(['road', 'home'])
    for game in games:
        away_team = game[-6:-3]
        home_team = game[-3:]

        if away_team == 'BKN':
            away_team = 'BRK'
        if home_team == 'BKN':
            home_team = 'BRK'

        matchups.append([away_team, home_team])

    return matchups[1:]
def get_todays_games(day, month, year):
    """Returns all of the games to be predicted by scraping nba.com courtesy of nba_py. 
    Parameters
    ----------
    
    day : int
    month : int
    year : int
    
    The integer values of the date. 
    
    Returns 
    -------
    
    matchup : arr
    
    Array of strings showing the matchup. 
    """

    from nba_py import Scoreboard

    ex = Scoreboard(month=month, day=day, year=year)

    exa = ex.json
    exb = exa['resultSets'][1]
    teams = []
    for i in range(np.shape(exb['rowSet'])[0]):

        teams.append(exb['rowSet'][i][4])
    #  away_teams.append(exb['rowSet'][i][4])
    #  home_teams.append(exb['rowSet'][2*(i+1)][4])
# print(away_teams)
# print(home_teams)
# print("Old Teams:",teams)
    new_teams = []
    for team in teams:
        if team == 'BKN':
            new_teams.append('BRK')
        else:
            new_teams.append(team)

# print("Fixed(?) Teams: " , new_teams)
    teams = new_teams
    home_teams = teams[1::2]
    away_teams = teams[0::2]
    matchups = []
    for i in range(len(home_teams)):
        matchups.append([away_teams[i], home_teams[i]])

    return matchups
示例#6
0
def load_custom_data(teamName, season, opponentTeam):
    #df = team.TeamOpponentSplits(TEAMS[teamName]['id'],location='Home',season=get_season(season),
    #                               opponent_team_id =TEAMS[opponentTeam]['id']).by_opponent()
    df = game.BoxscoreSummary(game_id='0041400122').line_score()
    #df = team.TeamGameLogs(TEAMS[teamName]['id'], get_season(season)).info()
    lf = Scoreboard().east_conf_standings_by_day()
    #df = team.TeamYearOverYearSplits(TEAMS[teamName]['id'], measure_type='Advanced',season=get_season(season), opponent_team_id =TEAMS[opponentTeam]['id']).by_year()
    #df = team.TeamOpponentSplits(TEAMS[teamName]['id'], measure_type='Advanced', season=get_season(season),                                 opponent_team_id=TEAMS[opponentTeam]['id']).by_opponent()
    print(list(lf))
    print(lf)
    print(list(df))
    print(df)
    #print(list(df))
    #return df
    df1 = team.TeamGameLogs(TEAMS[teamName]['id'], get_season(season)).info()
    #df1 = team.TeamLineups(TEAMS['MIL']['id']).overall()
    print(list(df1))
    return df1
示例#7
0
文件: app.py 项目: wilsonh0/nbastats
def home():
    """main page"""
    if request.method == 'POST':
        aDate = request.form.get("date")
        today = aDate.split()
        today = today[:6]
        today = " ".join(today)

        today = datetime.datetime.strptime(today, "%a %b %d %Y %X %Z%z")

    else:
        today = date.today()
    scores = Scoreboard(today.month, today.day, today.year, league_id="00")
    gameNo = scores.available()

    if not gameNo:
        scores = Scoreboard(today.month, today.day, today.year, league_id="01")
        gameNo = scores.available()
    #Dynamic array for number of games
    length = len(gameNo)
    allstats = []
    game = [{0: {}, 1: {}} for x in range(length)]
    teamstats = [{0: {}, 1: {}} for x in range(length)]

    #get stats from all games available
    #For every game ....
    for i in range(len(gameNo)):
        gameid = gameNo[i]["GAME_ID"]
        box = Boxscore(gameid)
        stats = box.team_stats()
        if len(stats) == 0:
            length = 0
        # get name and pts
        for j in range(len(stats)):
            teamstats[i][j]['name'] = stats[j]["TEAM_ABBREVIATION"]
            teamstats[i][j]['pts'] = stats[j]["PTS"]

            game[i] = teamstats[i]

        allstats.append(game[i])

    return render_template("mainpage.html",
                           gameNum=length,
                           allstats=allstats,
                           date=today,
                           gameId=gameNo)
示例#8
0
def load_customized_data(teamName, startYear, endYear):
    home_team = []
    away_team = []
    home_team_home_record_pct = []
    away_team_away_record_pct = []
    home_team_current_win_percentage = []
    away_team_current_win_percentage = []
    home_team_current_standing = []
    away_team_current_standing = []
    home_team_win_percentage_streak_over_last_n_games = []
    away_team_win_percentage_streak_over_last_n_games = []
    home_team_current_streak = []
    away_team_current_streak = []
    recent_head_to_head_wrt_home_team = []

    df = get_teamBoxScore(teamName, get_season(startYear))
    time.sleep(0.5)
    for index, row in df.iterrows():
        game_id = row["Game_ID"]
        print("game_id", game_id)
        game_summary = game.BoxscoreSummary(game_id=game_id).game_summary()
        time.sleep(0.5)
        game_summary = game_summary.iloc[0]

        home_team_id = game_summary["HOME_TEAM_ID"]

        away_team_id = game_summary["VISITOR_TEAM_ID"]
        home_team.append(home_team_id)
        away_team.append(away_team_id)
        date = datetime.datetime.strptime(row['GAME_DATE'], "%b %d, %Y")
        year, month, day = date.year, date.month, date.day
        scoreboard = Scoreboard(month=month, day=day, year=year)
        time.sleep(0.5)
        if IdToConference[str(home_team_id)] == 'Eastern':
            day_home_stats = scoreboard.east_conf_standings_by_day()
        else:
            day_home_stats = scoreboard.west_conf_standings_by_day()

        if IdToConference[str(away_team_id)] == 'Eastern':
            day_away_stats = scoreboard.east_conf_standings_by_day()
        else:
            day_away_stats = scoreboard.west_conf_standings_by_day()

        home_index = np.flatnonzero(
            day_home_stats['TEAM_ID'] == home_team_id)[0]
        away_index = np.flatnonzero(
            day_away_stats['TEAM_ID'] == away_team_id)[0]
        day_home_team_stats = day_home_stats.iloc[home_index]
        day_away_team_stats = day_away_stats.iloc[away_index]
        #print("idx::",day_home_team_stats)
        home_team_current_win_percentage.append(day_home_team_stats["W_PCT"])
        away_team_current_win_percentage.append(day_away_team_stats["W_PCT"])
        home_team_current_standing.append(home_index + 1)
        away_team_current_standing.append(away_index + 1)
        #print ("hhghg:",day_home_team_stats["HOME_RECORD"])
        home_wins, home_losses = map(
            int, day_home_team_stats["HOME_RECORD"].split('-'))
        away_wins, away_losses = map(
            int, day_away_team_stats["ROAD_RECORD"].split('-'))
        home_team_home_w_pct = 0
        away_team_away_w_pct = 0
        if home_wins + home_losses:
            home_team_home_w_pct = home_wins / (home_wins + home_losses)
        if away_wins + away_losses:
            away_team_away_w_pct = away_wins / (away_wins + away_losses)

        home_team_home_record_pct.append(home_team_home_w_pct)
        away_team_away_record_pct.append(away_team_away_w_pct)

    for i in range(endYear - startYear):
        season = get_season(startYear + 1 + i)
        print("season:::", season)
        additional_data = get_teamBoxScore(teamName, season)
        time.sleep(0.5)
        for index, row in additional_data.iterrows():
            game_id = row["Game_ID"]
            print("game_id::", game_id)
            game_summary = game.BoxscoreSummary(game_id=game_id).game_summary()
            time.sleep(0.5)
            game_summary = game_summary.iloc[0]
            home_team_id = game_summary["HOME_TEAM_ID"]
            away_team_id = game_summary["VISITOR_TEAM_ID"]
            home_team.append(home_team_id)
            away_team.append(away_team_id)
            date = datetime.datetime.strptime(row['GAME_DATE'], "%b %d, %Y")
            year, month, day = date.year, date.month, date.day
            scoreboard = Scoreboard(month=month, day=day, year=year)
            time.sleep(0.5)
            day_stats = None
            if IdToConference[str(home_team_id)] == 'Eastern':
                day_home_stats = scoreboard.east_conf_standings_by_day()
            else:
                day_home_stats = scoreboard.west_conf_standings_by_day()

            if IdToConference[str(away_team_id)] == 'Eastern':
                day_away_stats = scoreboard.east_conf_standings_by_day()
            else:
                day_away_stats = scoreboard.west_conf_standings_by_day()

            try:
                home_index = np.flatnonzero(
                    day_home_stats['TEAM_ID'] == home_team_id)[0]
            except:
                print("home_team_id::", home_team_id)
                print("stats::", day_home_stats)
                print("game_id:::", game_id, game_summary)
                raise Exception("sha")
            away_index = np.flatnonzero(
                day_away_stats['TEAM_ID'] == away_team_id)[0]
            day_home_team_stats = day_home_stats.iloc[home_index]
            day_away_team_stats = day_home_stats.iloc[away_index]
            home_team_current_win_percentage.append(
                day_home_team_stats["W_PCT"])
            away_team_current_win_percentage.append(
                day_away_team_stats["W_PCT"])
            home_team_current_standing.append(home_index + 1)
            away_team_current_standing.append(away_index + 1)
            home_wins, home_losses = map(
                int, day_home_team_stats["HOME_RECORD"].split('-'))
            away_wins, away_losses = map(
                int, day_away_team_stats["ROAD_RECORD"].split('-'))
            home_team_home_w_pct = 0
            away_team_away_w_pct = 0
            if home_wins + home_losses:
                home_team_home_w_pct = home_wins / (home_wins + home_losses)
            if away_wins + away_losses:
                away_team_away_w_pct = away_wins / (away_wins + away_losses)

            home_team_home_record_pct.append(home_team_home_w_pct)
            away_team_away_record_pct.append(away_team_away_w_pct)

        df = df.append(additional_data, ignore_index=True)

    home_team_series = pd.Series(home_team)
    away_team_series = pd.Series(away_team)
    home_team_home_record_pct_series = pd.Series(home_team_home_record_pct)
    away_team_away_record_pct_series = pd.Series(away_team_away_record_pct)
    home_team_current_win_percentage_series = pd.Series(
        home_team_current_win_percentage)
    away_team_current_win_percentage_series = pd.Series(
        away_team_current_win_percentage)
    home_team_current_standing_series = pd.Series(home_team_current_standing)
    away_team_current_standing_series = pd.Series(away_team_current_standing)

    print("length:::", len(home_team_series.values))
    print("df_length:::", df.index)
    df = df.assign(home_team=home_team_series.values)
    df = df.assign(away_team=away_team_series.values)
    df = df.assign(
        home_team_home_record_pct=home_team_home_record_pct_series.values)
    df = df.assign(
        away_team_home_record_pct=away_team_away_record_pct_series.values)
    df = df.assign(
        home_team_current_win_percentage=home_team_current_win_percentage_series
        .values)
    df = df.assign(
        away_team_current_win_percentage=away_team_current_win_percentage_series
        .values)
    df = df.assign(
        home_team_current_standing_series=home_team_current_standing_series.
        values)
    df = df.assign(
        away_team_current_standing_series=away_team_current_standing_series.
        values)

    print("headers:::", list(df))
    return df
示例#9
0
from nba_py import Scoreboard
from datetime import date
from datetime import timedelta
from time import sleep
import json

sd = date(2008, 5, 16)  # (1980,11,17)
ed = date.today()  # (2008,1,1)
league_id = '00'
day_offset = 0

gameids = set()


def daterange(start_date, end_date):
    for n in range(int((end_date - start_date).days)):
        yield start_date + timedelta(n)


file = open("../csv/game_ids.csv", 'a')
for date in daterange(sd, ed):
    try:
        sb = Scoreboard(date.month, date.day, date.year, league_id, day_offset)
        for game in sb.game_header():
            file.write(game['GAME_ID'] + '\n')
        print(date.strftime("%Y-%m-%d") + " successful")
        sleep(2)
    except Exception as exception:
        print(exception)

file.close()
示例#10
0
import datetime
import requests

def find_team_name(id):
    teams = constants.TEAMS
    for team, stats in teams.items():
        for key, val in stats.items():
            if key == 'id' and val == str(id):
                return stats['name']

    return None

base = datetime.datetime.today()
date_list = [base + datetime.timedelta(days=x) for x in range(0, 7)]

games = pd.DataFrame(columns=Scoreboard().game_header().columns)
for date in date_list:
    print(date.day, date.month, date.year)
    games = games.append(Scoreboard(year=date.year, day=date.day,
                            month=date.month).game_header())

games['VISITOR_TEAM_STR'] = games['VISITOR_TEAM_ID'].apply(find_team_name)
games['HOME_TEAM_STR'] = games['HOME_TEAM_ID'].apply(find_team_name)
games['MARQUEE_STR'] = games['VISITOR_TEAM_STR'] + ' @ ' + games['HOME_TEAM_STR']

my_data={'home_teams': str(list(games['HOME_TEAM_STR'])).replace('\'','\"'),
                    'away_teams': str(list(games['VISITOR_TEAM_STR'])).replace('\'', '\"'),
                    'marquee_strs': str(list(games['MARQUEE_STR'])).replace('\'', '\"'),
                    'form_name': 'NBA Pickems - Week 3'}
print(my_data)
示例#11
0
#stats.nba.com/stats/{endpoint}/?{params}

#stats.nba.com/stats/scoreboard/?GameDate=02/14/2015&LeagueID=00&DayOffset=0
import datetime
from nba_py import Scoreboard, game
import json

TODAY = datetime.date.today() - datetime.timedelta(days=1)


a = Scoreboard(
                 month=TODAY.month,
                 day=TODAY.day,
                 year=TODAY.year,
                 )
#values = json_inp['resultSets'][ndx]['rowSet']
bs = game.Boxscore('0021500745')
a.available().get_values()
bss = game.BoxscoreScoring('0021500745')
# print bs.game_summary()
# print bs.game_info()
# print bs.game_summary()

'''
LIST OF DICTS!
>>> bss.json['resource']
u'boxscore'
>>> type(bss.json['resource'])
<type 'unicode'>
>>> type(bss.json['resultSets'])
示例#12
0
def scoreboard(year, month, day):
    return Scoreboard(year=year, month=month, day=day)
示例#13
0
def main():


    print('Welcome to Abhi\'s NBA CLI!')
    loop=True
    while loop:
        # print('What would you like to do?')
        # print('1. Get information about a player')
        # # print()
        # print('2. View Completed/In Progress Games')
        # print('3. View Today\'s Upcoming Games')
        # # print()
        # print('9. Exit the program')
        # print('100. Used for testing')
        print_main_menu()
        main_choice = input("Pick a number from the list above\n")
        if int(main_choice) == 1:
            first_name = input("What is the first name of the player you'd like to view?\n")
            last_name = input("What is the last name?\n")

            print_player_information(first_name.strip(), last_name.strip())

        elif int(main_choice) == 2:
            print_scores()

        elif int(main_choice) == 3:
            print_upcoming_games()

        elif int(main_choice) == 4:
            team_choice = input("Enter the name of the team you'd like to view (ex. Boston Celtics)\n")
            print_team_information(team_choice)

        elif int(main_choice) == 5:
            board = Scoreboard()
            printer.pprint(board.east_conf_standings_by_day())
            
        elif int(main_choice) == 6:
            board = Scoreboard()
            printer.pprint(board.west_conf_standings_by_day())

        elif int(main_choice) == 9:
            print("Thank you for using Abhi's NBA Stats CLI!")
            return

        elif int(main_choice) == 100:
            # team_game_logs = team.TeamGameLogs("1610612738")
            # # print(type(team_game_logs))
            # printer.pprint(team_game_logs.info())
            # teamcommonroster = team.TeamCommonRoster("1610612738", season='2017-18')
            # coaches = teamcommonroster.coaches()
            # roster = teamcommonroster.roster()
            # print(coaches)
            # printer.pprint(roster)
            teamlist = team.TeamList(league_id='00')
            printer.pprint(teamlist.info())

        else:
            print("Invalid menu choice")


    last_choice = input("Would you like to run the program again? Press 1 to run again, or 2 to exit\n")
    if int(last_choice) == 1:
        main()
    elif int(last_choice) == 2:
        print("Thank you for using Abhi's NBA Stats CLI!")
        return
示例#14
0
from nba_py import game
from nba_py import constants
from nba_py import team
from nba_py import Scoreboard
import requests
import requests_cache
from datetime import date
pd.set_option('display.max_columns', None)

# Get todays date for input to nba_py module
today = str(date.today())
year, month, day = today.split("-")
year, month, day = int(year), int(month), int(day)

# Returns dataframe about todays NBA games, contains the ID's of the teams that are playing
games_df = Scoreboard(month=month, day=day, year=year)
games_df = games_df.game_header()

games = []

# Process dataframe and returns games which is a list of games being played
for index, row in games_df.iterrows():
    game = []
    # Get team ID and convert to team name
    road_team = row['VISITOR_TEAM_ID']
    road_team = team.TeamSummary(road_team)
    road_team = road_team.info()
    road_team = road_team['TEAM_NAME'].values[0]
    game.append(road_team)
    home_team = row['HOME_TEAM_ID']
    home_team = team.TeamSummary(home_team)