Search is not available for this dataset
text
stringlengths
75
104k
def choice_input(options=[], prompt='Press ENTER to continue.', showopts=True, qopt=False): """Get input from a list of choices (q to quit)""" choice = None if showopts: prompt = prompt + ' ' + str(options) if qopt: prompt = prompt + ' (q to quit)' while not choice: ...
def long_input(prompt='Multi-line input\n' + \ 'Enter EOF on a blank line to end ' + \ '(ctrl-D in *nix, ctrl-Z in windows)', maxlines = None, maxlength = None): """Get a multi-line string as input""" lines = [] print(prompt) lnum = 1 try: while True: ...
def list_input(prompt='List input - enter each item on a seperate line\n' + \ 'Enter EOF on a blank line to end ' + \ '(ctrl-D in *nix, ctrl-Z in windows)', maxitems=None, maxlength=None): """Get a list of strings as input""" lines = [] print(prompt) inum = 1 try: ...
def outfile_input(extension=None): """Get an output file name as input""" fileok = False while not fileok: filename = string_input('File name? ') if extension: if not filename.endswith(extension): if extension.startswith('.'): filenam...
def roster(self, year): """Returns the roster table for the given year. :year: The year for which we want the roster; defaults to current year. :returns: A DataFrame containing roster information for that year. """ doc = self.get_year_doc(year) table = doc('table#roster'...
def schedule(self, year): """Gets schedule information for a team-season. :year: The year for which we want the schedule. :returns: DataFrame of schedule information. """ doc = self.get_year_doc('{}_games'.format(year)) table = doc('table#games') df = sportsref.u...
def date(self): """Returns the date of the game. See Python datetime.date documentation for more. :returns: A datetime.date object with year, month, and day attributes. """ match = re.match(r'(\d{4})(\d{2})(\d{2})', self.boxscore_id) year, month, day = map(int, match.grou...
def weekday(self): """Returns the day of the week on which the game occurred. :returns: String representation of the day of the week for the game. """ days = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'] date = self.date() ...
def home(self): """Returns home team ID. :returns: 3-character string representing home team's ID. """ doc = self.get_doc() table = doc('table.linescore') relURL = table('tr').eq(2)('a').eq(2).attr['href'] home = sportsref.utils.rel_url_to_id(relURL) retur...
def home_score(self): """Returns score of the home team. :returns: int of the home score. """ doc = self.get_doc() table = doc('table.linescore') home_score = table('tr').eq(2)('td')[-1].text_content() return int(home_score)
def away_score(self): """Returns score of the away team. :returns: int of the away score. """ doc = self.get_doc() table = doc('table.linescore') away_score = table('tr').eq(1)('td')[-1].text_content() return int(away_score)
def winner(self): """Returns the team ID of the winning team. Returns NaN if a tie.""" hmScore = self.home_score() awScore = self.away_score() if hmScore > awScore: return self.home() elif hmScore < awScore: return self.away() else: ret...
def week(self): """Returns the week in which this game took place. 18 is WC round, 19 is Div round, 20 is CC round, 21 is SB. :returns: Integer from 1 to 21. """ doc = self.get_doc() raw = doc('div#div_other_scores h2 a').attr['href'] match = re.match( ...
def season(self): """ Returns the year ID of the season in which this game took place. Useful for week 17 January games. :returns: An int representing the year of the season. """ date = self.date() return date.year - 1 if date.month <= 3 else date.year
def starters(self): """Returns a DataFrame where each row is an entry in the starters table from PFR. The columns are: * player_id - the PFR player ID for the player (note that this column is not necessarily all unique; that is, one player can be a starter in multiple po...
def surface(self): """The playing surface on which the game was played. :returns: string representing the type of surface. Returns np.nan if not avaiable. """ doc = self.get_doc() table = doc('table#game_info') giTable = sportsref.utils.parse_info_table(table) ...
def over_under(self): """ Returns the over/under for the game as a float, or np.nan if not available. """ doc = self.get_doc() table = doc('table#game_info') giTable = sportsref.utils.parse_info_table(table) if 'over_under' in giTable: ou = giT...
def coin_toss(self): """Gets information relating to the opening coin toss. Keys are: * wonToss - contains the ID of the team that won the toss * deferred - bool whether the team that won the toss deferred it :returns: Dictionary of coin toss-related info. """ d...
def weather(self): """Returns a dictionary of weather-related info. Keys of the returned dict: * temp * windChill * relHumidity * windMPH :returns: Dict of weather data. """ doc = self.get_doc() table = doc('table#game_info') giTa...
def pbp(self): """Returns a dataframe of the play-by-play data from the game. Order of function calls: 1. parse_table on the play-by-play table 2. expand_details - calls parse_play_details & _clean_features 3. _add_team_columns 4. various ...
def ref_info(self): """Gets a dictionary of ref positions and the ref IDs of the refs for that game. :returns: A dictionary of ref positions and IDs. """ doc = self.get_doc() table = doc('table#officials') return sportsref.utils.parse_info_table(table)
def player_stats(self): """Gets the stats for offense, defense, returning, and kicking of individual players in the game. :returns: A DataFrame containing individual player stats. """ doc = self.get_doc() tableIDs = ('player_offense', 'player_defense', 'returns', 'kicking...
def snap_counts(self): """Gets the snap counts for both teams' players and returns them in a DataFrame. Note: only goes back to 2012. :returns: DataFrame of snap count data """ # TODO: combine duplicate players, see 201312150mia - ThomDa03 doc = self.get_doc() ta...
def get_main_doc(self): """Returns PyQuery object for the main season URL. :returns: PyQuery object. """ url = (sportsref.nba.BASE_URL + '/leagues/NBA_{}.html'.format(self.yr)) return pq(sportsref.utils.get_html(url))
def get_sub_doc(self, subpage): """Returns PyQuery object for a given subpage URL. :subpage: The subpage of the season, e.g. 'per_game'. :returns: PyQuery object. """ html = sportsref.utils.get_html(self._subpage_url(subpage)) return pq(html)
def get_team_ids(self): """Returns a list of the team IDs for the given year. :returns: List of team IDs. """ df = self.team_stats_per_game() if not df.empty: return df.index.tolist() else: print('ERROR: no teams found') return []
def team_ids_to_names(self): """Mapping from 3-letter team IDs to full team names. :returns: Dictionary with team IDs as keys and full team strings as values. """ doc = self.get_main_doc() table = doc('table#team-stats-per_game') flattened = sportsref.utils.parse_...
def team_names_to_ids(self): """Mapping from full team names to 3-letter team IDs. :returns: Dictionary with tean names as keys and team IDs as values. """ d = self.team_ids_to_names() return {v: k for k, v in d.items()}
def schedule(self, kind='R'): """Returns a list of BoxScore IDs for every game in the season. Only needs to handle 'R' or 'P' options because decorator handles 'B'. :param kind: 'R' for regular season, 'P' for playoffs, 'B' for both. Defaults to 'R'. :returns: DataFrame of s...
def standings(self): """Returns a DataFrame containing standings information.""" doc = self.get_sub_doc('standings') east_table = doc('table#divs_standings_E') east_df = pd.DataFrame(sportsref.utils.parse_table(east_table)) east_df.sort_values('wins', ascending=False, inplace=Tr...
def _get_team_stats_table(self, selector): """Helper function for stats tables on season pages. Returns a DataFrame.""" doc = self.get_main_doc() table = doc(selector) df = sportsref.utils.parse_table(table) df.set_index('team_id', inplace=True) return df
def _get_player_stats_table(self, identifier): """Helper function for player season stats. :identifier: string identifying the type of stat, e.g. 'per_game'. :returns: A DataFrame of stats. """ doc = self.get_sub_doc(identifier) table = doc('table#{}_stats'.format(identi...
def roy_voting(self): """Returns a DataFrame containing information about ROY voting.""" url = '{}/awards/awards_{}.html'.format(sportsref.nba.BASE_URL, self.yr) doc = pq(sportsref.utils.get_html(url)) table = doc('table#roy') df = sportsref.utils.parse_table(table) retur...
def linescore(self): """Returns the linescore for the game as a DataFrame.""" doc = self.get_main_doc() table = doc('table#line_score') columns = [th.text() for th in table('tr.thead').items('th')] columns[0] = 'team_id' data = [ [sportsref.utils.flatten_lin...
def season(self): """ Returns the year ID of the season in which this game took place. :returns: An int representing the year of the season. """ d = self.date() if d.month >= 9: return d.year + 1 else: return d.year
def _get_player_stats(self, table_id_fmt): """Returns a DataFrame of player stats from the game (either basic or advanced, depending on the argument. :param table_id_fmt: Format string for str.format with a placeholder for the team ID (e.g. 'box_{}_basic') :returns: DataFram...
def pbp(self, dense_lineups=False, sparse_lineups=False): """Returns a dataframe of the play-by-play data from the game. :param dense_lineups: If True, adds 10 columns containing the names of the players on the court. Defaults to False. :param sparse_lineups: If True, adds binary co...
def switch_to_dir(dirPath): """ Decorator that switches to given directory before executing function, and then returning to orignal directory. """ def decorator(func): @funcutils.wraps(func) def wrapper(*args, **kwargs): orig_cwd = os.getcwd() os.chdir(dirPat...
def cache(func): """Caches the HTML returned by the specified function `func`. Caches it in the user cache determined by the appdirs package. """ CACHE_DIR = appdirs.user_cache_dir('sportsref', getpass.getuser()) if not os.path.isdir(CACHE_DIR): os.makedirs(CACHE_DIR) @funcutils.wraps(...
def get_class_instance_key(cls, args, kwargs): """ Returns a unique identifier for a class instantiation. """ l = [id(cls)] for arg in args: l.append(id(arg)) l.extend((k, id(v)) for k, v in kwargs.items()) return tuple(sorted(l))
def memoize(fun): """A decorator for memoizing functions. Only works on functions that take simple arguments - arguments that take list-like or dict-like arguments will not be memoized, and this function will raise a TypeError. """ @funcutils.wraps(fun) def wrapper(*args, **kwargs): ...
def age(self, year, month=2, day=1): """Returns the age of the player on a given date. :year: int representing the year. :month: int representing the month (1-12). :day: int representing the day within the month (1-31). :returns: Age in years as a float. """ doc ...
def height(self): """Returns the player's height (in inches). :returns: An int representing a player's height in inches. """ doc = self.get_main_doc() raw = doc('span[itemprop="height"]').text() try: feet, inches = map(int, raw.split('-')) return f...
def weight(self): """Returns the player's weight (in pounds). :returns: An int representing a player's weight in pounds. """ doc = self.get_main_doc() raw = doc('span[itemprop="weight"]').text() try: weight = re.match(r'(\d+)lb', raw).group(1) retu...
def hand(self): """Returns the player's handedness. :returns: 'L' for left-handed, 'R' for right-handed. """ doc = self.get_main_doc() hand = re.search(r'Shoots:\s*(L|R)', doc.text()).group(1) return hand
def draft_pick(self): """Returns when in the draft the player was picked. :returns: TODO """ doc = self.get_main_doc() try: p_tags = doc('div#meta p') draft_p_tag = next(p for p in p_tags.items() if p.text().lower().startswith('draft')) draft_p...
def _get_stats_table(self, table_id, kind='R', summary=False): """Gets a stats table from the player page; helper function that does the work for per-game, per-100-poss, etc. stats. :table_id: the ID of the HTML table. :kind: specifies regular season, playoffs, or both. One of 'R', 'P',...
def stats_per_game(self, kind='R', summary=False): """Returns a DataFrame of per-game box score stats.""" return self._get_stats_table('per_game', kind=kind, summary=summary)
def stats_totals(self, kind='R', summary=False): """Returns a DataFrame of total box score statistics by season.""" return self._get_stats_table('totals', kind=kind, summary=summary)
def stats_per36(self, kind='R', summary=False): """Returns a DataFrame of per-36-minutes stats.""" return self._get_stats_table('per_minute', kind=kind, summary=summary)
def stats_per100(self, kind='R', summary=False): """Returns a DataFrame of per-100-possession stats.""" return self._get_stats_table('per_poss', kind=kind, summary=summary)
def stats_advanced(self, kind='R', summary=False): """Returns a DataFrame of advanced stats.""" return self._get_stats_table('advanced', kind=kind, summary=summary)
def stats_shooting(self, kind='R', summary=False): """Returns a DataFrame of shooting stats.""" return self._get_stats_table('shooting', kind=kind, summary=summary)
def stats_pbp(self, kind='R', summary=False): """Returns a DataFrame of play-by-play stats.""" return self._get_stats_table('advanced_pbp', kind=kind, summary=summary)
def gamelog_basic(self, year, kind='R'): """Returns a table of a player's basic game-by-game stats for a season. :param year: The year representing the desired season. :param kind: specifies regular season, playoffs, or both. One of 'R', 'P', 'B'. Defaults to 'R'. :returns: ...
def parse_play(boxscore_id, details, is_hm): """Parse play details from a play-by-play string describing a play. Assuming valid input, this function returns structured data in a dictionary describing the play. If the play detail string was invalid, this function returns None. :param boxscore_id: t...
def clean_features(df): """Fixes up columns of the passed DataFrame, such as casting T/F columns to boolean and filling in NaNs for team and opp. :param df: DataFrame of play-by-play data. :returns: Dataframe with cleaned columns. """ df = pd.DataFrame(df) bool_vals = set([True, False, Non...
def clean_multigame_features(df): """TODO: Docstring for clean_multigame_features. :df: TODO :returns: TODO """ df = pd.DataFrame(df) if df.index.value_counts().max() > 1: df.reset_index(drop=True, inplace=True) df = clean_features(df) # if it's many games in one DataFrame, ma...
def get_period_starters(df): """TODO """ def players_from_play(play): """Figures out what players are in the game based on the players mentioned in a play. Returns away and home players as two sets. :param play: A dictionary representing a parsed play. :returns: (aw_players...
def get_sparse_lineups(df): """TODO: Docstring for get_sparse_lineups. :param df: TODO :returns: TODO """ # get the lineup data using get_dense_lineups if necessary if (set(ALL_LINEUP_COLS) - set(df.columns)): lineup_df = get_dense_lineups(df) else: lineup_df = df[ALL_LINEU...
def get_dense_lineups(df): """Returns a new DataFrame based on the one it is passed. Specifically, it adds five columns for each team (ten total), where each column has the ID of a player on the court during the play. This information is figured out sequentially from the game's substitution data in...
def GamePlayFinder(**kwargs): """ Docstring will be filled in by __init__.py """ querystring = _kwargs_to_qs(**kwargs) url = '{}?{}'.format(GPF_URL, querystring) # if verbose, print url if kwargs.get('verbose', False): print(url) html = utils.get_html(url) doc = pq(html) # pars...
def _kwargs_to_qs(**kwargs): """Converts kwargs given to GPF to a querystring. :returns: the querystring. """ # start with defaults inpOptDef = inputs_options_defaults() opts = { name: dct['value'] for name, dct in inpOptDef.items() } # clean up keys and values for ...
def inputs_options_defaults(): """Handles scraping options for play finder form. :returns: {'name1': {'value': val, 'options': [opt1, ...] }, ... } """ # set time variables if os.path.isfile(GPF_CONSTANTS_FILENAME): modtime = int(os.path.getmtime(GPF_CONSTANTS_FILENAME)) curtime = ...
def get(self): ''' Please don't do this in production environments. ''' self.write("Memory Session Object Demo:") if "sv" in self.session: current_value = self.session["sv"] self.write("current sv value is %s, and system will delete this value.<br/>" % sel...
def expand_details(df, detailCol='detail'): """Expands the details column of the given dataframe and returns the resulting DataFrame. :df: The input DataFrame. :detailCol: The detail column name. :returns: Returns DataFrame with new columns from pbp parsing. """ df = copy.deepcopy(df) d...
def parse_play_details(details): """Parses play details from play-by-play string and returns structured data. :details: detail string for play :returns: dictionary of play attributes """ # if input isn't a string, return None if not isinstance(details, basestring): return None ...
def _clean_features(struct): """Cleans up the features collected in parse_play_details. :struct: Pandas Series of features parsed from details string. :returns: the same dict, but with cleaner features (e.g., convert bools, ints, etc.) """ struct = dict(struct) # First, clean up play type b...
def _loc_to_features(loc): """Converts a location string "{Half}, {YardLine}" into a tuple of those values, the second being an int. :l: The string from the play by play table representing location. :returns: A tuple that separates out the values, making them missing (np.nan) when necessary. "...
def _add_team_columns(features): """Function that adds 'team' and 'opp' columns to the features by iterating through the rows in order. A precondition is that the features dicts are in order in a continuous game sense and that all rows are from the same game. :features: A DataFrame with each row repres...
def _team_and_opp(struct, curTm=None, curOpp=None): """Given a dict representing a play and the current team with the ball, returns (team, opp) where team is the team with the ball and opp is the team without the ball at the end of the play. :struct: A Series/dict representing the play. :curTm: The...
def _add_team_features(df): """Adds extra convenience features based on teams with and without possession, with the precondition that the there are 'team' and 'opp' specified in row. :df: A DataFrame representing a game's play-by-play data after _clean_features has been called and 'team' and 'o...
def _get_player_stats_table(self, subpage, table_id): """Helper function for player season stats. :identifier: string identifying the type of stat, e.g. 'passing'. :returns: A DataFrame of stats. """ doc = self.get_sub_doc(subpage) table = doc('table#{}'.format(table_id)...
def initialWinProb(line): """Gets the initial win probability of a game given its Vegas line. :line: The Vegas line from the home team's perspective (negative means home team is favored). :returns: A float in [0., 100.] that represents the win probability. """ line = float(line) probWin = 1...
def gamelog(self, year=None, kind='R'): """Gets the career gamelog of the given player. :kind: One of 'R', 'P', or 'B' (for regular season, playoffs, or both). Case-insensitive; defaults to 'R'. :year: The year for which the gamelog should be returned; if None, return entire care...
def passing(self, kind='R'): """Gets yearly passing stats for the player. :kind: One of 'R', 'P', or 'B'. Case-insensitive; defaults to 'R'. :returns: Pandas DataFrame with passing stats. """ doc = self.get_doc() table = (doc('table#passing') if kind == 'R' else ...
def rushing_and_receiving(self, kind='R'): """Gets yearly rushing/receiving stats for the player. :kind: One of 'R', 'P', or 'B'. Case-insensitive; defaults to 'R'. :returns: Pandas DataFrame with rushing/receiving stats. """ doc = self.get_doc() table = (doc('table#rush...
def _plays(self, year, play_type, expand_details): """Returns a DataFrame of plays for a given year for a given play type (like rushing, receiving, or passing). :year: The year for the season. :play_type: A type of play for which there are plays (as of this writing, either "pass...
def advanced_splits(self, year=None): """Returns a DataFrame of advanced splits data for a player-year. Note: only go back to 2012. :year: The year for the season in question. If None, returns career advanced splits. :returns: A DataFrame of advanced splits data. """...
def _simple_year_award(self, award_id): """Template for simple award functions that simply list years, such as pro bowls and first-team all pro. :award_id: The div ID that is appended to "leaderboard_" in selecting the table's div. :returns: List of years for the award. ...
def team_names(year): """Returns a mapping from team ID to full team name for a given season. Example of a full team name: "New England Patriots" :year: The year of the season in question (as an int). :returns: A dictionary with teamID keys and full team name values. """ doc = pq(sportsref.util...
def team_ids(year): """Returns a mapping from team name to team ID for a given season. Inverse mapping of team_names. Example of a full team name: "New England Patriots" :year: The year of the season in question (as an int). :returns: A dictionary with full team name keys and teamID values. """ ...
def name(self): """Returns the real name of the franchise given the team ID. Examples: 'nwe' -> 'New England Patriots' 'sea' -> 'Seattle Seahawks' :returns: A string corresponding to the team's full name. """ doc = self.get_main_doc() headerwords = doc('...
def roster(self, year): """Returns the roster table for the given year. :year: The year for which we want the roster; defaults to current year. :returns: A DataFrame containing roster information for that year. """ doc = self.get_year_doc('{}_roster'.format(year)) roster...
def boxscores(self, year): """Gets list of BoxScore objects corresponding to the box scores from that year. :year: The year for which we want the boxscores; defaults to current year. :returns: np.array of strings representing boxscore IDs. """ doc = self.get_year...
def _year_info_pq(self, year, keyword): """Returns a PyQuery object containing the info from the meta div at the top of the team year page with the given keyword. :year: Int representing the season. :keyword: A keyword to filter to a single p tag in the meta div. :returns: A PyQ...
def head_coaches_by_game(self, year): """Returns head coach data by game. :year: An int representing the season in question. :returns: An array with an entry per game of the season that the team played (including playoffs). Each entry is the head coach's ID for that game in the ...
def wins(self, year): """Returns the # of regular season wins a team in a year. :year: The year for the season in question. :returns: The number of regular season wins. """ schedule = self.schedule(year) if schedule.empty: return np.nan return schedul...
def schedule(self, year): """Returns a DataFrame with schedule information for the given year. :year: The year for the season in question. :returns: Pandas DataFrame with schedule information. """ doc = self.get_year_doc(year) table = doc('table#games') df = spor...
def srs(self, year): """Returns the SRS (Simple Rating System) for a team in a year. :year: The year for the season in question. :returns: A float of SRS. """ try: srs_text = self._year_info_pq(year, 'SRS').text() except ValueError: return None ...
def sos(self, year): """Returns the SOS (Strength of Schedule) for a team in a year, based on SRS. :year: The year for the season in question. :returns: A float of SOS. """ try: sos_text = self._year_info_pq(year, 'SOS').text() except ValueError: ...
def off_coordinator(self, year): """Returns the coach ID for the team's OC in a given year. :year: An int representing the year. :returns: A string containing the coach ID of the OC. """ try: oc_anchor = self._year_info_pq(year, 'Offensive Coordinator')('a') ...
def def_coordinator(self, year): """Returns the coach ID for the team's DC in a given year. :year: An int representing the year. :returns: A string containing the coach ID of the DC. """ try: dc_anchor = self._year_info_pq(year, 'Defensive Coordinator')('a') ...
def stadium(self, year): """Returns the ID for the stadium in which the team played in a given year. :year: The year in question. :returns: A string representing the stadium ID. """ anchor = self._year_info_pq(year, 'Stadium')('a') return sportsref.utils.rel_url_...
def off_scheme(self, year): """Returns the name of the offensive scheme the team ran in the given year. :year: Int representing the season year. :returns: A string representing the offensive scheme. """ scheme_text = self._year_info_pq(year, 'Offensive Scheme').text() ...
def def_alignment(self, year): """Returns the name of the defensive alignment the team ran in the given year. :year: Int representing the season year. :returns: A string representing the defensive alignment. """ scheme_text = self._year_info_pq(year, 'Defensive Alignment...
def team_stats(self, year): """Returns a Series (dict-like) of team stats from the team-season page. :year: Int representing the season. :returns: A Series of team stats. """ doc = self.get_year_doc(year) table = doc('table#team_stats') df = sportsref.uti...
def opp_stats(self, year): """Returns a Series (dict-like) of the team's opponent's stats from the team-season page. :year: Int representing the season. :returns: A Series of team stats. """ doc = self.get_year_doc(year) table = doc('table#team_stats') df...
def off_splits(self, year): """Returns a DataFrame of offensive team splits for a season. :year: int representing the season. :returns: Pandas DataFrame of split data. """ doc = self.get_year_doc('{}_splits'.format(year)) tables = doc('table.stats_table') dfs = [...
def get_html(url): """Gets the HTML for the given URL using a GET request. :url: the absolute URL of the desired page. :returns: a string of HTML. """ global last_request_time with throttle_process_lock: with throttle_thread_lock: # sleep until THROTTLE_DELAY secs have passe...