def build_2018_line_dict():
    new_lines = []
    with open(FILENAME_2018, "r") as csvfile:
        readCSV = csv.reader(csvfile, delimiter=",")
        next(readCSV, None)
        readCSV = list(readCSV)
        for i in range(0, len(readCSV) - 1, 2):
            new_lines.append((readCSV[i][3], readCSV[i + 1][3], readCSV[i][11],
                              readCSV[i + 1][11]))

    new_and_improved_lines = []
    for game in new_lines:
        full_away_team_info = teams.find_teams_by_city(game[0])
        if len(full_away_team_info) == 0:
            new_name = resolve_ambiguous_name(game[0])
            full_away_team_info = teams.find_team_by_abbreviation(new_name)

        full_home_team_info = teams.find_teams_by_city(game[1])
        if len(full_home_team_info) == 0:
            new_name = resolve_ambiguous_name(game[1])
            full_home_team_info = teams.find_team_by_abbreviation(new_name)

        new_games = []

        if type(full_away_team_info) is list:
            full_away_team_info = full_away_team_info[0]

        if type(full_home_team_info) is list:
            full_home_team_info = full_home_team_info[0]

        new_games.append(full_away_team_info["id"])
        new_games.append(full_home_team_info["id"])
        new_games.append(game[2])
        new_games.append(game[3])

        new_and_improved_lines.append(new_games)

    game_dict = {}
    game_counter = 21800001
    for i in range(1230):
        game_dict[game_counter + i] = 0

    final_game_list = []
    for game in new_and_improved_lines:
        for key in game_dict:
            if game_dict[key] == 0:
                boxscore = file_dumps.read_json(f"games2018/00{key}")
                away_team_id = boxscore[0][1]
                home_team_id = boxscore[-1][1]

                if away_team_id == game[0] and home_team_id == game[1]:
                    game_dict[key] = 1
                    final_game_list.append(
                        (boxscore[0][0], game[0], game[1], game[2], game[3]))
                    break
    line_dict = {}
    for game in final_game_list:
        line_dict[int(game[0])] = (int(game[3]), int(game[4]))
    return line_dict
Exemple #2
0
def print_team_stats(team_abbr):
    tid = teams.find_team_by_abbreviation(team_abbr.lower())["id"]
    df = teamplayerdashboard.TeamPlayerDashboard(
        tid, per_mode_detailed=PerModeDetailed.per_game).get_data_frames()[1]

    def splits(row):
        return "/".join([
            str(round(row[field] * 100))
            for field in ("FG_PCT", "FG3_PCT", "FT_PCT")
        ])

    df["SCORING"] = df.apply(lambda row: splits(row), axis=1)
    outdf = df[[
        "PLAYER_NAME",
        "GP",
        "MIN",
        "SCORING",
        "PTS",
        "REB",
        "AST",
        "TOV",
        "STL",
        "BLK",
    ]]

    print(
        tabulate.tabulate(
            outdf.sort_values("MIN", ascending=False),
            headers="keys",
            showindex="never",
            floatfmt=".1f",
        ))
Exemple #3
0
    def __get_player_raw_gamelogs(self, player_name):
        """Hidden method that returns a player's gamelog given a player's name
        
        Args:
            player_name (str): Player's complete name (ex: Nikola Vucevic)
        
        Returns:
            gamelog_df: pd.DataFrame
        """
        player_id = self.__fetch_player_id(player_name)
        logger.info("Gathering gamelogs for player " + str(player_name) +
                    "...")
        gamelog = playergamelog.PlayerGameLog(player_id=player_id)

        gamelog_df = gamelog.get_data_frames()[0]

        gamelog_df.loc[:,
                       "GAME_DATE"] = pd.to_datetime(gamelog_df["GAME_DATE"])

        gamelog_df.loc[:, "Team"] = gamelog_df["MATCHUP"].astype(str).str[0:3]

        gamelog_df.loc[:, "Team_ID"] = gamelog_df["Team"].apply(
            lambda x: teams.find_team_by_abbreviation(x)["id"])
        # round minutes up (sports ws seems to do that)
        #TODO minute comes already rounded up. Try to solve this, although
        # it is probably very complicated
        gamelog_df.loc[:,
                       "MIN"] = gamelog_df["MIN"].apply(lambda x: math.ceil(x))

        gamelog_df = gamelog_df.drop(["Team", "PLUS_MINUS", "VIDEO_AVAILABLE"],
                                     axis=1)

        return gamelog_df
