def team_box(): print("retrieving team box scores") try: # hard coded 2019 team box scores for month in range(10, 13): # print("searching in month {}".format(month)) for day in range(1, 32): # print("searching on day {}".format(day)) client.team_box_scores( day=1, month=1, year=2020, output_type=OutputType.CSV, output_file_path= "C:\\Users\\NWHAL\\Documents\\nba_project\\team_scores_2019_{}_{}.csv" .format(month, day)) print(msg) except InvalidDate: pass try: for month in range(1, m + 1): # print("searching in month {}".format(month)) for day in range(1, 32): # print("searching on day {}".format(day)) client.team_box_scores( day=1, month=1, year=2020, output_type=OutputType.CSV, output_file_path= "C:\\Users\\NWHAL\\Documents\\nba_project\\team_scores_2020_{}_{}.csv" .format(month, day)) print(msg) except InvalidDate: pass
def output_2018_01_01_team_box_scores_to_csv(self): client.team_box_scores(day=1, month=1, year=2018, output_type=OutputType.CSV, output_file_path=self.file_path, output_write_option=OutputWriteOption.WRITE)
def test_2018_01_01_team_box_scores_csv_box_scores_to_file(self): client.team_box_scores( day=1, month=1, year=2018, output_type=OutputType.CSV, output_file_path="./2018_01_01_team_box_scores.csv", output_write_option=OutputWriteOption.WRITE)
def test_2018_01_01_team_box_scores_json_box_scores_output_to_file(self): client.team_box_scores(day=1, month=1, year=2018, output_type=OutputType.JSON, output_file_path=self.file_path, output_write_option=OutputWriteOption.WRITE) self.assertTrue(Path(self.file_path).exists()) self.assertTrue(Path(self.file_path).is_file())
def test_2018_01_01_team_box_scores_json_box_scores_match_expected_output(self): client.team_box_scores( day=1, month=1, year=2018, output_type=OutputType.JSON, output_file_path=self.file_path, output_write_option=OutputWriteOption.WRITE ) with open(self.file_path, 'r', encoding="utf8") as output_file, open(self.expected_file_path, 'r', encoding="utf8") as expected_file: self.assertEqual( json.load(output_file), json.load(expected_file), )
def get_teams_played_on_date(date_obj=None, timeout=1): """ Gets a list of all teams that played on the provided date. :param datetime.datetime date_obj: Datetime object for starting day to search. :param int timeout: Number of days to search before giving up. :return: The active teams on the given date. :rtype: list """ teams = [] if date_obj is None: date_obj = datetime.datetime.today() while True: if timeout > 0: team_box_scores = client.team_box_scores(day=date_obj.day, month=date_obj.month, year=date_obj.year) if len(team_box_scores) > 1: teams = [entry['team'].name for entry in team_box_scores] break date_obj -= datetime.timedelta(days=1) timeout -= 1 else: break return teams
def test_2019_10_22_box_score_teams_and_outcomes(self): team_box_scores = client.team_box_scores(day=22, month=10, year=2019) lakers_box_score = team_box_scores[0] self.assertEqual(Team.LOS_ANGELES_LAKERS, lakers_box_score["team"]) self.assertEqual(Outcome.LOSS, lakers_box_score["outcome"]) self.assertEqual(102, lakers_box_score["points"]) clippers_box_score = team_box_scores[1] self.assertEqual(Team.LOS_ANGELES_CLIPPERS, clippers_box_score["team"]) self.assertEqual(Outcome.WIN, clippers_box_score["outcome"]) self.assertEqual(112, clippers_box_score["points"]) pelicans_box_score = team_box_scores[2] self.assertEqual(Team.NEW_ORLEANS_PELICANS, pelicans_box_score["team"]) self.assertEqual(Outcome.LOSS, pelicans_box_score["outcome"]) self.assertEqual(122, pelicans_box_score["points"]) raptors_box_score = team_box_scores[3] self.assertEqual(Team.TORONTO_RAPTORS, raptors_box_score["team"]) self.assertEqual(Outcome.WIN, raptors_box_score["outcome"]) self.assertEqual(130, raptors_box_score["points"])
def teamTotalsToReddit(day, month, year, team): team_totals = client.team_box_scores(day=day, month=month, year=year) for score in team_totals: if score['team'] == team: attempted_field_goals = '{}-{} ({}%)'.format( score['made_field_goals'], score['attempted_field_goals'], str( round( score['made_field_goals'] / score['attempted_field_goals'] * 100, 2))) attempted_threes = '{}-{} ({}%)'.format( score['made_three_point_field_goals'], score['attempted_three_point_field_goals'], str( round( score['made_three_point_field_goals'] / score['attempted_three_point_field_goals'] * 100, 2))) free_throws = '{}-{} ({}%)'.format( score['made_free_throws'], score['attempted_free_throws'], str( round( score['made_free_throws'] / score['attempted_free_throws'] * 100, 2))) points = score['made_free_throws'] + ( (score['made_field_goals'] - score['made_three_point_field_goals']) * 2) + (score['made_three_point_field_goals'] * 3) data = 'TOTALS: | {} | {} | {} | {} | {} | {} | {} | {} | {} | {} | {} | {} | --- |'.format( score['minutes_played'], attempted_field_goals, attempted_threes, free_throws, score['offensive_rebounds'], score['offensive_rebounds'] + score['defensive_rebounds'], score['assists'], score['turnovers'], score['steals'], score['blocks'], score['personal_fouls'], points) data += "\n" return data
def nba(jarvis, s): d = datetime.now() pyyear = int(d.strftime('%Y')) pymonth = int(d.strftime('%m')) pyday = int(d.strftime('%d')) s = client.team_box_scores(day=pyday, month=pymonth, year=pyyear) f = str(s) jarvis.say(f)
def getDataLocal(val, d=curd, m=curm, y=cury): global finstr if (val == 0): fstr = str(d) + "_" + str(m) + "_" + str( y) + "_" + "player_box_scores.json" finstr = finstr + fstr client.player_box_scores( day=d, month=m, year=y, output_type=OutputType.JSON, output_file_path= "/Users/pranavkrishnakumar/repos/BeardBot/Data/player_box_scores/" + fstr) elif (val == 1): fstr = str(d) + "_" + str(m) + "_" + str( y) + "_" + "team_box_scores.json" finstr = finstr + fstr client.team_box_scores( day=d, month=m, year=y, output_type=OutputType.JSON, output_file_path= "/Users/pranavkrishnakumar/repos/BeardBot/Data/team_box_scores/" + fstr) elif (val == 2): fstr = str(y) + "_" + "season_schedule" + ".json" finstr = finstr + fstr client.season_schedule( season_end_year=y, output_type=OutputType.JSON, output_file_path= "/Users/pranavkrishnakumar/repos/BeardBot/Data/season_schedule/" + fstr) elif (val == 3): fstr = str(y) + "_" + "season_standings" + ".json" finstr = finstr + fstr client.standings( season_end_year=y, output_type=OutputType.JSON, output_file_path= "/Users/pranavkrishnakumar/repos/BeardBot/Data/season_standings/" + fstr) return val
def test_2018_01_01_team_box_scores_json_box_scores_to_memory(self): january_first_box_scores = client.team_box_scores( day=1, month=1, year=2018, output_type=OutputType.JSON, ) with open(self.expected_file_path, encoding="utf8") as expected_json: self.assertEqual(json.loads(january_first_box_scores), json.load(expected_json))
def test_2018_01_01_team_box_scores_json_box_scores_to_memory(self): january_first_box_scores = client.team_box_scores( day=1, month=1, year=2018, output_type=OutputType.JSON, ) self.assertIsNotNone(january_first_box_scores)
def getData(val, d=curd, m=curm, y=cury): global finstr if (val == 0): return client.player_box_scores(day=d, month=m, year=y) elif (val == 1): return client.team_box_scores(day=d, month=m, year=y) elif (val == 2): return client.season_schedule(season_end_year=y) elif (val == 3): return client.standings(season_end_year=y)
def get_team_box_score(team, date_obj=None, timeout=3): """ Gets the team box score data for a specific day. :param str team: The team to search for. :param datetime.datetime date_obj: Datetime object for starting day to search. :param int timeout: Number of days to search before giving up. :return: """ if date_obj is None: date_obj = datetime.datetime.today() team_bs = None while True: if timeout > 0: team_bs = client.team_box_scores(day=date_obj.day, month=date_obj.month, year=date_obj.year) # todo date_obj -= datetime.timedelta(days=1) timeout -= 1 else: break return team_bs
def load_scores(): filename = 'ratings.csv' if os.path.exists(filename): f = open(filename) reader = csv.reader(f) rows = [] for row in reader: rows.append(row) return rows # First day of season is Oct 22, 2019. d = date(2019, 10, 22) end_date = date(2019, 10, 22) + timedelta(days=2) # end_date = datetime.now() - timedelta(days=1) games = [] while d < end_date: print('Loading scores for %s.' % d) scores = client.team_box_scores(d.day, d.month, d.year) if len(scores) % 2 != 0: raise Exception('Odd number of scores on %s!' % d) i = 0 while i < len(scores): away_stats = scores[i] home_stats = scores[i+1] games.append([away_stats['team'].name, away_stats['offensive_rating'], home_stats['team'].name, home_stats['offensive_rating']]) i += 2 d += timedelta(days=1) f = open('ratings.csv', 'w') w = csv.writer(f) for game in games: w.writerow(game) f.close() return games
def main(): print("\n#######################################################################") print("#######################################################################") print("######################### NBA Report exporter #########################") print("#######################################################################") print("#######################################################################\n") while (True): print( "1. Players box scores by a date\ \n2. Players season statistics for a season\ \n3. Players advanced season statistics for a season\ \n4. All Team box scores by a date\ \n5. Schedule for a season\ \n6. Exit" ) reportObject = input("\nPlease select a option: ") # Players box scores by a date if (reportObject == "1"): inputDate = input("\nEnter a date (use this format 1-1-2018): ") fileName = "all-player-box-report-" + inputDate + ".csv" dateList = inputDate.split("-") print("Exporting report please wait..........") # Call Export function client.player_box_scores( day=dateList[0], month=dateList[1], year=dateList[2], output_type=OutputType.CSV, output_file_path="exported_files/" + fileName ) print("Report exported at: " + abspath("exported_files/" + fileName) + "!!\n\n") # Players season statistics for a season elif (reportObject == "2"): endYear = input("\nEnter season end year: ") fileName = "all-player-season-report-" + endYear + ".csv" print("Exporting report please wait..........") # Call Export function client.players_season_totals( season_end_year=endYear, output_type=OutputType.CSV, output_file_path="exported_files/" + fileName ) print("Report exported at: " + abspath("exported_files/" + fileName) + "!!\n\n") # Players advanced season statistics for a season elif (reportObject == "3"): endYear = input("\nEnter season end year: ") fileName = "all-player-advanced-season-report-" + endYear + ".csv" print("Exporting report please wait..........") # Call Export function client.players_advanced_season_totals( season_end_year=endYear, output_type=OutputType.CSV, output_file_path="exported_files/" + fileName ) print("Report exported at: " + abspath("exported_files/" + fileName) + "!!\n\n") # All Team box scores by a date elif (reportObject == "4"): inputDate = input("\nEnter a date (use this format 1-1-2018): ") fileName = "all-team-report-" + inputDate + ".csv" dateList = inputDate.split("-") print("Exporting report please wait..........") # Call Export function client.team_box_scores( day=dateList[0], month=dateList[1], year=dateList[2], output_type=OutputType.CSV, output_file_path="exported_files/" + fileName ) print("Report exported at: " + abspath("exported_files/" + fileName) + "!!\n\n") # Schedule for a season elif (reportObject == "5"): endYear = input("\nEnter season end year: ") fileName = "season-schedule-" + endYear + ".csv" print("Exporting report please wait..........") # Call Export function client.season_schedule( season_end_year=endYear, output_type=OutputType.CSV, output_file_path="exported_files/" + fileName ) print("Report exported at: " + abspath("exported_files/" + fileName) + "!!\n\n") # Exit elif (reportObject == "6"): print("\n#######################################################################") print("################################# Bye #################################") print("#######################################################################\n") break # Error else: print("Invalid option!!\n\n")
from basketball_reference_web_scraper import client from basketball_reference_web_scraper.data import OutputType from time import sleep from os import path days = [day for day in range(1, 32)] months = [month for month in range(1, 13)] years = [year for year in range(2009, 2021)] for a_year in years: for a_month in months: for a_day in days: date = "-".join([str(a_year), str(a_month), str(a_day)]) file_path = "./game_files/" + date + "_box_scores.csv" if path.exists(file_path): pass else: client.team_box_scores(day=a_day, month=a_month, year=a_year, output_type=OutputType.CSV, output_file_path=file_path) print(date, "done") sleep(1.5)
boxscores_1 = {} boxscores_2 = {} for k, v in year_month.items(): for month in v['months']: for day in days: date_list = [ str(int(v['year'])), str(int(month)).zfill(2), str(int(day)).zfill(2) ] s = '-' date_formatted = s.join(date_list) box_score_1 = client.team_box_scores(day=int(day), month=int(month), year=int(v['year']), adv=False) box_score_2 = client.team_box_scores(day=int(day), month=int(month), year=int(v['year']), adv=True) if len(box_score_2) is not 0: boxscores_1.update({date_formatted: box_score_1}) boxscores_2.update({date_formatted: box_score_2}) output.team_box_scores_to_csv_adv(boxscores_2, '2012to2013adv.csv', 'w') output.team_box_scores_to_csv(boxscores_1, '2012to2013basic.csv', 'w') df1 = pd.read_csv('2012to2013adv.csv') df2 = pd.read_csv('2012to2013basic.csv') result = pd.concat([df2, df1], axis=1)
def test_2004_01_02_team_box_scores(self): team_box_scores = client.team_box_scores(day=2, month=1, year=2004) self.assertIsNotNone(team_box_scores)
def test_2018_01_01_team_box_scores(self): team_box_scores = client.team_box_scores(day=1, month=1, year=2018) self.assertIsNotNone(team_box_scores)
def get_team_scores(self, day, month, year): team_scores = client.team_box_scores(day, month, year) return team_scores
from basketball_reference_web_scraper import client from basketball_reference_web_scraper.data import OutputType import csv # Output all team box scores for January 1st, 2018 in JSON format to 1_1_2018_box_scores.csv client.team_box_scores(day=1, month=1, year=2018, output_type=OutputType.CSV, output_file_path="./1_1_2018_box_scores.csv") with open("schedule.csv") as schedule: next(schedule) reader = csv.reader(schedule, delimiter=',') for r in reader: date = r[0] date = date.split(' ') date = date[0].split('-') year = date[0] month = date[1] day = date[2] if (int(day) > 2 and int(month) == 1): break print(date) client.player_box_scores( day=day, month=month, year=year, output_type=OutputType.CSV, output_file_path="./allBoxScores/{}_{}_{}_box_scores.csv".format( month, day, year))
def test_2004_01_02_team_box_scores_with_new_orleans_hornets(self): team_box_scores = client.team_box_scores(day=11, month=12, year=2003) self.assertListEqual( team_box_scores, [ { "team": Team.DETROIT_PISTONS, "outcome": Outcome.LOSS, "minutes_played": 240, "made_field_goals": 28, "attempted_field_goals": 78, "made_three_point_field_goals": 3, "attempted_three_point_field_goals": 8, "made_free_throws": 27, "attempted_free_throws": 32, "offensive_rebounds": 10, "defensive_rebounds": 18, "assists": 19, "steals": 12, "blocks": 2, "turnovers": 14, "personal_fouls": 25, "points": 86, }, { "team": Team.CLEVELAND_CAVALIERS, "outcome": Outcome.WIN, "minutes_played": 240, "made_field_goals": 35, "attempted_field_goals": 66, "made_three_point_field_goals": 2, "attempted_three_point_field_goals": 5, "made_free_throws": 23, "attempted_free_throws": 30, "offensive_rebounds": 10, "defensive_rebounds": 35, "assists": 25, "steals": 6, "blocks": 9, "turnovers": 22, "personal_fouls": 30, "points": 95, }, { "team": Team.SAN_ANTONIO_SPURS, "outcome": Outcome.WIN, "minutes_played": 240, "made_field_goals": 27, "attempted_field_goals": 84, "made_three_point_field_goals": 6, "attempted_three_point_field_goals": 21, "made_free_throws": 11, "attempted_free_throws": 21, "offensive_rebounds": 15, "defensive_rebounds": 31, "assists": 17, "steals": 11, "blocks": 6, "turnovers": 12, "personal_fouls": 13, "points": 71, }, { "team": Team.HOUSTON_ROCKETS, "outcome": Outcome.LOSS, "minutes_played": 240, "made_field_goals": 30, "attempted_field_goals": 75, "made_three_point_field_goals": 2, "attempted_three_point_field_goals": 5, "made_free_throws": 5, "attempted_free_throws": 6, "offensive_rebounds": 7, "defensive_rebounds": 35, "assists": 15, "steals": 7, "blocks": 8, "turnovers": 20, "personal_fouls": 24, "points": 67, }, { "team": Team.NEW_ORLEANS_HORNETS, "outcome": Outcome.WIN, "minutes_played": 240, "made_field_goals": 40, "attempted_field_goals": 81, "made_three_point_field_goals": 10, "attempted_three_point_field_goals": 27, "made_free_throws": 21, "attempted_free_throws": 29, "offensive_rebounds": 12, "defensive_rebounds": 28, "assists": 18, "steals": 11, "blocks": 3, "turnovers": 16, "personal_fouls": 17, "points": 111, }, { "team": Team.PHOENIX_SUNS, "outcome": Outcome.LOSS, "minutes_played": 240, "made_field_goals": 40, "attempted_field_goals": 74, "made_three_point_field_goals": 9, "attempted_three_point_field_goals": 17, "made_free_throws": 12, "attempted_free_throws": 18, "offensive_rebounds": 3, "defensive_rebounds": 22, "assists": 28, "steals": 8, "blocks": 1, "turnovers": 13, "personal_fouls": 23, "points": 101, }, ] )
def test_2001_01_01_team_box_scores_with_charlotte_hornets(self): team_box_scores = client.team_box_scores(day=1, month=1, year=2001) self.assertListEqual( team_box_scores, [ { "team": Team.HOUSTON_ROCKETS, "outcome": Outcome.LOSS, "minutes_played": 240, "made_field_goals": 31, "attempted_field_goals": 77, "made_three_point_field_goals": 6, "attempted_three_point_field_goals": 17, "made_free_throws": 28, "attempted_free_throws": 37, "offensive_rebounds": 10, "defensive_rebounds": 26, "assists": 16, "steals": 4, "blocks": 3, "turnovers": 11, "personal_fouls": 19, "points": 96, }, { "team": Team.MINNESOTA_TIMBERWOLVES, "outcome": Outcome.WIN, "minutes_played": 240, "made_field_goals": 41, "attempted_field_goals": 82, "made_three_point_field_goals": 3, "attempted_three_point_field_goals": 9, "made_free_throws": 21, "attempted_free_throws": 27, "offensive_rebounds": 11, "defensive_rebounds": 36, "assists": 35, "steals": 6, "blocks": 2, "turnovers": 8, "personal_fouls": 29, "points": 106, }, { "team": Team.CHARLOTTE_HORNETS, "outcome": Outcome.LOSS, "minutes_played": 240, "made_field_goals": 26, "attempted_field_goals": 80, "made_three_point_field_goals": 3, "attempted_three_point_field_goals": 10, "made_free_throws": 12, "attempted_free_throws": 14, "offensive_rebounds": 15, "defensive_rebounds": 26, "assists": 16, "steals": 7, "blocks": 1, "turnovers": 15, "personal_fouls": 25, "points": 67, }, { "team": Team.PORTLAND_TRAIL_BLAZERS, "outcome": Outcome.WIN, "minutes_played": 240, "made_field_goals": 29, "attempted_field_goals": 70, "made_three_point_field_goals": 4, "attempted_three_point_field_goals": 15, "made_free_throws": 27, "attempted_free_throws": 30, "offensive_rebounds": 11, "defensive_rebounds": 36, "assists": 20, "steals": 8, "blocks": 4, "turnovers": 14, "personal_fouls": 17, "points": 89, } ])
def test_2018_01_01_team_box_scores(self): team_box_scores = client.team_box_scores(day=1, month=1, year=2018) self.assertListEqual( team_box_scores, [ { "team": Team.ORLANDO_MAGIC, "outcome": Outcome.LOSS, "minutes_played": 240, "made_field_goals": 35, "attempted_field_goals": 96, "made_three_point_field_goals": 6, "attempted_three_point_field_goals": 31, "made_free_throws": 19, "attempted_free_throws": 25, "offensive_rebounds": 19, "defensive_rebounds": 33, "assists": 16, "steals": 5, "blocks": 5, "turnovers": 12, "personal_fouls": 18, "points": 95, }, { "team": Team.BROOKLYN_NETS, "outcome": Outcome.WIN, "minutes_played": 240, "made_field_goals": 36, "attempted_field_goals": 82, "made_three_point_field_goals": 9, "attempted_three_point_field_goals": 25, "made_free_throws": 17, "attempted_free_throws": 23, "offensive_rebounds": 10, "defensive_rebounds": 42, "assists": 17, "steals": 7, "blocks": 10, "turnovers": 13, "personal_fouls": 22, "points": 98, }, { "team": Team.PORTLAND_TRAIL_BLAZERS, "outcome": Outcome.WIN, "minutes_played": 265, "made_field_goals": 47, "attempted_field_goals": 108, "made_three_point_field_goals": 14, "attempted_three_point_field_goals": 33, "made_free_throws": 16, "attempted_free_throws": 18, "offensive_rebounds": 12, "defensive_rebounds": 38, "assists": 25, "steals": 7, "blocks": 5, "turnovers": 8, "personal_fouls": 16, "points": 124, }, { "team": Team.CHICAGO_BULLS, "outcome": Outcome.LOSS, "minutes_played": 265, "made_field_goals": 45, "attempted_field_goals": 104, "made_three_point_field_goals": 11, "attempted_three_point_field_goals": 27, "made_free_throws": 19, "attempted_free_throws": 23, "offensive_rebounds": 15, "defensive_rebounds": 43, "assists": 28, "steals": 5, "blocks": 7, "turnovers": 12, "personal_fouls": 21, "points": 120, }, { "team": Team.LOS_ANGELES_LAKERS, "outcome": Outcome.LOSS, "minutes_played": 240, "made_field_goals": 34, "attempted_field_goals": 76, "made_three_point_field_goals": 8, "attempted_three_point_field_goals": 26, "made_free_throws": 20, "attempted_free_throws": 29, "offensive_rebounds": 9, "defensive_rebounds": 28, "assists": 18, "steals": 12, "blocks": 4, "turnovers": 24, "personal_fouls": 25, "points": 96, }, { "team": Team.MINNESOTA_TIMBERWOLVES, "outcome": Outcome.WIN, "minutes_played": 240, "made_field_goals": 40, "attempted_field_goals": 81, "made_three_point_field_goals": 7, "attempted_three_point_field_goals": 20, "made_free_throws": 27, "attempted_free_throws": 30, "offensive_rebounds": 7, "defensive_rebounds": 34, "assists": 26, "steals": 14, "blocks": 5, "turnovers": 17, "personal_fouls": 24, "points": 114, }, { "team": Team.MILWAUKEE_BUCKS, "outcome": Outcome.LOSS, "minutes_played": 265, "made_field_goals": 44, "attempted_field_goals": 93, "made_three_point_field_goals": 13, "attempted_three_point_field_goals": 27, "made_free_throws": 26, "attempted_free_throws": 28, "offensive_rebounds": 10, "defensive_rebounds": 33, "assists": 27, "steals": 9, "blocks": 3, "turnovers": 14, "personal_fouls": 23, "points": 127, }, { "team": Team.TORONTO_RAPTORS, "outcome": Outcome.WIN, "minutes_played": 265, "made_field_goals": 45, "attempted_field_goals": 91, "made_three_point_field_goals": 14, "attempted_three_point_field_goals": 33, "made_free_throws": 27, "attempted_free_throws": 33, "offensive_rebounds": 6, "defensive_rebounds": 34, "assists": 25, "steals": 8, "blocks": 8, "turnovers": 12, "personal_fouls": 20, "points": 131, }, ] )
def test_2019_10_22_has_four_team_box_scores(self): team_box_scores = client.team_box_scores(day=22, month=10, year=2019) self.assertEqual(4, len(team_box_scores))