def get_games(): scoreboard = nba_py.Scoreboard(month=12, day=25, year=2017, league_id='00', offset=0) line_score = scoreboard.line_score() games = [] current_game = {} current_game_sequence = 0 game_sequence_counter = 0 for team in line_score: if (team["GAME_SEQUENCE"] != current_game_sequence): current_game["TEAM_1_ABBREVIATION"] = team["TEAM_ABBREVIATION"] current_game["TEAM_1_WINS_LOSSES"] = team["TEAM_WINS_LOSSES"] current_game["TEAM_1_PTS"] = team["PTS"] current_game["TEAM_1_ID"] = team["TEAM_ID"] current_game_sequence = team["GAME_SEQUENCE"] game_sequence_counter += 1 elif (game_sequence_counter == 1): current_game["TEAM_2_ABBREVIATION"] = team["TEAM_ABBREVIATION"] current_game["TEAM_2_WINS_LOSSES"] = team["TEAM_WINS_LOSSES"] current_game["TEAM_2_PTS"] = team["PTS"] current_game["TEAM_2_ID"] = team["TEAM_ID"] current_game["GAME_ID"] = team["GAME_ID"] games.append(current_game) current_game = {} game_sequence_counter = 0 return games
def GetAllBoxScores(next_n_days, start_month, start_day, start_year): print("GETTING ALL BOXSCORES") for i in range(next_n_days, 0, -1): # Request Scoreboard scoreboard = nba_py.Scoreboard(month=start_month, day=start_day, year=start_year, league_id='00', offset=i) box_scores_summaries.append(scoreboard.game_header()) time.sleep(1) print("SCOREBOARD REQUEST COMPLETE: " + str(i)) for game_id in scoreboard.available()['GAME_ID']: # Request Boxscore player_stats = game.Boxscore(game_id).player_stats() box_scores_player_stats.append(player_stats) time.sleep(1) team_stats = game.Boxscore(game_id).team_stats() box_scores_team_stats.append(team_stats) time.sleep(1) print("BOXSCORE REQUEST COMPLETE")
def get_all_scoreboards(): log_path = 'logs/scoreboards.json' if not os.path.exists(log_path): logs = {} else: logs = load_json(log_path) end_date = date.today() start_date = date(2017, 8, 1) day_count = (end_date - start_date).days + 1 for single_date in [ d for d in (end_date - timedelta(n) for n in range(day_count)) if d > start_date ]: day, month, year = (single_date.timetuple().tm_mday, single_date.timetuple().tm_mon, single_date.timetuple().tm_year) key = '-'.join([str(year), str(month), str(day)]) path = 'scoreboards/' + key + '.json' if logs.has_key(key): continue if os.path.exists(path): logs[key] = 'Done' continue try: print((day, month, year)) write_json(path, nba_py.Scoreboard(month=month, day=day, year=year).json) logs[key] = 'Done' time.sleep(4) except Exception as e: print e logs[key] = e.message write_json(log_path, logs)
def read_scores_by_date(dt): bs = nba_py.Scoreboard(month=dt.month, day=dt.day, year=dt.year) away_teams = [] home_teams = [] away_points = [] home_points = [] for table in bs.json['resultSets']: # Get the proper table with the scores if table['name'] == 'LineScore': header = table['headers'] team_ind = header.index("TEAM_ABBREVIATION") points_ind = header.index("PTS") game_list = table['rowSet'] # Away team always comes first for g in range(0, len(game_list), 2): away_teams.append(game_list[g][team_ind]) away_points.append(game_list[g][points_ind]) home_teams.append(game_list[g + 1][team_ind]) home_points.append(game_list[g + 1][points_ind]) df = pd.DataFrame() df['AwayTeam'] = [NBA_ABBREV_MAP.TEAM_ABBREV_MAP[t] for t in away_teams] df['HomeTeam'] = [NBA_ABBREV_MAP.TEAM_ABBREV_MAP[t] for t in home_teams] df['AwayPoints'] = away_points df['HomePoints'] = home_points game_dt_str = "%s%02d%02d" % (dt.year, dt.month, dt.day) df['GameTime'] = game_dt_str return (df)
def get_games(date): scoreboard = nba_py.Scoreboard(month=date.month, day=date.day,year=date.year) line_score = scoreboard.line_score() games=[] current_game = {} current_game_sequence =0 game_sequence_counter=0 for team in line_score: if (team["GAME_SEQUENCE"] != current_game_sequence): current_game["TEAM_1_ABBREVIATION"] =team ["TEAM_ABBREVIATION"] current_game["TEAM_1_WINS_LOSSES"] =team ["TEAM_WINS_LOSSES"] current_game["TEAM_1_PTS"] =team ["PTS"] current_game["TEAM_1_ID"] =team ["TEAM_ID"] current_game_sequence = team["GAME_SEQUENCE"] game_sequence_counter +=1 elif (game_sequence_counter==1): current_game["TEAM_2_ABBREVIATION"] =team ["TEAM_ABBREVIATION"] current_game["TEAM_2_WINS_LOSSES"] =team ["TEAM_WINS_LOSSES"] current_game["TEAM_2_PTS"] =team ["PTS"] current_game["TEAM_2_ID"] =team ["TEAM_ID"] games.append(current_game) current_game = {} game_sequence_counter=0 return games
def testScoreboard(self): scoreboard = nba_py.Scoreboard(month=2, day=21, year=2015) available = scoreboard.available() self.assertTrue((5, 2), available.shape) self.assertTrue(('0021400817' == available[1:2].GAME_ID).all()) eastconfstandingsbyday = scoreboard.east_conf_standings_by_day() self.assertTrue((15, 12), eastconfstandingsbyday.shape) self.assertTrue(('Toronto' == eastconfstandingsbyday[1:2].TEAM).all()) westconfstandingsbyday = scoreboard.west_conf_standings_by_day() self.assertTrue((15, 12), westconfstandingsbyday.shape) self.assertTrue(('Memphis' == westconfstandingsbyday[1:2].TEAM).all()) gameheader = scoreboard.game_header() self.assertTrue((5, 14), gameheader.shape) self.assertTrue(('20150221/NOPMIA' == gameheader[1:2].GAMECODE).all()) lastmeeting = scoreboard.last_meeting() self.assertTrue((5, 13), lastmeeting.shape) self.assertTrue( ('Heat' == lastmeeting[1:2].LAST_GAME_HOME_TEAM_NAME).all()) linescore = scoreboard.line_score() self.assertTrue((10, 28), linescore.shape) self.assertTrue(('Charlotte' == linescore[1:2].TEAM_CITY_NAME).all()) seriesstandings = scoreboard.series_standings() self.assertTrue((5, 7), seriesstandings.shape) self.assertTrue(('Tied' == seriesstandings[1:2].SERIES_LEADER).all())
def get_games(date): scoreboard = nba_py.Scoreboard( month=date.month, day=date.day, year=date.year) line_score = scoreboard.line_score() games = [] current_game = {} current_game_sequence = 0 game_sequence_counter = 0 for team in line_score: if (team['GAME_SEQUENCE'] != current_game_sequence): current_game['TEAM_1_ABBREVIATION'] = team['TEAM_ABBREVIATION'] current_game['TEAM_1_CITY_NAME'] = team['TEAM_CITY_NAME'] current_game['TEAM_1_ID'] = team['TEAM_ID'] current_game['TEAM_1_PTS'] = team['PTS'] current_game_sequence = team['GAME_SEQUENCE'] game_sequence_counter += 1 elif (game_sequence_counter == 1): current_game['TEAM_2_ABBREVIATION'] = team['TEAM_ABBREVIATION'] current_game['TEAM_2_CITY_NAME'] = team['TEAM_CITY_NAME'] current_game['TEAM_2_ID'] = team['TEAM_ID'] current_game['TEAM_2_PTS'] = team['PTS'] current_game['GAME_ID'] = team['GAME_ID'] games.append(current_game) current_game = {} game_sequence_counter = 0 return games
def get_games(date): scorecard = nba_py.Scoreboard(month=int(date[5:7]), day=int(date[8:10]), year=int(date[0:4])) scoreboard = scorecard.json result_set = scoreboard['resultSets'] today_games = result_set[0]['rowSet'] game_id_index = 2 hometeam_id_index = 6 awayteam_id_index = 7 game_time_index = 4 games_scheduled = {} for game in today_games: games_scheduled[game[game_id_index]] = [ game[hometeam_id_index], game[awayteam_id_index], game[game_time_index] ] games_list = [] for key in games_scheduled: hometeam_id = games_scheduled[key][0] awayteam_id = games_scheduled[key][1] game_time = games_scheduled[key][2] games_list.append( str(team_details[str(awayteam_id)]) + " @ " + str(team_details[str(hometeam_id)]) + " at " + str(game_time)) g_list = '' for games in games_list[0:-1]: g_list += (games + '\n') if (len(g_list) != 0): g_list += games_list[-1] else: g_list = 'There seems to be no games today' return (g_list)
def get_day_games(date, nb_players, nb_shorlist, _season, _season_type): # init shortlist shortlist = pandas.DataFrame() # get scoreboard for specified date games = nba.Scoreboard(date.month, date.day, date.year).game_header() # fetch teams IDs for home and visitors home_teams = games['HOME_TEAM_ID'].values visitor_teams = games['VISITOR_TEAM_ID'].values # fetch injuries report injuries_report = get_injuries_report() # --- print date print "----------" # iterate through home and visitor teams IDs lists for ht_id, vt_id in zip(home_teams, visitor_teams): # get teams infos (ht_abbr, ht_conf, ht_rank) = team.get_team_info(ht_id) (vt_abbr, vt_conf, vt_rank) = team.get_team_info(vt_id) print "%s (%d) vs. %s (%d)" % (ht_abbr, ht_rank, vt_abbr, vt_rank) print "----------" # fetch and print N best players from home team ht_br_players = team.get_team_best_rated_players( ht_id, ht_abbr, nb_players, injuries_report, _season, _season_type) print_players(ht_br_players, nb_players) print "vs." # fetch and print N best players from visitor team vt_br_players = team.get_team_best_rated_players( vt_id, vt_abbr, nb_players, injuries_report, _season, _season_type) print_players(vt_br_players, nb_players) print "----------" shortlist = shortlist.append(ht_br_players) shortlist = shortlist.append(vt_br_players) print "SHORTLIST" print "----------" shortlist = shortlist.sort_values('TTFL_SCORE', ascending=False)[0:nb_shorlist] print_players(shortlist, nb_shorlist) print "----------" return shortlist
def index(): scoreboard = nba_py.Scoreboard() linescore = scoreboard.line_score() teams = list(linescore['TEAM_ABBREVIATION']) points = list(linescore['PTS']) games = game_data(teams, points) MAX = len(games) date = today.date() graph_data = graph_gen(linescore) return render_template('index.html', games = games, max = MAX, today=date, graph_data = graph_data)
def get_games(date): """Get list of games in daily scoreboard. Args: date: datetime object of the scoreboard that we want. Returns: games: Array with dictionaries of the games for the date given. """ scoreboard = nba_py.Scoreboard(month=date.month, day=date.day, year=date.year) line_score = scoreboard.line_score() # Get games current_game_sequence = 0 game_sequence_counter = 0 games = [] current_game = {} for team in line_score: if team["GAME_SEQUENCE"] != current_game_sequence: current_game["TEAM_1_ABBREVIATION"] = team["TEAM_ABBREVIATION"] current_game["TEAM_1_WINS_LOSSES"] = team["TEAM_WINS_LOSSES"] if (team["PTS"]): current_game["TEAM_1_PTS"] = team["PTS"] else: current_game["TEAM_1_PTS"] = "" current_game["TEAM_1_ID"] = team["TEAM_ID"] current_game_sequence = team["GAME_SEQUENCE"] game_sequence_counter += 1 elif game_sequence_counter == 1: current_game["TEAM_2_ABBREVIATION"] = team["TEAM_ABBREVIATION"] current_game["TEAM_2_WINS_LOSSES"] = team["TEAM_WINS_LOSSES"] if (team["PTS"]): current_game["TEAM_2_PTS"] = team["PTS"] else: current_game["TEAM_2_PTS"] = "" current_game["TEAM_2_ID"] = team["TEAM_ID"] current_game["GAME_ID"] = team["GAME_ID"] games.append(current_game) current_game = {} game_sequence_counter = 0 return games
def get_games(date): """ :param date: datetime.date, the match day :return: df, all the games on the given day """ return nba_py.Scoreboard( month=date.month, day=date.day, year=date.year, league_id='00', offset=0).game_header()[['GAME_ID', 'HOME_TEAM_ID', 'VISITOR_TEAM_ID']]
def standings(): """Default standings page.""" scoreboard = nba_py.Scoreboard() east_standings = scoreboard.east_conf_standings_by_day() west_standings = scoreboard.west_conf_standings_by_day() return render_template("standings.html", title="standings", east_standings=enumerate(east_standings, 1), west_standings=enumerate(west_standings, 1), team=CITY_TO_TEAM)
def standings_by_season(season): """Standings page by the season year. """ season = int(season) + 1 scoreboard = nba_py.Scoreboard(month=7, day=1, year=season) east_standings = scoreboard.east_conf_standings_by_day() west_standings = scoreboard.west_conf_standings_by_day() return render_template("standings.html", title="standings", east_standings=enumerate(east_standings, 1), west_standings=enumerate(west_standings, 1), team=CITY_TO_TEAM)
def process(): date = request.form['date'] day = int(date[8:10]) month = int(date[5:7]) year = int(date[0:4]) scoreboard = nba_py.Scoreboard(day=day, month=month, year=year) linescore = scoreboard.line_score() teams = list(linescore['TEAM_ABBREVIATION']) points = list(linescore['PTS']) games = game_data(teams, points) MAX = len(games) graph_data = graph_gen(linescore) return render_template('index.html', games = games, max = MAX, today=date, graph_data = graph_data)
def get_scores(_date): st = time.time() s_str = '' scorecard = nba_py.Scoreboard(month=int(_date[5:7]), day=int(_date[8:10]), year=int(_date[0:4])) scoreboard = scorecard.json result_set = scoreboard['resultSets'] today_games = result_set[0]['rowSet'] live_score_set = result_set[1]['rowSet'] game_id_index = 2 hometeam_id_index = 6 awayteam_id_index = 7 game_time_index = 4 games_scheduled = {} i = 0 for game in today_games: hometeam = game[hometeam_id_index] awayteam = game[awayteam_id_index] game_time = game[game_time_index] hometeam_score = None awayteam_score = None if ((live_score_set[i][3]) == hometeam): hometeam_score = live_score_set[i][21] awayteam_score = live_score_set[i + 1][21] else: hometeam_score = live_score_set[i + 1][21] awayteam_score = live_score_set[i][21] games_scheduled[game[game_id_index]] = [ hometeam, awayteam, hometeam_score, awayteam_score, game_time ] i += 2 s_list = [] for key in games_scheduled: hometeam_id = games_scheduled[key][0] hometeam_score = games_scheduled[key][2] awayteam_id = games_scheduled[key][1] awayteam_score = games_scheduled[key][3] game_time = games_scheduled[key][4] s_list.append( str(team_details[str(awayteam_id)]) + " " + str(awayteam_score) + " @ " + str(team_details[str(hometeam_id)]) + " " + str(hometeam_score) + ' ' + game_time) for g in s_list[0:-1]: s_str += (g + '\n') if (len(s_list) != 0): s_str += s_list[-1] else: s_str = "There seems to be no games today" return (s_str)
def align_rotowire(): with codecs.open("temp.json", "r", "utf-8") as f: rotodat = json.load(f) data = [] delts = [ datetime.timedelta(days=0), datetime.timedelta(days=-1), datetime.timedelta(days=1), datetime.timedelta(days=-2), datetime.timedelta(days=2) ] for daykey, dayvals in rotodat.iteritems(): date_pieces = daykey.split('_') day = datetime.date(int(date_pieces[0]), int(date_pieces[1]), int(date_pieces[2])) for thing in dayvals: foundgame = False rulhome1 = thing["home"].split()[0] if rulhome1 == "Los" and "Clippers" in thing["home"]: rulhome1 = "LA" rulaway1 = thing["away"].split()[0] if rulaway1 == "Los" and "Clippers" in thing["away"]: rulaway1 = "LA" for delt in delts: newday = day + delt scoreboard = nba_py.Scoreboard(month=newday.month, day=newday.day, year=newday.year) linescores = scoreboard.line_score() for i in xrange(0, len(linescores), 2): awaycity1 = linescores.iloc[i][5].split()[0] homecity1 = linescores.iloc[i + 1][5].split()[0] #print "got", homecity1, awaycity1 if rulhome1 == homecity1 and rulaway1 == awaycity1 or rulhome1 == awaycity1 and rulaway1 == homecity1: # found it add_to_data(newday, linescores, i, thing["summaries"], data) foundgame = True break if foundgame: break if not foundgame: print >> sys.stderr, "couldn't find", daykey, rulhome1, rulaway1 with codecs.open("rotoaligned.json", "w+", "utf-8") as f: json.dump(data, f)
def get_games(date): """Get lists of games for the day. Args: date: datetime object of the day that we want games. Returns: games: An array of dictionaries of the games that were played today. """ scoreboard = nba_py.Scoreboard(month=date.month, day=date.day, year=date.year) line_score = scoreboard.line_score() # List of games games = [] # Dictionary of the current game we're looking at current_game = {} current_game_sequence = 0 game_sequence_counter = 0 for index, team in line_score.iterrows(): if (team["GAME_SEQUENCE"] != current_game_sequence): current_game["TEAM_1_ABBREVIATION"] = team["TEAM_ABBREVIATION"] current_game["TEAM_1_WINS_LOSSES"] = team["TEAM_WINS_LOSSES"] current_game["TEAM_1_PTS"] = team["PTS"] current_game["TEAM_1_ID"] = team["TEAM_ID"] current_game_sequence = team["GAME_SEQUENCE"] game_sequence_counter += 1 elif (game_sequence_counter == 1): current_game["TEAM_2_ABBREVIATION"] = team["TEAM_ABBREVIATION"] current_game["TEAM_2_WINS_LOSSES"] = team["TEAM_WINS_LOSSES"] current_game["TEAM_2_PTS"] = team["PTS"] current_game["TEAM_2_ID"] = team["TEAM_ID"] current_game["GAME_ID"] = team["GAME_ID"] games.append(current_game) current_game = {} game_sequence_counter = 0 return games
def find_games(date): """Get games for the current day. Arguments date: the date which we want to see the games This will return an array of the games that are played for that day """ scoreboard = nba_py.Scoreboard(month=date.month, day=date.day, year=date.year) line_score = scoreboard.line_score() # the total list of games games = [] #current game currently looked at current_game = {} current_game_sequence = 0 counter_game = 0 for teams in line_score: if (teams["GAME_SEQUENCE"] != current_game_sequence): current_game["TEAM_1_ABBREVIATION"] = teams["TEAM_ABBREVIATION"] current_game["TEAM_1_WINS_LOSSES"] = teams["TEAM_WINS_LOSSES"] current_game["TEAM_1_PTS"] = teams["PTS"] current_game["TEAM_1_ID"] = teams["TEAM_ID"] current_game_sequence = teams["GAME_SEQUENCE"] counter_game += 1 elif (counter_game == 1): current_game["TEAM_2_ABBREVIATION"] = teams["TEAM_ABBREVIATION"] current_game["TEAM_2_WINS_LOSSES"] = teams["TEAM_WINS_LOSSES"] current_game["TEAM_2_PTS"] = teams["PTS"] current_game["TEAM_2_ID"] = teams["TEAM_ID"] current_game["GAME_ID"] = teams["GAME_ID"] games.append(current_game) current_game = {} counter_game = 0 return games
def standings_post_request(): """Standings page after using the datepicker plugin. """ date = request.form["date"] datetime_object = datetime.datetime.strptime(date, "%m-%d-%Y") scoreboard = nba_py.Scoreboard(month=datetime_object.month, day=datetime_object.day, year=datetime_object.year) east_standings = scoreboard.east_conf_standings_by_day() west_standings = scoreboard.west_conf_standings_by_day() return render_template("standings.html", title="standings", east_standings=enumerate(east_standings, 1), west_standings=enumerate(west_standings, 1), team=CITY_TO_TEAM)
def scores(bot, update): date = datetime.today() scoreboard = nba_py.Scoreboard(month=date.month - 3, day=date.day, year=date.year) line_score = scoreboard.line_score() # Get games current_game_sequence = 0 game_sequence_counter = 0 games = [] for team in line_score: if team["GAME_SEQUENCE"] != current_game_sequence: home = team["TEAM_ABBREVIATION"] record_home = "Record: " + team["TEAM_WINS_LOSSES"] if (team["PTS"]): points = str(team["PTS"]) + " - " current_game_sequence = team["GAME_SEQUENCE"] game_sequence_counter += 1 elif game_sequence_counter == 1: away = team["TEAM_ABBREVIATION"] record_away = "Record: " + team["TEAM_WINS_LOSSES"] if (team["PTS"]): points += str(team["PTS"]) else: points = "Game did not start yet!" current_game = home + " vs. " + away + "\n" + home + " " + record_home + "\n" + away + " " + record_away + "\n" + "Score: " + points games.append(current_game) # current_game = {} game_sequence_counter = 0 final = "" for game in games: bot.send_message(chat_id=update.message.chat_id, text=game)
def _url_metadata(l2m_url): """Parse data included in l2m url. Args: l2m_url (str) - url to l2m .pdf Returns: (list) - [l2m_url, away team abbr, home team abbr, datetime] """ # -- Split url basename on '@' or '-'. bname = re.split("-|@", os.path.basename(l2m_url).rstrip(".pdf")) # -- Pull away team abbr and home team abbr from split basename. away, home = bname[1], bname[2] # -- Pull and format date from split basename. if len(bname[5]) == 4: date = datetime(2000 + int(bname[5][-2:]), int(bname[3]), int(bname[4])) elif len(bname[5]) == 3: date = datetime(2000 + int(bname[5][:-1]), int(bname[3]), int(bname[4])) elif len(bname[5]) == 2: date = datetime(2000 + int(bname[5]), int(bname[3]), int(bname[4])) else: date = datetime(9999, int(bname[3]), int(bname[4])) # -- PHO v. PHX exception if away == "PHO": away = "PHX" if home == "PHO": home = "PHX" # -- Team abbr dictionary. TEAMS = nba_py.constants.TEAMS team_dict = {k: int(TEAMS[k]["id"]) for k in TEAMS.keys()} # -- Use nba_py to get results for a given day. api_call = nba_py.Scoreboard(date.month, date.day, date.year).json # -- Filter results to the correct game. game_res = api_call["resultSets"][0]["rowSet"] game = filter(lambda x: team_dict[away] == x[7], game_res)[0] score_res = api_call["resultSets"][1]["rowSet"] # -- Grab gameid, season, and scores. gameid, season = game[2], game[8] away_score = filter(lambda x: team_dict[away] == x[3], score_res)[0][21] home_score = filter(lambda x: team_dict[home] == x[3], score_res)[0][21] # print("{}, {}, {}, {}, {}, {}, {}".format( # gameid, season, date, away, away_score, home, home_score)) return [gameid, season, date, away, away_score, home, home_score, l2m_url]
def get_games(date): datetime_today = datetime.today() datetime_today = datetime.strptime('Jan 15 2018', '%b %d %Y') scoreboard = nba_py.Scoreboard(month=date.month, day=date.day, year=date.year) line_score = scoreboard.line_score() # List of games games = [] # Dictionary of the current game we're looking at current_game = {} current_game_sequence = 0 game_sequence_counter = 0 for team in line_score: if (team["GAME_SEQUENCE"] != current_game_sequence): current_game["TEAM_1_ABBREVIATION"] = team["TEAM_ABBREVIATION"] current_game["TEAM_1_WINS_LOSSES"] = team["TEAM_WINS_LOSSES"] current_game["TEAM_1_PTS"] = team["TEAM_PTS"] current_game["TEAM_1_ID"] = team["TEAM_ID"] current_game_sequence = team["GAME SEQUENCE"] game_sequence_counter += 1 elif (game_sequence_counter == 1): current_game["TEAM_2_ABBREVIATION"] = team["TEAM_ABBREVIATION"] current_game["TEAM_2_WINS_LOSSES"] = team["TEAM_WINS_LOSSES"] current_game["TEAM_2_PTS"] = team["TEAM_PTS"] current_game["TEAM_2_ID"] = team["TEAM_ID"] current_game["GAME_ID"] = team["GAME_ID"] games.append(current_game) current_game = {} game_sequence_counter = 0 return games
def get_game_data(game_id, date): scoreboard = nba_py.Scoreboard( month=date.month, day=date.day, year=date.year) line_score = scoreboard.line_score() current_game = {} game_sequence_counter = 0 for team in line_score: if (team['GAME_ID'] == game_id and game_sequence_counter != 1): current_game['TEAM_1_ABBREVIATION'] = team['TEAM_ABBREVIATION'] current_game['TEAM_1_CITY_NAME'] = team['TEAM_CITY_NAME'] current_game['TEAM_1_ID'] = team['TEAM_ID'] current_game['TEAM_1_WINS_LOSSES'] = team['TEAM_WINS_LOSSES'] current_game['TEAM_1_PTS'] = team['PTS'] current_game['TEAM_1_PTS_QTR1'] = team['PTS_QTR1'] current_game['TEAM_1_PTS_QTR2'] = team['PTS_QTR2'] current_game['TEAM_1_PTS_QTR3'] = team['PTS_QTR3'] current_game['TEAM_1_PTS_QTR4'] = team['PTS_QTR4'] game_sequence_counter += 1 elif (team['GAME_ID'] == game_id and game_sequence_counter == 1): current_game['TEAM_2_ABBREVIATION'] = team['TEAM_ABBREVIATION'] current_game['TEAM_2_CITY_NAME'] = team['TEAM_CITY_NAME'] current_game['TEAM_2_ID'] = team['TEAM_ID'] current_game['TEAM_2_WINS_LOSSES'] = team['TEAM_WINS_LOSSES'] current_game['TEAM_2_PTS'] = team['PTS'] current_game['TEAM_2_PTS_QTR1'] = team['PTS_QTR1'] current_game['TEAM_2_PTS_QTR2'] = team['PTS_QTR2'] current_game['TEAM_2_PTS_QTR3'] = team['PTS_QTR3'] current_game['TEAM_2_PTS_QTR4'] = team['PTS_QTR4'] current_game['GAME_ID'] = team['GAME_ID'] break game_sequence_counter = 0 return current_game
def get_games(db=os.path.join("..", "data", "outputs", "NBA_ELO.db")): """Using nba_py get data for all games that are not in the DB. NOTE: seasons variable must be updated for future seasons (this is dumb). Returns: new_games - pandas dataframe of all new games. """ # -- Exclude pre-season. seasons = pd.concat([pd.date_range("2015-10-27", "2016-06-02").to_series(), pd.date_range("2016-10-25", "2017-06-01").to_series(), pd.date_range("2017-10-17", "2018-06-17").to_series()]) # -- Load data from db. df = read_db(db) new_games = pd.DataFrame() # Empty df to append new game data. cols1 = ["GAME_ID", "GAME_DATE_EST", "TEAM_ABBREVIATION", "PTS"] # -- For each day since last game, check for game data. for day in pd.date_range(df.date_game.max(), pd.datetime.today()): if day in seasons: print("Collecting data for games on: {}".format(day.date()), end="\r") sys.stdout.flush() try: sb = nba_py.Scoreboard(day.month, day.day, day.year) days_games = sb.line_score()[cols1] if len(days_games) > 0 : away = days_games[days_games.index % 2 == 0] home = days_games[days_games.index % 2 == 1] days_games = away.merge(home, on=["GAME_DATE_EST", "GAME_ID"], suffixes=("_AWAY", "_HOME")) \ .drop("GAME_ID", axis=1) new_games = pd.concat([new_games, days_games]) except: print("Error at {}. Rerun, to continue from here.".format(day)) break return new_games
def main(): # get date and that date's game today = datetime.datetime.now() todaysData = nba_py.Scoreboard(month=today.month, day=today.day, year=today.year) todaysGames = todaysData.game_header() mostInteresting = {} homeID = 0 awayID = 0 foundOne = 0 currComp = 99999 # Iterate through all of today's games for game in todaysGames: # Get info for current game currAwayId = game["VISITOR_TEAM_ID"] currHomeId = game["HOME_TEAM_ID"] currStatus = game["GAME_STATUS_TEXT"] competitiveness = calcComp(currHomeId, currAwayId) if competitiveness < currComp and currStatus != 'Final': currComp = competitiveness mostInteresting = game homeID = currHomeId awayID = currAwayId foundOne = 1 # If a game has been found, print info about it if foundOne == 1: printGame(mostInteresting, homeID, awayID) # Otherwise just return no items found message else: print("No games left today. Sorry!")
def get_day_results(self, year, month, day, quality="high"): results = [] scoreboard = nba_py.Scoreboard(month=int(month), day=int(day), year=int(year)) date = "%s/%s/%s" % (year, month, day) game_results = self.from_linescore_to_game_result( scoreboard.line_score(), date, quality) for game_id in game_results: game = self.nba_repository.get_results_by_game_id(game_id) if game: if game.is_incomplete(): updated_game = self.nba_repository.update( game.id, game_results[game_id]) results.append(updated_game.serialize()) else: results.append(game.serialize()) else: new_game = self.nba_repository.create(game_results[game_id]) results.append(new_game.serialize()) return results
def get_standings(conf): today = date.today() scorecard = nba_py.Scoreboard(month=today.month, day=today.day, year=today.year) standings = None if (conf != ''): if (conf[0] == 'e' or conf[0] == 'E'): standings = scorecard.east_conf_standings_by_day() elif (conf[0] == 'w' or conf[0] == 'W'): standings = scorecard.west_conf_standings_by_day() std = standings.iloc[:, 5:9] headers = ['Team', 'GP', 'W', 'L'] std_str = '' temp_str = ' '.join(map(str, headers)) std_str += (temp_str + "\n") for row in std.values[0:-1]: temp_str = ' '.join(map(str, row)) std_str += (temp_str + "\n") if (len(std.values) != 0): temp_str = ' '.join(map(str, std.values[-1])) std_str += (temp_str + "\n") return (std_str)
def get_games(): scoreboard = nba.Scoreboard() return scoreboard.line_score()
def test(): return nba_py.Scoreboard(month=2, day=21, year=2015)