Exemple #4
0
def print_boxscore(team_abbr):
    game_id = (teamgamelog.TeamGameLog(
        teams.find_team_by_abbreviation(
            team_abbr.lower())["id"]).get_data_frames()[0].iloc[0].Game_ID)

    b = (boxscoretraditionalv2.BoxScoreTraditionalV2(
        game_id).get_data_frames()[0].dropna())
    b["PLAYER"] = b["PLAYER_NAME"].apply(
        lambda s: s.ljust(b.PLAYER_NAME.str.len().max(), " "))
    b.MIN = b.MIN.str.rjust(5, "0")
    for field in ["FGM", "FGA", "FG3M", "FG3A", "FTM", "FTA"]:
        b[field] = b[field].fillna(0).astype(int)

    b["FG"] = (b["FGM"].map(str) + "-" + b["FGA"].map(str)).str.pad(5)
    b["FG3"] = (b["FG3M"].map(str) + "-" + b["FG3A"].map(str)).str.pad(5)
    b["FT"] = (b["FTM"].map(str) + "-" + b["FTA"].map(str)).str.pad(5)

    for team_name, bscore in b.groupby("TEAM_ABBREVIATION"):
        print(team_name)

        tabulate.PRESERVE_WHITESPACE = True
        outb = bscore[[
            "PLAYER", "MIN", "FG", "FG3", "FT", "REB", "AST", "STL", "BLK",
            "TO", "PF", "PTS"
        ]]
        print(tabulate.tabulate(outb, headers="keys", showindex="never"))
        tabulate.PRESERVE_WHITESPACE = False
Exemple #5
0
def list_team_api(request, team_code=None):
    if request.method == 'GET':
        response = Response()  # Create a rest_framework.Response object
        response[
            'Content-type'] = 'application/json'  # Set it up as a json response
        team_found = teams.find_team_by_abbreviation(abbreviation=team_code)
        if team_found is None:
            response.status_code = 400
            response.data = {'NOT VALID ABBREVIATION'}
            return response
        else:
            return render(request, 'list_team.html', team_found)

    elif request.method == 'POST':
        abbreviation: str = request.data.get('team_field')
        team_found = teams.find_team_by_abbreviation(abbreviation=abbreviation)

        return render(request, 'list_team.html', team_found)
Exemple #6
0
def teamopponentstatpull(teamabb, season=2020): ##retrieve a team's entire opponent box scores over a season
    team=teams.find_team_by_abbreviation(teamabb)
    games=teamgamelog.TeamGameLog(team_id=team.get("id"),season=season)
    games=(games.get_data_frames())[0]
    gameids=games['Game_ID']
    outcome=pd.DataFrame()
    for i in range (len (gameids)):
        temp=gamestatgen(gameids[i],teamabb)
        outcome=outcome.append(temp)
    outcome=outcome.dropna()
    return outcome
Exemple #7
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
    ]
Exemple #8
0
 def Kings(self):
     from nba_api.stats.static import teams
     kings = teams.find_team_by_abbreviation('sac')
     kingsid = kings['id']
Exemple #9
0
def lal():
    hometeam = teams.find_team_by_abbreviation("LAL")
    return render_template("lakers.html",
                           city=hometeam[0]["city"],
                           state=hometeam[0]["state"],
                           year=hometeam[0]["year_founded"])
Exemple #10
0
    def get_lineup_data(self):
        helpers = Helpers()

        team_to_opp_team = {}
        team_to_status = {}

        current_player_data = pd.DataFrame(columns=[
            'TEAM', 'NAME', 'START', 'PLAYERSTATUS', 'PLAYERCHANCE'
        ])

        URL = 'https://www.rotowire.com/basketball/nba-lineups.php'
        page = requests.get(URL)
        soup = BeautifulSoup(page.content, 'html.parser')

        games = soup.find_all('div', class_='lineup is-nba')
        for game in games:
            away_team = game.find('a', class_='lineup__team is-visit').find('div', class_='lineup__abbr').text
            away_team = helpers.prepare_team(away_team)
            away_lineup = game.find('ul', class_='lineup__list is-visit')
            away_player_data, away_lineup_status = helpers.get_player_data(away_lineup)
            away_player_data['TEAM'] = away_team
            away_player_data['NAME'] = away_player_data['NAME'].apply(lambda x: helpers.prepare_name(x, away_team))

            home_team = game.find('a', class_='lineup__team is-home').find('div', class_='lineup__abbr').text
            home_team = helpers.prepare_team(home_team)
            home_lineup = game.find('ul', class_='lineup__list is-home')
            home_player_data, home_lineup_status = helpers.get_player_data(home_lineup)
            home_player_data['TEAM'] = home_team
            home_player_data['NAME'] = home_player_data['NAME'].apply(lambda x: helpers.prepare_name(x, home_team))
            
            team_to_opp_team[away_team] = home_team
            team_to_opp_team[home_team] = away_team
            team_to_status[away_team] = away_lineup_status
            team_to_status[home_team] = home_lineup_status
            
            current_player_data = current_player_data.append(away_player_data)
            current_player_data = current_player_data.append(home_player_data)
        
        current_player_data = current_player_data.loc[
            ~current_player_data['NAME'].isin(UNKNOWN_PLAYERS)
        ]

        roster_data = pd.DataFrame()
        for team_abbreviation in current_player_data['TEAM'].unique():
            team = find_team_by_abbreviation(team_abbreviation)
            team_id = team['id']

            roster = CommonTeamRoster(season=CURRENT_SEASON, team_id=team_id).get_data_frames()[0]
            time.sleep(0.500)
            
            roster['TEAM'] = team['abbreviation']

            roster_data = roster_data.append(roster)

        roster_data = roster_data.rename(columns={'TeamID': 'TEAMID', 'PLAYER_ID': 'PLAYERID', 'PLAYER': 'NAME'})

        roster_data['POSITION'] = roster_data['POSITION'].str.replace('G', 'Guard')
        roster_data['POSITION'] = roster_data['POSITION'].str.replace('F', 'Forward')
        roster_data['POSITION'] = roster_data['POSITION'].str.replace('C', 'Center')

        current_data = roster_data.merge(current_player_data, on=['NAME', 'TEAM'], how='left')

        current_data['LINEUPSTATUS'] = current_data['TEAM'].apply(lambda x: team_to_status[x])
        current_data['OPP_TEAM'] = current_data['TEAM'].apply(lambda x: team_to_opp_team[x])

        current_data['START'] = current_data['START'].fillna(0)
        current_data['PLAYERSTATUS'] = current_data['PLAYERSTATUS'].fillna('Healthy')
        current_data['PLAYERCHANCE'] = current_data['PLAYERCHANCE'].fillna(100)
        current_data['SEASON'] = CURRENT_SEASON

        current_data = current_data[[
            'SEASON', 'LINEUPSTATUS', 'PLAYERID', 'TEAM', 'OPP_TEAM', 'NAME', 'POSITION',
            'START', 'PLAYERSTATUS', 'PLAYERCHANCE'
            ]]

        missing_players = current_player_data.loc[
            ~current_player_data['NAME'].isin(roster_data['NAME'].unique())
            ]['NAME'].unique()

        if len(missing_players) > 0:
            raise Exception('Unknown player names in rotowire projected lineups: {}'.format(','.join(missing_players)))

        return current_data
Exemple #11
0
def get_roster(team_abbr):
    roster = commonteamroster.CommonTeamRoster(
        teams.find_team_by_abbreviation(team_abbr.lower())["id"])
    return roster.get_data_frames()[0]
Exemple #12
0
import numpy

from nba_api.stats.endpoints import leaguegamefinder
from nba_api.stats.static import teams

nba_teams = teams.get_teams()
team_abbreviations = []

rows = []

for team in nba_teams:
    team_abbreviations.append(team['abbreviation'])

for abb in team_abbreviations:
    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']
    for x in range(0, 20):
        print("Processing games for " + abb)
        game = games.iloc[x]
        points = game.PTS
        field_goals_attempted = game.FGA
        field_goal_percentage = game.FG_PCT
        field_goal_3_attempted = game.FG3A
        field_goal_3_percentage = game.FG3_PCT
        free_throws_made = game.FTM
        offensive_rebounds = game.OREB
        defensive_rebounds = game.DREB
Exemple #13
0
parser = argparse.ArgumentParser()
parser.add_argument("--teams", "-t", help="Supply two teams to calculate against", nargs=2);
args = parser.parse_args()

# print(args.teams)

gdf = pd.read_csv('2019_scores.csv')
gdf.columns

team1 = args.teams[0]
team2 = args.teams[1]
# print("Teams", args.teams)


team1Return = teams.find_team_by_abbreviation(team1)
team2Return = teams.find_team_by_abbreviation(team2)
# print(team1Return)
# print(team2Return)

# Check for teams last 5 games results

gamefinder1 = leaguegamefinder.LeagueGameFinder(team_id_nullable=team1Return["id"])
# The first DataFrame of those returned is what we want.
games1 = gamefinder1.get_data_frames()[0]
#print(games1)
team1Record = games1.head()["WL"]

gamefinder2 = leaguegamefinder.LeagueGameFinder(team_id_nullable=team2Return["id"])
# The first DataFrame of those returned is what we want.
games2 = gamefinder2.get_data_frames()[0]