From c6b9bf0595565923729fee070650499d6d8b913f Mon Sep 17 00:00:00 2001 From: Joseph Armstrong <70788681+armstjc@users.noreply.github.com> Date: Mon, 16 Sep 2024 18:28:06 -0400 Subject: [PATCH] 0.2.4 The "Speedy" Update - Refactored `cfbd_json_py.games.get_cfbd_player_game_stats()`, `cfbd_json_py.plays.get_cfbd_pbp_play_types()`, and `cfbd_json_py.players.get_cfbd_player_season_stats()` to use a significantly faster process to parse player stats. - Changed `print()` statements into `logging.info()` statements for `cfbd_json_py.games.get_cfbd_player_advanced_game_stats()` - For `cfbd_json_py.metrics.get_cfbd_predicted_ppa_from_down_distance()`, a `logging.warn()` call is now a `logging.warning()` call due to a pending deprecation of `logging.warn()`. - Fixed an issue found in `cfbd_json_py.players.get_cfbd_pbp_stats()` where the function would warn the user about an issue that the user should not have triggered. - Removed `tqdm` integration with `cfbd_json_py.plays.get_cfbd_pbp_play_types()`, `cfbd_json_py.rankings.get_cfbd_poll rankings()`. - Updated the package version to `0.2.4`. --- .vscode/settings.json | 5 + CHANGELOG.md | 9 + README.md | 2 +- cfbd_json_py/betting.py | 2 +- cfbd_json_py/drives.py | 2 +- cfbd_json_py/games.py | 2035 +-- cfbd_json_py/metrics.py | 4 +- cfbd_json_py/players.py | 645 +- cfbd_json_py/plays.py | 43 +- cfbd_json_py/rankings.py | 6 +- cfbd_json_py/recruiting.py | 24 +- cfbd_json_py/stats.py | 7 +- cfbd_json_py/utls.py | 2 +- cfbd_json_py/venues.py | 6 +- docs/cfbd_json_py.html | 2 +- docs/cfbd_json_py/_early_access.html | 2 +- docs/cfbd_json_py/betting.html | 532 +- docs/cfbd_json_py/coaches.html | 2 +- docs/cfbd_json_py/conferences.html | 2 +- docs/cfbd_json_py/draft.html | 2 +- docs/cfbd_json_py/drives.html | 6 +- docs/cfbd_json_py/games.html | 16797 ++++++++++--------------- docs/cfbd_json_py/metrics.html | 6 +- docs/cfbd_json_py/players.html | 6216 ++++----- docs/cfbd_json_py/plays.html | 2886 ++--- docs/cfbd_json_py/rankings.html | 8 +- docs/cfbd_json_py/ratings.html | 2 +- docs/cfbd_json_py/recruiting.html | 2746 ++-- docs/cfbd_json_py/stats.html | 5044 ++++---- docs/cfbd_json_py/teams.html | 2 +- docs/cfbd_json_py/utls.html | 9 +- docs/cfbd_json_py/venues.html | 670 +- docs/index.html | 2 +- docs/search.js | 10 +- pyproject.toml | 2 +- 35 files changed, 16452 insertions(+), 21288 deletions(-) create mode 100644 .vscode/settings.json diff --git a/.vscode/settings.json b/.vscode/settings.json new file mode 100644 index 0000000..62152ec --- /dev/null +++ b/.vscode/settings.json @@ -0,0 +1,5 @@ +{ + "cSpell.words": [ + "Opportunies" + ] +} \ No newline at end of file diff --git a/CHANGELOG.md b/CHANGELOG.md index a78b762..78fda8f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,14 @@ # CHANGELOG: cfbd_json_py + +## 0.2.4 The "Speedy" Update. +- Refactored `cfbd_json_py.games.get_cfbd_player_game_stats()`, `cfbd_json_py.plays.get_cfbd_pbp_play_types()`, and `cfbd_json_py.players.get_cfbd_player_season_stats()` to use a significantly faster process to parse player stats. +- Changed `print()` statements into `logging.info()` statements for `cfbd_json_py.games.get_cfbd_player_advanced_game_stats()` +- For `cfbd_json_py.metrics.get_cfbd_predicted_ppa_from_down_distance()`, a `logging.warn()` call is now a `logging.warning()` call due to a pending deprecation of `logging.warn()`. +- Fixed an issue found in `cfbd_json_py.players.get_cfbd_pbp_stats()` where the function would warn the user about an issue that the user should not have triggered. +- Removed `tqdm` integration with `cfbd_json_py.plays.get_cfbd_pbp_play_types()`, `cfbd_json_py.rankings.get_cfbd_poll rankings()`. +- Updated the package version to `0.2.4`. + ## 0.2.3 The "Hotfix" Update. - Fixed an issue raised in #51 where the `[player_id]` column would be entirely blank in `cfbd_json_py.players.get_cfbd_player_season_stats()`. - Updated the package version to `0.2.3`. diff --git a/README.md b/README.md index d0604d7..7fa7c5e 100644 --- a/README.md +++ b/README.md @@ -47,4 +47,4 @@ You can view the status of the project [by clicking on this link](https://github If you find an issue/bug while using this python package, [please feel free to raise an issue](https://github.com/armstjc/cfbd-json-py/issues), we're only human, and there will inevitably be issues found! ## Docs -For the cfbd-json-py docs, they can be found at [armstjc.github.io/cfbd-json-py/](armstjc.github.io/cfbd-json-py/) \ No newline at end of file +For the cfbd-json-py docs, they can be found at [armstjc.github.io/cfbd-json-py/](https://armstjc.github.io/cfbd-json-py/cfbd_json_py.html) \ No newline at end of file diff --git a/cfbd_json_py/betting.py b/cfbd_json_py/betting.py index 2642cbd..0859daf 100644 --- a/cfbd_json_py/betting.py +++ b/cfbd_json_py/betting.py @@ -1,5 +1,5 @@ # Creation Date: 08/30/2023 01:13 EDT -# Last Updated Date: 08/13/2024 02:10 PM EDT +# Last Updated Date: 08/28/2024 11:00 PM EDT # Author: Joseph Armstrong (armstrongjoseph08@gmail.com) # File Name: betting.py # Purpose: Houses functions pertaining to betting data within the CFBD API. diff --git a/cfbd_json_py/drives.py b/cfbd_json_py/drives.py index 311c24e..df2e474 100644 --- a/cfbd_json_py/drives.py +++ b/cfbd_json_py/drives.py @@ -1,5 +1,5 @@ # Creation Date: 08/30/2023 01:13 EDT -# Last Updated Date: 08/13/2024 02:10 PM EDT +# Last Updated Date: 08/28/2024 11:00 PM EDT # Author: Joseph Armstrong (armstrongjoseph08@gmail.com) # File Name: drives.py # Purpose: Houses functions pertaining to CFB drive data within the CFBD API. diff --git a/cfbd_json_py/games.py b/cfbd_json_py/games.py index dda2793..e4bfaae 100644 --- a/cfbd_json_py/games.py +++ b/cfbd_json_py/games.py @@ -1,5 +1,5 @@ # Creation Date: 08/30/2023 01:13 EDT -# Last Updated Date: 08/13/2024 02:10 PM EDT +# Last Updated Date: 09/16/2024 06:10 PM EDT # Author: Joseph Armstrong (armstrongjoseph08@gmail.com) # File Name: games.py # Purpose: Houses functions pertaining to CFB game data within the CFBD API. @@ -8,6 +8,7 @@ import logging from datetime import datetime +import numpy as np import pandas as pd import requests from tqdm import tqdm @@ -1894,10 +1895,13 @@ def get_cfbd_player_game_stats( """ - rebuilt_json = {} now = datetime.now() + + rebuilt_json = {} + rebuilt_json_list = [] + cfb_games_df = pd.DataFrame() - row_df = pd.DataFrame() + # row_df = pd.DataFrame() url = "https://api.collegefootballdata.com/games/players" stat_columns = [ "season", @@ -2142,1568 +2146,30 @@ def get_cfbd_player_game_stats( team_conference = team["conference"] home_away = team["homeAway"] - for s_category in team["categories"]: - if s_category["name"] == "passing": - for stat in s_category["types"]: - if stat["name"] == "C/ATT": # passing_C/ATT - for i in stat["athletes"]: - player_id = int(i["id"]) - player_name = i["name"] - player_stat = i["stat"] - - if rebuilt_json.get(player_id) is None: - rebuilt_json[player_id] = {} - - rebuilt_json[player_id]["game_id"] = game_id - rebuilt_json[player_id][ - "team_name" - ] = team_name - rebuilt_json[player_id][ - "team_conference" - ] = team_conference - rebuilt_json[player_id][ - "player_id" - ] = player_id - rebuilt_json[player_id][ - "player_name" - ] = player_name - rebuilt_json[player_id][ - "home_away" - ] = home_away - rebuilt_json[player_id][ - "passing_C/ATT" - ] = player_stat - - elif stat["name"] == "YDS": # passing_YDS - for i in stat["athletes"]: - player_id = int(i["id"]) - player_name = i["name"] - player_stat = int(i["stat"]) - - if rebuilt_json.get(player_id) is None: - rebuilt_json[player_id] = {} - - rebuilt_json[player_id]["game_id"] = game_id - rebuilt_json[player_id][ - "team_name" - ] = team_name - rebuilt_json[player_id][ - "team_conference" - ] = team_conference - rebuilt_json[player_id][ - "player_id" - ] = player_id - rebuilt_json[player_id][ - "player_name" - ] = player_name - rebuilt_json[player_id][ - "home_away" - ] = home_away - rebuilt_json[player_id][ - "passing_YDS" - ] = player_stat - - elif stat["name"] == "AVG": # passing_AVG - for i in stat["athletes"]: - player_id = int(i["id"]) - player_name = i["name"] - player_stat = float(i["stat"]) - - if rebuilt_json.get(player_id) is None: - rebuilt_json[player_id] = {} - - rebuilt_json[player_id]["game_id"] = game_id - rebuilt_json[player_id][ - "team_name" - ] = team_name - rebuilt_json[player_id][ - "team_conference" - ] = team_conference - rebuilt_json[player_id][ - "player_id" - ] = player_id - rebuilt_json[player_id][ - "player_name" - ] = player_name - rebuilt_json[player_id][ - "home_away" - ] = home_away - rebuilt_json[player_id][ - "passing_AVG" - ] = player_stat - - elif stat["name"] == "TD": # passing_TD - for i in stat["athletes"]: - player_id = int(i["id"]) - player_name = i["name"] - player_stat = int(i["stat"]) - - if rebuilt_json.get(player_id) is None: - rebuilt_json[player_id] = {} - - rebuilt_json[player_id]["game_id"] = game_id - rebuilt_json[player_id][ - "team_name" - ] = team_name - rebuilt_json[player_id][ - "team_conference" - ] = team_conference - rebuilt_json[player_id][ - "player_id" - ] = player_id - rebuilt_json[player_id][ - "player_name" - ] = player_name - rebuilt_json[player_id][ - "home_away" - ] = home_away - rebuilt_json[player_id][ - "passing_TD" - ] = player_stat - - elif stat["name"] == "INT": # passing_INT - for i in stat["athletes"]: - player_id = int(i["id"]) - player_name = i["name"] - player_stat = int(i["stat"]) - - if rebuilt_json.get(player_id) is None: - rebuilt_json[player_id] = {} - - rebuilt_json[player_id]["game_id"] = game_id - rebuilt_json[player_id][ - "team_name" - ] = team_name - rebuilt_json[player_id][ - "team_conference" - ] = team_conference - rebuilt_json[player_id][ - "player_id" - ] = player_id - rebuilt_json[player_id][ - "player_name" - ] = player_name - rebuilt_json[player_id][ - "home_away" - ] = home_away - rebuilt_json[player_id][ - "passing_INT" - ] = player_stat - - elif stat["name"] == "QBR": # passing_QBR - for i in stat["athletes"]: - player_id = int(i["id"]) - player_name = i["name"] - try: - player_stat = float(i["stat"]) - except: # noqa: E722 - player_stat = None - - if rebuilt_json.get(player_id) is None: - rebuilt_json[player_id] = {} - - rebuilt_json[player_id]["game_id"] = game_id - rebuilt_json[player_id][ - "team_name" - ] = team_name - rebuilt_json[player_id][ - "team_conference" - ] = team_conference - rebuilt_json[player_id][ - "player_id" - ] = player_id - rebuilt_json[player_id][ - "player_name" - ] = player_name - rebuilt_json[player_id][ - "home_away" - ] = home_away - rebuilt_json[player_id][ - "passing_QBR" - ] = player_stat - - else: - raise IndexError( - f"Unhandled stat: \t{stat['name']}" - ) - # passing_df = pd.DataFrame(s_category['types']) - elif s_category["name"] == "rushing": - for stat in s_category["types"]: - if stat["name"] == "CAR": # rushing_CAR - for i in stat["athletes"]: - player_id = int(i["id"]) - player_name = i["name"] - player_stat = int(i["stat"]) - - if rebuilt_json.get(player_id) is None: - rebuilt_json[player_id] = {} - - rebuilt_json[player_id]["game_id"] = game_id - rebuilt_json[player_id][ - "team_name" - ] = team_name - rebuilt_json[player_id][ - "team_conference" - ] = team_conference - rebuilt_json[player_id][ - "player_id" - ] = player_id - rebuilt_json[player_id][ - "player_name" - ] = player_name - rebuilt_json[player_id][ - "home_away" - ] = home_away - rebuilt_json[player_id][ - "rushing_CAR" - ] = player_stat - - elif stat["name"] == "YDS": # rushing_YDS - for i in stat["athletes"]: - player_id = int(i["id"]) - player_name = i["name"] - player_stat = int(i["stat"]) - - if rebuilt_json.get(player_id) is None: - rebuilt_json[player_id] = {} - - rebuilt_json[player_id]["game_id"] = game_id - rebuilt_json[player_id][ - "team_name" - ] = team_name - rebuilt_json[player_id][ - "team_conference" - ] = team_conference - rebuilt_json[player_id][ - "player_id" - ] = player_id - rebuilt_json[player_id][ - "player_name" - ] = player_name - rebuilt_json[player_id][ - "home_away" - ] = home_away - rebuilt_json[player_id][ - "rushing_YDS" - ] = player_stat - - elif stat["name"] == "AVG": # rushing_AVG - for i in stat["athletes"]: - player_id = int(i["id"]) - player_name = i["name"] - player_stat = float(i["stat"]) - - if rebuilt_json.get(player_id) is None: - rebuilt_json[player_id] = {} - - rebuilt_json[player_id]["game_id"] = game_id - rebuilt_json[player_id][ - "team_name" - ] = team_name - rebuilt_json[player_id][ - "team_conference" - ] = team_conference - rebuilt_json[player_id][ - "player_id" - ] = player_id - rebuilt_json[player_id][ - "player_name" - ] = player_name - rebuilt_json[player_id][ - "home_away" - ] = home_away - rebuilt_json[player_id][ - "rushing_AVG" - ] = player_stat - - elif stat["name"] == "TD": # rushing_TD - for i in stat["athletes"]: - player_id = int(i["id"]) - player_name = i["name"] - player_stat = int(i["stat"]) - - if rebuilt_json.get(player_id) is None: - rebuilt_json[player_id] = {} - - rebuilt_json[player_id]["game_id"] = game_id - rebuilt_json[player_id][ - "team_name" - ] = team_name - rebuilt_json[player_id][ - "team_conference" - ] = team_conference - rebuilt_json[player_id][ - "player_id" - ] = player_id - rebuilt_json[player_id][ - "player_name" - ] = player_name - rebuilt_json[player_id][ - "home_away" - ] = home_away - rebuilt_json[player_id][ - "rushing_TD" - ] = player_stat - - elif stat["name"] == "LONG": # rushing_LONG - for i in stat["athletes"]: - player_id = int(i["id"]) - player_name = i["name"] - player_stat = int(i["stat"]) - - if rebuilt_json.get(player_id) is None: - rebuilt_json[player_id] = {} - - rebuilt_json[player_id]["game_id"] = game_id - rebuilt_json[player_id][ - "team_name" - ] = team_name - rebuilt_json[player_id][ - "team_conference" - ] = team_conference - rebuilt_json[player_id][ - "player_id" - ] = player_id - rebuilt_json[player_id][ - "player_name" - ] = player_name - rebuilt_json[player_id][ - "home_away" - ] = home_away - rebuilt_json[player_id][ - "rushing_LONG" - ] = player_stat - - else: - raise IndexError( - f"Unhandled stat: \t{stat['name']}" - ) - - elif s_category["name"] == "receiving": - for stat in s_category["types"]: - if stat["name"] == "REC": # receiving_REC - for i in stat["athletes"]: - player_id = int(i["id"]) - player_name = i["name"] - player_stat = int(i["stat"]) - - if rebuilt_json.get(player_id) is None: - rebuilt_json[player_id] = {} - - rebuilt_json[player_id]["game_id"] = game_id - rebuilt_json[player_id][ - "team_name" - ] = team_name - rebuilt_json[player_id][ - "team_conference" - ] = team_conference - rebuilt_json[player_id][ - "player_id" - ] = player_id - rebuilt_json[player_id][ - "player_name" - ] = player_name - rebuilt_json[player_id][ - "home_away" - ] = home_away - rebuilt_json[player_id][ - "receiving_REC" - ] = player_stat - - elif stat["name"] == "YDS": # receiving_YDS - for i in stat["athletes"]: - player_id = int(i["id"]) - player_name = i["name"] - player_stat = int(i["stat"]) - - if rebuilt_json.get(player_id) is None: - rebuilt_json[player_id] = {} - - rebuilt_json[player_id]["game_id"] = game_id - rebuilt_json[player_id][ - "team_name" - ] = team_name - rebuilt_json[player_id][ - "team_conference" - ] = team_conference - rebuilt_json[player_id][ - "player_id" - ] = player_id - rebuilt_json[player_id][ - "player_name" - ] = player_name - rebuilt_json[player_id][ - "home_away" - ] = home_away - rebuilt_json[player_id][ - "receiving_YDS" - ] = player_stat - - elif stat["name"] == "AVG": # receiving_AVG - for i in stat["athletes"]: - player_id = int(i["id"]) - player_name = i["name"] - player_stat = float(i["stat"]) - - if rebuilt_json.get(player_id) is None: - rebuilt_json[player_id] = {} - - rebuilt_json[player_id]["game_id"] = game_id - rebuilt_json[player_id][ - "team_name" - ] = team_name - rebuilt_json[player_id][ - "team_conference" - ] = team_conference - rebuilt_json[player_id][ - "player_id" - ] = player_id - rebuilt_json[player_id][ - "player_name" - ] = player_name - rebuilt_json[player_id][ - "home_away" - ] = home_away - rebuilt_json[player_id][ - "receiving_AVG" - ] = player_stat - - elif stat["name"] == "TD": # receiving_TD - for i in stat["athletes"]: - player_id = int(i["id"]) - player_name = i["name"] - player_stat = int(i["stat"]) - - if rebuilt_json.get(player_id) is None: - rebuilt_json[player_id] = {} - - rebuilt_json[player_id]["game_id"] = game_id - rebuilt_json[player_id][ - "team_name" - ] = team_name - rebuilt_json[player_id][ - "team_conference" - ] = team_conference - rebuilt_json[player_id][ - "player_id" - ] = player_id - rebuilt_json[player_id][ - "player_name" - ] = player_name - rebuilt_json[player_id][ - "home_away" - ] = home_away - rebuilt_json[player_id][ - "receiving_TD" - ] = player_stat - - elif stat["name"] == "LONG": # receiving_LONG - for i in stat["athletes"]: - player_id = int(i["id"]) - player_name = i["name"] - player_stat = int(i["stat"]) - - if rebuilt_json.get(player_id) is None: - rebuilt_json[player_id] = {} - - rebuilt_json[player_id]["game_id"] = game_id - rebuilt_json[player_id][ - "team_name" - ] = team_name - rebuilt_json[player_id][ - "team_conference" - ] = team_conference - rebuilt_json[player_id][ - "player_id" - ] = player_id - rebuilt_json[player_id][ - "player_name" - ] = player_name - rebuilt_json[player_id][ - "home_away" - ] = home_away - rebuilt_json[player_id][ - "receiving_LONG" - ] = player_stat - - else: - raise IndexError( - f"Unhandled stat: \t{stat['name']}" - ) - - elif s_category["name"] == "fumbles": - for stat in s_category["types"]: - if stat["name"] == "FUM": # fumbles_FUM - for i in stat["athletes"]: - player_id = int(i["id"]) - player_name = i["name"] - player_stat = int(i["stat"]) - - if rebuilt_json.get(player_id) is None: - rebuilt_json[player_id] = {} - - rebuilt_json[player_id]["game_id"] = game_id - rebuilt_json[player_id][ - "team_name" - ] = team_name - rebuilt_json[player_id][ - "team_conference" - ] = team_conference - rebuilt_json[player_id][ - "player_id" - ] = player_id - rebuilt_json[player_id][ - "player_name" - ] = player_name - rebuilt_json[player_id][ - "home_away" - ] = home_away - rebuilt_json[player_id][ - "fumbles_FUM" - ] = player_stat - - elif stat["name"] == "LOST": # fumbles_LOST - for i in stat["athletes"]: - player_id = int(i["id"]) - player_name = i["name"] - player_stat = int(i["stat"]) - - if rebuilt_json.get(player_id) is None: - rebuilt_json[player_id] = {} - - rebuilt_json[player_id]["game_id"] = game_id - rebuilt_json[player_id][ - "team_name" - ] = team_name - rebuilt_json[player_id][ - "team_conference" - ] = team_conference - rebuilt_json[player_id][ - "player_id" - ] = player_id - rebuilt_json[player_id][ - "player_name" - ] = player_name - rebuilt_json[player_id][ - "home_away" - ] = home_away - rebuilt_json[player_id][ - "fumbles_LOST" - ] = player_stat - - elif stat["name"] == "REC": # fumbles_REC - for i in stat["athletes"]: - player_id = int(i["id"]) - player_name = i["name"] - player_stat = int(i["stat"]) - - if rebuilt_json.get(player_id) is None: - rebuilt_json[player_id] = {} - - rebuilt_json[player_id]["game_id"] = game_id - rebuilt_json[player_id][ - "team_name" - ] = team_name - rebuilt_json[player_id][ - "team_conference" - ] = team_conference - rebuilt_json[player_id][ - "player_id" - ] = player_id - rebuilt_json[player_id][ - "player_name" - ] = player_name - rebuilt_json[player_id][ - "home_away" - ] = home_away - rebuilt_json[player_id][ - "fumbles_REC" - ] = player_stat - - else: - raise IndexError( - f"Unhandled stat: \t{stat['name']}" - ) - - elif s_category["name"] == "defensive": - for stat in s_category["types"]: - if stat["name"] == "TOT": # defensive_TOT - for i in stat["athletes"]: - player_id = int(i["id"]) - player_name = i["name"] - player_stat = int(i["stat"]) - - if rebuilt_json.get(player_id) is None: - rebuilt_json[player_id] = {} - - rebuilt_json[player_id]["game_id"] = game_id - rebuilt_json[player_id][ - "team_name" - ] = team_name - rebuilt_json[player_id][ - "team_conference" - ] = team_conference - rebuilt_json[player_id][ - "player_id" - ] = player_id - rebuilt_json[player_id][ - "player_name" - ] = player_name - rebuilt_json[player_id][ - "home_away" - ] = home_away - rebuilt_json[player_id][ - "defensive_TOT" - ] = player_stat - - elif stat["name"] == "SOLO": # defensive_SOLO - for i in stat["athletes"]: - player_id = int(i["id"]) - player_name = i["name"] - player_stat = int(i["stat"]) - - if rebuilt_json.get(player_id) is None: - rebuilt_json[player_id] = {} - - rebuilt_json[player_id]["game_id"] = game_id - rebuilt_json[player_id][ - "team_name" - ] = team_name - rebuilt_json[player_id][ - "team_conference" - ] = team_conference - rebuilt_json[player_id][ - "player_id" - ] = player_id - rebuilt_json[player_id][ - "player_name" - ] = player_name - rebuilt_json[player_id][ - "home_away" - ] = home_away - rebuilt_json[player_id][ - "defensive_SOLO" - ] = player_stat - - elif stat["name"] == "TFL": # defensive_TFL - for i in stat["athletes"]: - player_id = int(i["id"]) - player_name = i["name"] - player_stat = float(i["stat"]) - - if rebuilt_json.get(player_id) is None: - rebuilt_json[player_id] = {} - - rebuilt_json[player_id]["game_id"] = game_id - rebuilt_json[player_id][ - "team_name" - ] = team_name - rebuilt_json[player_id][ - "team_conference" - ] = team_conference - rebuilt_json[player_id][ - "player_id" - ] = player_id - rebuilt_json[player_id][ - "player_name" - ] = player_name - rebuilt_json[player_id][ - "home_away" - ] = home_away - rebuilt_json[player_id][ - "defensive_TFL" - ] = player_stat - - elif stat["name"] == "QB HUR": # defensive_QB HUR - for i in stat["athletes"]: - player_id = int(i["id"]) - player_name = i["name"] - player_stat = int(i["stat"]) - - if rebuilt_json.get(player_id) is None: - rebuilt_json[player_id] = {} - - rebuilt_json[player_id]["game_id"] = game_id - rebuilt_json[player_id][ - "team_name" - ] = team_name - rebuilt_json[player_id][ - "team_conference" - ] = team_conference - rebuilt_json[player_id][ - "player_id" - ] = player_id - rebuilt_json[player_id][ - "player_name" - ] = player_name - rebuilt_json[player_id][ - "home_away" - ] = home_away - rebuilt_json[player_id][ - "defensive_QB HUR" - ] = player_stat - - elif stat["name"] == "SACKS": # defensive_SACKS - for i in stat["athletes"]: - player_id = int(i["id"]) - player_name = i["name"] - player_stat = float(i["stat"]) - - if rebuilt_json.get(player_id) is None: - rebuilt_json[player_id] = {} - - rebuilt_json[player_id]["game_id"] = game_id - rebuilt_json[player_id][ - "team_name" - ] = team_name - rebuilt_json[player_id][ - "team_conference" - ] = team_conference - rebuilt_json[player_id][ - "player_id" - ] = player_id - rebuilt_json[player_id][ - "player_name" - ] = player_name - rebuilt_json[player_id][ - "home_away" - ] = home_away - rebuilt_json[player_id][ - "defensive_SACKS" - ] = player_stat - - elif stat["name"] == "PD": # defensive_PD - for i in stat["athletes"]: - player_id = int(i["id"]) - player_name = i["name"] - player_stat = int(i["stat"]) - - if rebuilt_json.get(player_id) is None: - rebuilt_json[player_id] = {} - - rebuilt_json[player_id]["game_id"] = game_id - rebuilt_json[player_id][ - "team_name" - ] = team_name - rebuilt_json[player_id][ - "team_conference" - ] = team_conference - rebuilt_json[player_id][ - "player_id" - ] = player_id - rebuilt_json[player_id][ - "player_name" - ] = player_name - rebuilt_json[player_id][ - "home_away" - ] = home_away - rebuilt_json[player_id][ - "defensive_PD" - ] = player_stat - - elif stat["name"] == "TD": # defensive_TD - for i in stat["athletes"]: - player_id = int(i["id"]) - player_name = i["name"] - player_stat = int(i["stat"]) - - if rebuilt_json.get(player_id) is None: - rebuilt_json[player_id] = {} - - rebuilt_json[player_id]["game_id"] = game_id - rebuilt_json[player_id][ - "team_name" - ] = team_name - rebuilt_json[player_id][ - "team_conference" - ] = team_conference - rebuilt_json[player_id][ - "player_id" - ] = player_id - rebuilt_json[player_id][ - "player_name" - ] = player_name - rebuilt_json[player_id][ - "home_away" - ] = home_away - rebuilt_json[player_id][ - "defensive_TD" - ] = player_stat - - else: - raise IndexError( - f"Unhandled stat: \t{stat['name']}" - ) - - elif s_category["name"] == "interceptions": - for stat in s_category["types"]: - if stat["name"] == "INT": # interceptions_INT - for i in stat["athletes"]: - player_id = int(i["id"]) - player_name = i["name"] - player_stat = int(i["stat"]) - - if rebuilt_json.get(player_id) is None: - rebuilt_json[player_id] = {} - - rebuilt_json[player_id]["game_id"] = game_id - rebuilt_json[player_id][ - "team_name" - ] = team_name - rebuilt_json[player_id][ - "team_conference" - ] = team_conference - rebuilt_json[player_id][ - "player_id" - ] = player_id - rebuilt_json[player_id][ - "player_name" - ] = player_name - rebuilt_json[player_id][ - "home_away" - ] = home_away - rebuilt_json[player_id][ - "interceptions_INT" - ] = player_stat - - elif stat["name"] == "YDS": # interceptions_YDS - for i in stat["athletes"]: - player_id = int(i["id"]) - player_name = i["name"] - player_stat = int(i["stat"]) - - if rebuilt_json.get(player_id) is None: - rebuilt_json[player_id] = {} - - rebuilt_json[player_id]["game_id"] = game_id - rebuilt_json[player_id][ - "team_name" - ] = team_name - rebuilt_json[player_id][ - "team_conference" - ] = team_conference - rebuilt_json[player_id][ - "player_id" - ] = player_id - rebuilt_json[player_id][ - "player_name" - ] = player_name - rebuilt_json[player_id][ - "home_away" - ] = home_away - rebuilt_json[player_id][ - "interceptions_YDS" - ] = player_stat - - elif stat["name"] == "TD": # interceptions_TD - for i in stat["athletes"]: - player_id = int(i["id"]) - player_name = i["name"] - player_stat = int(i["stat"]) - - if rebuilt_json.get(player_id) is None: - rebuilt_json[player_id] = {} - - rebuilt_json[player_id]["game_id"] = game_id - rebuilt_json[player_id][ - "team_name" - ] = team_name - rebuilt_json[player_id][ - "team_conference" - ] = team_conference - rebuilt_json[player_id][ - "player_id" - ] = player_id - rebuilt_json[player_id][ - "player_name" - ] = player_name - rebuilt_json[player_id][ - "home_away" - ] = home_away - rebuilt_json[player_id][ - "interceptions_TD" - ] = player_stat - - else: - raise IndexError( - f"Unhandled stat: \t{stat['name']}" - ) - - elif s_category["name"] == "punting": - for stat in s_category["types"]: - if stat["name"] == "NO": # punting_NO - for i in stat["athletes"]: - player_id = int(i["id"]) - player_name = i["name"] - player_stat = int(i["stat"]) - - if rebuilt_json.get(player_id) is None: - rebuilt_json[player_id] = {} - - rebuilt_json[player_id]["game_id"] = game_id - rebuilt_json[player_id][ - "team_name" - ] = team_name - rebuilt_json[player_id][ - "team_conference" - ] = team_conference - rebuilt_json[player_id][ - "player_id" - ] = player_id - rebuilt_json[player_id][ - "player_name" - ] = player_name - rebuilt_json[player_id][ - "home_away" - ] = home_away - rebuilt_json[player_id][ - "punting_NO" - ] = player_stat - - elif stat["name"] == "YDS": # punting_YDS - for i in stat["athletes"]: - player_id = int(i["id"]) - player_name = i["name"] - player_stat = int(i["stat"]) - - if rebuilt_json.get(player_id) is None: - rebuilt_json[player_id] = {} - - rebuilt_json[player_id]["game_id"] = game_id - rebuilt_json[player_id][ - "team_name" - ] = team_name - rebuilt_json[player_id][ - "team_conference" - ] = team_conference - rebuilt_json[player_id][ - "player_id" - ] = player_id - rebuilt_json[player_id][ - "player_name" - ] = player_name - rebuilt_json[player_id][ - "home_away" - ] = home_away - rebuilt_json[player_id][ - "punting_YDS" - ] = player_stat - - elif stat["name"] == "AVG": # punting_AVG - for i in stat["athletes"]: - player_id = int(i["id"]) - player_name = i["name"] - player_stat = float(i["stat"]) - - if rebuilt_json.get(player_id) is None: - rebuilt_json[player_id] = {} - - rebuilt_json[player_id]["game_id"] = game_id - rebuilt_json[player_id][ - "team_name" - ] = team_name - rebuilt_json[player_id][ - "team_conference" - ] = team_conference - rebuilt_json[player_id][ - "player_id" - ] = player_id - rebuilt_json[player_id][ - "player_name" - ] = player_name - rebuilt_json[player_id][ - "home_away" - ] = home_away - rebuilt_json[player_id][ - "punting_AVG" - ] = player_stat - - elif stat["name"] == "TB": # punting_TB - for i in stat["athletes"]: - player_id = int(i["id"]) - player_name = i["name"] - player_stat = int(i["stat"]) - - if rebuilt_json.get(player_id) is None: - rebuilt_json[player_id] = {} - - rebuilt_json[player_id]["game_id"] = game_id - rebuilt_json[player_id][ - "team_name" - ] = team_name - rebuilt_json[player_id][ - "team_conference" - ] = team_conference - rebuilt_json[player_id][ - "player_id" - ] = player_id - rebuilt_json[player_id][ - "player_name" - ] = player_name - rebuilt_json[player_id][ - "home_away" - ] = home_away - rebuilt_json[player_id][ - "punting_TB" - ] = player_stat - - elif stat["name"] == "In 20": # punting_In 20 - for i in stat["athletes"]: - player_id = int(i["id"]) - player_name = i["name"] - player_stat = int(i["stat"]) - - if rebuilt_json.get(player_id) is None: - rebuilt_json[player_id] = {} - - rebuilt_json[player_id]["game_id"] = game_id - rebuilt_json[player_id][ - "team_name" - ] = team_name - rebuilt_json[player_id][ - "team_conference" - ] = team_conference - rebuilt_json[player_id][ - "player_id" - ] = player_id - rebuilt_json[player_id][ - "player_name" - ] = player_name - rebuilt_json[player_id][ - "home_away" - ] = home_away - rebuilt_json[player_id][ - "punting_In 20" - ] = player_stat - - elif stat["name"] == "LONG": # punting_LONG - for i in stat["athletes"]: - player_id = int(i["id"]) - player_name = i["name"] - player_stat = int(i["stat"]) - - if rebuilt_json.get(player_id) is None: - rebuilt_json[player_id] = {} - - rebuilt_json[player_id]["game_id"] = game_id - rebuilt_json[player_id][ - "team_name" - ] = team_name - rebuilt_json[player_id][ - "team_conference" - ] = team_conference - rebuilt_json[player_id][ - "player_id" - ] = player_id - rebuilt_json[player_id][ - "player_name" - ] = player_name - rebuilt_json[player_id][ - "home_away" - ] = home_away - rebuilt_json[player_id][ - "punting_LONG" - ] = player_stat - - else: - raise IndexError( - f"Unhandled stat: \t{stat['name']}" - ) - - elif s_category["name"] == "kicking": - for stat in s_category["types"]: - if stat["name"] == "FG": # kicking_FG - for i in stat["athletes"]: - player_id = int(i["id"]) - player_name = i["name"] - player_stat = i["stat"] - - if rebuilt_json.get(player_id) is None: - rebuilt_json[player_id] = {} - - rebuilt_json[player_id]["game_id"] = game_id - rebuilt_json[player_id][ - "team_name" - ] = team_name - rebuilt_json[player_id][ - "team_conference" - ] = team_conference - rebuilt_json[player_id][ - "player_id" - ] = player_id - rebuilt_json[player_id][ - "player_name" - ] = player_name - rebuilt_json[player_id][ - "home_away" - ] = home_away - rebuilt_json[player_id][ - "kicking_FG" - ] = player_stat - - elif stat["name"] == "TOT": # kicking_FG, special case - for i in stat["athletes"]: - player_id = int(i["id"]) - player_name = i["name"] - player_stat = i["stat"] - - if rebuilt_json.get(player_id) is None: - rebuilt_json[player_id] = {} - - rebuilt_json[player_id]["game_id"] = game_id - rebuilt_json[player_id][ - "team_name" - ] = team_name - rebuilt_json[player_id][ - "team_conference" - ] = team_conference - rebuilt_json[player_id][ - "player_id" - ] = player_id - rebuilt_json[player_id][ - "player_name" - ] = player_name - rebuilt_json[player_id][ - "home_away" - ] = home_away - rebuilt_json[player_id][ - "kicking_FG" - ] = player_stat - - elif stat["name"] == "PCT": # kicking_PCT - for i in stat["athletes"]: - player_id = int(i["id"]) - player_name = i["name"] - player_stat = float(i["stat"]) - - if rebuilt_json.get(player_id) is None: - rebuilt_json[player_id] = {} - - rebuilt_json[player_id]["game_id"] = game_id - rebuilt_json[player_id][ - "team_name" - ] = team_name - rebuilt_json[player_id][ - "team_conference" - ] = team_conference - rebuilt_json[player_id][ - "player_id" - ] = player_id - rebuilt_json[player_id][ - "player_name" - ] = player_name - rebuilt_json[player_id][ - "home_away" - ] = home_away - rebuilt_json[player_id][ - "kicking_PCT" - ] = player_stat - - elif stat["name"] == "LONG": # kicking_LONG - for i in stat["athletes"]: - player_id = int(i["id"]) - player_name = i["name"] - player_stat = int(i["stat"]) - - if rebuilt_json.get(player_id) is None: - rebuilt_json[player_id] = {} - - rebuilt_json[player_id]["game_id"] = game_id - rebuilt_json[player_id][ - "team_name" - ] = team_name - rebuilt_json[player_id][ - "team_conference" - ] = team_conference - rebuilt_json[player_id][ - "player_id" - ] = player_id - rebuilt_json[player_id][ - "player_name" - ] = player_name - rebuilt_json[player_id][ - "home_away" - ] = home_away - rebuilt_json[player_id][ - "kicking_LONG" - ] = player_stat - - elif stat["name"] == "XP": # kicking_XP - for i in stat["athletes"]: - player_id = int(i["id"]) - player_name = i["name"] - player_stat = i["stat"] - - if rebuilt_json.get(player_id) is None: - rebuilt_json[player_id] = {} - - rebuilt_json[player_id]["game_id"] = game_id - rebuilt_json[player_id][ - "team_name" - ] = team_name - rebuilt_json[player_id][ - "team_conference" - ] = team_conference - rebuilt_json[player_id][ - "player_id" - ] = player_id - rebuilt_json[player_id][ - "player_name" - ] = player_name - rebuilt_json[player_id][ - "home_away" - ] = home_away - rebuilt_json[player_id][ - "kicking_XP" - ] = player_stat - - elif stat["name"] == "PTS": # kicking_PTS - for i in stat["athletes"]: - player_id = int(i["id"]) - player_name = i["name"] - player_stat = int(i["stat"]) - - if rebuilt_json.get(player_id) is None: - rebuilt_json[player_id] = {} - - rebuilt_json[player_id]["game_id"] = game_id - rebuilt_json[player_id][ - "team_name" - ] = team_name - rebuilt_json[player_id][ - "team_conference" - ] = team_conference - rebuilt_json[player_id][ - "player_id" - ] = player_id - rebuilt_json[player_id][ - "player_name" - ] = player_name - rebuilt_json[player_id][ - "home_away" - ] = home_away - rebuilt_json[player_id][ - "kicking_PTS" - ] = player_stat - - else: - raise IndexError( - f"Unhandled stat: \t{stat['name']}" - ) - - elif s_category["name"] == "kickReturns": - for stat in s_category["types"]: - if stat["name"] == "NO": # kickReturns_NO - for i in stat["athletes"]: - player_id = int(i["id"]) - player_name = i["name"] - player_stat = int(i["stat"]) - - if rebuilt_json.get(player_id) is None: - rebuilt_json[player_id] = {} - - rebuilt_json[player_id]["game_id"] = game_id - rebuilt_json[player_id][ - "team_name" - ] = team_name - rebuilt_json[player_id][ - "team_conference" - ] = team_conference - rebuilt_json[player_id][ - "player_id" - ] = player_id - rebuilt_json[player_id][ - "player_name" - ] = player_name - rebuilt_json[player_id][ - "home_away" - ] = home_away - rebuilt_json[player_id][ - "kickReturns_NO" - ] = player_stat - - elif stat["name"] == "YDS": # kickReturns_YDS - for i in stat["athletes"]: - player_id = int(i["id"]) - player_name = i["name"] - player_stat = int(i["stat"]) - - if rebuilt_json.get(player_id) is None: - rebuilt_json[player_id] = {} - - rebuilt_json[player_id]["game_id"] = game_id - rebuilt_json[player_id][ - "team_name" - ] = team_name - rebuilt_json[player_id][ - "team_conference" - ] = team_conference - rebuilt_json[player_id][ - "player_id" - ] = player_id - rebuilt_json[player_id][ - "player_name" - ] = player_name - rebuilt_json[player_id][ - "home_away" - ] = home_away - rebuilt_json[player_id][ - "kickReturns_YDS" - ] = player_stat - - elif stat["name"] == "AVG": # kickReturns_AVG - for i in stat["athletes"]: - player_id = int(i["id"]) - player_name = i["name"] - player_stat = float(i["stat"]) - - if rebuilt_json.get(player_id) is None: - rebuilt_json[player_id] = {} - - rebuilt_json[player_id]["game_id"] = game_id - rebuilt_json[player_id][ - "team_name" - ] = team_name - rebuilt_json[player_id][ - "team_conference" - ] = team_conference - rebuilt_json[player_id][ - "player_id" - ] = player_id - rebuilt_json[player_id][ - "player_name" - ] = player_name - rebuilt_json[player_id][ - "home_away" - ] = home_away - rebuilt_json[player_id][ - "kickReturns_AVG" - ] = player_stat - - elif stat["name"] == "TD": # kickReturns_TD - for i in stat["athletes"]: - player_id = int(i["id"]) - player_name = i["name"] - player_stat = int(i["stat"]) - - if rebuilt_json.get(player_id) is None: - rebuilt_json[player_id] = {} - - rebuilt_json[player_id]["game_id"] = game_id - rebuilt_json[player_id][ - "team_name" - ] = team_name - rebuilt_json[player_id][ - "team_conference" - ] = team_conference - rebuilt_json[player_id][ - "player_id" - ] = player_id - rebuilt_json[player_id][ - "player_name" - ] = player_name - rebuilt_json[player_id][ - "home_away" - ] = home_away - rebuilt_json[player_id][ - "kickReturns_TD" - ] = player_stat - - elif stat["name"] == "LONG": # kickReturns_LONG - for i in stat["athletes"]: - player_id = int(i["id"]) - player_name = i["name"] - player_stat = int(i["stat"]) - - if rebuilt_json.get(player_id) is None: - rebuilt_json[player_id] = {} - - rebuilt_json[player_id]["game_id"] = game_id - rebuilt_json[player_id][ - "team_name" - ] = team_name - rebuilt_json[player_id][ - "team_conference" - ] = team_conference - rebuilt_json[player_id][ - "player_id" - ] = player_id - rebuilt_json[player_id][ - "player_name" - ] = player_name - rebuilt_json[player_id][ - "home_away" - ] = home_away - rebuilt_json[player_id][ - "kickReturns_LONG" - ] = player_stat - - else: - raise IndexError( - f"Unhandled stat: \t{stat['name']}" - ) - - elif s_category["name"] == "puntReturns": - for stat in s_category["types"]: - if stat["name"] == "NO": # puntReturns_NO - for i in stat["athletes"]: - player_id = int(i["id"]) - player_name = i["name"] - player_stat = int(i["stat"]) - - if rebuilt_json.get(player_id) is None: - rebuilt_json[player_id] = {} - - rebuilt_json[player_id]["game_id"] = game_id - rebuilt_json[player_id][ - "team_name" - ] = team_name - rebuilt_json[player_id][ - "team_conference" - ] = team_conference - rebuilt_json[player_id][ - "player_id" - ] = player_id - rebuilt_json[player_id][ - "player_name" - ] = player_name - rebuilt_json[player_id][ - "home_away" - ] = home_away - rebuilt_json[player_id][ - "puntReturns_NO" - ] = player_stat - - elif stat["name"] == "YDS": # puntReturns_YDS - for i in stat["athletes"]: - player_id = int(i["id"]) - player_name = i["name"] - player_stat = int(i["stat"]) - - if rebuilt_json.get(player_id) is None: - rebuilt_json[player_id] = {} - - rebuilt_json[player_id]["game_id"] = game_id - rebuilt_json[player_id][ - "team_name" - ] = team_name - rebuilt_json[player_id][ - "team_conference" - ] = team_conference - rebuilt_json[player_id][ - "player_id" - ] = player_id - rebuilt_json[player_id][ - "player_name" - ] = player_name - rebuilt_json[player_id][ - "home_away" - ] = home_away - rebuilt_json[player_id][ - "puntReturns_YDS" - ] = player_stat - - elif stat["name"] == "AVG": # puntReturns_AVG - for i in stat["athletes"]: - player_id = int(i["id"]) - player_name = i["name"] - player_stat = float(i["stat"]) - - if rebuilt_json.get(player_id) is None: - rebuilt_json[player_id] = {} - - rebuilt_json[player_id]["game_id"] = game_id - rebuilt_json[player_id][ - "team_name" - ] = team_name - rebuilt_json[player_id][ - "team_conference" - ] = team_conference - rebuilt_json[player_id][ - "player_id" - ] = player_id - rebuilt_json[player_id][ - "player_name" - ] = player_name - rebuilt_json[player_id][ - "home_away" - ] = home_away - rebuilt_json[player_id][ - "puntReturns_AVG" - ] = player_stat - - elif stat["name"] == "TD": # puntReturns_TD - for i in stat["athletes"]: - player_id = int(i["id"]) - player_name = i["name"] - player_stat = int(i["stat"]) - - if rebuilt_json.get(player_id) is None: - rebuilt_json[player_id] = {} - - rebuilt_json[player_id]["game_id"] = game_id - rebuilt_json[player_id][ - "team_name" - ] = team_name - rebuilt_json[player_id][ - "team_conference" - ] = team_conference - rebuilt_json[player_id][ - "player_id" - ] = player_id - rebuilt_json[player_id][ - "player_name" - ] = player_name - rebuilt_json[player_id][ - "home_away" - ] = home_away - rebuilt_json[player_id][ - "puntReturns_TD" - ] = player_stat - - elif stat["name"] == "LONG": # puntReturns_LONG - for i in stat["athletes"]: - player_id = int(i["id"]) - player_name = i["name"] - player_stat = int(i["stat"]) - - if rebuilt_json.get(player_id) is None: - rebuilt_json[player_id] = {} - - rebuilt_json[player_id]["game_id"] = game_id - rebuilt_json[player_id][ - "team_name" - ] = team_name - rebuilt_json[player_id][ - "team_conference" - ] = team_conference - rebuilt_json[player_id][ - "player_id" - ] = player_id - rebuilt_json[player_id][ - "player_name" - ] = player_name - rebuilt_json[player_id][ - "home_away" - ] = home_away - rebuilt_json[player_id][ - "puntReturns_LONG" - ] = player_stat - - else: - raise IndexError( - f"Unhandled stat: \t{stat['name']}" - ) - - else: - raise IndexError( - f"Unhandled stat category: \t{s_category['name']}" - ) - - for key, value in tqdm(rebuilt_json.items()): - row_df = pd.json_normalize(value) - cfb_games_df = pd.concat([cfb_games_df, row_df], ignore_index=True) - del row_df + for stat_category in team["categories"]: + stat_category = stat_category["name"] + for s_type in stat_category["types"]: + stat_name = s_type["name"] + for player in s_type["athletes"]: + p_id = player["id"] + p_name = player["name"] + full_stat_name = f"{stat_category}_{stat_name}" + stat_value = player["stat"] + + if rebuilt_json.get(p_id) is None: + rebuilt_json[p_id] = {} + rebuilt_json[p_id]["player_id"] = p_id + rebuilt_json[p_id]["game_id"] = game_id + rebuilt_json[p_id]["team_name"] = team_name + rebuilt_json[p_id]["team_conference"] = team_conference + rebuilt_json[p_id]["home_away"] = home_away + rebuilt_json[p_id]["player_name"] = p_name + rebuilt_json[p_id][full_stat_name] = stat_value + + for _, value in rebuilt_json.items(): + rebuilt_json_list.append(value) + cfb_games_df = pd.DataFrame(rebuilt_json_list) + cfb_games_df["season"] = season cfb_games_df[["passing_COMP", "passing_ATT"]] = cfb_games_df[ "passing_C/ATT" @@ -3714,225 +2180,258 @@ def get_cfbd_player_game_stats( ].str.split( "/", expand=True ) - cfb_games_df[["kicking_XPM", "kicking_XPA"]] = cfb_games_df[ + + cfb_games_df[["kicking_XP", "kicking_XPM"]] = cfb_games_df[ "kicking_XP" ].str.split( "/", expand=True ) - cfb_games_df = cfb_games_df.fillna(0) + cfb_games_df = cfb_games_df.reindex( + columns=stat_columns + ) + cfb_games_df = cfb_games_df.replace(np.nan, 0) cfb_games_df = cfb_games_df.astype( { - "passing_COMP": "int", - "passing_ATT": "int", - "kicking_FGM": "int", - "kicking_FGA": "int", - "kicking_XPM": "int", - "kicking_XPA": "int", + "season": "uint16", + "game_id": "int64", + "team_name": "str", + "team_conference": "str", + "player_id": "int64", + "player_name": "str", + "home_away": "str", + + "passing_COMP": "uint16", + "passing_ATT": "uint16", + "passing_YDS": "int16", + "passing_TD": "uint16", + "passing_INT": "uint16", + "passing_AVG": "float16", + + "rushing_CAR": "uint16", + "rushing_YDS": "int16", + "rushing_AVG": "float16", + "rushing_TD": "uint16", + "rushing_LONG": "int16", + + "receiving_REC": "uint16", + "receiving_YDS": "int16", + "receiving_AVG": "float16", + "receiving_TD": "uint16", + "receiving_LONG": "int16", + + "fumbles_FUM": "uint8", + "fumbles_LOST": "uint8", + "fumbles_REC": "uint8", + + "defensive_TOT": "uint16", + "defensive_SOLO": "uint16", + "defensive_TFL": "float16", + "defensive_QB HUR": "uint16", + "defensive_SACKS": "float16", + "defensive_PD": "uint16", + "defensive_TD": "uint8", + + "interceptions_INT": "uint8", + "interceptions_YDS": "int16", + "interceptions_TD": "uint8", + + "punting_NO": "uint16", + "punting_YDS": "int16", + "punting_AVG": "float16", + "punting_TB": "uint8", + "punting_In 20": "uint8", + "punting_LONG": "int8", + + "kicking_FGM": "uint16", + "kicking_FGA": "uint16", + "kicking_PCT": "float16", + "kicking_LONG": "uint8", + "kicking_XPM": "uint16", + "kicking_XPA": "uint16", + "kicking_PTS": "uint16", + + "kickReturns_NO": "uint16", + "kickReturns_YDS": "int16", + "kickReturns_AVG": "float16", + "kickReturns_TD": "uint8", + "kickReturns_LONG": "int8", + + "puntReturns_NO": "uint16", + "puntReturns_YDS": "int16", + "puntReturns_AVG": "float16", + "puntReturns_TD": "uint8", + "puntReturns_LONG": "int8", } ) - # print(cfb_games_df.columns) - cfb_games_df["season"] = season - - if filter_by_stat_category is False: - cfb_games_df = cfb_games_df.reindex(columns=stat_columns) - - elif filter_by_stat_category is True and stat_category == "passing": - cfb_games_df = cfb_games_df[ - [ - "season", - "game_id", - "team_name", - "team_conference", - "player_id", - "player_name", - "home_away", - # PASS - "passing_C/ATT", - "passing_COMP", - "passing_ATT", - "passing_YDS", - "passing_AVG", - "passing_TD", - "passing_INT", - "passing_QBR", - ] - ] + if filter_by_stat_category is True and stat_category == "passing": + cfb_games_df = cfb_games_df[[ + "season", + "game_id", + "team_name", + "team_conference", + "player_id", + "player_name", + "home_away", + # PASS + "passing_C/ATT", + "passing_COMP", + "passing_ATT", + "passing_YDS", + "passing_AVG", + "passing_TD", + "passing_INT", + "passing_QBR", + ]] elif filter_by_stat_category is True and stat_category == "rushing": - cfb_games_df = cfb_games_df[ - [ - "season", - "game_id", - "team_name", - "team_conference", - "player_id", - "player_name", - "home_away", - # RUSH - "rushing_CAR", - "rushing_YDS", - "rushing_AVG", - "rushing_TD", - "rushing_LONG", - ] - ] - + cfb_games_df = cfb_games_df[[ + "season", + "game_id", + "team_name", + "team_conference", + "player_id", + "player_name", + "home_away", + # RUSH + "rushing_CAR", + "rushing_YDS", + "rushing_AVG", + "rushing_TD", + "rushing_LONG", + ]] elif filter_by_stat_category is True and stat_category == "receiving": - cfb_games_df = cfb_games_df[ - [ - "season", - "game_id", - "team_name", - "team_conference", - "player_id", - "player_name", - "home_away", - # REC - "receiving_REC", - "receiving_YDS", - "receiving_AVG", - "receiving_TD", - "receiving_LONG", - ] - ] - + cfb_games_df = cfb_games_df[[ + "season", + "game_id", + "team_name", + "team_conference", + "player_id", + "player_name", + "home_away", + # REC + "receiving_REC", + "receiving_YDS", + "receiving_AVG", + "receiving_TD", + "receiving_LONG", + ]] elif filter_by_stat_category is True and stat_category == "fumbles": - cfb_games_df = cfb_games_df[ - [ - "season", - "game_id", - "team_name", - "team_conference", - "player_id", - "player_name", - "home_away", - # FUM - "fumbles_FUM", - "fumbles_LOST", - "fumbles_REC", - ] - ] - + cfb_games_df = cfb_games_df[[ + "season", + "game_id", + "team_name", + "team_conference", + "player_id", + "player_name", + "home_away", + # FUM + "fumbles_FUM", + "fumbles_LOST", + "fumbles_REC", + ]] elif filter_by_stat_category is True and stat_category == "defensive": - cfb_games_df = cfb_games_df[ - [ - "season", - "game_id", - "team_name", - "team_conference", - "player_id", - "player_name", - "home_away", - # DEFENSE - "defensive_TOT", - "defensive_SOLO", - "defensive_TFL", - "defensive_QB HUR", - "defensive_SACKS", - "defensive_PD", - "defensive_TD", - ] - ] - + cfb_games_df = cfb_games_df[[ + "season", + "game_id", + "team_name", + "team_conference", + "player_id", + "player_name", + "home_away", + # DEFENSE + "defensive_TOT", + "defensive_SOLO", + "defensive_TFL", + "defensive_QB HUR", + "defensive_SACKS", + "defensive_PD", + "defensive_TD", + ]] elif filter_by_stat_category is True and stat_category == "interceptions": - cfb_games_df = cfb_games_df[ - [ - "season", - "game_id", - "team_name", - "team_conference", - "player_id", - "player_name", - "home_away", - # INT - "interceptions_INT", - "interceptions_YDS", - "interceptions_TD", - ] - ] - + cfb_games_df = cfb_games_df[[ + "season", + "game_id", + "team_name", + "team_conference", + "player_id", + "player_name", + "home_away", + # INT + "interceptions_INT", + "interceptions_YDS", + "interceptions_TD", + ]] elif filter_by_stat_category is True and stat_category == "punting": - cfb_games_df = cfb_games_df[ - [ - "season", - "game_id", - "team_name", - "team_conference", - "player_id", - "player_name", - "home_away", - # PUNT - "punting_NO", - "punting_YDS", - "punting_AVG", - "punting_TB", - "punting_In 20", - "punting_LONG", - ] - ] - + cfb_games_df = cfb_games_df[[ + "season", + "game_id", + "team_name", + "team_conference", + "player_id", + "player_name", + "home_away", + # PUNT + "punting_NO", + "punting_YDS", + "punting_AVG", + "punting_TB", + "punting_In 20", + "punting_LONG", + ]] elif filter_by_stat_category is True and stat_category == "kicking": - cfb_games_df = cfb_games_df[ - [ - "season", - "game_id", - "team_name", - "team_conference", - "player_id", - "player_name", - "home_away", - # KICK - "kicking_FG", - "kicking_FGM", - "kicking_FGA", - "kicking_PCT", - "kicking_LONG", - "kicking_XP", - "kicking_XPM", - "kicking_XPA", - "kicking_PTS", - ] - ] - + cfb_games_df = cfb_games_df[[ + "season", + "game_id", + "team_name", + "team_conference", + "player_id", + "player_name", + "home_away", + # KICK + "kicking_FG", + "kicking_FGM", + "kicking_FGA", + "kicking_PCT", + "kicking_LONG", + "kicking_XP", + "kicking_XPM", + "kicking_XPA", + "kicking_PTS", + ]] elif filter_by_stat_category is True and stat_category == "kickReturns": - cfb_games_df = cfb_games_df[ - [ - "season", - "game_id", - "team_name", - "team_conference", - "player_id", - "player_name", - "home_away", - # KR - "kickReturns_NO", - "kickReturns_YDS", - "kickReturns_AVG", - "kickReturns_TD", - "kickReturns_LONG", - ] - ] - + cfb_games_df = cfb_games_df[[ + "season", + "game_id", + "team_name", + "team_conference", + "player_id", + "player_name", + "home_away", + # KR + "kickReturns_NO", + "kickReturns_YDS", + "kickReturns_AVG", + "kickReturns_TD", + "kickReturns_LONG", + ]] elif filter_by_stat_category is True and stat_category == "puntReturns": - cfb_games_df = cfb_games_df[ - [ - "season", - "game_id", - "team_name", - "team_conference", - "player_id", - "player_name", - "home_away", - # KR - "puntReturns_NO", - "puntReturns_YDS", - "puntReturns_AVG", - "puntReturns_TD", - "puntReturns_LONG", - ] - ] + cfb_games_df = cfb_games_df[[ + "season", + "game_id", + "team_name", + "team_conference", + "player_id", + "player_name", + "home_away", + # KR + "puntReturns_NO", + "puntReturns_YDS", + "puntReturns_AVG", + "puntReturns_TD", + "puntReturns_LONG", + ]] return cfb_games_df @@ -4132,8 +2631,8 @@ def get_cfbd_player_advanced_game_stats( game_excitement_score = json_data["gameInfo"]["excitement"] # Parsing Usage - print("Parsing player usage data.") - for player in tqdm(json_data["players"]["usage"]): + logging.info("Parsing player usage data.") + for player in json_data["players"]["usage"]: row_df = pd.DataFrame({"game_id": game_id}, index=[0]) row_df["player_name"] = player["player"] row_df["team"] = player["team"] @@ -4151,8 +2650,8 @@ def get_cfbd_player_advanced_game_stats( del row_df # Parsing PPA - print("Parsing player PPA data.") - for player in tqdm(json_data["players"]["ppa"]): + logging.info("Parsing player PPA data.") + for player in json_data["players"]["ppa"]: row_df = pd.DataFrame({"game_id": game_id}, index=[0]) row_df["player_name"] = player["player"] row_df["team"] = player["team"] diff --git a/cfbd_json_py/metrics.py b/cfbd_json_py/metrics.py index 97866d2..cd4eafb 100644 --- a/cfbd_json_py/metrics.py +++ b/cfbd_json_py/metrics.py @@ -1,5 +1,5 @@ # Creation Date: 08/30/2023 01:13 EDT -# Last Updated Date: 08/13/2024 02:10 PM EDT +# Last Updated Date: 09/16/2024 06:10 PM EDT # Author: Joseph Armstrong (armstrongjoseph08@gmail.com) # File Name: metrics.py # Purpose: Houses functions pertaining to various CFB @@ -197,7 +197,7 @@ def get_cfbd_predicted_ppa_from_down_distance( # but we have to convey to the person calling this # function that setting `down = 5` # is not something they should be doing. - logging.warn( + logging.warning( 'There is a very limited number of "5th down" situations ' + "in American Football history. " + "Do not expect anything back when calling this function, " diff --git a/cfbd_json_py/players.py b/cfbd_json_py/players.py index 3b63058..3d2df8f 100644 --- a/cfbd_json_py/players.py +++ b/cfbd_json_py/players.py @@ -1,16 +1,16 @@ # Creation Date: 08/30/2023 01:13 EDT -# Last Updated Date: 08/13/2024 02:10 PM EDT +# Last Updated Date: 09/16/2024 06:10 PM EDT # Author: Joseph Armstrong (armstrongjoseph08@gmail.com) # File Name: players.py # Purpose: Houses functions pertaining to CFB player data within the CFBD API. ############################################################################### -import logging +# import logging from datetime import datetime import pandas as pd import requests -from tqdm import tqdm +# from tqdm import tqdm # from cfbd_json_py.games import get_cfbd_player_game_stats from cfbd_json_py.utls import get_cfbd_api_token @@ -782,7 +782,6 @@ def get_cfbd_player_usage( if player_id is not None: url += f"&playerId={player_id}" - # print() if exclude_garbage_time is not None: url += f"&excludeGarbageTime={gt_str}" @@ -1518,6 +1517,8 @@ def get_cfbd_player_season_stats( """ rebuilt_json = {} + rebuilt_json_list = [] + stat_columns = [ "season", "team_name", @@ -1749,452 +1750,109 @@ def get_cfbd_player_season_stats( if return_as_dict is True: return json_data - for player in tqdm(json_data): - player_id = int(player["playerId"]) + for player in json_data: + player_id = player["playerId"] player_name = player["player"] team_name = player["team"] team_conference = player["conference"] - s_category = player["category"] - s_type = player["statType"] - s_num = player["stat"] if rebuilt_json.get(player_id) is None: rebuilt_json[player_id] = {} - if s_category == "passing": - if s_type == "COMPLETIONS": - rebuilt_json[player_id]["player_id"] = player_name - rebuilt_json[player_id]["player_name"] = player_name - rebuilt_json[player_id]["team_name"] = team_name - rebuilt_json[player_id]["team_conference"] = team_conference - rebuilt_json[player_id]["passing_COMP"] = s_num - - elif s_type == "ATT": - rebuilt_json[player_id]["player_name"] = player_name - rebuilt_json[player_id]["team_name"] = team_name - rebuilt_json[player_id]["team_conference"] = team_conference - rebuilt_json[player_id]["passing_ATT"] = s_num - - elif s_type == "YDS": - rebuilt_json[player_id]["player_name"] = player_name - rebuilt_json[player_id]["team_name"] = team_name - rebuilt_json[player_id]["team_conference"] = team_conference - rebuilt_json[player_id]["passing_YDS"] = s_num - - elif s_type == "TD": - rebuilt_json[player_id]["player_name"] = player_name - rebuilt_json[player_id]["team_name"] = team_name - rebuilt_json[player_id]["team_conference"] = team_conference - rebuilt_json[player_id]["passing_TD"] = s_num - - elif s_type == "INT": - rebuilt_json[player_id]["player_name"] = player_name - rebuilt_json[player_id]["team_name"] = team_name - rebuilt_json[player_id]["team_conference"] = team_conference - rebuilt_json[player_id]["passing_INT"] = s_num - # we can calculate these two later - elif s_type == "PCT": - pass - - elif s_type == "YPA": - pass - - else: - raise ValueError(f"Unhandled stat type: {s_type}") - - elif s_category == "rushing": - if s_type == "CAR": - rebuilt_json[player_id]["player_name"] = player_name - rebuilt_json[player_id]["team_name"] = team_name - rebuilt_json[player_id]["team_conference"] = team_conference - rebuilt_json[player_id]["rushing_CAR"] = s_num - - elif s_type == "YDS": - rebuilt_json[player_id]["player_name"] = player_name - rebuilt_json[player_id]["team_name"] = team_name - rebuilt_json[player_id]["team_conference"] = team_conference - rebuilt_json[player_id]["rushing_YDS"] = s_num - - elif s_type == "TD": - rebuilt_json[player_id]["player_name"] = player_name - rebuilt_json[player_id]["team_name"] = team_name - rebuilt_json[player_id]["team_conference"] = team_conference - rebuilt_json[player_id]["rushing_TD"] = s_num - - elif s_type == "LONG": - rebuilt_json[player_id]["player_name"] = player_name - rebuilt_json[player_id]["team_name"] = team_name - rebuilt_json[player_id]["team_conference"] = team_conference - rebuilt_json[player_id]["rushing_LONG"] = s_num - # we can calculate this later - elif s_type == "YPC": - pass - - else: - raise ValueError(f"Unhandled stat type: {s_type}") - - elif s_category == "receiving": - if s_type == "REC": - rebuilt_json[player_id]["player_name"] = player_name - rebuilt_json[player_id]["team_name"] = team_name - rebuilt_json[player_id]["team_conference"] = team_conference - rebuilt_json[player_id]["receiving_REC"] = s_num - - elif s_type == "YDS": - rebuilt_json[player_id]["player_name"] = player_name - rebuilt_json[player_id]["team_name"] = team_name - rebuilt_json[player_id]["team_conference"] = team_conference - rebuilt_json[player_id]["receiving_YDS"] = s_num - - elif s_type == "TD": - rebuilt_json[player_id]["player_name"] = player_name - rebuilt_json[player_id]["team_name"] = team_name - rebuilt_json[player_id]["team_conference"] = team_conference - rebuilt_json[player_id]["receiving_TD"] = s_num - - elif s_type == "LONG": - rebuilt_json[player_id]["player_name"] = player_name - rebuilt_json[player_id]["team_name"] = team_name - rebuilt_json[player_id]["team_conference"] = team_conference - rebuilt_json[player_id]["receiving_LONG"] = s_num - # we can calculate this later - elif s_type == "YPR": - pass - - else: - raise ValueError(f"Unhandled stat type: {s_type}") - - elif s_category == "fumbles": - if s_type == "FUM": - rebuilt_json[player_id]["player_name"] = player_name - rebuilt_json[player_id]["team_name"] = team_name - rebuilt_json[player_id]["team_conference"] = team_conference - rebuilt_json[player_id]["fumbles_FUM"] = s_num - - elif s_type == "LOST": - rebuilt_json[player_id]["player_name"] = player_name - rebuilt_json[player_id]["team_name"] = team_name - rebuilt_json[player_id]["team_conference"] = team_conference - rebuilt_json[player_id]["fumbles_LOST"] = s_num - - elif s_type == "REC": - rebuilt_json[player_id]["player_name"] = player_name - rebuilt_json[player_id]["team_name"] = team_name - rebuilt_json[player_id]["team_conference"] = team_conference - rebuilt_json[player_id]["fumbles_LOST"] = s_num - - else: - raise ValueError(f"Unhandled stat type: {s_type}") - - elif s_category == "defensive": - if s_type == "TOT": - rebuilt_json[player_id]["player_name"] = player_name - rebuilt_json[player_id]["team_name"] = team_name - rebuilt_json[player_id]["team_conference"] = team_conference - rebuilt_json[player_id]["defensive_TOT"] = s_num - - elif s_type == "SOLO": - rebuilt_json[player_id]["player_name"] = player_name - rebuilt_json[player_id]["team_name"] = team_name - rebuilt_json[player_id]["team_conference"] = team_conference - rebuilt_json[player_id]["defensive_SOLO"] = s_num - - elif s_type == "TFL": - rebuilt_json[player_id]["player_name"] = player_name - rebuilt_json[player_id]["team_name"] = team_name - rebuilt_json[player_id]["team_conference"] = team_conference - rebuilt_json[player_id]["defensive_TFL"] = s_num - - elif s_type == "QB HUR": - rebuilt_json[player_id]["player_name"] = player_name - rebuilt_json[player_id]["team_name"] = team_name - rebuilt_json[player_id]["team_conference"] = team_conference - rebuilt_json[player_id]["defensive_QB HUR"] = s_num - - elif s_type == "SACKS": - rebuilt_json[player_id]["player_name"] = player_name - rebuilt_json[player_id]["team_name"] = team_name - rebuilt_json[player_id]["team_conference"] = team_conference - rebuilt_json[player_id]["defensive_SACKS"] = s_num - - elif s_type == "PD": - rebuilt_json[player_id]["player_name"] = player_name - rebuilt_json[player_id]["team_name"] = team_name - rebuilt_json[player_id]["team_conference"] = team_conference - rebuilt_json[player_id]["defensive_PD"] = s_num - - elif s_type == "TD": - rebuilt_json[player_id]["player_name"] = player_name - rebuilt_json[player_id]["team_name"] = team_name - rebuilt_json[player_id]["team_conference"] = team_conference - rebuilt_json[player_id]["defensive_TD"] = s_num - - else: - raise ValueError(f"Unhandled stat type: {s_type}") - - elif s_category == "interceptions": - if s_type == "INT": - rebuilt_json[player_id]["player_name"] = player_name - rebuilt_json[player_id]["team_name"] = team_name - rebuilt_json[player_id]["team_conference"] = team_conference - rebuilt_json[player_id]["interceptions_INT"] = s_num - - elif s_type == "YDS": - rebuilt_json[player_id]["player_name"] = player_name - rebuilt_json[player_id]["team_name"] = team_name - rebuilt_json[player_id]["team_conference"] = team_conference - rebuilt_json[player_id]["interceptions_YDS"] = s_num - - elif s_type == "TD": - rebuilt_json[player_id]["player_name"] = player_name - rebuilt_json[player_id]["team_name"] = team_name - rebuilt_json[player_id]["team_conference"] = team_conference - rebuilt_json[player_id]["interceptions_TD"] = s_num - - elif s_type == "AVG": - pass - - else: - raise ValueError(f"Unhandled stat type: {s_type}") - - elif s_category == "punting": - if s_type == "NO": - rebuilt_json[player_id]["player_name"] = player_name - rebuilt_json[player_id]["team_name"] = team_name - rebuilt_json[player_id]["team_conference"] = team_conference - rebuilt_json[player_id]["punting_NO"] = s_num - - elif s_type == "YDS": - rebuilt_json[player_id]["player_name"] = player_name - rebuilt_json[player_id]["team_name"] = team_name - rebuilt_json[player_id]["team_conference"] = team_conference - rebuilt_json[player_id]["punting_YDS"] = s_num - - elif s_type == "TB": - rebuilt_json[player_id]["player_name"] = player_name - rebuilt_json[player_id]["team_name"] = team_name - rebuilt_json[player_id]["team_conference"] = team_conference - rebuilt_json[player_id]["punting_TB"] = s_num - - elif s_type == "In 20": - rebuilt_json[player_id]["player_name"] = player_name - rebuilt_json[player_id]["team_name"] = team_name - rebuilt_json[player_id]["team_conference"] = team_conference - rebuilt_json[player_id]["punting_In 20"] = s_num - - elif s_type == "LONG": - rebuilt_json[player_id]["player_name"] = player_name - rebuilt_json[player_id]["team_name"] = team_name - rebuilt_json[player_id]["team_conference"] = team_conference - rebuilt_json[player_id]["punting_LONG"] = s_num - - elif s_type == "YPP": - pass - - else: - raise ValueError(f"Unhandled stat type: {s_type}") - - elif s_category == "kicking": - if s_type == "FGM": - rebuilt_json[player_id]["player_name"] = player_name - rebuilt_json[player_id]["team_name"] = team_name - rebuilt_json[player_id]["team_conference"] = team_conference - rebuilt_json[player_id]["kicking_FGM"] = s_num - - elif s_type == "FGA": - rebuilt_json[player_id]["player_name"] = player_name - rebuilt_json[player_id]["team_name"] = team_name - rebuilt_json[player_id]["team_conference"] = team_conference - rebuilt_json[player_id]["kicking_FGA"] = s_num - - elif s_type == "LONG": - rebuilt_json[player_id]["player_name"] = player_name - rebuilt_json[player_id]["team_name"] = team_name - rebuilt_json[player_id]["team_conference"] = team_conference - rebuilt_json[player_id]["kicking_LONG"] = s_num - - elif s_type == "XPM": - rebuilt_json[player_id]["player_name"] = player_name - rebuilt_json[player_id]["team_name"] = team_name - rebuilt_json[player_id]["team_conference"] = team_conference - rebuilt_json[player_id]["kicking_XPM"] = s_num - - elif s_type == "XPA": - rebuilt_json[player_id]["player_name"] = player_name - rebuilt_json[player_id]["team_name"] = team_name - rebuilt_json[player_id]["team_conference"] = team_conference - rebuilt_json[player_id]["kicking_XPA"] = s_num - - elif s_type == "PTS": - pass - - elif s_type == "PCT": - pass - - else: - raise ValueError(f"Unhandled stat type: {s_type}") - - elif s_category == "kickReturns": - if s_type == "NO": - rebuilt_json[player_id]["player_name"] = player_name - rebuilt_json[player_id]["team_name"] = team_name - rebuilt_json[player_id]["team_conference"] = team_conference - rebuilt_json[player_id]["kickReturns_NO"] = s_num - - elif s_type == "YDS": - rebuilt_json[player_id]["player_name"] = player_name - rebuilt_json[player_id]["team_name"] = team_name - rebuilt_json[player_id]["team_conference"] = team_conference - rebuilt_json[player_id]["kickReturns_YDS"] = s_num - - elif s_type == "TD": - rebuilt_json[player_id]["player_name"] = player_name - rebuilt_json[player_id]["team_name"] = team_name - rebuilt_json[player_id]["team_conference"] = team_conference - rebuilt_json[player_id]["kickReturns_TD"] = s_num - - elif s_type == "LONG": - rebuilt_json[player_id]["player_name"] = player_name - rebuilt_json[player_id]["team_name"] = team_name - rebuilt_json[player_id]["team_conference"] = team_conference - rebuilt_json[player_id]["kickReturns_LONG"] = s_num - # we can calculate this later - elif s_type == "AVG": - pass - - else: - raise ValueError(f"Unhandled stat type: {s_type}") - - elif s_category == "puntReturns": - if s_type == "NO": - rebuilt_json[player_id]["player_name"] = player_name - rebuilt_json[player_id]["team_name"] = team_name - rebuilt_json[player_id]["team_conference"] = team_conference - rebuilt_json[player_id]["puntReturns_NO"] = s_num - - elif s_type == "YDS": - rebuilt_json[player_id]["player_name"] = player_name - rebuilt_json[player_id]["team_name"] = team_name - rebuilt_json[player_id]["team_conference"] = team_conference - rebuilt_json[player_id]["puntReturns_YDS"] = s_num - - elif s_type == "TD": - rebuilt_json[player_id]["player_name"] = player_name - rebuilt_json[player_id]["team_name"] = team_name - rebuilt_json[player_id]["team_conference"] = team_conference - rebuilt_json[player_id]["puntReturns_TD"] = s_num - - elif s_type == "LONG": - rebuilt_json[player_id]["player_name"] = player_name - rebuilt_json[player_id]["team_name"] = team_name - rebuilt_json[player_id]["team_conference"] = team_conference - rebuilt_json[player_id]["puntReturns_LONG"] = s_num - # we can calculate this later - elif s_type == "AVG": - pass - - else: - raise ValueError(f"Unhandled stat type: {s_type}") - - else: - raise ValueError(f"Unhandled stat category: {s_category}") - - del player_id, player_name, team_name, \ - team_conference, s_category, s_type, s_num - - for key, value in tqdm(rebuilt_json.items()): - row_df = pd.json_normalize(value) - row_df["player_id"] = key - final_df = pd.concat([final_df, row_df], ignore_index=True) - del row_df + stat_category = player["category"] + stat_type = player["statType"] + stat_name = f"{stat_category}_{stat_type}" - final_df = final_df.fillna(0) + stat_value = player["stat"] - final_df["season"] = season + rebuilt_json[player_id]["player_id"] = player_id + rebuilt_json[player_id]["player_name"] = player_name + rebuilt_json[player_id]["team_name"] = team_name + rebuilt_json[player_id]["team_conference"] = team_conference + rebuilt_json[player_id][stat_name] = stat_value - if filter_by_stat_category is False: - final_df = final_df.reindex(columns=stat_columns) - final_df = final_df.astype( - { - "passing_COMP": "int", - "passing_ATT": "int", - "rushing_CAR": "int", - "rushing_YDS": "int", - "receiving_REC": "int", - "receiving_YDS": "int", - "punting_NO": "int", - "punting_YDS": "int", - "kicking_FGM": "int", - "kicking_FGA": "int", - "kicking_XPM": "int", - "kicking_XPA": "int", - "kickReturns_NO": "int", - "kickReturns_YDS": "int", - "puntReturns_NO": "int", - "puntReturns_YDS": "int", - } - ) + for _, value in rebuilt_json.items(): + rebuilt_json_list.append(value) - final_df.loc[final_df["passing_ATT"] > 0, "passing_COMP%"] = ( - final_df["passing_COMP"] / final_df["passing_ATT"] - ) - final_df["passing_COMP%"] = final_df["passing_COMP%"].round(3) - - final_df.loc[final_df["rushing_CAR"] > 0, "rushing_AVG"] = ( - final_df["rushing_YDS"] / final_df["rushing_CAR"] - ) - final_df["rushing_AVG"] = final_df["rushing_AVG"].round(3) + final_df = pd.DataFrame(rebuilt_json_list) + final_df["season"] = season + # print(final_df.columns) - final_df.loc[final_df["receiving_REC"] > 0, "receiving_AVG"] = ( - final_df["receiving_YDS"] / final_df["receiving_REC"] - ) - final_df["receiving_AVG"] = final_df["receiving_AVG"].round(3) + final_df = final_df.rename( + columns={ + "passing_COMPLETIONS": "passing_COMP", + "passing_YPA": "passing_AVG", + "passing_PCT": "passing_COMP%", + "rushing_YPC": "rushing_AVG", + "punting_YPP": "punting_AVG", + "kicking_PCT": "kicking_FG%", + "receiving_YPR": "receiving_AVG", + } + ) + final_df = final_df.reindex(columns=stat_columns) + final_df = final_df.fillna(0) + final_df = final_df.astype( + { + "passing_COMP": "int", + "passing_ATT": "int", + "rushing_CAR": "int", + "rushing_YDS": "int", + "receiving_REC": "int", + "receiving_YDS": "int", + "punting_NO": "int", + "punting_YDS": "int", + "kicking_FGM": "int", + "kicking_FGA": "int", + "kicking_XPM": "int", + "kicking_XPA": "int", + "kickReturns_NO": "int", + "kickReturns_YDS": "int", + "puntReturns_NO": "int", + "puntReturns_YDS": "int", + }, + # errors="ignore" + ) - final_df.loc[final_df["punting_NO"] > 0, "punting_AVG"] = ( - final_df["punting_YDS"] / final_df["punting_NO"] - ) - final_df["punting_AVG"] = final_df["punting_AVG"].round(3) + final_df.loc[final_df["passing_ATT"] > 0, "passing_COMP%"] = ( + final_df["passing_COMP"] / final_df["passing_ATT"] + ) + final_df["passing_COMP%"] = final_df["passing_COMP%"].round(3) - final_df.loc[final_df["kicking_FGA"] > 0, "kicking_FG%"] = ( - final_df["kicking_FGM"] / final_df["kicking_FGA"] - ) - final_df["kicking_FG%"] = final_df["kicking_FG%"].round(5) + final_df.loc[final_df["rushing_CAR"] > 0, "rushing_AVG"] = ( + final_df["rushing_YDS"] / final_df["rushing_CAR"] + ) + final_df["rushing_AVG"] = final_df["rushing_AVG"].round(3) - final_df.loc[final_df["kicking_XPA"] > 0, "kicking_XP%"] = ( - final_df["kicking_XPM"] / final_df["kicking_XPA"] - ) - final_df["kicking_XP%"] = final_df["kicking_XP%"].round(5) + final_df.loc[final_df["receiving_REC"] > 0, "receiving_AVG"] = ( + final_df["receiving_YDS"] / final_df["receiving_REC"] + ) + final_df["receiving_AVG"] = final_df["receiving_AVG"].round(3) - final_df.loc[final_df["kickReturns_NO"] > 0, "kickReturns_AVG"] = ( - final_df["kickReturns_YDS"] / final_df["kickReturns_NO"] - ) - final_df["kickReturns_AVG"] = final_df["kickReturns_AVG"].round(3) + final_df.loc[final_df["punting_NO"] > 0, "punting_AVG"] = ( + final_df["punting_YDS"] / final_df["punting_NO"] + ) + final_df["punting_AVG"] = final_df["punting_AVG"].round(3) - final_df.loc[final_df["puntReturns_NO"] > 0, "puntReturns_AVG"] = ( - final_df["puntReturns_YDS"] / final_df["puntReturns_NO"] - ) - final_df["puntReturns_AVG"] = final_df["puntReturns_AVG"].round(3) + final_df.loc[final_df["kicking_FGA"] > 0, "kicking_FG%"] = ( + final_df["kicking_FGM"] / final_df["kicking_FGA"] + ) + final_df["kicking_FG%"] = final_df["kicking_FG%"].round(5) - elif filter_by_stat_category is True and stat_category == "passing": - try: - final_df = final_df.astype( - { - "passing_COMP": "int", - "passing_ATT": "int", - } - ) - except Exception as e: - logging.warning( - "Could not reformat [passing_COMP]" - + " and [passing_ATT] into integers. " - + f"Full Exception: {e}" - ) + final_df.loc[final_df["kicking_XPA"] > 0, "kicking_XP%"] = ( + final_df["kicking_XPM"] / final_df["kicking_XPA"] + ) + final_df["kicking_XP%"] = final_df["kicking_XP%"].round(5) - final_df.loc[final_df["passing_ATT"] >= 1, "passing_COMP%"] = ( - final_df["passing_COMP"] / final_df["passing_ATT"] - ) + final_df.loc[final_df["kickReturns_NO"] > 0, "kickReturns_AVG"] = ( + final_df["kickReturns_YDS"] / final_df["kickReturns_NO"] + ) + final_df["kickReturns_AVG"] = final_df["kickReturns_AVG"].round(3) - final_df["passing_COMP%"] = final_df["passing_COMP%"].round(3) + final_df.loc[final_df["puntReturns_NO"] > 0, "puntReturns_AVG"] = ( + final_df["puntReturns_YDS"] / final_df["puntReturns_NO"] + ) + final_df["puntReturns_AVG"] = final_df["puntReturns_AVG"].round(3) + if filter_by_stat_category is True and stat_category == "passing": final_df = final_df[ [ @@ -2211,26 +1869,7 @@ def get_cfbd_player_season_stats( "passing_INT", ] ] - elif filter_by_stat_category is True and stat_category == "rushing": - try: - final_df = final_df.astype( - { - "rushing_CAR": "int", - "rushing_YDS": "int", - } - ) - except Exception as e: - logging.warning( - "Could not reformat [rushing_CAR] " - + "and [rushing_YDS] into integers. " - + f"Full Exception: {e}" - ) - - final_df.loc[final_df["rushing_CAR"] >= 1, "rushing_AVG"] = ( - final_df["rushing_YDS"] / final_df["rushing_CAR"] - ) - final_df["rushing_AVG"] = final_df["rushing_AVG"].round(3) final_df = final_df[ [ @@ -2247,26 +1886,7 @@ def get_cfbd_player_season_stats( "rushing_LONG", ] ] - elif filter_by_stat_category is True and stat_category == "receiving": - try: - final_df = final_df.astype( - { - "receiving_REC": "int", - "receiving_YDS": "int", - } - ) - except Exception as e: - logging.warning( - "Could not reformat [receiving_REC] " - + "and [receiving_YDS] into integers. " - + f"Full Exception: {e}" - ) - - final_df.loc[final_df["receiving_REC"] > 0, "receiving_AVG"] = ( - final_df["receiving_YDS"] / final_df["receiving_REC"] - ) - final_df["receiving_AVG"] = final_df["receiving_AVG"].round(3) final_df = final_df[ [ @@ -2283,7 +1903,6 @@ def get_cfbd_player_season_stats( "receiving_LONG", ] ] - elif filter_by_stat_category is True and stat_category == "fumbles": final_df = final_df[ [ @@ -2298,7 +1917,6 @@ def get_cfbd_player_season_stats( "fumbles_REC", ] ] - elif filter_by_stat_category is True and stat_category == "defensive": final_df = final_df[ [ @@ -2317,7 +1935,6 @@ def get_cfbd_player_season_stats( "defensive_TD", ] ] - elif filter_by_stat_category is True and stat_category == "interceptions": final_df = final_df[ [ @@ -2332,26 +1949,7 @@ def get_cfbd_player_season_stats( "interceptions_TD", ] ] - elif filter_by_stat_category is True and stat_category == "punting": - try: - final_df = final_df.astype( - { - "punting_NO": "int", - "punting_YDS": "int", - } - ) - except Exception as e: - logging.warning( - "Could not reformat [punting_YDS] " - + "and [punting_NO] into integers. " - + f"Full Exception: {e}" - ) - - final_df.loc[final_df["punting_NO"] > 0, "punting_AVG"] = ( - final_df["punting_YDS"] / final_df["punting_NO"] - ) - final_df["punting_AVG"] = final_df["punting_AVG"].round(3) final_df = final_df[ [ @@ -2369,36 +1967,7 @@ def get_cfbd_player_season_stats( "punting_LONG", ] ] - elif filter_by_stat_category is True and stat_category == "kicking": - try: - final_df = final_df.astype( - { - "kicking_FGM": "int", - "kicking_FGA": "int", - "kicking_XPM": "int", - "kicking_XPA": "int", - } - ) - except Exception as e: - logging.warning( - "Could not reformat the following columns into integers.:" - + "\n-[kicking_FGM]" - + "\n-[kicking_FGA]" - + "\n-[kicking_XPM]" - + "\n-[kicking_XPA]" - + f"\nFull Exception: {e}" - ) - - final_df.loc[final_df["kicking_FGA"] > 0, "kicking_FG%"] = ( - final_df["kicking_FGM"] / final_df["kicking_FGA"] - ) - final_df["kicking_FG%"] = final_df["kicking_FG%"].round(5) - - final_df.loc[final_df["kicking_XPA"] > 0, "kicking_XP%"] = ( - final_df["kicking_XPM"] / final_df["kicking_XPA"] - ) - final_df["kicking_XP%"] = final_df["kicking_XP%"].round(5) final_df = final_df[ [ @@ -2416,26 +1985,7 @@ def get_cfbd_player_season_stats( "kicking_XPA" "kicking_XP%", ] ] - elif filter_by_stat_category is True and stat_category == "kickReturns": - try: - final_df = final_df.astype( - { - "kickReturns_NO": "int", - "kickReturns_YDS": "int", - } - ) - except Exception as e: - logging.warning( - "Could not reformat [passing_COMP] " - + "and [kickReturns_YDS] into integers. " - + f"Full Exception: {e}" - ) - - final_df.loc[final_df["kickReturns_NO"] > 0, "kickReturns_AVG"] = ( - final_df["kickReturns_YDS"] / final_df["kickReturns_NO"] - ) - final_df["kickReturns_AVG"] = final_df["kickReturns_AVG"].round(3) final_df = final_df[ [ @@ -2452,26 +2002,7 @@ def get_cfbd_player_season_stats( "kickReturns_LONG", ] ] - elif filter_by_stat_category is True and stat_category == "puntReturns": - try: - final_df = final_df.astype( - { - "puntReturns_NO": "int", - "puntReturns_YDS": "int", - } - ) - except Exception as e: - logging.warning( - "Could not reformat [passing_COMP] " - + "and [puntReturns_YDS] into integers." - + f"Full Exception: {e}" - ) - - final_df.loc[final_df["puntReturns_NO"] > 0, "puntReturns_AVG"] = ( - final_df["puntReturns_YDS"] / final_df["puntReturns_NO"] - ) - final_df["puntReturns_AVG"] = final_df["puntReturns_AVG"].round(3) final_df = final_df[ [ diff --git a/cfbd_json_py/plays.py b/cfbd_json_py/plays.py index f5c8658..76f7119 100644 --- a/cfbd_json_py/plays.py +++ b/cfbd_json_py/plays.py @@ -1,5 +1,5 @@ # Creation Date: 08/30/2023 01:13 EDT -# Last Updated Date: 08/13/2024 02:10 PM EDT +# Last Updated Date: 09/16/2024 06:10 PM EDT # Author: Joseph Armstrong (armstrongjoseph08@gmail.com) # File Name: plays.py # Purpose: Houses functions pertaining to CFB play data within the CFBD API. @@ -10,7 +10,7 @@ import pandas as pd import requests -from tqdm import tqdm +# from tqdm import tqdm from cfbd_json_py.utls import get_cfbd_api_token @@ -634,7 +634,9 @@ def get_cfbd_pbp_data( def get_cfbd_pbp_play_types( - api_key: str = None, api_key_dir: str = None, return_as_dict: bool = False + api_key: str = None, + api_key_dir: str = None, + return_as_dict: bool = False ): """ Allows you to get CFBD PBP play types from the CFBD API. @@ -680,6 +682,7 @@ def get_cfbd_pbp_play_types( """ # now = datetime.now() plays_df = pd.DataFrame() + plays_df_arr = [] row_df = pd.DataFrame() url = "https://api.collegefootballdata.com/play/types" @@ -727,16 +730,17 @@ def get_cfbd_pbp_play_types( if return_as_dict is True: return json_data - for p in tqdm(json_data): + for p in json_data: p_id = p["id"] row_df = pd.DataFrame({"play_type_id": p_id}, index=[0]) row_df["play_type_text"] = p["text"] row_df["play_type_abv"] = p["abbreviation"] - plays_df = pd.concat([plays_df, row_df], ignore_index=True) - + # plays_df = pd.concat([plays_df, row_df], ignore_index=True) + plays_df_arr.append(row_df) del row_df del p_id + plays_df = pd.concat(plays_df_arr, ignore_index=True) return plays_df @@ -756,6 +760,7 @@ def get_cfbd_pbp_stats( """ Allows you to get stats for various players from CFB play-by-play (PBP) data within the CFBD API. + Parameters ---------- @@ -1096,13 +1101,16 @@ def get_cfbd_pbp_stats( ) if season is None and game_id is None: - logging.warn( + logging.warning( "This endpoint only returns the top 1,000 results. " + "Not setting a value for `season` or `game_id` " + "is not a recommended practice." ) - elif season is not None and game_id is None: - logging.warn( + elif ( + (season is not None) and + (game_id is not None) + ): + logging.warning( "Setting a value for both `season` and `game_id` " + "may not yeld the results you want. " + "If you just want PBP stats for a valid game ID, " @@ -1215,7 +1223,9 @@ def get_cfbd_pbp_stats( def get_cfbd_pbp_stat_types( - api_key: str = None, api_key_dir: str = None, return_as_dict: bool = False + api_key: str = None, + api_key_dir: str = None, + return_as_dict: bool = False ): """ Allows you to get CFBD PBP stat types from the CFBD API. @@ -1261,6 +1271,7 @@ def get_cfbd_pbp_stat_types( """ # now = datetime.now() plays_df = pd.DataFrame() + plays_df_arr = [] row_df = pd.DataFrame() url = "https://api.collegefootballdata.com/play/types" @@ -1308,15 +1319,21 @@ def get_cfbd_pbp_stat_types( if return_as_dict is True: return json_data - for p in tqdm(json_data): + for p in json_data: p_id = p["id"] row_df = pd.DataFrame({"stat_type_id": p_id}, index=[0]) - row_df["stat_type_text"] = p["name"] - plays_df = pd.concat([plays_df, row_df], ignore_index=True) + row_df["stat_type_abv"] = p["abbreviation"] + try: + row_df["stat_type_text"] = p["name"] + except KeyError: + row_df["stat_type_text"] = p["text"] + # plays_df = pd.concat([plays_df, row_df], ignore_index=True) + plays_df_arr.append(row_df) del row_df del p_id + plays_df = pd.concat(plays_df_arr, ignore_index=True) return plays_df diff --git a/cfbd_json_py/rankings.py b/cfbd_json_py/rankings.py index f063805..e195526 100644 --- a/cfbd_json_py/rankings.py +++ b/cfbd_json_py/rankings.py @@ -1,5 +1,5 @@ # Creation Date: 08/30/2023 01:13 EDT -# Last Updated Date: 08/13/2024 02:10 PM EDT +# Last Updated Date: 09/16/2024 06:10 PM EDT # Author: Joseph Armstrong (armstrongjoseph08@gmail.com) # File Name: rankings.py # Purpose: Houses functions pertaining to CFB poll data within the CFBD API. @@ -9,7 +9,7 @@ import pandas as pd import requests -from tqdm import tqdm +# from tqdm import tqdm from cfbd_json_py.utls import get_cfbd_api_token @@ -284,7 +284,7 @@ def get_cfbd_poll_rankings( if return_as_dict is True: return json_data - for week in tqdm(json_data): + for week in json_data: w_season = week["season"] w_season_type = week["seasonType"] w_week = week["week"] diff --git a/cfbd_json_py/recruiting.py b/cfbd_json_py/recruiting.py index 152efc7..51dadb4 100644 --- a/cfbd_json_py/recruiting.py +++ b/cfbd_json_py/recruiting.py @@ -1,5 +1,5 @@ # Creation Date: 08/30/2023 01:13 EDT -# Last Updated Date: 08/13/2024 02:10 PM EDT +# Last Updated Date: 09/16/2024 06:10 PM EDT # Author: Joseph Armstrong (armstrongjoseph08@gmail.com) # File Name: recruiting.py # Purpose: Houses functions pertaining to CFB recruiting data @@ -291,7 +291,7 @@ def get_cfbd_player_recruit_ratings( """ - now = datetime.now() + # now = datetime.now() recruit_df = pd.DataFrame() # row_df = pd.DataFrame() url = "https://api.collegefootballdata.com/recruiting/players" @@ -315,9 +315,12 @@ def get_cfbd_player_recruit_ratings( else: real_api_key = "Bearer " + real_api_key - if season > (now.year + 1): - raise ValueError(f"`season` cannot be greater than {season}.") - elif season < 1869: + # if season > (now.year + 1): + # raise ValueError(f"`season` cannot be greater than {season}.") + # elif season < 1869: + # raise ValueError("`season` cannot be less than 1869.") + + if season < 1869: raise ValueError("`season` cannot be less than 1869.") if ( @@ -570,7 +573,7 @@ def get_cfbd_team_recruiting_ratings( a dictionary object with CFB Poll data. """ - now = datetime.now() + # now = datetime.now() recruit_df = pd.DataFrame() # row_df = pd.DataFrame() url = "https://api.collegefootballdata.com/recruiting/teams" @@ -594,9 +597,12 @@ def get_cfbd_team_recruiting_ratings( else: real_api_key = "Bearer " + real_api_key - if season is not None and season > (now.year + 1): - raise ValueError(f"`season` cannot be greater than {season}.") - elif season is not None and season < 1869: + # if season > (now.year + 1): + # raise ValueError(f"`season` cannot be greater than {season}.") + # elif season < 1869: + # raise ValueError("`season` cannot be less than 1869.") + + if season < 1869: raise ValueError("`season` cannot be less than 1869.") if season is None and team is None: diff --git a/cfbd_json_py/stats.py b/cfbd_json_py/stats.py index acc0240..814a423 100644 --- a/cfbd_json_py/stats.py +++ b/cfbd_json_py/stats.py @@ -1,5 +1,5 @@ # Creation Date: 08/30/2023 01:13 PM EDT -# Last Updated Date: 08/13/2024 02:10 PM EDT +# Last Updated Date: 09/16/2024 06:10 PM EDT # Author: Joseph Armstrong (armstrongjoseph08@gmail.com) # File Name: stats.py # Purpose: Houses functions pertaining to CFB team/player @@ -611,7 +611,6 @@ def get_cfbd_team_season_stats( for key, value in tqdm(rebuilt_json.items()): row_df = pd.DataFrame(value, index=[0]) final_df = pd.concat([final_df, row_df], ignore_index=True) - # print() final_df = final_df[stat_columns] return final_df @@ -962,10 +961,6 @@ def get_cfbd_advanced_team_season_stats( if return_as_dict is True: return json_data - # final_df = pd.json_normalize(json_data) - - # print(final_df.columns) - for team in tqdm(json_data): t_season = team["season"] t_team = team["team"] diff --git a/cfbd_json_py/utls.py b/cfbd_json_py/utls.py index e4aaf5c..879ed77 100644 --- a/cfbd_json_py/utls.py +++ b/cfbd_json_py/utls.py @@ -1,5 +1,5 @@ # Creation Date: 08/30/2023 01:13 EDT -# Last Updated Date: 08/13/2024 02:10 PM EDT +# Last Updated Date: 08/28/2024 02:10 PM EDT # Author: Joseph Armstrong (armstrongjoseph08@gmail.com) # File Name: utls.py # Purpose: Houses utility functions for this python package. diff --git a/cfbd_json_py/venues.py b/cfbd_json_py/venues.py index 21a44c8..0557056 100644 --- a/cfbd_json_py/venues.py +++ b/cfbd_json_py/venues.py @@ -1,5 +1,5 @@ # Creation Date: 08/30/2023 01:13 EDT -# Last Updated Date: 08/13/2024 02:10 PM EDT +# Last Updated Date: 09/16/2024 06:10 PM EDT # Author: Joseph Armstrong (armstrongjoseph08@gmail.com) # File Name: venues.py # Purpose: Houses functions pertaining to @@ -13,7 +13,9 @@ def get_cfbd_venues( - api_key: str = None, api_key_dir: str = None, return_as_dict: bool = False + api_key: str = None, + api_key_dir: str = None, + return_as_dict: bool = False ): """ Allows a user to get CFB venue/stadium information from the CFBD API. diff --git a/docs/cfbd_json_py.html b/docs/cfbd_json_py.html index 26a1ea8..abc3657 100644 --- a/docs/cfbd_json_py.html +++ b/docs/cfbd_json_py.html @@ -1937,4 +1937,4 @@

Other Notes

- \ No newline at end of file + diff --git a/docs/cfbd_json_py/_early_access.html b/docs/cfbd_json_py/_early_access.html index 37e0cfc..da5c008 100644 --- a/docs/cfbd_json_py/_early_access.html +++ b/docs/cfbd_json_py/_early_access.html @@ -1748,4 +1748,4 @@

Purpos - \ No newline at end of file + diff --git a/docs/cfbd_json_py/betting.html b/docs/cfbd_json_py/betting.html index 676139b..d69ec5b 100644 --- a/docs/cfbd_json_py/betting.html +++ b/docs/cfbd_json_py/betting.html @@ -1481,7 +1481,7 @@

5# Purpose: Houses functions pertaining to betting data within the CFBD API. 6############################################################################### 7 - 8import warnings + 8# import warnings 9 10import pandas as pd 11import requests @@ -1494,7 +1494,7 @@

18 season: int = None, 19 api_key: str = None, 20 api_key_dir: str = None, - 21 game_id: int = None, + 21 # game_id: int = None, 22 week: int = None, 23 season_type: str = "regular", # "regular" or "postseason" 24 team: str = None, @@ -1537,7 +1537,7 @@

61 and will try to find a CFBD API key file in that directory. 62 63 `game_id` (int, optional): - 64 Optional argument. + 64 DEPRECATED FROM V1. 65 If `game_id` is set to a game ID, 66 `get_cfb_betting_lines()` will try to get 67 all betting information for that game ID. @@ -1878,12 +1878,12 @@

402 403 del year, home, away 404 -405 if game_id is not None and season is not None: -406 warnings.warn( -407 "If you are getting betting information for a single game, " -408 + "only set `game_id` to the game ID, " + -409 "and leave `season` as `NULL`." -410 ) +405 # if game_id is not None and season is not None: +406 # warnings.warn( +407 # "If you are getting betting information for a single game, " +408 # + "only set `game_id` to the game ID, " + +409 # "and leave `season` as `NULL`." +410 # ) 411 412 if season_type == "regular" or season_type == "postseason": 413 url += f"seasonType={season_type}" @@ -1892,129 +1892,134 @@

416 '`season_type` must be set to either "regular" or "postseason".' 417 ) 418 -419 if (game_id is None) and (season is None) and (week is not None): -420 raise ValueError( -421 "When setting a value for `week`, `season` cannot be null." -422 ) +419 # if (game_id is None) and (season is None) and (week is not None): +420 # raise ValueError( +421 # "When setting a value for `week`, `season` cannot be null." +422 # ) 423 -424 if api_key is not None: -425 real_api_key = api_key -426 del api_key -427 else: -428 real_api_key = get_cfbd_api_token(api_key_dir=api_key_dir) -429 -430 if real_api_key == "tigersAreAwesome": -431 raise ValueError( -432 "You actually need to change `cfbd_key` to your CFBD API key." -433 ) -434 elif "Bearer " in real_api_key: -435 pass -436 elif "Bearer" in real_api_key: -437 real_api_key = real_api_key.replace("Bearer", "Bearer ") -438 else: -439 real_api_key = "Bearer " + real_api_key -440 -441 # URL builder -442 ########################################################################## -443 -444 if game_id is not None: -445 url += f"&gameId={game_id}" -446 -447 if season is not None: -448 url += f"&year={season}" -449 -450 if week is not None: -451 url += f"&week={week}" -452 -453 if team is not None: -454 url += f"&team={team}" -455 -456 if home_team is not None: -457 url += f"&home={home_team}" -458 -459 if away_team is not None: -460 url += f"&away={away_team}" -461 -462 if conference is not None: -463 url += f"&conference={conference}" -464 -465 headers = { -466 "Authorization": f"{real_api_key}", "accept": "application/json" -467 } -468 -469 response = requests.get(url, headers=headers) -470 -471 if response.status_code == 200: -472 pass -473 elif response.status_code == 401: -474 raise ConnectionRefusedError( -475 "Could not connect. The connection was refused.\n" + -476 "HTTP Status Code 401." -477 ) -478 else: -479 raise ConnectionError( -480 f"Could not connect.\nHTTP Status code {response.status_code}" -481 ) -482 -483 json_data = response.json() -484 -485 if return_as_dict is True: -486 return json_data +424 if (season is None) and (week is not None): +425 raise ValueError( +426 "When setting a value for `week`, `season` cannot be null." +427 ) +428 +429 if api_key is not None: +430 real_api_key = api_key +431 del api_key +432 else: +433 real_api_key = get_cfbd_api_token(api_key_dir=api_key_dir) +434 +435 if real_api_key == "tigersAreAwesome": +436 raise ValueError( +437 "You actually need to change `cfbd_key` to your CFBD API key." +438 ) +439 elif "Bearer " in real_api_key: +440 pass +441 elif "Bearer" in real_api_key: +442 real_api_key = real_api_key.replace("Bearer", "Bearer ") +443 else: +444 real_api_key = "Bearer " + real_api_key +445 +446 # URL builder +447 ########################################################################## +448 +449 # if game_id is not None: +450 # url += f"&gameId={game_id}" +451 +452 if season is not None: +453 url += f"&year={season}" +454 +455 if week is not None: +456 url += f"&week={week}" +457 +458 if team is not None: +459 url += f"&team={team}" +460 +461 if home_team is not None: +462 url += f"&home={home_team}" +463 +464 if away_team is not None: +465 url += f"&away={away_team}" +466 +467 if conference is not None: +468 url += f"&conference={conference}" +469 +470 headers = { +471 "Authorization": f"{real_api_key}", "accept": "application/json" +472 } +473 +474 response = requests.get(url, headers=headers) +475 +476 if response.status_code == 200: +477 pass +478 elif response.status_code == 401: +479 raise ConnectionRefusedError( +480 "Could not connect. The connection was refused.\n" + +481 "HTTP Status Code 401." +482 ) +483 else: +484 raise ConnectionError( +485 f"Could not connect.\nHTTP Status code {response.status_code}" +486 ) 487 -488 for game in tqdm(json_data): -489 gameId = game["id"] -490 season = game["id"] -491 seasonType = game["seasonType"] -492 startDate = game["startDate"] -493 homeTeam = game["homeTeam"] -494 homeConference = game["homeConference"] -495 homeScore = game["homeScore"] -496 awayTeam = game["awayTeam"] -497 awayConference = game["awayConference"] -498 awayScore = game["awayScore"] -499 -500 for line in game["lines"]: -501 row_df = pd.DataFrame( -502 { -503 "game_id": gameId, -504 "season": season, -505 "season_type": seasonType, -506 "start_date": startDate, -507 "home_team_name": homeTeam, -508 "home_conference_name": homeConference, -509 "home_score": homeScore, -510 "away_team_name": awayTeam, -511 "away_conference_name": awayConference, -512 "away_score": awayScore, -513 }, -514 index=[0], -515 ) -516 -517 row_df["line_provider"] = line["provider"] -518 row_df["spread"] = line["spread"] -519 row_df["formatted_spread"] = line["formattedSpread"] -520 row_df["spread_open"] = line["spreadOpen"] -521 row_df["over_under"] = line["overUnder"] -522 row_df["over_under_open"] = line["overUnderOpen"] -523 row_df["home_moneyline"] = line["homeMoneyline"] -524 row_df["away_moneyline"] = line["awayMoneyline"] -525 -526 betting_df = pd.concat([betting_df, row_df], ignore_index=True) -527 del row_df -528 -529 del ( -530 gameId, -531 seasonType, -532 startDate, -533 homeTeam, -534 homeConference, -535 homeScore, -536 awayTeam, -537 awayConference, -538 awayScore, -539 ) -540 -541 return betting_df +488 json_data = response.json() +489 +490 if return_as_dict is True: +491 return json_data +492 +493 for game in tqdm(json_data): +494 gameId = game["id"] +495 season = game["id"] +496 seasonType = game["seasonType"] +497 startDate = game["startDate"] +498 homeTeam = game["homeTeam"] +499 homeConference = game["homeConference"] +500 homeScore = game["homeScore"] +501 awayTeam = game["awayTeam"] +502 awayConference = game["awayConference"] +503 awayScore = game["awayScore"] +504 +505 for line in game["lines"]: +506 row_df = pd.DataFrame( +507 { +508 "game_id": gameId, +509 "season": season, +510 "season_type": seasonType, +511 "start_date": startDate, +512 "home_team_name": homeTeam, +513 "home_conference_name": homeConference, +514 "home_score": homeScore, +515 "away_team_name": awayTeam, +516 "away_conference_name": awayConference, +517 "away_score": awayScore, +518 }, +519 index=[0], +520 ) +521 +522 row_df["line_provider"] = line["provider"] +523 row_df["spread"] = line["spread"] +524 row_df["formatted_spread"] = line["formattedSpread"] +525 row_df["spread_open"] = line["spreadOpen"] +526 row_df["over_under"] = line["overUnder"] +527 row_df["over_under_open"] = line["overUnderOpen"] +528 row_df["home_moneyline"] = line["homeMoneyline"] +529 row_df["away_moneyline"] = line["awayMoneyline"] +530 +531 betting_df = pd.concat([betting_df, row_df], ignore_index=True) +532 del row_df +533 +534 del ( +535 gameId, +536 seasonType, +537 startDate, +538 homeTeam, +539 homeConference, +540 homeScore, +541 awayTeam, +542 awayConference, +543 awayScore, +544 ) +545 +546 return betting_df @@ -2033,8 +2038,6 @@

class="o">= None, api_key_dir: str = None, game_id: int = None, week: int = None, season_type: str 19 season: int = None, 20 api_key: str = None, 21 api_key_dir: str = None, - 22 game_id: int = None, + 22 # game_id: int = None, 23 week: int = None, 24 season_type: str = "regular", # "regular" or "postseason" 25 team: str = None, @@ -2110,7 +2113,7 @@

62 and will try to find a CFBD API key file in that directory. 63 64 `game_id` (int, optional): - 65 Optional argument. + 65 DEPRECATED FROM V1. 66 If `game_id` is set to a game ID, 67 `get_cfb_betting_lines()` will try to get 68 all betting information for that game ID. @@ -2451,12 +2454,12 @@

403 404 del year, home, away 405 -406 if game_id is not None and season is not None: -407 warnings.warn( -408 "If you are getting betting information for a single game, " -409 + "only set `game_id` to the game ID, " + -410 "and leave `season` as `NULL`." -411 ) +406 # if game_id is not None and season is not None: +407 # warnings.warn( +408 # "If you are getting betting information for a single game, " +409 # + "only set `game_id` to the game ID, " + +410 # "and leave `season` as `NULL`." +411 # ) 412 413 if season_type == "regular" or season_type == "postseason": 414 url += f"seasonType={season_type}" @@ -2465,129 +2468,134 @@

417 '`season_type` must be set to either "regular" or "postseason".' 418 ) 419 -420 if (game_id is None) and (season is None) and (week is not None): -421 raise ValueError( -422 "When setting a value for `week`, `season` cannot be null." -423 ) +420 # if (game_id is None) and (season is None) and (week is not None): +421 # raise ValueError( +422 # "When setting a value for `week`, `season` cannot be null." +423 # ) 424 -425 if api_key is not None: -426 real_api_key = api_key -427 del api_key -428 else: -429 real_api_key = get_cfbd_api_token(api_key_dir=api_key_dir) -430 -431 if real_api_key == "tigersAreAwesome": -432 raise ValueError( -433 "You actually need to change `cfbd_key` to your CFBD API key." -434 ) -435 elif "Bearer " in real_api_key: -436 pass -437 elif "Bearer" in real_api_key: -438 real_api_key = real_api_key.replace("Bearer", "Bearer ") -439 else: -440 real_api_key = "Bearer " + real_api_key -441 -442 # URL builder -443 ########################################################################## -444 -445 if game_id is not None: -446 url += f"&gameId={game_id}" -447 -448 if season is not None: -449 url += f"&year={season}" -450 -451 if week is not None: -452 url += f"&week={week}" -453 -454 if team is not None: -455 url += f"&team={team}" -456 -457 if home_team is not None: -458 url += f"&home={home_team}" -459 -460 if away_team is not None: -461 url += f"&away={away_team}" -462 -463 if conference is not None: -464 url += f"&conference={conference}" -465 -466 headers = { -467 "Authorization": f"{real_api_key}", "accept": "application/json" -468 } -469 -470 response = requests.get(url, headers=headers) -471 -472 if response.status_code == 200: -473 pass -474 elif response.status_code == 401: -475 raise ConnectionRefusedError( -476 "Could not connect. The connection was refused.\n" + -477 "HTTP Status Code 401." -478 ) -479 else: -480 raise ConnectionError( -481 f"Could not connect.\nHTTP Status code {response.status_code}" -482 ) -483 -484 json_data = response.json() -485 -486 if return_as_dict is True: -487 return json_data +425 if (season is None) and (week is not None): +426 raise ValueError( +427 "When setting a value for `week`, `season` cannot be null." +428 ) +429 +430 if api_key is not None: +431 real_api_key = api_key +432 del api_key +433 else: +434 real_api_key = get_cfbd_api_token(api_key_dir=api_key_dir) +435 +436 if real_api_key == "tigersAreAwesome": +437 raise ValueError( +438 "You actually need to change `cfbd_key` to your CFBD API key." +439 ) +440 elif "Bearer " in real_api_key: +441 pass +442 elif "Bearer" in real_api_key: +443 real_api_key = real_api_key.replace("Bearer", "Bearer ") +444 else: +445 real_api_key = "Bearer " + real_api_key +446 +447 # URL builder +448 ########################################################################## +449 +450 # if game_id is not None: +451 # url += f"&gameId={game_id}" +452 +453 if season is not None: +454 url += f"&year={season}" +455 +456 if week is not None: +457 url += f"&week={week}" +458 +459 if team is not None: +460 url += f"&team={team}" +461 +462 if home_team is not None: +463 url += f"&home={home_team}" +464 +465 if away_team is not None: +466 url += f"&away={away_team}" +467 +468 if conference is not None: +469 url += f"&conference={conference}" +470 +471 headers = { +472 "Authorization": f"{real_api_key}", "accept": "application/json" +473 } +474 +475 response = requests.get(url, headers=headers) +476 +477 if response.status_code == 200: +478 pass +479 elif response.status_code == 401: +480 raise ConnectionRefusedError( +481 "Could not connect. The connection was refused.\n" + +482 "HTTP Status Code 401." +483 ) +484 else: +485 raise ConnectionError( +486 f"Could not connect.\nHTTP Status code {response.status_code}" +487 ) 488 -489 for game in tqdm(json_data): -490 gameId = game["id"] -491 season = game["id"] -492 seasonType = game["seasonType"] -493 startDate = game["startDate"] -494 homeTeam = game["homeTeam"] -495 homeConference = game["homeConference"] -496 homeScore = game["homeScore"] -497 awayTeam = game["awayTeam"] -498 awayConference = game["awayConference"] -499 awayScore = game["awayScore"] -500 -501 for line in game["lines"]: -502 row_df = pd.DataFrame( -503 { -504 "game_id": gameId, -505 "season": season, -506 "season_type": seasonType, -507 "start_date": startDate, -508 "home_team_name": homeTeam, -509 "home_conference_name": homeConference, -510 "home_score": homeScore, -511 "away_team_name": awayTeam, -512 "away_conference_name": awayConference, -513 "away_score": awayScore, -514 }, -515 index=[0], -516 ) -517 -518 row_df["line_provider"] = line["provider"] -519 row_df["spread"] = line["spread"] -520 row_df["formatted_spread"] = line["formattedSpread"] -521 row_df["spread_open"] = line["spreadOpen"] -522 row_df["over_under"] = line["overUnder"] -523 row_df["over_under_open"] = line["overUnderOpen"] -524 row_df["home_moneyline"] = line["homeMoneyline"] -525 row_df["away_moneyline"] = line["awayMoneyline"] -526 -527 betting_df = pd.concat([betting_df, row_df], ignore_index=True) -528 del row_df -529 -530 del ( -531 gameId, -532 seasonType, -533 startDate, -534 homeTeam, -535 homeConference, -536 homeScore, -537 awayTeam, -538 awayConference, -539 awayScore, -540 ) -541 -542 return betting_df +489 json_data = response.json() +490 +491 if return_as_dict is True: +492 return json_data +493 +494 for game in tqdm(json_data): +495 gameId = game["id"] +496 season = game["id"] +497 seasonType = game["seasonType"] +498 startDate = game["startDate"] +499 homeTeam = game["homeTeam"] +500 homeConference = game["homeConference"] +501 homeScore = game["homeScore"] +502 awayTeam = game["awayTeam"] +503 awayConference = game["awayConference"] +504 awayScore = game["awayScore"] +505 +506 for line in game["lines"]: +507 row_df = pd.DataFrame( +508 { +509 "game_id": gameId, +510 "season": season, +511 "season_type": seasonType, +512 "start_date": startDate, +513 "home_team_name": homeTeam, +514 "home_conference_name": homeConference, +515 "home_score": homeScore, +516 "away_team_name": awayTeam, +517 "away_conference_name": awayConference, +518 "away_score": awayScore, +519 }, +520 index=[0], +521 ) +522 +523 row_df["line_provider"] = line["provider"] +524 row_df["spread"] = line["spread"] +525 row_df["formatted_spread"] = line["formattedSpread"] +526 row_df["spread_open"] = line["spreadOpen"] +527 row_df["over_under"] = line["overUnder"] +528 row_df["over_under_open"] = line["overUnderOpen"] +529 row_df["home_moneyline"] = line["homeMoneyline"] +530 row_df["away_moneyline"] = line["awayMoneyline"] +531 +532 betting_df = pd.concat([betting_df, row_df], ignore_index=True) +533 del row_df +534 +535 del ( +536 gameId, +537 seasonType, +538 startDate, +539 homeTeam, +540 homeConference, +541 homeScore, +542 awayTeam, +543 awayConference, +544 awayScore, +545 ) +546 +547 return betting_df @@ -2620,7 +2628,7 @@

Parameters

and will try to find a CFBD API key file in that directory.

game_id (int, optional): - Optional argument. + DEPRECATED FROM V1. If game_id is set to a game ID, get_cfb_betting_lines() will try to get all betting information for that game ID. diff --git a/docs/cfbd_json_py/coaches.html b/docs/cfbd_json_py/coaches.html index d0235b8..500a6a7 100644 --- a/docs/cfbd_json_py/coaches.html +++ b/docs/cfbd_json_py/coaches.html @@ -2876,4 +2876,4 @@

Returns

- \ No newline at end of file + diff --git a/docs/cfbd_json_py/conferences.html b/docs/cfbd_json_py/conferences.html index 5c02b07..21f701a 100644 --- a/docs/cfbd_json_py/conferences.html +++ b/docs/cfbd_json_py/conferences.html @@ -2114,4 +2114,4 @@

Returns

- \ No newline at end of file + diff --git a/docs/cfbd_json_py/draft.html b/docs/cfbd_json_py/draft.html index 42f7dcf..121850a 100644 --- a/docs/cfbd_json_py/draft.html +++ b/docs/cfbd_json_py/draft.html @@ -3760,4 +3760,4 @@

Returns

- \ No newline at end of file + diff --git a/docs/cfbd_json_py/drives.html b/docs/cfbd_json_py/drives.html index 9fa97e3..16d2e6c 100644 --- a/docs/cfbd_json_py/drives.html +++ b/docs/cfbd_json_py/drives.html @@ -2096,7 +2096,7 @@

620 url += f"&defenseConference={defensive_conference}" 621 622 if ncaa_division is not None: -623 url += f"&classification={ncaa_division.lower}" +623 url += f"&classification={ncaa_division.lower()}" 624 625 headers = { 626 "Authorization": f"{real_api_key}", @@ -2810,7 +2810,7 @@

621 url += f"&defenseConference={defensive_conference}" 622 623 if ncaa_division is not None: -624 url += f"&classification={ncaa_division.lower}" +624 url += f"&classification={ncaa_division.lower()}" 625 626 headers = { 627 "Authorization": f"{real_api_key}", @@ -3491,4 +3491,4 @@

Returns

- \ No newline at end of file + diff --git a/docs/cfbd_json_py/games.html b/docs/cfbd_json_py/games.html index 0cee397..0949b9e 100644 --- a/docs/cfbd_json_py/games.html +++ b/docs/cfbd_json_py/games.html @@ -1506,4998 +1506,3504 @@

8import logging 9from datetime import datetime 10 - 11import pandas as pd - 12import requests - 13from tqdm import tqdm - 14 - 15from cfbd_json_py.utls import get_cfbd_api_token - 16 + 11import numpy as np + 12import pandas as pd + 13import requests + 14from tqdm import tqdm + 15 + 16from cfbd_json_py.utls import get_cfbd_api_token 17 - 18def get_cfbd_games( - 19 api_key: str = None, - 20 api_key_dir: str = None, - 21 season: int = None, - 22 season_type: str = "regular", - 23 week: int = None, - 24 team: str = None, - 25 home_team: str = None, - 26 away_team: str = None, - 27 conference: str = None, - 28 ncaa_division: str = "fbs", - 29 game_id: int = None, - 30 return_as_dict: bool = False, - 31): - 32 """ - 33 Retrieves game schedule data from the CFBD API. - 34 - 35 Parameters - 36 ---------- - 37 `season` (int, mandatory): - 38 Required argument. - 39 Specifies the season you want CFB game information from. - 40 This must be specified, otherwise this package, and by extension - 41 the CFBD API, will not accept the request to get CFB game information. - 42 - 43 `api_key` (str, optional): - 44 Semi-optional argument. - 45 If `api_key` is null, this function will attempt to load a CFBD API key - 46 from the python environment, or from a file on this computer. - 47 If `api_key` is not null, - 48 this function will automatically assume that the - 49 inputted `api_key` is a valid CFBD API key. - 50 - 51 `api_key_dir` (str, optional): - 52 Optional argument. - 53 If `api_key` is set to am empty string, this variable is ignored. - 54 If `api_key_dir` is null, and `api_key` is null, - 55 this function will try to find - 56 a CFBD API key file in this user's home directory. - 57 If `api_key_dir` is set to a string, and `api_key` is null, - 58 this function will assume that `api_key_dir` is a directory, - 59 and will try to find a CFBD API key file in that directory. - 60 - 61 `season_type` (str, semi-optional): - 62 Semi-optional argument. - 63 By default, this will be set to "regular", for the CFB regular season. - 64 If you want CFB game information for non-regular season games, - 65 set `season_type` to "postseason". - 66 If `season_type` is set to anything but "regular" or "postseason", - 67 a `ValueError()` will be raised. - 68 - 69 `week` (int, optional): - 70 Optional argument. - 71 If `week` is set to an integer, this function will attempt - 72 to load CFB game data from games in that season, and in that week. - 73 - 74 `team` (str, optional): - 75 Optional argument. - 76 If you only want CFB game information for a team, - 77 regardless if they are the home/away team, - 78 set `team` to the name of the team you want CFB game information from. - 79 - 80 `home_team` (str, optional): - 81 Optional argument. - 82 If you only want game information for a team, - 83 where that team was the home team in this season, - 84 set `home_team` to the name of the team you want game information for. - 85 - 86 `away_team` (str, optional): - 87 Optional argument. - 88 If you only want game information for a team, - 89 where that team was the away team in this season, - 90 set `away_team` to the name of the team you want game information for. - 91 - 92 `conference` (str, optional): - 93 Optional argument. - 94 If you only want game information from games - 95 involving teams a specific conference, - 96 set `conference` to the abbreviation - 97 of the conference you want game information from. - 98 - 99 `ncaa_division` (str, semi-optional): - 100 Semi-optional argument. - 101 By default, `ncaa_division` will be set to "fbs", - 102 short for the Football Bowl Subdivision (FBS), - 103 formerly known as D1-A (read as "division one single A"), - 104 the highest level in the NCAA football pyramid, - 105 where teams can scholarship up to 85 players - 106 on their football team solely for athletic ability, - 107 and often have the largest athletics budgets - 108 within the NCAA. - 109 - 110 Other valid inputs are: - 111 - "fcs": Football Championship Subdivision (FCS), - 112 formerly known as D1-AA (read as "division one double A"). - 113 An FCS school is still in the 1st division of the NCAA, - 114 making them eligible for the March Madness tournament, - 115 but may not have the resources to compete at the FBS level - 116 at this time. FCS schools are limited to 63 athletic scholarships - 117 for football. - 118 - "ii": NCAA Division II. Schools in this and D3 are not - 119 eligible for the March Madness tournament, - 120 and are limited to 36 athletic scholarships - 121 for their football team. - 122 - "iii": NCAA Division III. The largest single division within the - 123 NCAA football pyramid. - 124 D3 schools have the distinction of being part of - 125 the only NCAA division that cannot give out scholarships solely - 126 for athletic ability. - 127 - 128 `game_id` (int, optional): - 129 Optional argument. - 130 If `game_id` is set to a game ID, - 131 `get_cfb_betting_lines()` will try to get - 132 game information just for that game ID. - 133 - 134 `return_as_dict` (bool, semi-optional): - 135 Semi-optional argument. - 136 If you want this function to return - 137 the data as a dictionary (read: JSON object), - 138 instead of a pandas `DataFrame` object, - 139 set `return_as_dict` to `True`. - 140 - 141 Usage - 142 ---------- - 143 ``` - 144 import time - 145 - 146 from cfbd_json_py.games import get_cfbd_games - 147 + 18 + 19def get_cfbd_games( + 20 api_key: str = None, + 21 api_key_dir: str = None, + 22 season: int = None, + 23 season_type: str = "regular", + 24 week: int = None, + 25 team: str = None, + 26 home_team: str = None, + 27 away_team: str = None, + 28 conference: str = None, + 29 ncaa_division: str = "fbs", + 30 game_id: int = None, + 31 return_as_dict: bool = False, + 32): + 33 """ + 34 Retrieves game schedule data from the CFBD API. + 35 + 36 Parameters + 37 ---------- + 38 `season` (int, mandatory): + 39 Required argument. + 40 Specifies the season you want CFB game information from. + 41 This must be specified, otherwise this package, and by extension + 42 the CFBD API, will not accept the request to get CFB game information. + 43 + 44 `api_key` (str, optional): + 45 Semi-optional argument. + 46 If `api_key` is null, this function will attempt to load a CFBD API key + 47 from the python environment, or from a file on this computer. + 48 If `api_key` is not null, + 49 this function will automatically assume that the + 50 inputted `api_key` is a valid CFBD API key. + 51 + 52 `api_key_dir` (str, optional): + 53 Optional argument. + 54 If `api_key` is set to am empty string, this variable is ignored. + 55 If `api_key_dir` is null, and `api_key` is null, + 56 this function will try to find + 57 a CFBD API key file in this user's home directory. + 58 If `api_key_dir` is set to a string, and `api_key` is null, + 59 this function will assume that `api_key_dir` is a directory, + 60 and will try to find a CFBD API key file in that directory. + 61 + 62 `season_type` (str, semi-optional): + 63 Semi-optional argument. + 64 By default, this will be set to "regular", for the CFB regular season. + 65 If you want CFB game information for non-regular season games, + 66 set `season_type` to "postseason". + 67 If `season_type` is set to anything but "regular" or "postseason", + 68 a `ValueError()` will be raised. + 69 + 70 `week` (int, optional): + 71 Optional argument. + 72 If `week` is set to an integer, this function will attempt + 73 to load CFB game data from games in that season, and in that week. + 74 + 75 `team` (str, optional): + 76 Optional argument. + 77 If you only want CFB game information for a team, + 78 regardless if they are the home/away team, + 79 set `team` to the name of the team you want CFB game information from. + 80 + 81 `home_team` (str, optional): + 82 Optional argument. + 83 If you only want game information for a team, + 84 where that team was the home team in this season, + 85 set `home_team` to the name of the team you want game information for. + 86 + 87 `away_team` (str, optional): + 88 Optional argument. + 89 If you only want game information for a team, + 90 where that team was the away team in this season, + 91 set `away_team` to the name of the team you want game information for. + 92 + 93 `conference` (str, optional): + 94 Optional argument. + 95 If you only want game information from games + 96 involving teams a specific conference, + 97 set `conference` to the abbreviation + 98 of the conference you want game information from. + 99 + 100 `ncaa_division` (str, semi-optional): + 101 Semi-optional argument. + 102 By default, `ncaa_division` will be set to "fbs", + 103 short for the Football Bowl Subdivision (FBS), + 104 formerly known as D1-A (read as "division one single A"), + 105 the highest level in the NCAA football pyramid, + 106 where teams can scholarship up to 85 players + 107 on their football team solely for athletic ability, + 108 and often have the largest athletics budgets + 109 within the NCAA. + 110 + 111 Other valid inputs are: + 112 - "fcs": Football Championship Subdivision (FCS), + 113 formerly known as D1-AA (read as "division one double A"). + 114 An FCS school is still in the 1st division of the NCAA, + 115 making them eligible for the March Madness tournament, + 116 but may not have the resources to compete at the FBS level + 117 at this time. FCS schools are limited to 63 athletic scholarships + 118 for football. + 119 - "ii": NCAA Division II. Schools in this and D3 are not + 120 eligible for the March Madness tournament, + 121 and are limited to 36 athletic scholarships + 122 for their football team. + 123 - "iii": NCAA Division III. The largest single division within the + 124 NCAA football pyramid. + 125 D3 schools have the distinction of being part of + 126 the only NCAA division that cannot give out scholarships solely + 127 for athletic ability. + 128 + 129 `game_id` (int, optional): + 130 Optional argument. + 131 If `game_id` is set to a game ID, + 132 `get_cfb_betting_lines()` will try to get + 133 game information just for that game ID. + 134 + 135 `return_as_dict` (bool, semi-optional): + 136 Semi-optional argument. + 137 If you want this function to return + 138 the data as a dictionary (read: JSON object), + 139 instead of a pandas `DataFrame` object, + 140 set `return_as_dict` to `True`. + 141 + 142 Usage + 143 ---------- + 144 ``` + 145 import time + 146 + 147 from cfbd_json_py.games import get_cfbd_games 148 - 149 cfbd_key = "tigersAreAwesome" # placeholder for your CFBD API Key. - 150 - 151 if cfbd_key is not "tigersAreAwesome": - 152 print( - 153 "Using the user's API key declared in this script " + - 154 "for this example." - 155 ) - 156 - 157 # Get CFB games from the 2020 CFB season. - 158 print("Get CFB games from the 2020 CFB season.") - 159 json_data = get_cfbd_games( - 160 api_key=cfbd_key, - 161 season=2020 - 162 ) - 163 print(json_data) - 164 time.sleep(5) - 165 - 166 # Get CFB games from week 10 of the 2020 CFB season. - 167 print("Get CFB games from week 10 of the 2020 CFB season.") - 168 json_data = get_cfbd_games( - 169 api_key=cfbd_key, - 170 season=2020, - 171 week=10 - 172 ) - 173 print(json_data) - 174 time.sleep(5) - 175 - 176 # Get CFB games from the 2019 CFB season - 177 # that involved the 2019 LSU Tigers. - 178 print( - 179 "Get CFB games from the 2019 CFB season " + - 180 "that involved the 2019 LSU Tigers." - 181 ) - 182 json_data = get_cfbd_games( - 183 api_key=cfbd_key, - 184 season=2019, - 185 team="LSU" - 186 ) - 187 print(json_data) - 188 time.sleep(5) - 189 - 190 # Get 2021 Cincinnati Bearcats Football games - 191 # where the Bearcats were the home team. - 192 print( - 193 "Get 2021 Cincinnati Bearcats Football games " + - 194 "where the Bearcats were the home team." - 195 ) - 196 json_data = get_cfbd_games( - 197 api_key=cfbd_key, - 198 season=2021, - 199 home_team="Cincinnati" - 200 ) - 201 print(json_data) - 202 time.sleep(5) - 203 - 204 # Get 2018 Ohio Bobcats Football games - 205 # where the Bobcats were the away team. - 206 print( - 207 "Get 2018 Ohio Bobcats Football games " + - 208 "where the Bobcats were the away team." - 209 ) - 210 json_data = get_cfbd_games( - 211 api_key=cfbd_key, - 212 season=2019, - 213 away_team="Ohio" - 214 ) - 215 print(json_data) - 216 time.sleep(5) - 217 - 218 # Get 2022 college football games where one or more teams competing - 219 # was a Football Championship Subdivision team. - 220 print( - 221 "Get 2022 college football games where one or more " + - 222 "teams competing was a Football Championship Subdivision team." - 223 ) - 224 json_data = get_cfbd_games( - 225 api_key=cfbd_key, - 226 season=2018, - 227 away_team="Ohio" - 228 ) - 229 print(json_data) - 230 time.sleep(5) - 231 - 232 # Get game information for the - 233 # 2021 American Athletic conference (AAC) Championship Game. - 234 print( - 235 "Get game information for " + - 236 "the 2021 American Athletic conference (AAC) Championship Game." - 237 ) - 238 json_data = get_cfbd_games( - 239 api_key=cfbd_key, - 240 season=2018, - 241 game_id=401331162 - 242 ) - 243 print(json_data) - 244 time.sleep(5) - 245 - 246 # You can also tell this function to just return the API call as - 247 # a Dictionary (read: JSON) object. - 248 print( - 249 "You can also tell this function to just return the API call " + - 250 "as a Dictionary (read: JSON) object." - 251 ) - 252 json_data = get_cfbd_games( - 253 season=2020, - 254 week=10, - 255 api_key=cfbd_key, - 256 return_as_dict=True - 257 ) - 258 print(json_data) - 259 - 260 else: - 261 # Alternatively, if the CFBD API key exists in this python environment, - 262 # or it's been set by cfbd_json_py.utls.set_cfbd_api_token(), - 263 # you could just call these functions directly, - 264 # without setting the API key in the script. - 265 print( - 266 "Using the user's API key supposedly loaded " + - 267 "into this python environment for this example." - 268 ) - 269 - 270 # Get CFB games from the 2020 CFB season. - 271 print("Get CFB games from the 2020 CFB season.") - 272 json_data = get_cfbd_games( - 273 season=2020 - 274 ) - 275 print(json_data) - 276 time.sleep(5) - 277 - 278 # Get CFB games from week 10 of the 2020 CFB season. - 279 print("Get CFB games from week 10 of the 2020 CFB season.") - 280 json_data = get_cfbd_games( - 281 season=2020, - 282 week=10 - 283 ) - 284 print(json_data) - 285 time.sleep(5) - 286 - 287 # Get CFB games from the 2019 CFB season - 288 # that involved the 2019 LSU Tigers. - 289 print( - 290 "Get CFB games from the 2019 CFB season " + - 291 "that involved the 2019 LSU Tigers." - 292 ) - 293 json_data = get_cfbd_games( - 294 season=2019, - 295 team="LSU" - 296 ) - 297 print(json_data) - 298 time.sleep(5) - 299 - 300 # Get 2021 Cincinnati Bearcats Football games - 301 # where the Bearcats were the home team. - 302 print( - 303 "Get 2021 Cincinnati Bearcats Football games " + - 304 "where the Bearcats were the home team." - 305 ) - 306 json_data = get_cfbd_games( - 307 season=2021, - 308 home_team="Cincinnati" - 309 ) - 310 print(json_data) - 311 time.sleep(5) - 312 - 313 # Get 2018 Ohio Bobcats Football games - 314 # where the Bobcats were the away team. - 315 print( - 316 "Get 2018 Ohio Bobcats Football games " + - 317 "where the Bobcats were the away team." - 318 ) - 319 json_data = get_cfbd_games( - 320 season=2019, - 321 away_team="Ohio" - 322 ) - 323 print(json_data) - 324 time.sleep(5) - 325 - 326 # Get 2018 Ohio Bobcats Football games - 327 # where the Bobcats were the away team. - 328 print( - 329 "Get 2018 Ohio Bobcats Football games " + - 330 "where the Bobcats were the away team." - 331 ) - 332 json_data = get_cfbd_games( - 333 season=2018, - 334 away_team="Ohio" - 335 ) - 336 print(json_data) - 337 time.sleep(5) - 338 - 339 # Get 2022 college football games where one or more teams competing - 340 # was a Football Championship Subdivision team. - 341 print( - 342 "Get 2022 college football games where one or more " + - 343 "teams competing was a Football Championship Subdivision team." - 344 ) - 345 json_data = get_cfbd_games( - 346 season=2018, - 347 away_team="Ohio" - 348 ) - 349 print(json_data) - 350 time.sleep(5) - 351 - 352 # Get game information for the - 353 # 2021 American Athletic conference (AAC) Championship Game. - 354 print( - 355 "Get game information for " + - 356 "the 2021 American Athletic conference (AAC) Championship Game." - 357 ) - 358 json_data = get_cfbd_games( - 359 season=2018, - 360 game_id=401331162 - 361 ) - 362 print(json_data) - 363 time.sleep(5) - 364 - 365 # You can also tell this function to just return the API call as - 366 # a Dictionary (read: JSON) object. - 367 print( - 368 "You can also tell this function to just return the API call " + - 369 "as a Dictionary (read: JSON) object." - 370 ) - 371 json_data = get_cfbd_games( - 372 season=2020, - 373 week=10, - 374 return_as_dict=True - 375 ) - 376 print(json_data) - 377 - 378 ``` - 379 Returns - 380 ---------- - 381 A pandas `DataFrame` object with college football game information, - 382 or (if `return_as_dict` is set to `True`) - 383 a dictionary object with college football game information. - 384 """ - 385 - 386 now = datetime.now() - 387 cfb_games_df = pd.DataFrame() - 388 url = "https://api.collegefootballdata.com/games" - 389 - 390 ########################################################################## - 391 - 392 if api_key is not None: - 393 real_api_key = api_key - 394 del api_key - 395 else: - 396 real_api_key = get_cfbd_api_token(api_key_dir=api_key_dir) - 397 - 398 if real_api_key == "tigersAreAwesome": - 399 raise ValueError( - 400 "You actually need to change `cfbd_key` to your CFBD API key." - 401 ) - 402 elif "Bearer " in real_api_key: - 403 pass - 404 elif "Bearer" in real_api_key: - 405 real_api_key = real_api_key.replace("Bearer", "Bearer ") - 406 else: - 407 real_api_key = "Bearer " + real_api_key - 408 - 409 if season is None: - 410 # This should never happen without user tampering, but if it does, - 411 # we need to raise an error, - 412 # because the CFBD API will refuse this call without a valid season. - 413 raise SystemError( - 414 "I don't know how, I don't know why, " - 415 + "but you managed to call this function " - 416 + "while `season` was `None` (NULL)," - 417 + " and the function got to this point in the code." - 418 + "\nIf you have a GitHub account, " - 419 + "please raise an issue on this python package's GitHub page:\n" - 420 + "https://github.com/armstjc/cfbd-json-py/issues" - 421 ) - 422 elif season > (now.year + 1): - 423 raise ValueError(f"`season` cannot be greater than {season}.") - 424 elif season < 1869: - 425 raise ValueError("`season` cannot be less than 1869.") - 426 - 427 if season_type != "regular" and season_type != "postseason": - 428 raise ValueError( - 429 "`season_type` must be set to either " - 430 + '"regular" or "postseason" for this function to work.' - 431 ) - 432 - 433 if ( - 434 ncaa_division.lower() == "fbs" - 435 or ncaa_division.lower() == "fcs" - 436 or ncaa_division.lower() == "ii" - 437 or ncaa_division.lower() == "iii" - 438 ): - 439 pass - 440 else: - 441 raise ValueError( - 442 "An invalid NCAA Division was inputted when calling this function." - 443 + '\nValid inputs are:\n-"fbs"\n-"fcs"\n-"ii"\n-"iii"' - 444 + f"\n\nYou entered: \n{ncaa_division}" - 445 ) - 446 - 447 # URL builder - 448 ########################################################################## - 449 - 450 # Required by API - 451 url += f"?seasonType={season_type}" - 452 - 453 if game_id is not None: - 454 url += f"&year={season}" - 455 url += f"&id={game_id}" - 456 - 457 if ( - 458 team is not None - 459 or home_team is not None - 460 or away_team is not None - 461 or conference is not None - 462 or week is not None - 463 ): - 464 logging.warning( - 465 "When calling `cfbd_json_py.games.get_cfbd_games()`, " - 466 + "and setting `game_id` to a non-null value, " - 467 + "only `season` and `game_id` are considered " - 468 + "when calling the CFBD API." - 469 ) - 470 - 471 else: - 472 url += f"&year={season}" - 473 - 474 # Optional for the API - 475 if week is not None: - 476 url += f"&week={week}" - 477 - 478 if team is not None: - 479 url += f"&team={team}" - 480 - 481 if home_team is not None: - 482 url += f"&home={home_team}" - 483 - 484 if away_team is not None: - 485 url += f"&away={away_team}" - 486 - 487 if conference is not None: - 488 url += f"&conference={conference}" - 489 - 490 if ncaa_division is not None: - 491 url += f"&division={ncaa_division}" - 492 - 493 headers = { - 494 "Authorization": f"{real_api_key}", - 495 "accept": "application/json" - 496 } - 497 - 498 response = requests.get(url, headers=headers) - 499 - 500 if response.status_code == 200: - 501 pass - 502 elif response.status_code == 401: - 503 raise ConnectionRefusedError( - 504 "Could not connect. The connection was refused." + - 505 "\nHTTP Status Code 401." - 506 ) - 507 else: - 508 raise ConnectionError( - 509 f"Could not connect.\nHTTP Status code {response.status_code}" - 510 ) - 511 - 512 json_data = response.json() - 513 - 514 if return_as_dict is True: - 515 return json_data - 516 - 517 cfb_games_df = pd.json_normalize(json_data) - 518 # print(cfb_games_df.columns) - 519 if len(cfb_games_df) == 0: - 520 logging.error( - 521 "The CFBD API accepted your inputs, " - 522 + "but found no data within your specified input parameters." - 523 + " Please double check your input parameters." - 524 ) - 525 - 526 return cfb_games_df - 527 + 149 + 150 cfbd_key = "tigersAreAwesome" # placeholder for your CFBD API Key. + 151 + 152 if cfbd_key is not "tigersAreAwesome": + 153 print( + 154 "Using the user's API key declared in this script " + + 155 "for this example." + 156 ) + 157 + 158 # Get CFB games from the 2020 CFB season. + 159 print("Get CFB games from the 2020 CFB season.") + 160 json_data = get_cfbd_games( + 161 api_key=cfbd_key, + 162 season=2020 + 163 ) + 164 print(json_data) + 165 time.sleep(5) + 166 + 167 # Get CFB games from week 10 of the 2020 CFB season. + 168 print("Get CFB games from week 10 of the 2020 CFB season.") + 169 json_data = get_cfbd_games( + 170 api_key=cfbd_key, + 171 season=2020, + 172 week=10 + 173 ) + 174 print(json_data) + 175 time.sleep(5) + 176 + 177 # Get CFB games from the 2019 CFB season + 178 # that involved the 2019 LSU Tigers. + 179 print( + 180 "Get CFB games from the 2019 CFB season " + + 181 "that involved the 2019 LSU Tigers." + 182 ) + 183 json_data = get_cfbd_games( + 184 api_key=cfbd_key, + 185 season=2019, + 186 team="LSU" + 187 ) + 188 print(json_data) + 189 time.sleep(5) + 190 + 191 # Get 2021 Cincinnati Bearcats Football games + 192 # where the Bearcats were the home team. + 193 print( + 194 "Get 2021 Cincinnati Bearcats Football games " + + 195 "where the Bearcats were the home team." + 196 ) + 197 json_data = get_cfbd_games( + 198 api_key=cfbd_key, + 199 season=2021, + 200 home_team="Cincinnati" + 201 ) + 202 print(json_data) + 203 time.sleep(5) + 204 + 205 # Get 2018 Ohio Bobcats Football games + 206 # where the Bobcats were the away team. + 207 print( + 208 "Get 2018 Ohio Bobcats Football games " + + 209 "where the Bobcats were the away team." + 210 ) + 211 json_data = get_cfbd_games( + 212 api_key=cfbd_key, + 213 season=2019, + 214 away_team="Ohio" + 215 ) + 216 print(json_data) + 217 time.sleep(5) + 218 + 219 # Get 2022 college football games where one or more teams competing + 220 # was a Football Championship Subdivision team. + 221 print( + 222 "Get 2022 college football games where one or more " + + 223 "teams competing was a Football Championship Subdivision team." + 224 ) + 225 json_data = get_cfbd_games( + 226 api_key=cfbd_key, + 227 season=2018, + 228 away_team="Ohio" + 229 ) + 230 print(json_data) + 231 time.sleep(5) + 232 + 233 # Get game information for the + 234 # 2021 American Athletic conference (AAC) Championship Game. + 235 print( + 236 "Get game information for " + + 237 "the 2021 American Athletic conference (AAC) Championship Game." + 238 ) + 239 json_data = get_cfbd_games( + 240 api_key=cfbd_key, + 241 season=2018, + 242 game_id=401331162 + 243 ) + 244 print(json_data) + 245 time.sleep(5) + 246 + 247 # You can also tell this function to just return the API call as + 248 # a Dictionary (read: JSON) object. + 249 print( + 250 "You can also tell this function to just return the API call " + + 251 "as a Dictionary (read: JSON) object." + 252 ) + 253 json_data = get_cfbd_games( + 254 season=2020, + 255 week=10, + 256 api_key=cfbd_key, + 257 return_as_dict=True + 258 ) + 259 print(json_data) + 260 + 261 else: + 262 # Alternatively, if the CFBD API key exists in this python environment, + 263 # or it's been set by cfbd_json_py.utls.set_cfbd_api_token(), + 264 # you could just call these functions directly, + 265 # without setting the API key in the script. + 266 print( + 267 "Using the user's API key supposedly loaded " + + 268 "into this python environment for this example." + 269 ) + 270 + 271 # Get CFB games from the 2020 CFB season. + 272 print("Get CFB games from the 2020 CFB season.") + 273 json_data = get_cfbd_games( + 274 season=2020 + 275 ) + 276 print(json_data) + 277 time.sleep(5) + 278 + 279 # Get CFB games from week 10 of the 2020 CFB season. + 280 print("Get CFB games from week 10 of the 2020 CFB season.") + 281 json_data = get_cfbd_games( + 282 season=2020, + 283 week=10 + 284 ) + 285 print(json_data) + 286 time.sleep(5) + 287 + 288 # Get CFB games from the 2019 CFB season + 289 # that involved the 2019 LSU Tigers. + 290 print( + 291 "Get CFB games from the 2019 CFB season " + + 292 "that involved the 2019 LSU Tigers." + 293 ) + 294 json_data = get_cfbd_games( + 295 season=2019, + 296 team="LSU" + 297 ) + 298 print(json_data) + 299 time.sleep(5) + 300 + 301 # Get 2021 Cincinnati Bearcats Football games + 302 # where the Bearcats were the home team. + 303 print( + 304 "Get 2021 Cincinnati Bearcats Football games " + + 305 "where the Bearcats were the home team." + 306 ) + 307 json_data = get_cfbd_games( + 308 season=2021, + 309 home_team="Cincinnati" + 310 ) + 311 print(json_data) + 312 time.sleep(5) + 313 + 314 # Get 2018 Ohio Bobcats Football games + 315 # where the Bobcats were the away team. + 316 print( + 317 "Get 2018 Ohio Bobcats Football games " + + 318 "where the Bobcats were the away team." + 319 ) + 320 json_data = get_cfbd_games( + 321 season=2019, + 322 away_team="Ohio" + 323 ) + 324 print(json_data) + 325 time.sleep(5) + 326 + 327 # Get 2018 Ohio Bobcats Football games + 328 # where the Bobcats were the away team. + 329 print( + 330 "Get 2018 Ohio Bobcats Football games " + + 331 "where the Bobcats were the away team." + 332 ) + 333 json_data = get_cfbd_games( + 334 season=2018, + 335 away_team="Ohio" + 336 ) + 337 print(json_data) + 338 time.sleep(5) + 339 + 340 # Get 2022 college football games where one or more teams competing + 341 # was a Football Championship Subdivision team. + 342 print( + 343 "Get 2022 college football games where one or more " + + 344 "teams competing was a Football Championship Subdivision team." + 345 ) + 346 json_data = get_cfbd_games( + 347 season=2018, + 348 away_team="Ohio" + 349 ) + 350 print(json_data) + 351 time.sleep(5) + 352 + 353 # Get game information for the + 354 # 2021 American Athletic conference (AAC) Championship Game. + 355 print( + 356 "Get game information for " + + 357 "the 2021 American Athletic conference (AAC) Championship Game." + 358 ) + 359 json_data = get_cfbd_games( + 360 season=2018, + 361 game_id=401331162 + 362 ) + 363 print(json_data) + 364 time.sleep(5) + 365 + 366 # You can also tell this function to just return the API call as + 367 # a Dictionary (read: JSON) object. + 368 print( + 369 "You can also tell this function to just return the API call " + + 370 "as a Dictionary (read: JSON) object." + 371 ) + 372 json_data = get_cfbd_games( + 373 season=2020, + 374 week=10, + 375 return_as_dict=True + 376 ) + 377 print(json_data) + 378 + 379 ``` + 380 Returns + 381 ---------- + 382 A pandas `DataFrame` object with college football game information, + 383 or (if `return_as_dict` is set to `True`) + 384 a dictionary object with college football game information. + 385 """ + 386 + 387 now = datetime.now() + 388 cfb_games_df = pd.DataFrame() + 389 url = "https://api.collegefootballdata.com/games" + 390 + 391 ########################################################################## + 392 + 393 if api_key is not None: + 394 real_api_key = api_key + 395 del api_key + 396 else: + 397 real_api_key = get_cfbd_api_token(api_key_dir=api_key_dir) + 398 + 399 if real_api_key == "tigersAreAwesome": + 400 raise ValueError( + 401 "You actually need to change `cfbd_key` to your CFBD API key." + 402 ) + 403 elif "Bearer " in real_api_key: + 404 pass + 405 elif "Bearer" in real_api_key: + 406 real_api_key = real_api_key.replace("Bearer", "Bearer ") + 407 else: + 408 real_api_key = "Bearer " + real_api_key + 409 + 410 if season is None: + 411 # This should never happen without user tampering, but if it does, + 412 # we need to raise an error, + 413 # because the CFBD API will refuse this call without a valid season. + 414 raise SystemError( + 415 "I don't know how, I don't know why, " + 416 + "but you managed to call this function " + 417 + "while `season` was `None` (NULL)," + 418 + " and the function got to this point in the code." + 419 + "\nIf you have a GitHub account, " + 420 + "please raise an issue on this python package's GitHub page:\n" + 421 + "https://github.com/armstjc/cfbd-json-py/issues" + 422 ) + 423 elif season > (now.year + 1): + 424 raise ValueError(f"`season` cannot be greater than {season}.") + 425 elif season < 1869: + 426 raise ValueError("`season` cannot be less than 1869.") + 427 + 428 if season_type != "regular" and season_type != "postseason": + 429 raise ValueError( + 430 "`season_type` must be set to either " + 431 + '"regular" or "postseason" for this function to work.' + 432 ) + 433 + 434 if ( + 435 ncaa_division.lower() == "fbs" + 436 or ncaa_division.lower() == "fcs" + 437 or ncaa_division.lower() == "ii" + 438 or ncaa_division.lower() == "iii" + 439 ): + 440 pass + 441 else: + 442 raise ValueError( + 443 "An invalid NCAA Division was inputted when calling this function." + 444 + '\nValid inputs are:\n-"fbs"\n-"fcs"\n-"ii"\n-"iii"' + 445 + f"\n\nYou entered: \n{ncaa_division}" + 446 ) + 447 + 448 # URL builder + 449 ########################################################################## + 450 + 451 # Required by API + 452 url += f"?seasonType={season_type}" + 453 + 454 if game_id is not None: + 455 url += f"&year={season}" + 456 url += f"&id={game_id}" + 457 + 458 if ( + 459 team is not None + 460 or home_team is not None + 461 or away_team is not None + 462 or conference is not None + 463 or week is not None + 464 ): + 465 logging.warning( + 466 "When calling `cfbd_json_py.games.get_cfbd_games()`, " + 467 + "and setting `game_id` to a non-null value, " + 468 + "only `season` and `game_id` are considered " + 469 + "when calling the CFBD API." + 470 ) + 471 + 472 else: + 473 url += f"&year={season}" + 474 + 475 # Optional for the API + 476 if week is not None: + 477 url += f"&week={week}" + 478 + 479 if team is not None: + 480 url += f"&team={team}" + 481 + 482 if home_team is not None: + 483 url += f"&home={home_team}" + 484 + 485 if away_team is not None: + 486 url += f"&away={away_team}" + 487 + 488 if conference is not None: + 489 url += f"&conference={conference}" + 490 + 491 if ncaa_division is not None: + 492 url += f"&division={ncaa_division}" + 493 + 494 headers = { + 495 "Authorization": f"{real_api_key}", + 496 "accept": "application/json" + 497 } + 498 + 499 response = requests.get(url, headers=headers) + 500 + 501 if response.status_code == 200: + 502 pass + 503 elif response.status_code == 401: + 504 raise ConnectionRefusedError( + 505 "Could not connect. The connection was refused." + + 506 "\nHTTP Status Code 401." + 507 ) + 508 else: + 509 raise ConnectionError( + 510 f"Could not connect.\nHTTP Status code {response.status_code}" + 511 ) + 512 + 513 json_data = response.json() + 514 + 515 if return_as_dict is True: + 516 return json_data + 517 + 518 cfb_games_df = pd.json_normalize(json_data) + 519 # print(cfb_games_df.columns) + 520 if len(cfb_games_df) == 0: + 521 logging.error( + 522 "The CFBD API accepted your inputs, " + 523 + "but found no data within your specified input parameters." + 524 + " Please double check your input parameters." + 525 ) + 526 + 527 return cfb_games_df 528 - 529def get_cfbd_team_records( - 530 api_key: str = None, - 531 api_key_dir: str = None, - 532 season: int = None, - 533 team: str = None, # Must specify either a year or team - 534 conference: str = None, - 535 return_as_dict: bool = False, - 536): - 537 """ - 538 Get a team, or multiple team's record (wins, losses, ties) - 539 for home games, away games, - 540 conference games, and the team's record for that season. - 541 - 542 Parameters - 543 ---------- - 544 - 545 `api_key` (str, optional): - 546 Semi-optional argument. - 547 If `api_key` is null, this function will attempt to load a CFBD API key - 548 from the python environment, or from a file on this computer. - 549 If `api_key` is not null, - 550 this function will automatically assume that the - 551 inputted `api_key` is a valid CFBD API key. - 552 - 553 `api_key_dir` (str, optional): - 554 Optional argument. - 555 If `api_key` is set to am empty string, this variable is ignored. - 556 If `api_key_dir` is null, and `api_key` is null, - 557 this function will try to find - 558 a CFBD API key file in this user's home directory. - 559 If `api_key_dir` is set to a string, and `api_key` is null, - 560 this function will assume that `api_key_dir` is a directory, - 561 and will try to find a CFBD API key file in that directory. - 562 - 563 `season` (int, optional): - 564 Semi-optional argument. - 565 Specifies the season you want CFB team records data from. - 566 You MUST set `season` or `team` to a non-null value for - 567 this function to work. If you don't, a `ValueError()` - 568 will be raised. - 569 - 570 `team` (str, optional): - 571 Semi-optional argument. - 572 If you only want CFB team records data for a specific team, - 573 set `team` to the name of the team you want CFB drive data from. - 574 You MUST set `season` or `team` to a non-null value for - 575 this function to work. If you don't, a `ValueError()` - 576 will be raised. - 577 - 578 `conference` (str, optional): - 579 Optional argument. - 580 If you only want CFB team records data from games - 581 involving teams from a specific conference, - 582 set `conference` to the abbreviation - 583 of the conference you want CFB team records data from. - 584 For a list of conferences, - 585 use the `cfbd_json_py.conferences.get_cfbd_conference_info()` - 586 function. - 587 - 588 `return_as_dict` (bool, semi-optional): - 589 Semi-optional argument. - 590 If you want this function to return - 591 the data as a dictionary (read: JSON object), - 592 instead of a pandas `DataFrame` object, - 593 set `return_as_dict` to `True`. - 594 - 595 Usage - 596 ---------- - 597 ``` - 598 import time - 599 - 600 from cfbd_json_py.games import get_cfbd_team_records - 601 + 529 + 530def get_cfbd_team_records( + 531 api_key: str = None, + 532 api_key_dir: str = None, + 533 season: int = None, + 534 team: str = None, # Must specify either a year or team + 535 conference: str = None, + 536 return_as_dict: bool = False, + 537): + 538 """ + 539 Get a team, or multiple team's record (wins, losses, ties) + 540 for home games, away games, + 541 conference games, and the team's record for that season. + 542 + 543 Parameters + 544 ---------- + 545 + 546 `api_key` (str, optional): + 547 Semi-optional argument. + 548 If `api_key` is null, this function will attempt to load a CFBD API key + 549 from the python environment, or from a file on this computer. + 550 If `api_key` is not null, + 551 this function will automatically assume that the + 552 inputted `api_key` is a valid CFBD API key. + 553 + 554 `api_key_dir` (str, optional): + 555 Optional argument. + 556 If `api_key` is set to am empty string, this variable is ignored. + 557 If `api_key_dir` is null, and `api_key` is null, + 558 this function will try to find + 559 a CFBD API key file in this user's home directory. + 560 If `api_key_dir` is set to a string, and `api_key` is null, + 561 this function will assume that `api_key_dir` is a directory, + 562 and will try to find a CFBD API key file in that directory. + 563 + 564 `season` (int, optional): + 565 Semi-optional argument. + 566 Specifies the season you want CFB team records data from. + 567 You MUST set `season` or `team` to a non-null value for + 568 this function to work. If you don't, a `ValueError()` + 569 will be raised. + 570 + 571 `team` (str, optional): + 572 Semi-optional argument. + 573 If you only want CFB team records data for a specific team, + 574 set `team` to the name of the team you want CFB drive data from. + 575 You MUST set `season` or `team` to a non-null value for + 576 this function to work. If you don't, a `ValueError()` + 577 will be raised. + 578 + 579 `conference` (str, optional): + 580 Optional argument. + 581 If you only want CFB team records data from games + 582 involving teams from a specific conference, + 583 set `conference` to the abbreviation + 584 of the conference you want CFB team records data from. + 585 For a list of conferences, + 586 use the `cfbd_json_py.conferences.get_cfbd_conference_info()` + 587 function. + 588 + 589 `return_as_dict` (bool, semi-optional): + 590 Semi-optional argument. + 591 If you want this function to return + 592 the data as a dictionary (read: JSON object), + 593 instead of a pandas `DataFrame` object, + 594 set `return_as_dict` to `True`. + 595 + 596 Usage + 597 ---------- + 598 ``` + 599 import time + 600 + 601 from cfbd_json_py.games import get_cfbd_team_records 602 - 603 cfbd_key = "tigersAreAwesome" # placeholder for your CFBD API Key. - 604 - 605 if cfbd_key is not "tigersAreAwesome": - 606 print( - 607 "Using the user's API key declared in this script " + - 608 "for this example." - 609 ) - 610 - 611 # Get CFB team records from the 2020 CFB season. - 612 print("Get CFB team records from the 2020 CFB season.") - 613 json_data = get_cfbd_team_records( - 614 api_key=cfbd_key, - 615 season=2020 - 616 ) - 617 print(json_data) - 618 time.sleep(5) - 619 - 620 # Get team records from football teams - 621 # fielded by the University of Cincinnati. - 622 print( - 623 "Get team records from football teams fielded " + - 624 "by the University of Cincinnati." - 625 ) - 626 json_data = get_cfbd_team_records( - 627 api_key=cfbd_key, - 628 team="Cincinnati" - 629 ) - 630 print(json_data) - 631 time.sleep(5) - 632 - 633 # Get team records from football teams that played - 634 # in the Big 10 (B1G) conference in the 2017 CFB season - 635 print( - 636 "Get team records from football teams that played " + - 637 "in the Big 10 (B1G) conference in the 2017 CFB season" - 638 ) - 639 json_data = get_cfbd_team_records( - 640 api_key=cfbd_key, - 641 season=2017, - 642 conference="B1G" - 643 ) - 644 print(json_data) - 645 time.sleep(5) - 646 + 603 + 604 cfbd_key = "tigersAreAwesome" # placeholder for your CFBD API Key. + 605 + 606 if cfbd_key is not "tigersAreAwesome": + 607 print( + 608 "Using the user's API key declared in this script " + + 609 "for this example." + 610 ) + 611 + 612 # Get CFB team records from the 2020 CFB season. + 613 print("Get CFB team records from the 2020 CFB season.") + 614 json_data = get_cfbd_team_records( + 615 api_key=cfbd_key, + 616 season=2020 + 617 ) + 618 print(json_data) + 619 time.sleep(5) + 620 + 621 # Get team records from football teams + 622 # fielded by the University of Cincinnati. + 623 print( + 624 "Get team records from football teams fielded " + + 625 "by the University of Cincinnati." + 626 ) + 627 json_data = get_cfbd_team_records( + 628 api_key=cfbd_key, + 629 team="Cincinnati" + 630 ) + 631 print(json_data) + 632 time.sleep(5) + 633 + 634 # Get team records from football teams that played + 635 # in the Big 10 (B1G) conference in the 2017 CFB season + 636 print( + 637 "Get team records from football teams that played " + + 638 "in the Big 10 (B1G) conference in the 2017 CFB season" + 639 ) + 640 json_data = get_cfbd_team_records( + 641 api_key=cfbd_key, + 642 season=2017, + 643 conference="B1G" + 644 ) + 645 print(json_data) + 646 time.sleep(5) 647 - 648 # You can also tell this function to just return the API call as - 649 # a Dictionary (read: JSON) object. - 650 print( - 651 "You can also tell this function to just return the API call " + - 652 "as a Dictionary (read: JSON) object." - 653 ) - 654 json_data = get_cfbd_team_records( - 655 season=2020, - 656 api_key=cfbd_key, - 657 return_as_dict=True - 658 ) - 659 print(json_data) - 660 - 661 else: - 662 # Alternatively, if the CFBD API key exists in this python environment, - 663 # or it's been set by cfbd_json_py.utls.set_cfbd_api_token(), - 664 # you could just call these functions directly, - 665 # without setting the API key in the script. - 666 print( - 667 "Using the user's API key supposedly loaded " + - 668 "into this python environment for this example." - 669 ) - 670 - 671 # Get CFB team records from the 2020 CFB season. - 672 print("Get CFB team records from the 2020 CFB season.") - 673 json_data = get_cfbd_team_records( - 674 season=2020 - 675 ) - 676 print(json_data) - 677 time.sleep(5) - 678 - 679 # Get team records from football teams - 680 # fielded by the University of Cincinnati. - 681 print( - 682 "Get team records from football teams " + - 683 "fielded by the University of Cincinnati." - 684 ) - 685 json_data = get_cfbd_team_records( - 686 team="Cincinnati" - 687 ) - 688 print(json_data) - 689 time.sleep(5) - 690 - 691 # Get team records from football teams that played - 692 # in the Big 10 (B1G) conference in the 2017 CFB season - 693 print( - 694 "Get team records from football teams that played " + - 695 "in the Big 10 (B1G) conference in the 2017 CFB season" - 696 ) - 697 json_data = get_cfbd_team_records( - 698 season=2017, - 699 conference="B1G" - 700 ) - 701 print(json_data) - 702 time.sleep(5) - 703 - 704 # You can also tell this function to just return the API call as - 705 # a Dictionary (read: JSON) object. - 706 print( - 707 "You can also tell this function to just return the API call " + - 708 "as a Dictionary (read: JSON) object." - 709 ) - 710 json_data = get_cfbd_team_records( - 711 season=2020, - 712 return_as_dict=True - 713 ) - 714 print(json_data) - 715 - 716 ``` - 717 - 718 Returns - 719 ---------- - 720 A pandas `DataFrame` object with CFB team records data, - 721 or (if `return_as_dict` is set to `True`) - 722 a dictionary object with CFB team records data. - 723 - 724 """ - 725 - 726 now = datetime.now() - 727 cfb_records_df = pd.DataFrame() - 728 # row_df = pd.DataFrame() - 729 url = "https://api.collegefootballdata.com/records" - 730 - 731 ########################################################################## - 732 - 733 if api_key is not None: - 734 real_api_key = api_key - 735 del api_key - 736 else: - 737 real_api_key = get_cfbd_api_token(api_key_dir=api_key_dir) - 738 - 739 if real_api_key == "tigersAreAwesome": - 740 raise ValueError( - 741 "You actually need to change `cfbd_key` to your CFBD API key." - 742 ) - 743 elif "Bearer " in real_api_key: - 744 pass - 745 elif "Bearer" in real_api_key: - 746 real_api_key = real_api_key.replace("Bearer", "Bearer ") - 747 else: - 748 real_api_key = "Bearer " + real_api_key - 749 - 750 if season is not None and season > now.year: - 751 raise ValueError(f"`season` cannot be greater than {season}.") - 752 elif season is not None and season < 1869: - 753 raise ValueError("`season` cannot be less than 1869.") - 754 - 755 if season is None and team is None: - 756 raise ValueError( - 757 "If you call `cfbd_json_py.games.get_cfbd_team_records()`, " - 758 + "you must specify at least a team or CFB season." - 759 ) - 760 - 761 # URL builder - 762 ########################################################################## - 763 - 764 url_elements = 0 - 765 - 766 if season is not None and url_elements == 0: - 767 url += f"?year={season}" - 768 url_elements += 1 - 769 elif season is not None: - 770 url += f"&year={season}" - 771 url_elements += 1 - 772 - 773 if team is not None and url_elements == 0: - 774 url += f"?team={team}" - 775 url_elements += 1 - 776 elif team is not None: - 777 url += f"&team={team}" - 778 url_elements += 1 - 779 - 780 if conference is not None and url_elements == 0: - 781 url += f"?conference={conference}" - 782 url_elements += 1 - 783 elif conference is not None: - 784 url += f"&conference={conference}" - 785 url_elements += 1 - 786 - 787 headers = { - 788 "Authorization": f"{real_api_key}", - 789 "accept": "application/json" - 790 } - 791 response = requests.get(url, headers=headers) - 792 - 793 if response.status_code == 200: - 794 pass - 795 elif response.status_code == 401: - 796 raise ConnectionRefusedError( - 797 "Could not connect. The connection was refused." + - 798 "\nHTTP Status Code 401." - 799 ) - 800 else: - 801 raise ConnectionError( - 802 f"Could not connect.\nHTTP Status code {response.status_code}" - 803 ) - 804 - 805 json_data = response.json() - 806 - 807 if return_as_dict is True: - 808 return json_data - 809 - 810 cfb_records_df = pd.json_normalize(json_data) - 811 # print(cfb_records_df.columns) - 812 cfb_records_df.rename( - 813 columns={ - 814 "year": "season", - 815 "teamId": "team_id", - 816 "team": "team_name", - 817 "conference": "conference_name", - 818 "division": "division_name", - 819 "expectedWins": "expected_wins", - 820 "total.games": "games", - 821 "total.wins": "wins", - 822 "total.losses": "losses", - 823 "total.ties": "ties", - 824 "conferenceGames.games": "conf_games", - 825 "conferenceGames.wins": "conf_wins", - 826 "conferenceGames.losses": "conf_losses", - 827 "conferenceGames.ties": "conf_ties", - 828 "homeGames.games": "home_games", - 829 "homeGames.wins": "home_wins", - 830 "homeGames.losses": "home_losses", - 831 "homeGames.ties": "home_ties", - 832 "awayGames.games": "away_games", - 833 "awayGames.wins": "away_wins", - 834 "awayGames.losses": "away_losses", - 835 "awayGames.ties": "away_ties", - 836 }, - 837 inplace=True, - 838 ) - 839 return cfb_records_df - 840 + 648 + 649 # You can also tell this function to just return the API call as + 650 # a Dictionary (read: JSON) object. + 651 print( + 652 "You can also tell this function to just return the API call " + + 653 "as a Dictionary (read: JSON) object." + 654 ) + 655 json_data = get_cfbd_team_records( + 656 season=2020, + 657 api_key=cfbd_key, + 658 return_as_dict=True + 659 ) + 660 print(json_data) + 661 + 662 else: + 663 # Alternatively, if the CFBD API key exists in this python environment, + 664 # or it's been set by cfbd_json_py.utls.set_cfbd_api_token(), + 665 # you could just call these functions directly, + 666 # without setting the API key in the script. + 667 print( + 668 "Using the user's API key supposedly loaded " + + 669 "into this python environment for this example." + 670 ) + 671 + 672 # Get CFB team records from the 2020 CFB season. + 673 print("Get CFB team records from the 2020 CFB season.") + 674 json_data = get_cfbd_team_records( + 675 season=2020 + 676 ) + 677 print(json_data) + 678 time.sleep(5) + 679 + 680 # Get team records from football teams + 681 # fielded by the University of Cincinnati. + 682 print( + 683 "Get team records from football teams " + + 684 "fielded by the University of Cincinnati." + 685 ) + 686 json_data = get_cfbd_team_records( + 687 team="Cincinnati" + 688 ) + 689 print(json_data) + 690 time.sleep(5) + 691 + 692 # Get team records from football teams that played + 693 # in the Big 10 (B1G) conference in the 2017 CFB season + 694 print( + 695 "Get team records from football teams that played " + + 696 "in the Big 10 (B1G) conference in the 2017 CFB season" + 697 ) + 698 json_data = get_cfbd_team_records( + 699 season=2017, + 700 conference="B1G" + 701 ) + 702 print(json_data) + 703 time.sleep(5) + 704 + 705 # You can also tell this function to just return the API call as + 706 # a Dictionary (read: JSON) object. + 707 print( + 708 "You can also tell this function to just return the API call " + + 709 "as a Dictionary (read: JSON) object." + 710 ) + 711 json_data = get_cfbd_team_records( + 712 season=2020, + 713 return_as_dict=True + 714 ) + 715 print(json_data) + 716 + 717 ``` + 718 + 719 Returns + 720 ---------- + 721 A pandas `DataFrame` object with CFB team records data, + 722 or (if `return_as_dict` is set to `True`) + 723 a dictionary object with CFB team records data. + 724 + 725 """ + 726 + 727 now = datetime.now() + 728 cfb_records_df = pd.DataFrame() + 729 # row_df = pd.DataFrame() + 730 url = "https://api.collegefootballdata.com/records" + 731 + 732 ########################################################################## + 733 + 734 if api_key is not None: + 735 real_api_key = api_key + 736 del api_key + 737 else: + 738 real_api_key = get_cfbd_api_token(api_key_dir=api_key_dir) + 739 + 740 if real_api_key == "tigersAreAwesome": + 741 raise ValueError( + 742 "You actually need to change `cfbd_key` to your CFBD API key." + 743 ) + 744 elif "Bearer " in real_api_key: + 745 pass + 746 elif "Bearer" in real_api_key: + 747 real_api_key = real_api_key.replace("Bearer", "Bearer ") + 748 else: + 749 real_api_key = "Bearer " + real_api_key + 750 + 751 if season is not None and season > now.year: + 752 raise ValueError(f"`season` cannot be greater than {season}.") + 753 elif season is not None and season < 1869: + 754 raise ValueError("`season` cannot be less than 1869.") + 755 + 756 if season is None and team is None: + 757 raise ValueError( + 758 "If you call `cfbd_json_py.games.get_cfbd_team_records()`, " + 759 + "you must specify at least a team or CFB season." + 760 ) + 761 + 762 # URL builder + 763 ########################################################################## + 764 + 765 url_elements = 0 + 766 + 767 if season is not None and url_elements == 0: + 768 url += f"?year={season}" + 769 url_elements += 1 + 770 elif season is not None: + 771 url += f"&year={season}" + 772 url_elements += 1 + 773 + 774 if team is not None and url_elements == 0: + 775 url += f"?team={team}" + 776 url_elements += 1 + 777 elif team is not None: + 778 url += f"&team={team}" + 779 url_elements += 1 + 780 + 781 if conference is not None and url_elements == 0: + 782 url += f"?conference={conference}" + 783 url_elements += 1 + 784 elif conference is not None: + 785 url += f"&conference={conference}" + 786 url_elements += 1 + 787 + 788 headers = { + 789 "Authorization": f"{real_api_key}", + 790 "accept": "application/json" + 791 } + 792 response = requests.get(url, headers=headers) + 793 + 794 if response.status_code == 200: + 795 pass + 796 elif response.status_code == 401: + 797 raise ConnectionRefusedError( + 798 "Could not connect. The connection was refused." + + 799 "\nHTTP Status Code 401." + 800 ) + 801 else: + 802 raise ConnectionError( + 803 f"Could not connect.\nHTTP Status code {response.status_code}" + 804 ) + 805 + 806 json_data = response.json() + 807 + 808 if return_as_dict is True: + 809 return json_data + 810 + 811 cfb_records_df = pd.json_normalize(json_data) + 812 # print(cfb_records_df.columns) + 813 cfb_records_df.rename( + 814 columns={ + 815 "year": "season", + 816 "teamId": "team_id", + 817 "team": "team_name", + 818 "conference": "conference_name", + 819 "division": "division_name", + 820 "expectedWins": "expected_wins", + 821 "total.games": "games", + 822 "total.wins": "wins", + 823 "total.losses": "losses", + 824 "total.ties": "ties", + 825 "conferenceGames.games": "conf_games", + 826 "conferenceGames.wins": "conf_wins", + 827 "conferenceGames.losses": "conf_losses", + 828 "conferenceGames.ties": "conf_ties", + 829 "homeGames.games": "home_games", + 830 "homeGames.wins": "home_wins", + 831 "homeGames.losses": "home_losses", + 832 "homeGames.ties": "home_ties", + 833 "awayGames.games": "away_games", + 834 "awayGames.wins": "away_wins", + 835 "awayGames.losses": "away_losses", + 836 "awayGames.ties": "away_ties", + 837 }, + 838 inplace=True, + 839 ) + 840 return cfb_records_df 841 - 842def get_cfbd_season_weeks( - 843 season: int, - 844 api_key: str = None, - 845 api_key_dir: str = None, - 846 return_as_dict: bool = False, - 847): - 848 """ - 849 Retrieves a list of weeks that occurred in a given CFB season. - 850 - 851 Parameters - 852 ---------- - 853 `season` (int, mandatory): - 854 Required argument. - 855 Specifies the season you want a list of weeks that occurred - 856 in a given CFB season information from. - 857 This must be specified, otherwise this package, and by extension - 858 the CFBD API, will not accept the request - 859 to get a list of weeks that occurred in a given CFB season information. - 860 - 861 `api_key` (str, optional): - 862 Semi-optional argument. - 863 If `api_key` is null, this function will attempt to load a CFBD API key - 864 from the python environment, or from a file on this computer. - 865 If `api_key` is not null, - 866 this function will automatically assume that the - 867 inputted `api_key` is a valid CFBD API key. - 868 - 869 `api_key_dir` (str, optional): - 870 Optional argument. - 871 If `api_key` is set to am empty string, this variable is ignored. - 872 If `api_key_dir` is null, and `api_key` is null, - 873 this function will try to find - 874 a CFBD API key file in this user's home directory. - 875 If `api_key_dir` is set to a string, and `api_key` is null, - 876 this function will assume that `api_key_dir` is a directory, - 877 and will try to find a CFBD API key file in that directory. - 878 - 879 `return_as_dict` (bool, semi-optional): - 880 Semi-optional argument. - 881 If you want this function to return - 882 the data as a dictionary (read: JSON object), - 883 instead of a pandas `DataFrame` object, - 884 set `return_as_dict` to `True`. - 885 + 842 + 843def get_cfbd_season_weeks( + 844 season: int, + 845 api_key: str = None, + 846 api_key_dir: str = None, + 847 return_as_dict: bool = False, + 848): + 849 """ + 850 Retrieves a list of weeks that occurred in a given CFB season. + 851 + 852 Parameters + 853 ---------- + 854 `season` (int, mandatory): + 855 Required argument. + 856 Specifies the season you want a list of weeks that occurred + 857 in a given CFB season information from. + 858 This must be specified, otherwise this package, and by extension + 859 the CFBD API, will not accept the request + 860 to get a list of weeks that occurred in a given CFB season information. + 861 + 862 `api_key` (str, optional): + 863 Semi-optional argument. + 864 If `api_key` is null, this function will attempt to load a CFBD API key + 865 from the python environment, or from a file on this computer. + 866 If `api_key` is not null, + 867 this function will automatically assume that the + 868 inputted `api_key` is a valid CFBD API key. + 869 + 870 `api_key_dir` (str, optional): + 871 Optional argument. + 872 If `api_key` is set to am empty string, this variable is ignored. + 873 If `api_key_dir` is null, and `api_key` is null, + 874 this function will try to find + 875 a CFBD API key file in this user's home directory. + 876 If `api_key_dir` is set to a string, and `api_key` is null, + 877 this function will assume that `api_key_dir` is a directory, + 878 and will try to find a CFBD API key file in that directory. + 879 + 880 `return_as_dict` (bool, semi-optional): + 881 Semi-optional argument. + 882 If you want this function to return + 883 the data as a dictionary (read: JSON object), + 884 instead of a pandas `DataFrame` object, + 885 set `return_as_dict` to `True`. 886 - 887 Usage - 888 ---------- - 889 ``` - 890 import time - 891 - 892 from cfbd_json_py.games import get_cfbd_season_weeks - 893 + 887 + 888 Usage + 889 ---------- + 890 ``` + 891 import time + 892 + 893 from cfbd_json_py.games import get_cfbd_season_weeks 894 - 895 cfbd_key = "tigersAreAwesome" # placeholder for your CFBD API Key. - 896 - 897 if cfbd_key is not "tigersAreAwesome": - 898 print( - 899 "Using the user's API key declared in this script " + - 900 "for this example." - 901 ) - 902 - 903 # Get a list of weeks in the 2020 CFB season. - 904 print("Get a list of weeks in the 2020 CFB season.") - 905 json_data = get_cfbd_season_weeks( - 906 api_key=cfbd_key, - 907 season=2020 - 908 ) - 909 print(json_data) - 910 time.sleep(5) - 911 + 895 + 896 cfbd_key = "tigersAreAwesome" # placeholder for your CFBD API Key. + 897 + 898 if cfbd_key is not "tigersAreAwesome": + 899 print( + 900 "Using the user's API key declared in this script " + + 901 "for this example." + 902 ) + 903 + 904 # Get a list of weeks in the 2020 CFB season. + 905 print("Get a list of weeks in the 2020 CFB season.") + 906 json_data = get_cfbd_season_weeks( + 907 api_key=cfbd_key, + 908 season=2020 + 909 ) + 910 print(json_data) + 911 time.sleep(5) 912 - 913 # You can also tell this function to just return the API call as - 914 # a Dictionary (read: JSON) object. - 915 print( - 916 "You can also tell this function to just return the API call " + - 917 "as a Dictionary (read: JSON) object." - 918 ) - 919 json_data = get_cfbd_season_weeks( - 920 season=2020, - 921 api_key=cfbd_key, - 922 return_as_dict=True - 923 ) - 924 print(json_data) - 925 - 926 else: - 927 # Alternatively, if the CFBD API key exists in this python environment, - 928 # or it's been set by cfbd_json_py.utls.set_cfbd_api_token(), - 929 # you could just call these functions directly, - 930 # without setting the API key in the script. - 931 print( - 932 "Using the user's API key supposedly loaded " + - 933 "into this python environment for this example." - 934 ) - 935 - 936 # Get a list of weeks in the 2020 CFB season. - 937 print("Get a list of weeks in the 2020 CFB season.") - 938 json_data = get_cfbd_season_weeks( - 939 season=2020 - 940 ) - 941 print(json_data) - 942 time.sleep(5) - 943 + 913 + 914 # You can also tell this function to just return the API call as + 915 # a Dictionary (read: JSON) object. + 916 print( + 917 "You can also tell this function to just return the API call " + + 918 "as a Dictionary (read: JSON) object." + 919 ) + 920 json_data = get_cfbd_season_weeks( + 921 season=2020, + 922 api_key=cfbd_key, + 923 return_as_dict=True + 924 ) + 925 print(json_data) + 926 + 927 else: + 928 # Alternatively, if the CFBD API key exists in this python environment, + 929 # or it's been set by cfbd_json_py.utls.set_cfbd_api_token(), + 930 # you could just call these functions directly, + 931 # without setting the API key in the script. + 932 print( + 933 "Using the user's API key supposedly loaded " + + 934 "into this python environment for this example." + 935 ) + 936 + 937 # Get a list of weeks in the 2020 CFB season. + 938 print("Get a list of weeks in the 2020 CFB season.") + 939 json_data = get_cfbd_season_weeks( + 940 season=2020 + 941 ) + 942 print(json_data) + 943 time.sleep(5) 944 - 945 # You can also tell this function to just return the API call as - 946 # a Dictionary (read: JSON) object. - 947 print( - 948 "You can also tell this function to just return the API call " + - 949 "as a Dictionary (read: JSON) object." - 950 ) - 951 json_data = get_cfbd_season_weeks( - 952 season=2020, - 953 return_as_dict=True - 954 ) - 955 print(json_data) - 956 ``` - 957 Returns - 958 ---------- - 959 A pandas `DataFrame` object - 960 with a list of valid weeks in a given CFB season, - 961 or (if `return_as_dict` is set to `True`) - 962 a dictionary object with a list of valid weeks in a given CFB season. - 963 """ - 964 - 965 now = datetime.now() - 966 cfb_weeks_df = pd.DataFrame() - 967 # row_df = pd.DataFrame() - 968 url = "https://api.collegefootballdata.com/calendar" - 969 - 970 ########################################################################## - 971 - 972 if api_key is not None: - 973 real_api_key = api_key - 974 del api_key - 975 else: - 976 real_api_key = get_cfbd_api_token(api_key_dir=api_key_dir) - 977 - 978 if real_api_key == "tigersAreAwesome": - 979 raise ValueError( - 980 "You actually need to change `cfbd_key` to your CFBD API key." - 981 ) - 982 elif "Bearer " in real_api_key: - 983 pass - 984 elif "Bearer" in real_api_key: - 985 real_api_key = real_api_key.replace("Bearer", "Bearer ") - 986 else: - 987 real_api_key = "Bearer " + real_api_key - 988 - 989 if season is None: - 990 # This should never happen without user tampering, but if it does, - 991 # we need to raise an error, - 992 # because the CFBD API will refuse this call without a valid season. - 993 raise SystemError( - 994 "I don't know how, I don't know why, " - 995 + "but you managed to call this function " - 996 + "while `season` was `None` (NULL)," - 997 + " and the function got to this point in the code." - 998 + "\nIf you have a GitHub account, " - 999 + "please raise an issue on this python package's GitHub page:\n" -1000 + "https://github.com/armstjc/cfbd-json-py/issues" -1001 ) -1002 elif season > (now.year + 1): -1003 raise ValueError(f"`season` cannot be greater than {season}.") -1004 elif season < 1869: -1005 raise ValueError("`season` cannot be less than 1869.") -1006 -1007 # URL builder -1008 ########################################################################## -1009 -1010 # Required by API -1011 url += f"?year={season}" -1012 -1013 headers = { -1014 "Authorization": f"{real_api_key}", -1015 "accept": "application/json" -1016 } -1017 response = requests.get(url, headers=headers) -1018 -1019 if response.status_code == 200: -1020 pass -1021 elif response.status_code == 401: -1022 raise ConnectionRefusedError( -1023 "Could not connect. The connection was refused." + -1024 "\nHTTP Status Code 401." -1025 ) -1026 else: -1027 raise ConnectionError( -1028 f"Could not connect.\nHTTP Status code {response.status_code}" -1029 ) -1030 -1031 json_data = response.json() -1032 -1033 if return_as_dict is True: -1034 return json_data -1035 -1036 cfb_weeks_df = pd.json_normalize(json_data) -1037 # print(cfb_weeks_df.columns) -1038 cfb_weeks_df.rename( -1039 columns={ -1040 "firstGameStart": "first_game_start", -1041 "lastGameStart": "last_game_start", -1042 } -1043 ) -1044 return cfb_weeks_df -1045 + 945 + 946 # You can also tell this function to just return the API call as + 947 # a Dictionary (read: JSON) object. + 948 print( + 949 "You can also tell this function to just return the API call " + + 950 "as a Dictionary (read: JSON) object." + 951 ) + 952 json_data = get_cfbd_season_weeks( + 953 season=2020, + 954 return_as_dict=True + 955 ) + 956 print(json_data) + 957 ``` + 958 Returns + 959 ---------- + 960 A pandas `DataFrame` object + 961 with a list of valid weeks in a given CFB season, + 962 or (if `return_as_dict` is set to `True`) + 963 a dictionary object with a list of valid weeks in a given CFB season. + 964 """ + 965 + 966 now = datetime.now() + 967 cfb_weeks_df = pd.DataFrame() + 968 # row_df = pd.DataFrame() + 969 url = "https://api.collegefootballdata.com/calendar" + 970 + 971 ########################################################################## + 972 + 973 if api_key is not None: + 974 real_api_key = api_key + 975 del api_key + 976 else: + 977 real_api_key = get_cfbd_api_token(api_key_dir=api_key_dir) + 978 + 979 if real_api_key == "tigersAreAwesome": + 980 raise ValueError( + 981 "You actually need to change `cfbd_key` to your CFBD API key." + 982 ) + 983 elif "Bearer " in real_api_key: + 984 pass + 985 elif "Bearer" in real_api_key: + 986 real_api_key = real_api_key.replace("Bearer", "Bearer ") + 987 else: + 988 real_api_key = "Bearer " + real_api_key + 989 + 990 if season is None: + 991 # This should never happen without user tampering, but if it does, + 992 # we need to raise an error, + 993 # because the CFBD API will refuse this call without a valid season. + 994 raise SystemError( + 995 "I don't know how, I don't know why, " + 996 + "but you managed to call this function " + 997 + "while `season` was `None` (NULL)," + 998 + " and the function got to this point in the code." + 999 + "\nIf you have a GitHub account, " +1000 + "please raise an issue on this python package's GitHub page:\n" +1001 + "https://github.com/armstjc/cfbd-json-py/issues" +1002 ) +1003 elif season > (now.year + 1): +1004 raise ValueError(f"`season` cannot be greater than {season}.") +1005 elif season < 1869: +1006 raise ValueError("`season` cannot be less than 1869.") +1007 +1008 # URL builder +1009 ########################################################################## +1010 +1011 # Required by API +1012 url += f"?year={season}" +1013 +1014 headers = { +1015 "Authorization": f"{real_api_key}", +1016 "accept": "application/json" +1017 } +1018 response = requests.get(url, headers=headers) +1019 +1020 if response.status_code == 200: +1021 pass +1022 elif response.status_code == 401: +1023 raise ConnectionRefusedError( +1024 "Could not connect. The connection was refused." + +1025 "\nHTTP Status Code 401." +1026 ) +1027 else: +1028 raise ConnectionError( +1029 f"Could not connect.\nHTTP Status code {response.status_code}" +1030 ) +1031 +1032 json_data = response.json() +1033 +1034 if return_as_dict is True: +1035 return json_data +1036 +1037 cfb_weeks_df = pd.json_normalize(json_data) +1038 # print(cfb_weeks_df.columns) +1039 cfb_weeks_df.rename( +1040 columns={ +1041 "firstGameStart": "first_game_start", +1042 "lastGameStart": "last_game_start", +1043 } +1044 ) +1045 return cfb_weeks_df 1046 -1047def get_cfbd_game_media_info( -1048 season: int, -1049 api_key: str = None, -1050 api_key_dir: str = None, -1051 season_type: str = "regular", # "regular", "postseason", or "both" -1052 week: int = None, -1053 team: str = None, -1054 conference: str = None, -1055 media_type: str = "all", # "tv", "radio", "web", "ppv", or "mobile" -1056 ncaa_division: str = "fbs", -1057 return_as_dict: bool = False, -1058): -1059 """ -1060 Gets known media information for CFB games in a given CFB season. -1061 -1062 Parameters -1063 ---------- -1064 `season` (int, mandatory): -1065 Required argument. -1066 Specifies the season you want CFB media information from. -1067 This must be specified, otherwise this package, and by extension -1068 the CFBD API, will not accept the request to get CFB media information. -1069 -1070 `api_key` (str, optional): -1071 Semi-optional argument. -1072 If `api_key` is null, this function will attempt to load a CFBD API key -1073 from the python environment, or from a file on this computer. -1074 If `api_key` is not null, -1075 this function will automatically assume that the -1076 inputted `api_key` is a valid CFBD API key. -1077 -1078 `api_key_dir` (str, optional): -1079 Optional argument. -1080 If `api_key` is set to am empty string, this variable is ignored. -1081 If `api_key_dir` is null, and `api_key` is null, -1082 this function will try to find -1083 a CFBD API key file in this user's home directory. -1084 If `api_key_dir` is set to a string, and `api_key` is null, -1085 this function will assume that `api_key_dir` is a directory, -1086 and will try to find a CFBD API key file in that directory. -1087 -1088 `season_type` (str, semi-optional): -1089 Semi-optional argument. -1090 By default, this will be set to "regular", for the CFB regular season. -1091 If you want CFB media information for non-regular season games, -1092 set `season_type` to "postseason". -1093 If you want both "regular" and "postseason" games returned, -1094 set `season_type` to "both" -1095 If `season_type` is set to anything but "regular" or "postseason", -1096 a `ValueError()` will be raised. -1097 -1098 `week` (int, optional): -1099 Optional argument. -1100 If `week` is set to an integer, this function will attempt -1101 to load CFB media information from games in that season, -1102 and in that week. -1103 -1104 `team` (str, optional): -1105 Optional argument. -1106 If you only want CFB media information for a team, -1107 regardless if they are the home/away team, -1108 set `team` to the name of the team you want CFB media information from. -1109 -1110 `conference` (str, optional): -1111 Optional argument. -1112 If you only want media information from games -1113 involving teams a specific conference, -1114 set `conference` to the abbreviation -1115 of the conference you want game information from. -1116 -1117 `media_type` (str, semi-optional): -1118 Semi-optional argument. -1119 If you only want game broadcast information -1120 for a specific type of broadcast, -1121 set this to the type of broadcast. -1122 -1123 Valid inputs are: -1124 - `all` (default): Returns all games, -1125 and all known broadcasters for those games. -1126 - `tv`: Returns all known TV broadcasters for CFB games -1127 in the requested time frame. -1128 - `radio`: Returns all known radio broadcasters -1129 for CFB games in the requested time frame. -1130 - `web`: Returns all known web broadcasts (like ESPN+) -1131 for CFB games in the requested time frame. -1132 - `ppv`: Returns all known Pay Per View (PPV) broadcasts -1133 for CFB games in the requested time frame. -1134 - `mobile`: Returns all known broadcasters that only broadcasted -1135 games on mobile devices (?) -1136 -1137 `ncaa_division` (str, semi-optional): -1138 Semi-optional argument. -1139 By default, `ncaa_division` will be set to "fbs", -1140 short for the Football Bowl Subdivision (FBS), -1141 formerly known as D1-A (read as "division one single A"), -1142 the highest level in the NCAA football pyramid, -1143 where teams can scholarship up to 85 players -1144 on their football team solely for athletic ability, -1145 and often have the largest athletics budgets -1146 within the NCAA. -1147 -1148 Other valid inputs are: -1149 - "fcs": Football Championship Subdivision (FCS), -1150 formerly known as D1-AA (read as "division one double A"). -1151 An FCS school is still in the 1st division of the NCAA, -1152 making them eligible for the March Madness tournament, -1153 but may not have the resources to compete at the FBS level -1154 at this time. FCS schools are limited to 63 athletic scholarships -1155 for football. -1156 - "ii": NCAA Division II. Schools in this and D3 are not -1157 eligible for the March Madness tournament, -1158 and are limited to 36 athletic scholarships -1159 for their football team. -1160 - "iii": NCAA Division III. The largest single division within the -1161 NCAA football pyramid. -1162 D3 schools have the distinction of being part of -1163 the only NCAA division that cannot give out scholarships solely -1164 for athletic ability. -1165 -1166 `return_as_dict` (bool, semi-optional): -1167 Semi-optional argument. -1168 If you want this function to return -1169 the data as a dictionary (read: JSON object), -1170 instead of a pandas `DataFrame` object, -1171 set `return_as_dict` to `True`. -1172 -1173 Usage -1174 ---------- -1175 ``` -1176 import time -1177 -1178 from cfbd_json_py.games import get_cfbd_game_media_info -1179 +1047 +1048def get_cfbd_game_media_info( +1049 season: int, +1050 api_key: str = None, +1051 api_key_dir: str = None, +1052 season_type: str = "regular", # "regular", "postseason", or "both" +1053 week: int = None, +1054 team: str = None, +1055 conference: str = None, +1056 media_type: str = "all", # "tv", "radio", "web", "ppv", or "mobile" +1057 ncaa_division: str = "fbs", +1058 return_as_dict: bool = False, +1059): +1060 """ +1061 Gets known media information for CFB games in a given CFB season. +1062 +1063 Parameters +1064 ---------- +1065 `season` (int, mandatory): +1066 Required argument. +1067 Specifies the season you want CFB media information from. +1068 This must be specified, otherwise this package, and by extension +1069 the CFBD API, will not accept the request to get CFB media information. +1070 +1071 `api_key` (str, optional): +1072 Semi-optional argument. +1073 If `api_key` is null, this function will attempt to load a CFBD API key +1074 from the python environment, or from a file on this computer. +1075 If `api_key` is not null, +1076 this function will automatically assume that the +1077 inputted `api_key` is a valid CFBD API key. +1078 +1079 `api_key_dir` (str, optional): +1080 Optional argument. +1081 If `api_key` is set to am empty string, this variable is ignored. +1082 If `api_key_dir` is null, and `api_key` is null, +1083 this function will try to find +1084 a CFBD API key file in this user's home directory. +1085 If `api_key_dir` is set to a string, and `api_key` is null, +1086 this function will assume that `api_key_dir` is a directory, +1087 and will try to find a CFBD API key file in that directory. +1088 +1089 `season_type` (str, semi-optional): +1090 Semi-optional argument. +1091 By default, this will be set to "regular", for the CFB regular season. +1092 If you want CFB media information for non-regular season games, +1093 set `season_type` to "postseason". +1094 If you want both "regular" and "postseason" games returned, +1095 set `season_type` to "both" +1096 If `season_type` is set to anything but "regular" or "postseason", +1097 a `ValueError()` will be raised. +1098 +1099 `week` (int, optional): +1100 Optional argument. +1101 If `week` is set to an integer, this function will attempt +1102 to load CFB media information from games in that season, +1103 and in that week. +1104 +1105 `team` (str, optional): +1106 Optional argument. +1107 If you only want CFB media information for a team, +1108 regardless if they are the home/away team, +1109 set `team` to the name of the team you want CFB media information from. +1110 +1111 `conference` (str, optional): +1112 Optional argument. +1113 If you only want media information from games +1114 involving teams a specific conference, +1115 set `conference` to the abbreviation +1116 of the conference you want game information from. +1117 +1118 `media_type` (str, semi-optional): +1119 Semi-optional argument. +1120 If you only want game broadcast information +1121 for a specific type of broadcast, +1122 set this to the type of broadcast. +1123 +1124 Valid inputs are: +1125 - `all` (default): Returns all games, +1126 and all known broadcasters for those games. +1127 - `tv`: Returns all known TV broadcasters for CFB games +1128 in the requested time frame. +1129 - `radio`: Returns all known radio broadcasters +1130 for CFB games in the requested time frame. +1131 - `web`: Returns all known web broadcasts (like ESPN+) +1132 for CFB games in the requested time frame. +1133 - `ppv`: Returns all known Pay Per View (PPV) broadcasts +1134 for CFB games in the requested time frame. +1135 - `mobile`: Returns all known broadcasters that only broadcasted +1136 games on mobile devices (?) +1137 +1138 `ncaa_division` (str, semi-optional): +1139 Semi-optional argument. +1140 By default, `ncaa_division` will be set to "fbs", +1141 short for the Football Bowl Subdivision (FBS), +1142 formerly known as D1-A (read as "division one single A"), +1143 the highest level in the NCAA football pyramid, +1144 where teams can scholarship up to 85 players +1145 on their football team solely for athletic ability, +1146 and often have the largest athletics budgets +1147 within the NCAA. +1148 +1149 Other valid inputs are: +1150 - "fcs": Football Championship Subdivision (FCS), +1151 formerly known as D1-AA (read as "division one double A"). +1152 An FCS school is still in the 1st division of the NCAA, +1153 making them eligible for the March Madness tournament, +1154 but may not have the resources to compete at the FBS level +1155 at this time. FCS schools are limited to 63 athletic scholarships +1156 for football. +1157 - "ii": NCAA Division II. Schools in this and D3 are not +1158 eligible for the March Madness tournament, +1159 and are limited to 36 athletic scholarships +1160 for their football team. +1161 - "iii": NCAA Division III. The largest single division within the +1162 NCAA football pyramid. +1163 D3 schools have the distinction of being part of +1164 the only NCAA division that cannot give out scholarships solely +1165 for athletic ability. +1166 +1167 `return_as_dict` (bool, semi-optional): +1168 Semi-optional argument. +1169 If you want this function to return +1170 the data as a dictionary (read: JSON object), +1171 instead of a pandas `DataFrame` object, +1172 set `return_as_dict` to `True`. +1173 +1174 Usage +1175 ---------- +1176 ``` +1177 import time +1178 +1179 from cfbd_json_py.games import get_cfbd_game_media_info 1180 -1181 cfbd_key = "tigersAreAwesome" # placeholder for your CFBD API Key. -1182 -1183 if cfbd_key is not "tigersAreAwesome": -1184 print( -1185 "Using the user's API key declared in this script " + -1186 "for this example." -1187 ) -1188 -1189 # Get a media information for the 2020 CFB season. -1190 print("Get a media information for the 2020 CFB season.") -1191 json_data = get_cfbd_game_media_info( -1192 api_key=cfbd_key, -1193 season=2020 -1194 ) -1195 print(json_data) -1196 time.sleep(5) -1197 -1198 # Get a media information for postseason games in the 2020 CFB season. -1199 print("Get a media information for the 2020 CFB season.") -1200 json_data = get_cfbd_game_media_info( -1201 api_key=cfbd_key, -1202 season=2020, -1203 season_type="postseason" -1204 ) -1205 print(json_data) -1206 time.sleep(5) -1207 -1208 # Get a media information for week 10 games in the 2020 CFB season. -1209 print( -1210 "Get a media information for week 10 games in the 2020 CFB season." -1211 ) -1212 json_data = get_cfbd_game_media_info( -1213 api_key=cfbd_key, -1214 season=2020, -1215 week=10 -1216 ) -1217 print(json_data) -1218 time.sleep(5) -1219 -1220 # Get all known broadcasters for games played by -1221 # the Ohio State Football Program in the the 2019 CFB season. -1222 print( -1223 "Get all known broadcasters for games played by " + -1224 "the Ohio State Football Program in the the 2019 CFB season." -1225 ) -1226 json_data = get_cfbd_game_media_info( -1227 api_key=cfbd_key, -1228 season=2020, -1229 team="Ohio State" -1230 ) -1231 print(json_data) -1232 time.sleep(5) -1233 -1234 # Get all known radio broadcasters for games played by teams -1235 # within the American Athletic conference (AAC) -1236 # in the the 2021 CFB season. -1237 print( -1238 "Get all known radio broadcasters for games played " + -1239 "by teams within the American Athletic conference (AAC) " + -1240 "in the the 2021 CFB season." -1241 ) -1242 json_data = get_cfbd_game_media_info( -1243 api_key=cfbd_key, -1244 season=2020, -1245 conference="AAC" -1246 ) -1247 print(json_data) -1248 time.sleep(5) -1249 -1250 # Get all known radio broadcasters -1251 # for games in the the 2020 CFB season. -1252 print( -1253 "Get all known radio broadcasters " + -1254 "for games in the the 2020 CFB season." -1255 ) -1256 json_data = get_cfbd_game_media_info( -1257 api_key=cfbd_key, -1258 season=2020, -1259 media_type="radio" -1260 ) -1261 print(json_data) -1262 time.sleep(5) -1263 -1264 # Get all known broadcasters for -1265 # the Football Championship Subdivision (FCS) games -1266 # in the 2020 CFB season. -1267 print( -1268 "Get all known broadcasters for " + -1269 "the Football Championship Subdivision (FCS) games " + -1270 "in the 2020 CFB season." -1271 ) -1272 json_data = get_cfbd_game_media_info( -1273 api_key=cfbd_key, -1274 season=2020, -1275 ncaa_division="fcs" -1276 ) -1277 print(json_data) -1278 time.sleep(5) -1279 -1280 # You can also tell this function to just return the API call as -1281 # a Dictionary (read: JSON) object. -1282 print( -1283 "You can also tell this function to just return the API call " + -1284 "as a Dictionary (read: JSON) object." -1285 ) -1286 json_data = get_cfbd_game_media_info( -1287 season=2020, -1288 api_key=cfbd_key, -1289 return_as_dict=True -1290 ) -1291 print(json_data) -1292 -1293 else: -1294 # Alternatively, if the CFBD API key exists in this python environment, -1295 # or it's been set by cfbd_json_py.utls.set_cfbd_api_token(), -1296 # you could just call these functions directly, -1297 # without setting the API key in the script. -1298 print( -1299 "Using the user's API key supposedly loaded " + -1300 "into this python environment for this example." -1301 ) -1302 -1303 # Get a media information for the 2020 CFB season. -1304 print("Get a media information for the 2020 CFB season.") -1305 json_data = get_cfbd_game_media_info( -1306 season=2020 -1307 ) -1308 print(json_data) -1309 time.sleep(5) -1310 -1311 # Get a media information for postseason games in the 2020 CFB season. -1312 print("Get a media information for the 2020 CFB season.") -1313 json_data = get_cfbd_game_media_info( -1314 season=2020, -1315 season_type="postseason" -1316 ) -1317 print(json_data) -1318 time.sleep(5) -1319 -1320 # Get a media information for week 10 games in the 2020 CFB season. -1321 print( -1322 "Get a media information for week 10 games in the 2020 CFB season." -1323 ) -1324 json_data = get_cfbd_game_media_info( -1325 season=2020, -1326 week=10 -1327 ) -1328 print(json_data) -1329 time.sleep(5) -1330 -1331 # Get all known broadcasters for games played by -1332 # the Ohio State Football Program in the the 2019 CFB season. -1333 print( -1334 "Get all known broadcasters for games played by " + -1335 "the Ohio State Football Program in the the 2019 CFB season." -1336 ) -1337 json_data = get_cfbd_game_media_info( -1338 season=2020, -1339 team="Ohio State" -1340 ) -1341 print(json_data) -1342 time.sleep(5) -1343 -1344 # Get all known radio broadcasters for games played by teams -1345 # within the American Athletic conference (AAC) -1346 # in the the 2021 CFB season. -1347 print( -1348 "Get all known radio broadcasters for games played " + -1349 "by teams within the American Athletic conference (AAC) " + -1350 "in the the 2021 CFB season." -1351 ) -1352 json_data = get_cfbd_game_media_info( -1353 season=2020, -1354 conference="AAC" -1355 ) -1356 print(json_data) -1357 time.sleep(5) -1358 -1359 # Get all known radio broadcasters -1360 # for games in the the 2020 CFB season. -1361 print( -1362 "Get all known radio broadcasters " + -1363 "for games in the the 2020 CFB season." -1364 ) -1365 json_data = get_cfbd_game_media_info( -1366 season=2020, -1367 media_type="radio" -1368 ) -1369 print(json_data) -1370 time.sleep(5) -1371 -1372 # Get all known broadcasters for -1373 # the Football Championship Subdivision (FCS) games -1374 # in the 2020 CFB season. -1375 print( -1376 "Get all known broadcasters for " + -1377 "the Football Championship Subdivision (FCS) games " + -1378 "in the 2020 CFB season." -1379 ) -1380 json_data = get_cfbd_game_media_info( -1381 season=2020, -1382 ncaa_division="fcs" -1383 ) -1384 print(json_data) -1385 time.sleep(5) -1386 +1181 +1182 cfbd_key = "tigersAreAwesome" # placeholder for your CFBD API Key. +1183 +1184 if cfbd_key is not "tigersAreAwesome": +1185 print( +1186 "Using the user's API key declared in this script " + +1187 "for this example." +1188 ) +1189 +1190 # Get a media information for the 2020 CFB season. +1191 print("Get a media information for the 2020 CFB season.") +1192 json_data = get_cfbd_game_media_info( +1193 api_key=cfbd_key, +1194 season=2020 +1195 ) +1196 print(json_data) +1197 time.sleep(5) +1198 +1199 # Get a media information for postseason games in the 2020 CFB season. +1200 print("Get a media information for the 2020 CFB season.") +1201 json_data = get_cfbd_game_media_info( +1202 api_key=cfbd_key, +1203 season=2020, +1204 season_type="postseason" +1205 ) +1206 print(json_data) +1207 time.sleep(5) +1208 +1209 # Get a media information for week 10 games in the 2020 CFB season. +1210 print( +1211 "Get a media information for week 10 games in the 2020 CFB season." +1212 ) +1213 json_data = get_cfbd_game_media_info( +1214 api_key=cfbd_key, +1215 season=2020, +1216 week=10 +1217 ) +1218 print(json_data) +1219 time.sleep(5) +1220 +1221 # Get all known broadcasters for games played by +1222 # the Ohio State Football Program in the the 2019 CFB season. +1223 print( +1224 "Get all known broadcasters for games played by " + +1225 "the Ohio State Football Program in the the 2019 CFB season." +1226 ) +1227 json_data = get_cfbd_game_media_info( +1228 api_key=cfbd_key, +1229 season=2020, +1230 team="Ohio State" +1231 ) +1232 print(json_data) +1233 time.sleep(5) +1234 +1235 # Get all known radio broadcasters for games played by teams +1236 # within the American Athletic conference (AAC) +1237 # in the the 2021 CFB season. +1238 print( +1239 "Get all known radio broadcasters for games played " + +1240 "by teams within the American Athletic conference (AAC) " + +1241 "in the the 2021 CFB season." +1242 ) +1243 json_data = get_cfbd_game_media_info( +1244 api_key=cfbd_key, +1245 season=2020, +1246 conference="AAC" +1247 ) +1248 print(json_data) +1249 time.sleep(5) +1250 +1251 # Get all known radio broadcasters +1252 # for games in the the 2020 CFB season. +1253 print( +1254 "Get all known radio broadcasters " + +1255 "for games in the the 2020 CFB season." +1256 ) +1257 json_data = get_cfbd_game_media_info( +1258 api_key=cfbd_key, +1259 season=2020, +1260 media_type="radio" +1261 ) +1262 print(json_data) +1263 time.sleep(5) +1264 +1265 # Get all known broadcasters for +1266 # the Football Championship Subdivision (FCS) games +1267 # in the 2020 CFB season. +1268 print( +1269 "Get all known broadcasters for " + +1270 "the Football Championship Subdivision (FCS) games " + +1271 "in the 2020 CFB season." +1272 ) +1273 json_data = get_cfbd_game_media_info( +1274 api_key=cfbd_key, +1275 season=2020, +1276 ncaa_division="fcs" +1277 ) +1278 print(json_data) +1279 time.sleep(5) +1280 +1281 # You can also tell this function to just return the API call as +1282 # a Dictionary (read: JSON) object. +1283 print( +1284 "You can also tell this function to just return the API call " + +1285 "as a Dictionary (read: JSON) object." +1286 ) +1287 json_data = get_cfbd_game_media_info( +1288 season=2020, +1289 api_key=cfbd_key, +1290 return_as_dict=True +1291 ) +1292 print(json_data) +1293 +1294 else: +1295 # Alternatively, if the CFBD API key exists in this python environment, +1296 # or it's been set by cfbd_json_py.utls.set_cfbd_api_token(), +1297 # you could just call these functions directly, +1298 # without setting the API key in the script. +1299 print( +1300 "Using the user's API key supposedly loaded " + +1301 "into this python environment for this example." +1302 ) +1303 +1304 # Get a media information for the 2020 CFB season. +1305 print("Get a media information for the 2020 CFB season.") +1306 json_data = get_cfbd_game_media_info( +1307 season=2020 +1308 ) +1309 print(json_data) +1310 time.sleep(5) +1311 +1312 # Get a media information for postseason games in the 2020 CFB season. +1313 print("Get a media information for the 2020 CFB season.") +1314 json_data = get_cfbd_game_media_info( +1315 season=2020, +1316 season_type="postseason" +1317 ) +1318 print(json_data) +1319 time.sleep(5) +1320 +1321 # Get a media information for week 10 games in the 2020 CFB season. +1322 print( +1323 "Get a media information for week 10 games in the 2020 CFB season." +1324 ) +1325 json_data = get_cfbd_game_media_info( +1326 season=2020, +1327 week=10 +1328 ) +1329 print(json_data) +1330 time.sleep(5) +1331 +1332 # Get all known broadcasters for games played by +1333 # the Ohio State Football Program in the the 2019 CFB season. +1334 print( +1335 "Get all known broadcasters for games played by " + +1336 "the Ohio State Football Program in the the 2019 CFB season." +1337 ) +1338 json_data = get_cfbd_game_media_info( +1339 season=2020, +1340 team="Ohio State" +1341 ) +1342 print(json_data) +1343 time.sleep(5) +1344 +1345 # Get all known radio broadcasters for games played by teams +1346 # within the American Athletic conference (AAC) +1347 # in the the 2021 CFB season. +1348 print( +1349 "Get all known radio broadcasters for games played " + +1350 "by teams within the American Athletic conference (AAC) " + +1351 "in the the 2021 CFB season." +1352 ) +1353 json_data = get_cfbd_game_media_info( +1354 season=2020, +1355 conference="AAC" +1356 ) +1357 print(json_data) +1358 time.sleep(5) +1359 +1360 # Get all known radio broadcasters +1361 # for games in the the 2020 CFB season. +1362 print( +1363 "Get all known radio broadcasters " + +1364 "for games in the the 2020 CFB season." +1365 ) +1366 json_data = get_cfbd_game_media_info( +1367 season=2020, +1368 media_type="radio" +1369 ) +1370 print(json_data) +1371 time.sleep(5) +1372 +1373 # Get all known broadcasters for +1374 # the Football Championship Subdivision (FCS) games +1375 # in the 2020 CFB season. +1376 print( +1377 "Get all known broadcasters for " + +1378 "the Football Championship Subdivision (FCS) games " + +1379 "in the 2020 CFB season." +1380 ) +1381 json_data = get_cfbd_game_media_info( +1382 season=2020, +1383 ncaa_division="fcs" +1384 ) +1385 print(json_data) +1386 time.sleep(5) 1387 -1388 # You can also tell this function to just return the API call as -1389 # a Dictionary (read: JSON) object. -1390 print( -1391 "You can also tell this function to just return the API call " + -1392 "as a Dictionary (read: JSON) object." -1393 ) -1394 json_data = get_cfbd_game_media_info( -1395 season=2020, -1396 return_as_dict=True -1397 ) -1398 print(json_data) -1399 -1400 ``` -1401 Returns -1402 ---------- -1403 A pandas `DataFrame` object with college football media information, -1404 or (if `return_as_dict` is set to `True`) -1405 a dictionary object with college football media information. -1406 -1407 """ -1408 -1409 now = datetime.now() -1410 cfb_games_df = pd.DataFrame() -1411 # row_df = pd.DataFrame() -1412 url = "https://api.collegefootballdata.com/games/media" -1413 -1414 ########################################################################## -1415 -1416 if api_key is not None: -1417 real_api_key = api_key -1418 del api_key -1419 else: -1420 real_api_key = get_cfbd_api_token(api_key_dir=api_key_dir) -1421 -1422 if real_api_key == "tigersAreAwesome": -1423 raise ValueError( -1424 "You actually need to change `cfbd_key` to your CFBD API key." -1425 ) -1426 elif "Bearer " in real_api_key: -1427 pass -1428 elif "Bearer" in real_api_key: -1429 real_api_key = real_api_key.replace("Bearer", "Bearer ") -1430 else: -1431 real_api_key = "Bearer " + real_api_key -1432 -1433 if season is None: -1434 # This should never happen without user tampering, but if it does, -1435 # we need to raise an error, -1436 # because the CFBD API will refuse this call without a valid season. -1437 raise SystemError( -1438 "I don't know how, I don't know why, " -1439 + "but you managed to call this function " -1440 + "while `season` was `None` (NULL)," -1441 + " and the function got to this point in the code." -1442 + "\nIf you have a GitHub account, " -1443 + "please raise an issue on this python package's GitHub page:\n" -1444 + "https://github.com/armstjc/cfbd-json-py/issues" -1445 ) -1446 elif season > (now.year + 1): -1447 raise ValueError(f"`season` cannot be greater than {season}.") -1448 elif season < 1869: -1449 raise ValueError("`season` cannot be less than 1869.") -1450 -1451 if ( -1452 season_type != "both" -1453 and season_type != "regular" -1454 and season_type != "postseason" -1455 ): -1456 raise ValueError( -1457 "`season_type` must be set to " -1458 + '"both", "regular", or "postseason" for this function to work.' -1459 ) -1460 -1461 if ( -1462 media_type != "all" -1463 and media_type != "tv" -1464 and media_type != "radio" -1465 and media_type != "web" -1466 and media_type != "ppv" -1467 and media_type != "mobile" -1468 ): -1469 raise ValueError( -1470 "`media_type` must be set " -1471 + "to one of the following values for this function to work:" -1472 + "\n\t- `all`" -1473 + "\n\t- `tv`" -1474 + "\n\t- `radio`" -1475 + "\n\t- `web`" -1476 + "\n\t- `ppv`" -1477 + "\n\t- `mobile`" -1478 ) -1479 -1480 if ( -1481 ncaa_division.lower() == "fbs" -1482 or ncaa_division.lower() == "fcs" -1483 or ncaa_division.lower() == "ii" -1484 or ncaa_division.lower() == "iii" -1485 ): -1486 pass -1487 else: -1488 raise ValueError( -1489 "An invalid NCAA Division was inputted when calling this function." -1490 + '\nValid inputs are:\n-"fbs"\n-"fcs"\n-"ii"\n-"iii"' -1491 + f"\n\nYou entered: \n{ncaa_division}" -1492 ) -1493 -1494 # URL builder -1495 ########################################################################## -1496 -1497 # Required by API -1498 url += f"?year={season}" -1499 -1500 if week is not None: -1501 url += f"&week={week}" -1502 -1503 if team is not None: -1504 url += f"&team={team}" -1505 -1506 if conference is not None: -1507 url += f"&conference={conference}" -1508 -1509 if season_type is not None: -1510 url += f"&seasonType={season_type}" -1511 -1512 if media_type == "all": -1513 # If we don't care about what media type we want back, -1514 # we don't need to add anything to the URL. -1515 pass -1516 elif media_type is not None: -1517 url += f"&mediaType={media_type}" -1518 -1519 if ncaa_division is not None: -1520 url += f"&classification={ncaa_division}" -1521 -1522 headers = { -1523 "Authorization": f"{real_api_key}", -1524 "accept": "application/json" -1525 } -1526 response = requests.get(url, headers=headers) -1527 -1528 if response.status_code == 200: -1529 pass -1530 elif response.status_code == 401: -1531 raise ConnectionRefusedError( -1532 "Could not connect. The connection was refused." + -1533 "\nHTTP Status Code 401." -1534 ) -1535 else: -1536 raise ConnectionError( -1537 f"Could not connect.\nHTTP Status code {response.status_code}" -1538 ) -1539 -1540 json_data = response.json() -1541 -1542 if return_as_dict is True: -1543 return json_data -1544 -1545 # for game in tqdm(json_data): -1546 # row_df = pd.DataFrame({"season": season}, index=[0]) -1547 # row_df["week"] = game["week"] -1548 # row_df["game_id"] = game["id"] -1549 # row_df["season_type"] = game["seasonType"] -1550 # row_df["game_start_time"] = game["startTime"] -1551 # row_df["is_start_time_tbd"] = game["isStartTimeTBD"] -1552 # row_df["home_team"] = game["homeTeam"] -1553 # row_df["home_conference"] = game["homeConference"] -1554 # row_df["away_team"] = game["awayTeam"] -1555 # row_df["away_conference"] = game["awayConference"] -1556 # row_df["media_type"] = game["mediaType"] -1557 # row_df["outlet"] = game["outlet"] -1558 -1559 # cfb_games_df = pd.concat([cfb_games_df, row_df], ignore_index=True) -1560 # del row_df -1561 -1562 cfb_games_df = pd.json_normalize(json_data) -1563 # print(cfb_games_df.columns) -1564 cfb_games_df.rename( -1565 columns={ -1566 "seasonType": "season_type", -1567 "startTime": "start_time", -1568 "isStartTimeTBD": "is_start_time_tbd", -1569 "homeTeam": "home_team_name", -1570 "homeConference": "home_conference_name", -1571 "awayTeam": "away_team_name", -1572 "awayConference": "away_conference_name", -1573 "mediaType": "media_type", -1574 }, -1575 inplace=True, -1576 ) -1577 return cfb_games_df -1578 +1388 +1389 # You can also tell this function to just return the API call as +1390 # a Dictionary (read: JSON) object. +1391 print( +1392 "You can also tell this function to just return the API call " + +1393 "as a Dictionary (read: JSON) object." +1394 ) +1395 json_data = get_cfbd_game_media_info( +1396 season=2020, +1397 return_as_dict=True +1398 ) +1399 print(json_data) +1400 +1401 ``` +1402 Returns +1403 ---------- +1404 A pandas `DataFrame` object with college football media information, +1405 or (if `return_as_dict` is set to `True`) +1406 a dictionary object with college football media information. +1407 +1408 """ +1409 +1410 now = datetime.now() +1411 cfb_games_df = pd.DataFrame() +1412 # row_df = pd.DataFrame() +1413 url = "https://api.collegefootballdata.com/games/media" +1414 +1415 ########################################################################## +1416 +1417 if api_key is not None: +1418 real_api_key = api_key +1419 del api_key +1420 else: +1421 real_api_key = get_cfbd_api_token(api_key_dir=api_key_dir) +1422 +1423 if real_api_key == "tigersAreAwesome": +1424 raise ValueError( +1425 "You actually need to change `cfbd_key` to your CFBD API key." +1426 ) +1427 elif "Bearer " in real_api_key: +1428 pass +1429 elif "Bearer" in real_api_key: +1430 real_api_key = real_api_key.replace("Bearer", "Bearer ") +1431 else: +1432 real_api_key = "Bearer " + real_api_key +1433 +1434 if season is None: +1435 # This should never happen without user tampering, but if it does, +1436 # we need to raise an error, +1437 # because the CFBD API will refuse this call without a valid season. +1438 raise SystemError( +1439 "I don't know how, I don't know why, " +1440 + "but you managed to call this function " +1441 + "while `season` was `None` (NULL)," +1442 + " and the function got to this point in the code." +1443 + "\nIf you have a GitHub account, " +1444 + "please raise an issue on this python package's GitHub page:\n" +1445 + "https://github.com/armstjc/cfbd-json-py/issues" +1446 ) +1447 elif season > (now.year + 1): +1448 raise ValueError(f"`season` cannot be greater than {season}.") +1449 elif season < 1869: +1450 raise ValueError("`season` cannot be less than 1869.") +1451 +1452 if ( +1453 season_type != "both" +1454 and season_type != "regular" +1455 and season_type != "postseason" +1456 ): +1457 raise ValueError( +1458 "`season_type` must be set to " +1459 + '"both", "regular", or "postseason" for this function to work.' +1460 ) +1461 +1462 if ( +1463 media_type != "all" +1464 and media_type != "tv" +1465 and media_type != "radio" +1466 and media_type != "web" +1467 and media_type != "ppv" +1468 and media_type != "mobile" +1469 ): +1470 raise ValueError( +1471 "`media_type` must be set " +1472 + "to one of the following values for this function to work:" +1473 + "\n\t- `all`" +1474 + "\n\t- `tv`" +1475 + "\n\t- `radio`" +1476 + "\n\t- `web`" +1477 + "\n\t- `ppv`" +1478 + "\n\t- `mobile`" +1479 ) +1480 +1481 if ( +1482 ncaa_division.lower() == "fbs" +1483 or ncaa_division.lower() == "fcs" +1484 or ncaa_division.lower() == "ii" +1485 or ncaa_division.lower() == "iii" +1486 ): +1487 pass +1488 else: +1489 raise ValueError( +1490 "An invalid NCAA Division was inputted when calling this function." +1491 + '\nValid inputs are:\n-"fbs"\n-"fcs"\n-"ii"\n-"iii"' +1492 + f"\n\nYou entered: \n{ncaa_division}" +1493 ) +1494 +1495 # URL builder +1496 ########################################################################## +1497 +1498 # Required by API +1499 url += f"?year={season}" +1500 +1501 if week is not None: +1502 url += f"&week={week}" +1503 +1504 if team is not None: +1505 url += f"&team={team}" +1506 +1507 if conference is not None: +1508 url += f"&conference={conference}" +1509 +1510 if season_type is not None: +1511 url += f"&seasonType={season_type}" +1512 +1513 if media_type == "all": +1514 # If we don't care about what media type we want back, +1515 # we don't need to add anything to the URL. +1516 pass +1517 elif media_type is not None: +1518 url += f"&mediaType={media_type}" +1519 +1520 if ncaa_division is not None: +1521 url += f"&classification={ncaa_division}" +1522 +1523 headers = { +1524 "Authorization": f"{real_api_key}", +1525 "accept": "application/json" +1526 } +1527 response = requests.get(url, headers=headers) +1528 +1529 if response.status_code == 200: +1530 pass +1531 elif response.status_code == 401: +1532 raise ConnectionRefusedError( +1533 "Could not connect. The connection was refused." + +1534 "\nHTTP Status Code 401." +1535 ) +1536 else: +1537 raise ConnectionError( +1538 f"Could not connect.\nHTTP Status code {response.status_code}" +1539 ) +1540 +1541 json_data = response.json() +1542 +1543 if return_as_dict is True: +1544 return json_data +1545 +1546 # for game in tqdm(json_data): +1547 # row_df = pd.DataFrame({"season": season}, index=[0]) +1548 # row_df["week"] = game["week"] +1549 # row_df["game_id"] = game["id"] +1550 # row_df["season_type"] = game["seasonType"] +1551 # row_df["game_start_time"] = game["startTime"] +1552 # row_df["is_start_time_tbd"] = game["isStartTimeTBD"] +1553 # row_df["home_team"] = game["homeTeam"] +1554 # row_df["home_conference"] = game["homeConference"] +1555 # row_df["away_team"] = game["awayTeam"] +1556 # row_df["away_conference"] = game["awayConference"] +1557 # row_df["media_type"] = game["mediaType"] +1558 # row_df["outlet"] = game["outlet"] +1559 +1560 # cfb_games_df = pd.concat([cfb_games_df, row_df], ignore_index=True) +1561 # del row_df +1562 +1563 cfb_games_df = pd.json_normalize(json_data) +1564 # print(cfb_games_df.columns) +1565 cfb_games_df.rename( +1566 columns={ +1567 "seasonType": "season_type", +1568 "startTime": "start_time", +1569 "isStartTimeTBD": "is_start_time_tbd", +1570 "homeTeam": "home_team_name", +1571 "homeConference": "home_conference_name", +1572 "awayTeam": "away_team_name", +1573 "awayConference": "away_conference_name", +1574 "mediaType": "media_type", +1575 }, +1576 inplace=True, +1577 ) +1578 return cfb_games_df 1579 -1580def get_cfbd_player_game_stats( -1581 season: int, -1582 api_key: str = None, -1583 api_key_dir: str = None, -1584 season_type: str = "regular", # "regular" or "postseason" -1585 week: int = None, -1586 team: str = None, -1587 conference: str = None, -1588 # `week`, `team`, and/or `conference` -1589 # must be not null for this function to work. -1590 stat_category: str = None, -1591 game_id: int = None, -1592 return_as_dict: bool = False, -1593): -1594 """ -1595 Retrieves player game stats for a given time frame. -1596 -1597 Parameters -1598 ---------- -1599 `season` (int, mandatory): -1600 Required argument. -1601 Specifies the season you want CFB player game stats from. -1602 This must be specified, otherwise this package, and by extension -1603 the CFBD API, will not accept the request to get CFB player game stats. -1604 -1605 `api_key` (str, optional): -1606 Semi-optional argument. -1607 If `api_key` is null, this function will attempt to load a CFBD API key -1608 from the python environment, or from a file on this computer. -1609 If `api_key` is not null, -1610 this function will automatically assume that the -1611 inputted `api_key` is a valid CFBD API key. -1612 -1613 `api_key_dir` (str, optional): -1614 Optional argument. -1615 If `api_key` is set to am empty string, this variable is ignored. -1616 If `api_key_dir` is null, and `api_key` is null, -1617 this function will try to find -1618 a CFBD API key file in this user's home directory. -1619 If `api_key_dir` is set to a string, and `api_key` is null, -1620 this function will assume that `api_key_dir` is a directory, -1621 and will try to find a CFBD API key file in that directory. -1622 -1623 `season_type` (str, semi-optional): -1624 Semi-optional argument. -1625 By default, this will be set to "regular", for the CFB regular season. -1626 If you want CFB player game stats for non-regular season games, -1627 set `season_type` to "postseason". -1628 If `season_type` is set to anything but "regular" or "postseason", -1629 a `ValueError()` will be raised. -1630 -1631 **For the following three variables, -1632 at least one must be set to -1633 a non-null variable when calling this function.** -1634 -1635 `week` (int, optional): -1636 Optional argument. -1637 If `week` is set to an integer, this function will attempt -1638 to load CFB player game stats from games in that season, -1639 and in that week. -1640 -1641 `team` (str, optional): -1642 Optional argument. -1643 If you only want CFB player game stats for a team, -1644 regardless if they are the home/away team, -1645 set `team` to the name of the team you want CFB player game stats from. -1646 -1647 `conference` (str, optional): -1648 Optional argument. -1649 If you only want player game stats from games -1650 involving teams a specific conference, -1651 set `conference` to the abbreviation -1652 of the conference you want stats from. -1653 -1654 `stat_category` (str, optional): -1655 Optional argument. -1656 If only want stats for a specific stat category, -1657 set this variable to that category. -1658 -1659 Valid inputs are: -1660 - `passing` -1661 - `rushing` -1662 - `receiving` -1663 - `fumbles` -1664 - `defensive` -1665 - `interceptions` -1666 - `punting` -1667 - `kicking` -1668 - `kickReturns` -1669 - `puntReturns` -1670 -1671 `game_id` (int, optional): -1672 Optional argument. -1673 If `game_id` is set to a game ID, `get_cfbd_player_game_stats()` -1674 will try to get player game stats just for that game ID. -1675 -1676 `return_as_dict` (bool, semi-optional): -1677 Semi-optional argument. -1678 If you want this function to return -1679 the data as a dictionary (read: JSON object), -1680 instead of a pandas `DataFrame` object, -1681 set `return_as_dict` to `True`. -1682 -1683 Usage -1684 ---------- -1685 ``` -1686 import time -1687 -1688 from cfbd_json_py.games import get_cfbd_player_game_stats -1689 +1580 +1581def get_cfbd_player_game_stats( +1582 season: int, +1583 api_key: str = None, +1584 api_key_dir: str = None, +1585 season_type: str = "regular", # "regular" or "postseason" +1586 week: int = None, +1587 team: str = None, +1588 conference: str = None, +1589 # `week`, `team`, and/or `conference` +1590 # must be not null for this function to work. +1591 s_category: str = None, +1592 game_id: int = None, +1593 return_as_dict: bool = False, +1594): +1595 """ +1596 Retrieves player game stats for a given time frame. +1597 +1598 Parameters +1599 ---------- +1600 `season` (int, mandatory): +1601 Required argument. +1602 Specifies the season you want CFB player game stats from. +1603 This must be specified, otherwise this package, and by extension +1604 the CFBD API, will not accept the request to get CFB player game stats. +1605 +1606 `api_key` (str, optional): +1607 Semi-optional argument. +1608 If `api_key` is null, this function will attempt to load a CFBD API key +1609 from the python environment, or from a file on this computer. +1610 If `api_key` is not null, +1611 this function will automatically assume that the +1612 inputted `api_key` is a valid CFBD API key. +1613 +1614 `api_key_dir` (str, optional): +1615 Optional argument. +1616 If `api_key` is set to am empty string, this variable is ignored. +1617 If `api_key_dir` is null, and `api_key` is null, +1618 this function will try to find +1619 a CFBD API key file in this user's home directory. +1620 If `api_key_dir` is set to a string, and `api_key` is null, +1621 this function will assume that `api_key_dir` is a directory, +1622 and will try to find a CFBD API key file in that directory. +1623 +1624 `season_type` (str, semi-optional): +1625 Semi-optional argument. +1626 By default, this will be set to "regular", for the CFB regular season. +1627 If you want CFB player game stats for non-regular season games, +1628 set `season_type` to "postseason". +1629 If `season_type` is set to anything but "regular" or "postseason", +1630 a `ValueError()` will be raised. +1631 +1632 **For the following three variables, +1633 at least one must be set to +1634 a non-null variable when calling this function.** +1635 +1636 `week` (int, optional): +1637 Optional argument. +1638 If `week` is set to an integer, this function will attempt +1639 to load CFB player game stats from games in that season, +1640 and in that week. +1641 +1642 `team` (str, optional): +1643 Optional argument. +1644 If you only want CFB player game stats for a team, +1645 regardless if they are the home/away team, +1646 set `team` to the name of the team you want CFB player game stats from. +1647 +1648 `conference` (str, optional): +1649 Optional argument. +1650 If you only want player game stats from games +1651 involving teams a specific conference, +1652 set `conference` to the abbreviation +1653 of the conference you want stats from. +1654 +1655 `stat_category` (str, optional): +1656 Optional argument. +1657 If only want stats for a specific stat category, +1658 set this variable to that category. +1659 +1660 Valid inputs are: +1661 - `passing` +1662 - `rushing` +1663 - `receiving` +1664 - `fumbles` +1665 - `defensive` +1666 - `interceptions` +1667 - `punting` +1668 - `kicking` +1669 - `kickReturns` +1670 - `puntReturns` +1671 +1672 `game_id` (int, optional): +1673 Optional argument. +1674 If `game_id` is set to a game ID, `get_cfbd_player_game_stats()` +1675 will try to get player game stats just for that game ID. +1676 +1677 `return_as_dict` (bool, semi-optional): +1678 Semi-optional argument. +1679 If you want this function to return +1680 the data as a dictionary (read: JSON object), +1681 instead of a pandas `DataFrame` object, +1682 set `return_as_dict` to `True`. +1683 +1684 Usage +1685 ---------- +1686 ``` +1687 import time +1688 +1689 from cfbd_json_py.games import get_cfbd_player_game_stats 1690 -1691 cfbd_key = "tigersAreAwesome" # placeholder for your CFBD API Key. -1692 -1693 if cfbd_key is not "tigersAreAwesome": -1694 print( -1695 "Using the user's API key declared in this script " + -1696 "for this example." -1697 ) -1698 -1699 # Get player game stats for week 10 of the 2020 CFB season. -1700 print("Get player game stats for week 10 of the 2020 CFB season.") -1701 json_data = get_cfbd_player_game_stats( -1702 api_key=cfbd_key, -1703 season=2020, -1704 week=10 -1705 ) -1706 print(json_data) -1707 time.sleep(5) -1708 -1709 # Get postseason player game stats for the 2020 CFB season. -1710 print("Get postseason player game stats for the 2020 CFB season.") -1711 json_data = get_cfbd_player_game_stats( -1712 api_key=cfbd_key, -1713 season=2020, -1714 season_type="postseason", -1715 week=1 -1716 ) -1717 print(json_data) -1718 time.sleep(5) -1719 -1720 # Get player game stats for -1721 # the Alabama Crimson Tide Football Team for the 2018 CFB season. -1722 print( -1723 "Get player game stats for " + -1724 "the Alabama Crimson Tide Football Team for the 2018 CFB season." -1725 ) -1726 json_data = get_cfbd_player_game_stats( -1727 api_key=cfbd_key, -1728 season=2018, -1729 team="Alabama" -1730 ) -1731 print(json_data) -1732 time.sleep(5) -1733 -1734 # Get player game stats for players of teams in -1735 # the Atlantic Coast Conference (ACC) in the 2020 CFB season. -1736 print( -1737 "Get player game stats for players of teams in " + -1738 "the Atlantic Coast Conference (ACC) in the 2020 CFB season." -1739 ) -1740 json_data = get_cfbd_player_game_stats( -1741 api_key=cfbd_key, -1742 season=2020, -1743 conference="ACC" -1744 ) -1745 print(json_data) -1746 time.sleep(5) -1747 -1748 # Get get passing stats from players who played -1749 # in week 7 of the 2017 CFB season. -1750 print( -1751 "Get get passing stats from players who played " + -1752 "in week 7 of the 2017 CFB season." -1753 ) -1754 json_data = get_cfbd_player_game_stats( -1755 api_key=cfbd_key, -1756 season=2017, -1757 week=7, -1758 stat_category="passing" -1759 ) -1760 print(json_data) -1761 time.sleep(5) -1762 -1763 # Get player game stats from the 2021 Virbo Citrus Bowl, -1764 # a bowl game that happened in the 2020 CFB season. -1765 print( -1766 "Get player game stats from the 2021 Virbo Citrus Bowl, " + -1767 "a bowl game that happened in the 2020 CFB season." -1768 ) -1769 json_data = get_cfbd_player_game_stats( -1770 api_key=cfbd_key, -1771 season=2020, -1772 game_id=401256199 -1773 ) -1774 print(json_data) -1775 time.sleep(5) -1776 -1777 # You can also tell this function to just return the API call as -1778 # a Dictionary (read: JSON) object. -1779 print( -1780 "You can also tell this function to just return the API call " + -1781 "as a Dictionary (read: JSON) object." -1782 ) -1783 json_data = get_cfbd_player_game_stats( -1784 season=2020, -1785 week=10, -1786 api_key=cfbd_key, -1787 return_as_dict=True -1788 ) -1789 print(json_data) -1790 -1791 else: -1792 # Alternatively, if the CFBD API key exists in this python environment, -1793 # or it's been set by cfbd_json_py.utls.set_cfbd_api_token(), -1794 # you could just call these functions directly, -1795 # without setting the API key in the script. -1796 print( -1797 "Using the user's API key supposedly loaded " + -1798 "into this python environment for this example." -1799 ) -1800 -1801 # Get player game stats for week 10 of the 2020 CFB season. -1802 print("Get player game stats for week 10 of the 2020 CFB season.") -1803 json_data = get_cfbd_player_game_stats( -1804 season=2020, -1805 week=10 -1806 ) -1807 print(json_data) -1808 time.sleep(5) -1809 -1810 # Get postseason player game stats for the 2020 CFB season. -1811 print("Get postseason player game stats for the 2020 CFB season.") -1812 json_data = get_cfbd_player_game_stats( -1813 season=2020, -1814 season_type="postseason", -1815 week=1 -1816 ) -1817 print(json_data) -1818 time.sleep(5) -1819 -1820 # Get player game stats for -1821 # the Alabama Crimson Tide Football Team for the 2018 CFB season. -1822 print( -1823 "Get player game stats for " + -1824 "the Alabama Crimson Tide Football Team for the 2018 CFB season." -1825 ) -1826 json_data = get_cfbd_player_game_stats( -1827 season=2018, -1828 team="Alabama" -1829 ) -1830 print(json_data) -1831 time.sleep(5) -1832 -1833 # Get player game stats for players of teams in -1834 # the Atlantic Coast Conference (ACC) in the 2020 CFB season. -1835 print( -1836 "Get player game stats for players of teams in " + -1837 "the Atlantic Coast Conference (ACC) in the 2020 CFB season." -1838 ) -1839 json_data = get_cfbd_player_game_stats( -1840 season=2020, -1841 conference="ACC" -1842 ) -1843 print(json_data) -1844 time.sleep(5) -1845 -1846 # Get get passing stats from players who played -1847 # in week 7 of the 2017 CFB season. -1848 print( -1849 "Get get passing stats from players who played " + -1850 "in week 7 of the 2017 CFB season." -1851 ) -1852 json_data = get_cfbd_player_game_stats( -1853 season=2017, -1854 week=7, -1855 stat_category="passing" -1856 ) -1857 print(json_data) -1858 time.sleep(5) -1859 -1860 # Get player game stats from the 2021 Virbo Citrus Bowl, -1861 # a bowl game that happened in the 2020 CFB season, -1862 # between the Aubrun Tigers, and the Northwestern Wildcats. -1863 print("Get player game stats from the 2021 Virbo Citrus Bowl, "+ -1864 "a bowl game that happened in the 2020 CFB season " + -1865 "between the Aubrun Tigers, and the Northwestern Wildcats." -1866 ) -1867 json_data = get_cfbd_player_game_stats( -1868 season=2020, -1869 game_id=401256199 -1870 ) -1871 print(json_data) -1872 time.sleep(5) -1873 +1691 +1692 cfbd_key = "tigersAreAwesome" # placeholder for your CFBD API Key. +1693 +1694 if cfbd_key is not "tigersAreAwesome": +1695 print( +1696 "Using the user's API key declared in this script " + +1697 "for this example." +1698 ) +1699 +1700 # Get player game stats for week 10 of the 2020 CFB season. +1701 print("Get player game stats for week 10 of the 2020 CFB season.") +1702 json_data = get_cfbd_player_game_stats( +1703 api_key=cfbd_key, +1704 season=2020, +1705 week=10 +1706 ) +1707 print(json_data) +1708 time.sleep(5) +1709 +1710 # Get postseason player game stats for the 2020 CFB season. +1711 print("Get postseason player game stats for the 2020 CFB season.") +1712 json_data = get_cfbd_player_game_stats( +1713 api_key=cfbd_key, +1714 season=2020, +1715 season_type="postseason", +1716 week=1 +1717 ) +1718 print(json_data) +1719 time.sleep(5) +1720 +1721 # Get player game stats for +1722 # the Alabama Crimson Tide Football Team for the 2018 CFB season. +1723 print( +1724 "Get player game stats for " + +1725 "the Alabama Crimson Tide Football Team for the 2018 CFB season." +1726 ) +1727 json_data = get_cfbd_player_game_stats( +1728 api_key=cfbd_key, +1729 season=2018, +1730 team="Alabama" +1731 ) +1732 print(json_data) +1733 time.sleep(5) +1734 +1735 # Get player game stats for players of teams in +1736 # the Atlantic Coast Conference (ACC) in the 2020 CFB season. +1737 print( +1738 "Get player game stats for players of teams in " + +1739 "the Atlantic Coast Conference (ACC) in the 2020 CFB season." +1740 ) +1741 json_data = get_cfbd_player_game_stats( +1742 api_key=cfbd_key, +1743 season=2020, +1744 conference="ACC" +1745 ) +1746 print(json_data) +1747 time.sleep(5) +1748 +1749 # Get get passing stats from players who played +1750 # in week 7 of the 2017 CFB season. +1751 print( +1752 "Get get passing stats from players who played " + +1753 "in week 7 of the 2017 CFB season." +1754 ) +1755 json_data = get_cfbd_player_game_stats( +1756 api_key=cfbd_key, +1757 season=2017, +1758 week=7, +1759 stat_category="passing" +1760 ) +1761 print(json_data) +1762 time.sleep(5) +1763 +1764 # Get player game stats from the 2021 Virbo Citrus Bowl, +1765 # a bowl game that happened in the 2020 CFB season. +1766 print( +1767 "Get player game stats from the 2021 Virbo Citrus Bowl, " + +1768 "a bowl game that happened in the 2020 CFB season." +1769 ) +1770 json_data = get_cfbd_player_game_stats( +1771 api_key=cfbd_key, +1772 season=2020, +1773 game_id=401256199 +1774 ) +1775 print(json_data) +1776 time.sleep(5) +1777 +1778 # You can also tell this function to just return the API call as +1779 # a Dictionary (read: JSON) object. +1780 print( +1781 "You can also tell this function to just return the API call " + +1782 "as a Dictionary (read: JSON) object." +1783 ) +1784 json_data = get_cfbd_player_game_stats( +1785 season=2020, +1786 week=10, +1787 api_key=cfbd_key, +1788 return_as_dict=True +1789 ) +1790 print(json_data) +1791 +1792 else: +1793 # Alternatively, if the CFBD API key exists in this python environment, +1794 # or it's been set by cfbd_json_py.utls.set_cfbd_api_token(), +1795 # you could just call these functions directly, +1796 # without setting the API key in the script. +1797 print( +1798 "Using the user's API key supposedly loaded " + +1799 "into this python environment for this example." +1800 ) +1801 +1802 # Get player game stats for week 10 of the 2020 CFB season. +1803 print("Get player game stats for week 10 of the 2020 CFB season.") +1804 json_data = get_cfbd_player_game_stats( +1805 season=2020, +1806 week=10 +1807 ) +1808 print(json_data) +1809 time.sleep(5) +1810 +1811 # Get postseason player game stats for the 2020 CFB season. +1812 print("Get postseason player game stats for the 2020 CFB season.") +1813 json_data = get_cfbd_player_game_stats( +1814 season=2020, +1815 season_type="postseason", +1816 week=1 +1817 ) +1818 print(json_data) +1819 time.sleep(5) +1820 +1821 # Get player game stats for +1822 # the Alabama Crimson Tide Football Team for the 2018 CFB season. +1823 print( +1824 "Get player game stats for " + +1825 "the Alabama Crimson Tide Football Team for the 2018 CFB season." +1826 ) +1827 json_data = get_cfbd_player_game_stats( +1828 season=2018, +1829 team="Alabama" +1830 ) +1831 print(json_data) +1832 time.sleep(5) +1833 +1834 # Get player game stats for players of teams in +1835 # the Atlantic Coast Conference (ACC) in the 2020 CFB season. +1836 print( +1837 "Get player game stats for players of teams in " + +1838 "the Atlantic Coast Conference (ACC) in the 2020 CFB season." +1839 ) +1840 json_data = get_cfbd_player_game_stats( +1841 season=2020, +1842 conference="ACC" +1843 ) +1844 print(json_data) +1845 time.sleep(5) +1846 +1847 # Get get passing stats from players who played +1848 # in week 7 of the 2017 CFB season. +1849 print( +1850 "Get get passing stats from players who played " + +1851 "in week 7 of the 2017 CFB season." +1852 ) +1853 json_data = get_cfbd_player_game_stats( +1854 season=2017, +1855 week=7, +1856 stat_category="passing" +1857 ) +1858 print(json_data) +1859 time.sleep(5) +1860 +1861 # Get player game stats from the 2021 Virbo Citrus Bowl, +1862 # a bowl game that happened in the 2020 CFB season, +1863 # between the Aubrun Tigers, and the Northwestern Wildcats. +1864 print("Get player game stats from the 2021 Virbo Citrus Bowl, "+ +1865 "a bowl game that happened in the 2020 CFB season " + +1866 "between the Aubrun Tigers, and the Northwestern Wildcats." +1867 ) +1868 json_data = get_cfbd_player_game_stats( +1869 season=2020, +1870 game_id=401256199 +1871 ) +1872 print(json_data) +1873 time.sleep(5) 1874 -1875 # You can also tell this function to just return the API call as -1876 # a Dictionary (read: JSON) object. -1877 print( -1878 "You can also tell this function to just return the API call " + -1879 "as a Dictionary (read: JSON) object." -1880 ) -1881 json_data = get_cfbd_player_game_stats( -1882 season=2020, -1883 week=10, -1884 return_as_dict=True -1885 ) -1886 print(json_data) -1887 -1888 ``` -1889 Returns -1890 ---------- -1891 A pandas `DataFrame` object with player game stats data, -1892 or (if `return_as_dict` is set to `True`) -1893 a dictionary object with player game stats data. -1894 -1895 """ -1896 -1897 rebuilt_json = {} +1875 +1876 # You can also tell this function to just return the API call as +1877 # a Dictionary (read: JSON) object. +1878 print( +1879 "You can also tell this function to just return the API call " + +1880 "as a Dictionary (read: JSON) object." +1881 ) +1882 json_data = get_cfbd_player_game_stats( +1883 season=2020, +1884 week=10, +1885 return_as_dict=True +1886 ) +1887 print(json_data) +1888 +1889 ``` +1890 Returns +1891 ---------- +1892 A pandas `DataFrame` object with player game stats data, +1893 or (if `return_as_dict` is set to `True`) +1894 a dictionary object with player game stats data. +1895 +1896 """ +1897 1898 now = datetime.now() -1899 cfb_games_df = pd.DataFrame() -1900 row_df = pd.DataFrame() -1901 url = "https://api.collegefootballdata.com/games/players" -1902 stat_columns = [ -1903 "season", -1904 "game_id", -1905 "team_name", -1906 "team_conference", -1907 "player_id", -1908 "player_name", -1909 "home_away", -1910 # PASS -1911 "passing_C/ATT", -1912 "passing_COMP", -1913 "passing_ATT", -1914 "passing_YDS", -1915 "passing_AVG", -1916 "passing_TD", -1917 "passing_INT", -1918 "passing_QBR", -1919 # RUSH -1920 "rushing_CAR", -1921 "rushing_YDS", -1922 "rushing_AVG", -1923 "rushing_TD", -1924 "rushing_LONG", -1925 # REC -1926 "receiving_REC", -1927 "receiving_YDS", -1928 "receiving_AVG", -1929 "receiving_TD", -1930 "receiving_LONG", -1931 # FUM -1932 "fumbles_FUM", -1933 "fumbles_LOST", -1934 "fumbles_REC", -1935 # DEFENSE -1936 "defensive_TOT", -1937 "defensive_SOLO", -1938 "defensive_TFL", -1939 "defensive_QB HUR", -1940 "defensive_SACKS", -1941 "defensive_PD", -1942 "defensive_TD", -1943 # INT -1944 "interceptions_INT", -1945 "interceptions_YDS", -1946 "interceptions_TD", -1947 # PUNT -1948 "punting_NO", -1949 "punting_YDS", -1950 "punting_AVG", -1951 "punting_TB", -1952 "punting_In 20", -1953 "punting_LONG", -1954 # KICK -1955 "kicking_FG", -1956 "kicking_FGM", -1957 "kicking_FGA", -1958 "kicking_PCT", -1959 "kicking_LONG", -1960 "kicking_XP", -1961 "kicking_XPM", -1962 "kicking_XPA", -1963 "kicking_PTS", -1964 # KR -1965 "kickReturns_NO", -1966 "kickReturns_YDS", -1967 "kickReturns_AVG", -1968 "kickReturns_TD", -1969 "kickReturns_LONG", -1970 # PR -1971 "puntReturns_NO", -1972 "puntReturns_YDS", -1973 "puntReturns_AVG", -1974 "puntReturns_TD", -1975 "puntReturns_LONG", -1976 ] -1977 -1978 ########################################################################## -1979 -1980 if api_key is not None: -1981 real_api_key = api_key -1982 del api_key -1983 else: -1984 real_api_key = get_cfbd_api_token(api_key_dir=api_key_dir) -1985 -1986 if real_api_key == "tigersAreAwesome": -1987 raise ValueError( -1988 "You actually need to change `cfbd_key` to your CFBD API key." -1989 ) -1990 elif "Bearer " in real_api_key: -1991 pass -1992 elif "Bearer" in real_api_key: -1993 real_api_key = real_api_key.replace("Bearer", "Bearer ") -1994 else: -1995 real_api_key = "Bearer " + real_api_key -1996 -1997 if season is None: -1998 # This should never happen without user tampering, but if it does, -1999 # we need to raise an error, -2000 # because the CFBD API will refuse this call without a valid season. -2001 raise SystemError( -2002 "I don't know how, I don't know why, " -2003 + "but you managed to call this function " -2004 + "while `season` was `None` (NULL)," -2005 + " and the function got to this point in the code." -2006 + "\nIf you have a GitHub account, " -2007 + "please raise an issue on this python package's GitHub page:\n" -2008 + "https://github.com/armstjc/cfbd-json-py/issues" -2009 ) -2010 elif season > (now.year + 1): -2011 raise ValueError(f"`season` cannot be greater than {season}.") -2012 elif season < 1869: -2013 raise ValueError("`season` cannot be less than 1869.") -2014 -2015 if season_type != "regular" and season_type != "postseason": -2016 raise ValueError( -2017 '`season_type` must be set to either "regular" or ' -2018 + '"postseason" for this function to work.' -2019 ) -2020 -2021 # `week`, `team`, and/or `conference` -2022 # must be not null for this function to work. -2023 -2024 if ( -2025 week is None and -2026 team is None and -2027 conference is None and -2028 game_id is None -2029 ): -2030 raise ValueError( -2031 "To use `get_cfbd_player_game_stats()`," -2032 + " `week`, `team`, and/or `conference` " -2033 + "need to be set to a non-null value." -2034 ) -2035 -2036 filter_by_stat_category = False -2037 -2038 if stat_category is None: -2039 pass -2040 elif stat_category == "passing": -2041 filter_by_stat_category = True -2042 elif stat_category == "rushing": -2043 filter_by_stat_category = True -2044 elif stat_category == "receiving": +1899 +1900 rebuilt_json = {} +1901 rebuilt_json_list = [] +1902 +1903 cfb_games_df = pd.DataFrame() +1904 # row_df = pd.DataFrame() +1905 url = "https://api.collegefootballdata.com/games/players" +1906 stat_columns = [ +1907 "season", +1908 "game_id", +1909 "team_name", +1910 "team_conference", +1911 "player_id", +1912 "player_name", +1913 "home_away", +1914 # PASS +1915 "passing_C/ATT", +1916 "passing_COMP", +1917 "passing_ATT", +1918 "passing_YDS", +1919 "passing_AVG", +1920 "passing_TD", +1921 "passing_INT", +1922 "passing_QBR", +1923 # RUSH +1924 "rushing_CAR", +1925 "rushing_YDS", +1926 "rushing_AVG", +1927 "rushing_TD", +1928 "rushing_LONG", +1929 # REC +1930 "receiving_REC", +1931 "receiving_YDS", +1932 "receiving_AVG", +1933 "receiving_TD", +1934 "receiving_LONG", +1935 # FUM +1936 "fumbles_FUM", +1937 "fumbles_LOST", +1938 "fumbles_REC", +1939 # DEFENSE +1940 "defensive_TOT", +1941 "defensive_SOLO", +1942 "defensive_TFL", +1943 "defensive_QB HUR", +1944 "defensive_SACKS", +1945 "defensive_PD", +1946 "defensive_TD", +1947 # INT +1948 "interceptions_INT", +1949 "interceptions_YDS", +1950 "interceptions_TD", +1951 # PUNT +1952 "punting_NO", +1953 "punting_YDS", +1954 "punting_AVG", +1955 "punting_TB", +1956 "punting_In 20", +1957 "punting_LONG", +1958 # KICK +1959 "kicking_FG", +1960 "kicking_FGM", +1961 "kicking_FGA", +1962 "kicking_PCT", +1963 "kicking_LONG", +1964 "kicking_XP", +1965 "kicking_XPM", +1966 "kicking_XPA", +1967 "kicking_PTS", +1968 # KR +1969 "kickReturns_NO", +1970 "kickReturns_YDS", +1971 "kickReturns_AVG", +1972 "kickReturns_TD", +1973 "kickReturns_LONG", +1974 # PR +1975 "puntReturns_NO", +1976 "puntReturns_YDS", +1977 "puntReturns_AVG", +1978 "puntReturns_TD", +1979 "puntReturns_LONG", +1980 ] +1981 +1982 ########################################################################## +1983 +1984 if api_key is not None: +1985 real_api_key = api_key +1986 del api_key +1987 else: +1988 real_api_key = get_cfbd_api_token(api_key_dir=api_key_dir) +1989 +1990 if real_api_key == "tigersAreAwesome": +1991 raise ValueError( +1992 "You actually need to change `cfbd_key` to your CFBD API key." +1993 ) +1994 elif "Bearer " in real_api_key: +1995 pass +1996 elif "Bearer" in real_api_key: +1997 real_api_key = real_api_key.replace("Bearer", "Bearer ") +1998 else: +1999 real_api_key = "Bearer " + real_api_key +2000 +2001 if season is None: +2002 # This should never happen without user tampering, but if it does, +2003 # we need to raise an error, +2004 # because the CFBD API will refuse this call without a valid season. +2005 raise SystemError( +2006 "I don't know how, I don't know why, " +2007 + "but you managed to call this function " +2008 + "while `season` was `None` (NULL)," +2009 + " and the function got to this point in the code." +2010 + "\nIf you have a GitHub account, " +2011 + "please raise an issue on this python package's GitHub page:\n" +2012 + "https://github.com/armstjc/cfbd-json-py/issues" +2013 ) +2014 elif season > (now.year + 1): +2015 raise ValueError(f"`season` cannot be greater than {season}.") +2016 elif season < 1869: +2017 raise ValueError("`season` cannot be less than 1869.") +2018 +2019 if season_type != "regular" and season_type != "postseason": +2020 raise ValueError( +2021 '`season_type` must be set to either "regular" or ' +2022 + '"postseason" for this function to work.' +2023 ) +2024 +2025 # `week`, `team`, and/or `conference` +2026 # must be not null for this function to work. +2027 +2028 if ( +2029 week is None and +2030 team is None and +2031 conference is None and +2032 game_id is None +2033 ): +2034 raise ValueError( +2035 "To use `get_cfbd_player_game_stats()`," +2036 + " `week`, `team`, and/or `conference` " +2037 + "need to be set to a non-null value." +2038 ) +2039 +2040 filter_by_stat_category = False +2041 +2042 if s_category is None: +2043 pass +2044 elif s_category == "passing": 2045 filter_by_stat_category = True -2046 elif stat_category == "fumbles": +2046 elif s_category == "rushing": 2047 filter_by_stat_category = True -2048 elif stat_category == "passing": +2048 elif s_category == "receiving": 2049 filter_by_stat_category = True -2050 elif stat_category == "defensive": +2050 elif s_category == "fumbles": 2051 filter_by_stat_category = True -2052 elif stat_category == "interceptions": +2052 elif s_category == "passing": 2053 filter_by_stat_category = True -2054 elif stat_category == "punting": +2054 elif s_category == "defensive": 2055 filter_by_stat_category = True -2056 elif stat_category == "kicking": +2056 elif s_category == "interceptions": 2057 filter_by_stat_category = True -2058 elif stat_category == "kickReturns": +2058 elif s_category == "punting": 2059 filter_by_stat_category = True -2060 elif stat_category == "puntReturns": +2060 elif s_category == "kicking": 2061 filter_by_stat_category = True -2062 else: -2063 raise ValueError( -2064 "Invalid input for `stat_category`." -2065 + "\nValid inputs are:" -2066 + """ -2067 - `passing` -2068 - `rushing` -2069 - `receiving` -2070 - `fumbles` -2071 - `defensive` -2072 - `interceptions` -2073 - `punting` -2074 - `kicking` -2075 - `kickReturns` -2076 - `puntReturns` -2077 """ -2078 ) -2079 -2080 # URL builder -2081 ########################################################################## -2082 -2083 # Required by the API -2084 url += f"?year={season}" -2085 -2086 if game_id is not None: -2087 url += f"&gameId={game_id}" -2088 -2089 if stat_category is not None: -2090 url += f"&category={stat_category}" -2091 -2092 if week is not None or team is not None or conference is not None: -2093 logging.warning( -2094 "When calling " -2095 + "`cfbd_json_py.games.get_cfbd_player_game_stats()`" -2096 + ", and setting `game_id` to a non-null value, " -2097 + "only `season`, `stat_category`, " -2098 + "and `game_id` are considered " -2099 + "when calling the CFBD API." -2100 ) -2101 else: -2102 if season_type is not None: -2103 url += f"&seasonType={season_type}" -2104 -2105 if week is not None: -2106 url += f"&week={week}" -2107 -2108 if team is not None: -2109 url += f"&team={team}" -2110 -2111 if conference is not None: -2112 url += f"&conference={conference}" -2113 -2114 headers = { -2115 "Authorization": f"{real_api_key}", -2116 "accept": "application/json" -2117 } -2118 response = requests.get(url, headers=headers) -2119 -2120 if response.status_code == 200: -2121 pass -2122 elif response.status_code == 401: -2123 raise ConnectionRefusedError( -2124 "Could not connect. The connection was refused." + -2125 "\nHTTP Status Code 401." -2126 ) -2127 else: -2128 raise ConnectionError( -2129 f"Could not connect.\nHTTP Status code {response.status_code}" +2062 elif s_category == "kickReturns": +2063 filter_by_stat_category = True +2064 elif s_category == "puntReturns": +2065 filter_by_stat_category = True +2066 else: +2067 raise ValueError( +2068 "Invalid input for `stat_category`." +2069 + "\nValid inputs are:" +2070 + """ +2071 - `passing` +2072 - `rushing` +2073 - `receiving` +2074 - `fumbles` +2075 - `defensive` +2076 - `interceptions` +2077 - `punting` +2078 - `kicking` +2079 - `kickReturns` +2080 - `puntReturns` +2081 """ +2082 ) +2083 +2084 # URL builder +2085 ########################################################################## +2086 +2087 # Required by the API +2088 url += f"?year={season}" +2089 +2090 if game_id is not None: +2091 url += f"&gameId={game_id}" +2092 +2093 if s_category is not None: +2094 url += f"&category={s_category}" +2095 +2096 if week is not None or team is not None or conference is not None: +2097 logging.warning( +2098 "When calling " +2099 + "`cfbd_json_py.games.get_cfbd_player_game_stats()`" +2100 + ", and setting `game_id` to a non-null value, " +2101 + "only `season`, `stat_category`, " +2102 + "and `game_id` are considered " +2103 + "when calling the CFBD API." +2104 ) +2105 else: +2106 if season_type is not None: +2107 url += f"&seasonType={season_type}" +2108 +2109 if week is not None: +2110 url += f"&week={week}" +2111 +2112 if team is not None: +2113 url += f"&team={team}" +2114 +2115 if conference is not None: +2116 url += f"&conference={conference}" +2117 +2118 headers = { +2119 "Authorization": f"{real_api_key}", +2120 "accept": "application/json" +2121 } +2122 response = requests.get(url, headers=headers) +2123 +2124 if response.status_code == 200: +2125 pass +2126 elif response.status_code == 401: +2127 raise ConnectionRefusedError( +2128 "Could not connect. The connection was refused." + +2129 "\nHTTP Status Code 401." 2130 ) -2131 -2132 json_data = response.json() -2133 -2134 if return_as_dict is True: -2135 return json_data -2136 -2137 for game in tqdm(json_data): -2138 game_id = game["id"] -2139 -2140 for team in game["teams"]: -2141 team_name = team["school"] -2142 team_conference = team["conference"] -2143 home_away = team["homeAway"] -2144 -2145 for s_category in team["categories"]: -2146 if s_category["name"] == "passing": -2147 for stat in s_category["types"]: -2148 if stat["name"] == "C/ATT": # passing_C/ATT -2149 for i in stat["athletes"]: -2150 player_id = int(i["id"]) -2151 player_name = i["name"] -2152 player_stat = i["stat"] -2153 -2154 if rebuilt_json.get(player_id) is None: -2155 rebuilt_json[player_id] = {} -2156 -2157 rebuilt_json[player_id]["game_id"] = game_id -2158 rebuilt_json[player_id][ -2159 "team_name" -2160 ] = team_name -2161 rebuilt_json[player_id][ -2162 "team_conference" -2163 ] = team_conference -2164 rebuilt_json[player_id][ -2165 "player_id" -2166 ] = player_id -2167 rebuilt_json[player_id][ -2168 "player_name" -2169 ] = player_name -2170 rebuilt_json[player_id][ -2171 "home_away" -2172 ] = home_away -2173 rebuilt_json[player_id][ -2174 "passing_C/ATT" -2175 ] = player_stat -2176 -2177 elif stat["name"] == "YDS": # passing_YDS -2178 for i in stat["athletes"]: -2179 player_id = int(i["id"]) -2180 player_name = i["name"] -2181 player_stat = int(i["stat"]) -2182 -2183 if rebuilt_json.get(player_id) is None: -2184 rebuilt_json[player_id] = {} -2185 -2186 rebuilt_json[player_id]["game_id"] = game_id -2187 rebuilt_json[player_id][ -2188 "team_name" -2189 ] = team_name -2190 rebuilt_json[player_id][ -2191 "team_conference" -2192 ] = team_conference -2193 rebuilt_json[player_id][ -2194 "player_id" -2195 ] = player_id -2196 rebuilt_json[player_id][ -2197 "player_name" -2198 ] = player_name -2199 rebuilt_json[player_id][ -2200 "home_away" -2201 ] = home_away -2202 rebuilt_json[player_id][ -2203 "passing_YDS" -2204 ] = player_stat -2205 -2206 elif stat["name"] == "AVG": # passing_AVG -2207 for i in stat["athletes"]: -2208 player_id = int(i["id"]) -2209 player_name = i["name"] -2210 player_stat = float(i["stat"]) +2131 else: +2132 raise ConnectionError( +2133 f"Could not connect.\nHTTP Status code {response.status_code}" +2134 ) +2135 +2136 json_data = response.json() +2137 +2138 if return_as_dict is True: +2139 return json_data +2140 +2141 for game in tqdm(json_data): +2142 game_id = game["id"] +2143 +2144 for team in game["teams"]: +2145 team_name = team["school"] +2146 team_conference = team["conference"] +2147 home_away = team["homeAway"] +2148 +2149 for s_category in team["categories"]: +2150 stat_category = s_category["name"] +2151 for s_type in s_category["types"]: +2152 stat_name = s_type["name"] +2153 for player in s_type["athletes"]: +2154 p_id = player["id"] +2155 p_name = player["name"] +2156 full_stat_name = f"{stat_category}_{stat_name}" +2157 stat_value = player["stat"] +2158 +2159 if rebuilt_json.get(p_id) is None: +2160 rebuilt_json[p_id] = {} +2161 rebuilt_json[p_id]["player_id"] = p_id +2162 rebuilt_json[p_id]["game_id"] = game_id +2163 rebuilt_json[p_id]["team_name"] = team_name +2164 rebuilt_json[p_id]["team_conference"] = team_conference +2165 rebuilt_json[p_id]["home_away"] = home_away +2166 rebuilt_json[p_id]["player_name"] = p_name +2167 rebuilt_json[p_id][full_stat_name] = stat_value +2168 +2169 for _, value in rebuilt_json.items(): +2170 rebuilt_json_list.append(value) +2171 cfb_games_df = pd.DataFrame(rebuilt_json_list) +2172 cfb_games_df["season"] = season +2173 +2174 cfb_games_df[["passing_COMP", "passing_ATT"]] = cfb_games_df[ +2175 "passing_C/ATT" +2176 ].str.split("/", expand=True) +2177 +2178 cfb_games_df[["kicking_FGM", "kicking_FGA"]] = cfb_games_df[ +2179 "kicking_FG" +2180 ].str.split( +2181 "/", expand=True +2182 ) +2183 +2184 cfb_games_df[["kicking_XP", "kicking_XPM"]] = cfb_games_df[ +2185 "kicking_XP" +2186 ].str.split( +2187 "/", expand=True +2188 ) +2189 +2190 cfb_games_df = cfb_games_df.reindex( +2191 columns=stat_columns +2192 ) +2193 +2194 cfb_games_df = cfb_games_df.replace(np.nan, 0) +2195 cfb_games_df = cfb_games_df.astype( +2196 { +2197 "season": "uint16", +2198 "game_id": "int64", +2199 "team_name": "str", +2200 "team_conference": "str", +2201 "player_id": "int64", +2202 "player_name": "str", +2203 "home_away": "str", +2204 +2205 "passing_COMP": "uint16", +2206 "passing_ATT": "uint16", +2207 "passing_YDS": "int16", +2208 "passing_TD": "uint16", +2209 "passing_INT": "uint16", +2210 "passing_AVG": "float16", 2211 -2212 if rebuilt_json.get(player_id) is None: -2213 rebuilt_json[player_id] = {} -2214 -2215 rebuilt_json[player_id]["game_id"] = game_id -2216 rebuilt_json[player_id][ -2217 "team_name" -2218 ] = team_name -2219 rebuilt_json[player_id][ -2220 "team_conference" -2221 ] = team_conference -2222 rebuilt_json[player_id][ -2223 "player_id" -2224 ] = player_id -2225 rebuilt_json[player_id][ -2226 "player_name" -2227 ] = player_name -2228 rebuilt_json[player_id][ -2229 "home_away" -2230 ] = home_away -2231 rebuilt_json[player_id][ -2232 "passing_AVG" -2233 ] = player_stat -2234 -2235 elif stat["name"] == "TD": # passing_TD -2236 for i in stat["athletes"]: -2237 player_id = int(i["id"]) -2238 player_name = i["name"] -2239 player_stat = int(i["stat"]) -2240 -2241 if rebuilt_json.get(player_id) is None: -2242 rebuilt_json[player_id] = {} -2243 -2244 rebuilt_json[player_id]["game_id"] = game_id -2245 rebuilt_json[player_id][ -2246 "team_name" -2247 ] = team_name -2248 rebuilt_json[player_id][ -2249 "team_conference" -2250 ] = team_conference -2251 rebuilt_json[player_id][ -2252 "player_id" -2253 ] = player_id -2254 rebuilt_json[player_id][ -2255 "player_name" -2256 ] = player_name -2257 rebuilt_json[player_id][ -2258 "home_away" -2259 ] = home_away -2260 rebuilt_json[player_id][ -2261 "passing_TD" -2262 ] = player_stat -2263 -2264 elif stat["name"] == "INT": # passing_INT -2265 for i in stat["athletes"]: -2266 player_id = int(i["id"]) -2267 player_name = i["name"] -2268 player_stat = int(i["stat"]) -2269 -2270 if rebuilt_json.get(player_id) is None: -2271 rebuilt_json[player_id] = {} -2272 -2273 rebuilt_json[player_id]["game_id"] = game_id -2274 rebuilt_json[player_id][ -2275 "team_name" -2276 ] = team_name -2277 rebuilt_json[player_id][ -2278 "team_conference" -2279 ] = team_conference -2280 rebuilt_json[player_id][ -2281 "player_id" -2282 ] = player_id -2283 rebuilt_json[player_id][ -2284 "player_name" -2285 ] = player_name -2286 rebuilt_json[player_id][ -2287 "home_away" -2288 ] = home_away -2289 rebuilt_json[player_id][ -2290 "passing_INT" -2291 ] = player_stat -2292 -2293 elif stat["name"] == "QBR": # passing_QBR -2294 for i in stat["athletes"]: -2295 player_id = int(i["id"]) -2296 player_name = i["name"] -2297 try: -2298 player_stat = float(i["stat"]) -2299 except: # noqa: E722 -2300 player_stat = None -2301 -2302 if rebuilt_json.get(player_id) is None: -2303 rebuilt_json[player_id] = {} -2304 -2305 rebuilt_json[player_id]["game_id"] = game_id -2306 rebuilt_json[player_id][ -2307 "team_name" -2308 ] = team_name -2309 rebuilt_json[player_id][ -2310 "team_conference" -2311 ] = team_conference -2312 rebuilt_json[player_id][ -2313 "player_id" -2314 ] = player_id -2315 rebuilt_json[player_id][ -2316 "player_name" -2317 ] = player_name -2318 rebuilt_json[player_id][ -2319 "home_away" -2320 ] = home_away -2321 rebuilt_json[player_id][ -2322 "passing_QBR" -2323 ] = player_stat -2324 -2325 else: -2326 raise IndexError( -2327 f"Unhandled stat: \t{stat['name']}" -2328 ) -2329 # passing_df = pd.DataFrame(s_category['types']) -2330 elif s_category["name"] == "rushing": -2331 for stat in s_category["types"]: -2332 if stat["name"] == "CAR": # rushing_CAR -2333 for i in stat["athletes"]: -2334 player_id = int(i["id"]) -2335 player_name = i["name"] -2336 player_stat = int(i["stat"]) -2337 -2338 if rebuilt_json.get(player_id) is None: -2339 rebuilt_json[player_id] = {} -2340 -2341 rebuilt_json[player_id]["game_id"] = game_id -2342 rebuilt_json[player_id][ -2343 "team_name" -2344 ] = team_name -2345 rebuilt_json[player_id][ -2346 "team_conference" -2347 ] = team_conference -2348 rebuilt_json[player_id][ -2349 "player_id" -2350 ] = player_id -2351 rebuilt_json[player_id][ -2352 "player_name" -2353 ] = player_name -2354 rebuilt_json[player_id][ -2355 "home_away" -2356 ] = home_away -2357 rebuilt_json[player_id][ -2358 "rushing_CAR" -2359 ] = player_stat -2360 -2361 elif stat["name"] == "YDS": # rushing_YDS -2362 for i in stat["athletes"]: -2363 player_id = int(i["id"]) -2364 player_name = i["name"] -2365 player_stat = int(i["stat"]) -2366 -2367 if rebuilt_json.get(player_id) is None: -2368 rebuilt_json[player_id] = {} -2369 -2370 rebuilt_json[player_id]["game_id"] = game_id -2371 rebuilt_json[player_id][ -2372 "team_name" -2373 ] = team_name -2374 rebuilt_json[player_id][ -2375 "team_conference" -2376 ] = team_conference -2377 rebuilt_json[player_id][ -2378 "player_id" -2379 ] = player_id -2380 rebuilt_json[player_id][ -2381 "player_name" -2382 ] = player_name -2383 rebuilt_json[player_id][ -2384 "home_away" -2385 ] = home_away -2386 rebuilt_json[player_id][ -2387 "rushing_YDS" -2388 ] = player_stat -2389 -2390 elif stat["name"] == "AVG": # rushing_AVG -2391 for i in stat["athletes"]: -2392 player_id = int(i["id"]) -2393 player_name = i["name"] -2394 player_stat = float(i["stat"]) -2395 -2396 if rebuilt_json.get(player_id) is None: -2397 rebuilt_json[player_id] = {} -2398 -2399 rebuilt_json[player_id]["game_id"] = game_id -2400 rebuilt_json[player_id][ -2401 "team_name" -2402 ] = team_name -2403 rebuilt_json[player_id][ -2404 "team_conference" -2405 ] = team_conference -2406 rebuilt_json[player_id][ -2407 "player_id" -2408 ] = player_id -2409 rebuilt_json[player_id][ -2410 "player_name" -2411 ] = player_name -2412 rebuilt_json[player_id][ -2413 "home_away" -2414 ] = home_away -2415 rebuilt_json[player_id][ -2416 "rushing_AVG" -2417 ] = player_stat -2418 -2419 elif stat["name"] == "TD": # rushing_TD -2420 for i in stat["athletes"]: -2421 player_id = int(i["id"]) -2422 player_name = i["name"] -2423 player_stat = int(i["stat"]) -2424 -2425 if rebuilt_json.get(player_id) is None: -2426 rebuilt_json[player_id] = {} -2427 -2428 rebuilt_json[player_id]["game_id"] = game_id -2429 rebuilt_json[player_id][ -2430 "team_name" -2431 ] = team_name -2432 rebuilt_json[player_id][ -2433 "team_conference" -2434 ] = team_conference -2435 rebuilt_json[player_id][ -2436 "player_id" -2437 ] = player_id -2438 rebuilt_json[player_id][ -2439 "player_name" -2440 ] = player_name -2441 rebuilt_json[player_id][ -2442 "home_away" -2443 ] = home_away -2444 rebuilt_json[player_id][ -2445 "rushing_TD" -2446 ] = player_stat +2212 "rushing_CAR": "uint16", +2213 "rushing_YDS": "int16", +2214 "rushing_AVG": "float16", +2215 "rushing_TD": "uint16", +2216 "rushing_LONG": "int16", +2217 +2218 "receiving_REC": "uint16", +2219 "receiving_YDS": "int16", +2220 "receiving_AVG": "float16", +2221 "receiving_TD": "uint16", +2222 "receiving_LONG": "int16", +2223 +2224 "fumbles_FUM": "uint8", +2225 "fumbles_LOST": "uint8", +2226 "fumbles_REC": "uint8", +2227 +2228 "defensive_TOT": "uint16", +2229 "defensive_SOLO": "uint16", +2230 "defensive_TFL": "float16", +2231 "defensive_QB HUR": "uint16", +2232 "defensive_SACKS": "float16", +2233 "defensive_PD": "uint16", +2234 "defensive_TD": "uint8", +2235 +2236 "interceptions_INT": "uint8", +2237 "interceptions_YDS": "int16", +2238 "interceptions_TD": "uint8", +2239 +2240 "punting_NO": "uint16", +2241 "punting_YDS": "int16", +2242 "punting_AVG": "float16", +2243 "punting_TB": "uint8", +2244 "punting_In 20": "uint8", +2245 "punting_LONG": "int8", +2246 +2247 "kicking_FGM": "uint16", +2248 "kicking_FGA": "uint16", +2249 "kicking_PCT": "float16", +2250 "kicking_LONG": "uint8", +2251 "kicking_XPM": "uint16", +2252 "kicking_XPA": "uint16", +2253 "kicking_PTS": "uint16", +2254 +2255 "kickReturns_NO": "uint16", +2256 "kickReturns_YDS": "int16", +2257 "kickReturns_AVG": "float16", +2258 "kickReturns_TD": "uint8", +2259 "kickReturns_LONG": "int8", +2260 +2261 "puntReturns_NO": "uint16", +2262 "puntReturns_YDS": "int16", +2263 "puntReturns_AVG": "float16", +2264 "puntReturns_TD": "uint8", +2265 "puntReturns_LONG": "int8", +2266 } +2267 ) +2268 +2269 if filter_by_stat_category is True and stat_category == "passing": +2270 cfb_games_df = cfb_games_df[[ +2271 "season", +2272 "game_id", +2273 "team_name", +2274 "team_conference", +2275 "player_id", +2276 "player_name", +2277 "home_away", +2278 # PASS +2279 "passing_C/ATT", +2280 "passing_COMP", +2281 "passing_ATT", +2282 "passing_YDS", +2283 "passing_AVG", +2284 "passing_TD", +2285 "passing_INT", +2286 "passing_QBR", +2287 ]] +2288 elif filter_by_stat_category is True and stat_category == "rushing": +2289 cfb_games_df = cfb_games_df[[ +2290 "season", +2291 "game_id", +2292 "team_name", +2293 "team_conference", +2294 "player_id", +2295 "player_name", +2296 "home_away", +2297 # RUSH +2298 "rushing_CAR", +2299 "rushing_YDS", +2300 "rushing_AVG", +2301 "rushing_TD", +2302 "rushing_LONG", +2303 ]] +2304 elif filter_by_stat_category is True and stat_category == "receiving": +2305 cfb_games_df = cfb_games_df[[ +2306 "season", +2307 "game_id", +2308 "team_name", +2309 "team_conference", +2310 "player_id", +2311 "player_name", +2312 "home_away", +2313 # REC +2314 "receiving_REC", +2315 "receiving_YDS", +2316 "receiving_AVG", +2317 "receiving_TD", +2318 "receiving_LONG", +2319 ]] +2320 elif filter_by_stat_category is True and stat_category == "fumbles": +2321 cfb_games_df = cfb_games_df[[ +2322 "season", +2323 "game_id", +2324 "team_name", +2325 "team_conference", +2326 "player_id", +2327 "player_name", +2328 "home_away", +2329 # FUM +2330 "fumbles_FUM", +2331 "fumbles_LOST", +2332 "fumbles_REC", +2333 ]] +2334 elif filter_by_stat_category is True and stat_category == "defensive": +2335 cfb_games_df = cfb_games_df[[ +2336 "season", +2337 "game_id", +2338 "team_name", +2339 "team_conference", +2340 "player_id", +2341 "player_name", +2342 "home_away", +2343 # DEFENSE +2344 "defensive_TOT", +2345 "defensive_SOLO", +2346 "defensive_TFL", +2347 "defensive_QB HUR", +2348 "defensive_SACKS", +2349 "defensive_PD", +2350 "defensive_TD", +2351 ]] +2352 elif filter_by_stat_category is True and stat_category == "interceptions": +2353 cfb_games_df = cfb_games_df[[ +2354 "season", +2355 "game_id", +2356 "team_name", +2357 "team_conference", +2358 "player_id", +2359 "player_name", +2360 "home_away", +2361 # INT +2362 "interceptions_INT", +2363 "interceptions_YDS", +2364 "interceptions_TD", +2365 ]] +2366 elif filter_by_stat_category is True and stat_category == "punting": +2367 cfb_games_df = cfb_games_df[[ +2368 "season", +2369 "game_id", +2370 "team_name", +2371 "team_conference", +2372 "player_id", +2373 "player_name", +2374 "home_away", +2375 # PUNT +2376 "punting_NO", +2377 "punting_YDS", +2378 "punting_AVG", +2379 "punting_TB", +2380 "punting_In 20", +2381 "punting_LONG", +2382 ]] +2383 elif filter_by_stat_category is True and stat_category == "kicking": +2384 cfb_games_df = cfb_games_df[[ +2385 "season", +2386 "game_id", +2387 "team_name", +2388 "team_conference", +2389 "player_id", +2390 "player_name", +2391 "home_away", +2392 # KICK +2393 "kicking_FG", +2394 "kicking_FGM", +2395 "kicking_FGA", +2396 "kicking_PCT", +2397 "kicking_LONG", +2398 "kicking_XP", +2399 "kicking_XPM", +2400 "kicking_XPA", +2401 "kicking_PTS", +2402 ]] +2403 elif filter_by_stat_category is True and stat_category == "kickReturns": +2404 cfb_games_df = cfb_games_df[[ +2405 "season", +2406 "game_id", +2407 "team_name", +2408 "team_conference", +2409 "player_id", +2410 "player_name", +2411 "home_away", +2412 # KR +2413 "kickReturns_NO", +2414 "kickReturns_YDS", +2415 "kickReturns_AVG", +2416 "kickReturns_TD", +2417 "kickReturns_LONG", +2418 ]] +2419 elif filter_by_stat_category is True and stat_category == "puntReturns": +2420 cfb_games_df = cfb_games_df[[ +2421 "season", +2422 "game_id", +2423 "team_name", +2424 "team_conference", +2425 "player_id", +2426 "player_name", +2427 "home_away", +2428 # KR +2429 "puntReturns_NO", +2430 "puntReturns_YDS", +2431 "puntReturns_AVG", +2432 "puntReturns_TD", +2433 "puntReturns_LONG", +2434 ]] +2435 +2436 return cfb_games_df +2437 +2438 +2439def get_cfbd_player_advanced_game_stats( +2440 game_id: int, +2441 api_key: str = None, +2442 api_key_dir: str = None, +2443 return_as_dict: bool = False, +2444): +2445 """ +2446 Retrieves advanced game stats from the CFBD API. 2447 -2448 elif stat["name"] == "LONG": # rushing_LONG -2449 for i in stat["athletes"]: -2450 player_id = int(i["id"]) -2451 player_name = i["name"] -2452 player_stat = int(i["stat"]) +2448 Parameters +2449 ---------- +2450 `game_id` (int, mandatory): +2451 Mandatory requirement. +2452 Specifies the game you want advanced game stats from. 2453 -2454 if rebuilt_json.get(player_id) is None: -2455 rebuilt_json[player_id] = {} -2456 -2457 rebuilt_json[player_id]["game_id"] = game_id -2458 rebuilt_json[player_id][ -2459 "team_name" -2460 ] = team_name -2461 rebuilt_json[player_id][ -2462 "team_conference" -2463 ] = team_conference -2464 rebuilt_json[player_id][ -2465 "player_id" -2466 ] = player_id -2467 rebuilt_json[player_id][ -2468 "player_name" -2469 ] = player_name -2470 rebuilt_json[player_id][ -2471 "home_away" -2472 ] = home_away -2473 rebuilt_json[player_id][ -2474 "rushing_LONG" -2475 ] = player_stat -2476 -2477 else: -2478 raise IndexError( -2479 f"Unhandled stat: \t{stat['name']}" -2480 ) -2481 -2482 elif s_category["name"] == "receiving": -2483 for stat in s_category["types"]: -2484 if stat["name"] == "REC": # receiving_REC -2485 for i in stat["athletes"]: -2486 player_id = int(i["id"]) -2487 player_name = i["name"] -2488 player_stat = int(i["stat"]) -2489 -2490 if rebuilt_json.get(player_id) is None: -2491 rebuilt_json[player_id] = {} -2492 -2493 rebuilt_json[player_id]["game_id"] = game_id -2494 rebuilt_json[player_id][ -2495 "team_name" -2496 ] = team_name -2497 rebuilt_json[player_id][ -2498 "team_conference" -2499 ] = team_conference -2500 rebuilt_json[player_id][ -2501 "player_id" -2502 ] = player_id -2503 rebuilt_json[player_id][ -2504 "player_name" -2505 ] = player_name -2506 rebuilt_json[player_id][ -2507 "home_away" -2508 ] = home_away -2509 rebuilt_json[player_id][ -2510 "receiving_REC" -2511 ] = player_stat -2512 -2513 elif stat["name"] == "YDS": # receiving_YDS -2514 for i in stat["athletes"]: -2515 player_id = int(i["id"]) -2516 player_name = i["name"] -2517 player_stat = int(i["stat"]) -2518 -2519 if rebuilt_json.get(player_id) is None: -2520 rebuilt_json[player_id] = {} -2521 -2522 rebuilt_json[player_id]["game_id"] = game_id -2523 rebuilt_json[player_id][ -2524 "team_name" -2525 ] = team_name -2526 rebuilt_json[player_id][ -2527 "team_conference" -2528 ] = team_conference -2529 rebuilt_json[player_id][ -2530 "player_id" -2531 ] = player_id -2532 rebuilt_json[player_id][ -2533 "player_name" -2534 ] = player_name -2535 rebuilt_json[player_id][ -2536 "home_away" -2537 ] = home_away -2538 rebuilt_json[player_id][ -2539 "receiving_YDS" -2540 ] = player_stat -2541 -2542 elif stat["name"] == "AVG": # receiving_AVG -2543 for i in stat["athletes"]: -2544 player_id = int(i["id"]) -2545 player_name = i["name"] -2546 player_stat = float(i["stat"]) +2454 `api_key` (str, optional): +2455 Semi-optional argument. +2456 If `api_key` is null, this function will attempt to load a CFBD API key +2457 from the python environment, or from a file on this computer. +2458 If `api_key` is not null, +2459 this function will automatically assume that the +2460 inputted `api_key` is a valid CFBD API key. +2461 +2462 `api_key_dir` (str, optional): +2463 Optional argument. +2464 If `api_key` is set to am empty string, this variable is ignored. +2465 If `api_key_dir` is null, and `api_key` is null, +2466 this function will try to find +2467 a CFBD API key file in this user's home directory. +2468 If `api_key_dir` is set to a string, and `api_key` is null, +2469 this function will assume that `api_key_dir` is a directory, +2470 and will try to find a CFBD API key file in that directory. +2471 +2472 `return_as_dict` (bool, semi-optional): +2473 Semi-optional argument. +2474 If you want this function to return +2475 the data as a dictionary (read: JSON object), +2476 instead of a pandas `DataFrame` object, +2477 set `return_as_dict` to `True`. +2478 +2479 Usage +2480 ---------- +2481 ``` +2482 import time +2483 +2484 from cfbd_json_py.games import get_cfbd_player_advanced_game_stats +2485 +2486 +2487 cfbd_key = "tigersAreAwesome" # placeholder for your CFBD API Key. +2488 +2489 if cfbd_key is not "tigersAreAwesome": +2490 print( +2491 "Using the user's API key declared in this script " + +2492 "for this example." +2493 ) +2494 +2495 # Get advanced player stats for a 2019 CFB game +2496 # between the LSU Tigers Football Program, +2497 # and the Oklahoma Sooners Football Program. +2498 print( +2499 "Get advanced player stats for a 2019 CFB game between " + +2500 "the LSU Tigers Football Program, " + +2501 "and the Oklahoma Sooners Football Program." +2502 ) +2503 json_data = get_cfbd_player_advanced_game_stats( +2504 api_key=cfbd_key, +2505 game_id=401135278 +2506 ) +2507 print(json_data) +2508 time.sleep(5) +2509 +2510 +2511 # You can also tell this function to just return the API call as +2512 # a Dictionary (read: JSON) object. +2513 print( +2514 "You can also tell this function to just return the API call " + +2515 "as a Dictionary (read: JSON) object." +2516 ) +2517 json_data = get_cfbd_player_advanced_game_stats( +2518 api_key=cfbd_key, +2519 game_id=401135278, +2520 return_as_dict=True +2521 ) +2522 print(json_data) +2523 +2524 else: +2525 # Alternatively, if the CFBD API key exists in this python environment, +2526 # or it's been set by cfbd_json_py.utls.set_cfbd_api_token(), +2527 # you could just call these functions directly, +2528 # without setting the API key in the script. +2529 print( +2530 "Using the user's API key supposedly loaded " + +2531 "into this python environment for this example." +2532 ) +2533 +2534 # Get advanced player stats for a 2019 CFB game +2535 # between the LSU Tigers Football Program, +2536 # and the Oklahoma Sooners Football Program. +2537 print( +2538 "Get advanced player stats for a 2019 CFB game " + +2539 "between the LSU Tigers Football Program, " + +2540 "and the Oklahoma Sooners Football Program." +2541 ) +2542 json_data = get_cfbd_player_advanced_game_stats( +2543 game_id=401135278 +2544 ) +2545 print(json_data) +2546 time.sleep(5) 2547 -2548 if rebuilt_json.get(player_id) is None: -2549 rebuilt_json[player_id] = {} -2550 -2551 rebuilt_json[player_id]["game_id"] = game_id -2552 rebuilt_json[player_id][ -2553 "team_name" -2554 ] = team_name -2555 rebuilt_json[player_id][ -2556 "team_conference" -2557 ] = team_conference -2558 rebuilt_json[player_id][ -2559 "player_id" -2560 ] = player_id -2561 rebuilt_json[player_id][ -2562 "player_name" -2563 ] = player_name -2564 rebuilt_json[player_id][ -2565 "home_away" -2566 ] = home_away -2567 rebuilt_json[player_id][ -2568 "receiving_AVG" -2569 ] = player_stat -2570 -2571 elif stat["name"] == "TD": # receiving_TD -2572 for i in stat["athletes"]: -2573 player_id = int(i["id"]) -2574 player_name = i["name"] -2575 player_stat = int(i["stat"]) -2576 -2577 if rebuilt_json.get(player_id) is None: -2578 rebuilt_json[player_id] = {} -2579 -2580 rebuilt_json[player_id]["game_id"] = game_id -2581 rebuilt_json[player_id][ -2582 "team_name" -2583 ] = team_name -2584 rebuilt_json[player_id][ -2585 "team_conference" -2586 ] = team_conference -2587 rebuilt_json[player_id][ -2588 "player_id" -2589 ] = player_id -2590 rebuilt_json[player_id][ -2591 "player_name" -2592 ] = player_name -2593 rebuilt_json[player_id][ -2594 "home_away" -2595 ] = home_away -2596 rebuilt_json[player_id][ -2597 "receiving_TD" -2598 ] = player_stat -2599 -2600 elif stat["name"] == "LONG": # receiving_LONG -2601 for i in stat["athletes"]: -2602 player_id = int(i["id"]) -2603 player_name = i["name"] -2604 player_stat = int(i["stat"]) -2605 -2606 if rebuilt_json.get(player_id) is None: -2607 rebuilt_json[player_id] = {} -2608 -2609 rebuilt_json[player_id]["game_id"] = game_id -2610 rebuilt_json[player_id][ -2611 "team_name" -2612 ] = team_name -2613 rebuilt_json[player_id][ -2614 "team_conference" -2615 ] = team_conference -2616 rebuilt_json[player_id][ -2617 "player_id" -2618 ] = player_id -2619 rebuilt_json[player_id][ -2620 "player_name" -2621 ] = player_name -2622 rebuilt_json[player_id][ -2623 "home_away" -2624 ] = home_away -2625 rebuilt_json[player_id][ -2626 "receiving_LONG" -2627 ] = player_stat -2628 -2629 else: -2630 raise IndexError( -2631 f"Unhandled stat: \t{stat['name']}" -2632 ) -2633 -2634 elif s_category["name"] == "fumbles": -2635 for stat in s_category["types"]: -2636 if stat["name"] == "FUM": # fumbles_FUM -2637 for i in stat["athletes"]: -2638 player_id = int(i["id"]) -2639 player_name = i["name"] -2640 player_stat = int(i["stat"]) -2641 -2642 if rebuilt_json.get(player_id) is None: -2643 rebuilt_json[player_id] = {} -2644 -2645 rebuilt_json[player_id]["game_id"] = game_id -2646 rebuilt_json[player_id][ -2647 "team_name" -2648 ] = team_name -2649 rebuilt_json[player_id][ -2650 "team_conference" -2651 ] = team_conference -2652 rebuilt_json[player_id][ -2653 "player_id" -2654 ] = player_id -2655 rebuilt_json[player_id][ -2656 "player_name" -2657 ] = player_name -2658 rebuilt_json[player_id][ -2659 "home_away" -2660 ] = home_away -2661 rebuilt_json[player_id][ -2662 "fumbles_FUM" -2663 ] = player_stat -2664 -2665 elif stat["name"] == "LOST": # fumbles_LOST -2666 for i in stat["athletes"]: -2667 player_id = int(i["id"]) -2668 player_name = i["name"] -2669 player_stat = int(i["stat"]) -2670 -2671 if rebuilt_json.get(player_id) is None: -2672 rebuilt_json[player_id] = {} -2673 -2674 rebuilt_json[player_id]["game_id"] = game_id -2675 rebuilt_json[player_id][ -2676 "team_name" -2677 ] = team_name -2678 rebuilt_json[player_id][ -2679 "team_conference" -2680 ] = team_conference -2681 rebuilt_json[player_id][ -2682 "player_id" -2683 ] = player_id -2684 rebuilt_json[player_id][ -2685 "player_name" -2686 ] = player_name -2687 rebuilt_json[player_id][ -2688 "home_away" -2689 ] = home_away -2690 rebuilt_json[player_id][ -2691 "fumbles_LOST" -2692 ] = player_stat -2693 -2694 elif stat["name"] == "REC": # fumbles_REC -2695 for i in stat["athletes"]: -2696 player_id = int(i["id"]) -2697 player_name = i["name"] -2698 player_stat = int(i["stat"]) -2699 -2700 if rebuilt_json.get(player_id) is None: -2701 rebuilt_json[player_id] = {} -2702 -2703 rebuilt_json[player_id]["game_id"] = game_id -2704 rebuilt_json[player_id][ -2705 "team_name" -2706 ] = team_name -2707 rebuilt_json[player_id][ -2708 "team_conference" -2709 ] = team_conference -2710 rebuilt_json[player_id][ -2711 "player_id" -2712 ] = player_id -2713 rebuilt_json[player_id][ -2714 "player_name" -2715 ] = player_name -2716 rebuilt_json[player_id][ -2717 "home_away" -2718 ] = home_away -2719 rebuilt_json[player_id][ -2720 "fumbles_REC" -2721 ] = player_stat +2548 +2549 # You can also tell this function to just return the API call as +2550 # a Dictionary (read: JSON) object. +2551 print( +2552 "You can also tell this function to just return the API call " + +2553 "as a Dictionary (read: JSON) object." +2554 ) +2555 json_data = get_cfbd_player_advanced_game_stats( +2556 game_id=401135278, +2557 return_as_dict=True +2558 ) +2559 print(json_data) +2560 +2561 ``` +2562 Returns +2563 ---------- +2564 A pandas `DataFrame` object with college football game information, +2565 or (if `return_as_dict` is set to `True`) +2566 a dictionary object with college football game information. +2567 """ +2568 +2569 # now = datetime.now() +2570 usage_df = pd.DataFrame() +2571 ppa_df = pd.DataFrame() +2572 adv_stats_df = pd.DataFrame() +2573 row_df = pd.DataFrame() +2574 url = "https://api.collegefootballdata.com/game/box/advanced" +2575 +2576 ########################################################################## +2577 +2578 if api_key is not None: +2579 real_api_key = api_key +2580 del api_key +2581 else: +2582 real_api_key = get_cfbd_api_token(api_key_dir=api_key_dir) +2583 +2584 if real_api_key == "tigersAreAwesome": +2585 raise ValueError( +2586 "You actually need to change `cfbd_key` to your CFBD API key." +2587 ) +2588 elif "Bearer " in real_api_key: +2589 pass +2590 elif "Bearer" in real_api_key: +2591 real_api_key = real_api_key.replace("Bearer", "Bearer ") +2592 else: +2593 real_api_key = "Bearer " + real_api_key +2594 +2595 # URL builder +2596 ########################################################################## +2597 +2598 # Required by API +2599 url += f"?gameId={game_id}" +2600 +2601 headers = { +2602 "Authorization": f"{real_api_key}", +2603 "accept": "application/json" +2604 } +2605 response = requests.get(url, headers=headers) +2606 +2607 if response.status_code == 200: +2608 pass +2609 elif response.status_code == 401: +2610 raise ConnectionRefusedError( +2611 "Could not connect. The connection was refused." + +2612 "\nHTTP Status Code 401." +2613 ) +2614 else: +2615 raise ConnectionError( +2616 f"Could not connect.\nHTTP Status code {response.status_code}" +2617 ) +2618 +2619 json_data = response.json() +2620 +2621 if return_as_dict is True: +2622 return json_data +2623 +2624 home_team_name = json_data["gameInfo"]["homeTeam"] +2625 home_points = json_data["gameInfo"]["homePoints"] +2626 home_win_prob = json_data["gameInfo"]["homeWinProb"] +2627 away_team_name = json_data["gameInfo"]["awayTeam"] +2628 away_points = json_data["gameInfo"]["awayPoints"] +2629 away_win_prob = json_data["gameInfo"]["awayWinProb"] +2630 home_winner = json_data["gameInfo"]["homeWinner"] +2631 game_excitement_score = json_data["gameInfo"]["excitement"] +2632 +2633 # Parsing Usage +2634 logging.info("Parsing player usage data.") +2635 for player in json_data["players"]["usage"]: +2636 row_df = pd.DataFrame({"game_id": game_id}, index=[0]) +2637 row_df["player_name"] = player["player"] +2638 row_df["team"] = player["team"] +2639 row_df["position"] = player["position"] +2640 +2641 row_df["total_usage"] = player["total"] +2642 row_df["q1_usage"] = player["quarter1"] +2643 row_df["q2_usage"] = player["quarter2"] +2644 row_df["q3_usage"] = player["quarter3"] +2645 row_df["q4_usage"] = player["quarter4"] +2646 row_df["rushing_usage"] = player["rushing"] +2647 row_df["passing_usage"] = player["passing"] +2648 +2649 usage_df = pd.concat([usage_df, row_df], ignore_index=True) +2650 del row_df +2651 +2652 # Parsing PPA +2653 logging.info("Parsing player PPA data.") +2654 for player in json_data["players"]["ppa"]: +2655 row_df = pd.DataFrame({"game_id": game_id}, index=[0]) +2656 row_df["player_name"] = player["player"] +2657 row_df["team"] = player["team"] +2658 row_df["position"] = player["position"] +2659 +2660 row_df["average_ppa_total"] = player["average"]["total"] +2661 row_df["average_ppa_q1"] = player["average"]["quarter1"] +2662 row_df["average_ppa_q2"] = player["average"]["quarter2"] +2663 row_df["average_ppa_q3"] = player["average"]["quarter3"] +2664 row_df["average_ppa_q4"] = player["average"]["quarter4"] +2665 row_df["average_ppa_rushing"] = player["average"]["rushing"] +2666 row_df["average_ppa_passing"] = player["average"]["passing"] +2667 +2668 row_df["cumulative_ppa_total"] = player["cumulative"]["total"] +2669 row_df["cumulative_ppa_q1"] = player["cumulative"]["quarter1"] +2670 row_df["cumulative_ppa_q2"] = player["cumulative"]["quarter2"] +2671 row_df["cumulative_ppa_q3"] = player["cumulative"]["quarter3"] +2672 row_df["cumulative_ppa_q4"] = player["cumulative"]["quarter4"] +2673 row_df["cumulative_ppa_rushing"] = player["cumulative"]["rushing"] +2674 row_df["cumulative_ppa_passing"] = player["cumulative"]["passing"] +2675 +2676 ppa_df = pd.concat([ppa_df, row_df], ignore_index=True) +2677 +2678 # Join `usage_df` and `ppa_df` together +2679 adv_stats_df = pd.merge( +2680 left=usage_df, +2681 right=ppa_df, +2682 how="outer", +2683 on=["game_id", "player_name", "team", "position"], +2684 ) +2685 +2686 # Add in these columns for completeness. +2687 +2688 adv_stats_df.loc[ +2689 adv_stats_df["team"] == home_team_name, "home_away" +2690 ] = "home" +2691 adv_stats_df.loc[adv_stats_df["team"] == home_team_name, "opponent"] = ( +2692 away_team_name +2693 ) +2694 +2695 adv_stats_df.loc[ +2696 adv_stats_df["team"] == away_team_name, "home_away" +2697 ] = "away" +2698 adv_stats_df.loc[adv_stats_df["team"] == away_team_name, "opponent"] = ( +2699 home_team_name +2700 ) +2701 +2702 adv_stats_df["home_team"] = home_team_name +2703 adv_stats_df["away_team"] = away_team_name +2704 +2705 adv_stats_df["home_win_prob"] = home_win_prob +2706 adv_stats_df["away_win_prob"] = away_win_prob +2707 +2708 adv_stats_df["home_points"] = home_points +2709 adv_stats_df["away_points"] = away_points +2710 +2711 adv_stats_df["home_winner"] = home_winner +2712 adv_stats_df["game_excitement_score"] = game_excitement_score +2713 +2714 return adv_stats_df +2715 +2716 +2717############################################################################### +2718# Patreon Only Functions. +2719# No caching, because the entire point of these functions are to get people +2720# data ASAP, and right before kickoff. +2721############################################################################### 2722 -2723 else: -2724 raise IndexError( -2725 f"Unhandled stat: \t{stat['name']}" -2726 ) -2727 -2728 elif s_category["name"] == "defensive": -2729 for stat in s_category["types"]: -2730 if stat["name"] == "TOT": # defensive_TOT -2731 for i in stat["athletes"]: -2732 player_id = int(i["id"]) -2733 player_name = i["name"] -2734 player_stat = int(i["stat"]) -2735 -2736 if rebuilt_json.get(player_id) is None: -2737 rebuilt_json[player_id] = {} -2738 -2739 rebuilt_json[player_id]["game_id"] = game_id -2740 rebuilt_json[player_id][ -2741 "team_name" -2742 ] = team_name -2743 rebuilt_json[player_id][ -2744 "team_conference" -2745 ] = team_conference -2746 rebuilt_json[player_id][ -2747 "player_id" -2748 ] = player_id -2749 rebuilt_json[player_id][ -2750 "player_name" -2751 ] = player_name -2752 rebuilt_json[player_id][ -2753 "home_away" -2754 ] = home_away -2755 rebuilt_json[player_id][ -2756 "defensive_TOT" -2757 ] = player_stat -2758 -2759 elif stat["name"] == "SOLO": # defensive_SOLO -2760 for i in stat["athletes"]: -2761 player_id = int(i["id"]) -2762 player_name = i["name"] -2763 player_stat = int(i["stat"]) -2764 -2765 if rebuilt_json.get(player_id) is None: -2766 rebuilt_json[player_id] = {} -2767 -2768 rebuilt_json[player_id]["game_id"] = game_id -2769 rebuilt_json[player_id][ -2770 "team_name" -2771 ] = team_name -2772 rebuilt_json[player_id][ -2773 "team_conference" -2774 ] = team_conference -2775 rebuilt_json[player_id][ -2776 "player_id" -2777 ] = player_id -2778 rebuilt_json[player_id][ -2779 "player_name" -2780 ] = player_name -2781 rebuilt_json[player_id][ -2782 "home_away" -2783 ] = home_away -2784 rebuilt_json[player_id][ -2785 "defensive_SOLO" -2786 ] = player_stat -2787 -2788 elif stat["name"] == "TFL": # defensive_TFL -2789 for i in stat["athletes"]: -2790 player_id = int(i["id"]) -2791 player_name = i["name"] -2792 player_stat = float(i["stat"]) +2723 +2724def get_cfbd_live_scoreboard( +2725 ncaa_division: str = "fbs", +2726 conference: str = None, +2727 api_key: str = None, +2728 api_key_dir: str = None, +2729 return_as_dict: bool = False, +2730): +2731 """ +2732 YOU MUST BE SUBSCRIBED TO THE CFBD PATREON FOR THIS FUNCTION TO WORK! +2733 To view the CFBD Patreon, visit https://www.patreon.com/collegefootballdata +2734 +2735 Retrieves live scoreboard data from the CFBD API, +2736 assuming the API key is an API key from a Patreon supporter. +2737 +2738 Parameters +2739 ---------- +2740 `ncaa_division` (str, semi-optional): +2741 Semi-optional argument. +2742 By default, `ncaa_division` will be set to "fbs", +2743 short for the Football Bowl Subdivision (FBS), +2744 formerly known as D1-A (read as "division one single A"), +2745 the highest level in the NCAA football pyramid, +2746 where teams can scholarship up to 85 players +2747 on their football team solely for athletic ability, +2748 and often have the largest athletics budgets +2749 within the NCAA. +2750 +2751 Other valid inputs are: +2752 - "fcs": Football Championship Subdivision (FCS), +2753 formerly known as D1-AA (read as "division one double A"). +2754 An FCS school is still in the 1st division of the NCAA, +2755 making them eligible for the March Madness tournament, +2756 but may not have the resources to compete at the FBS level +2757 at this time. FCS schools are limited to 63 athletic scholarships +2758 for football. +2759 - "ii": NCAA Division II. Schools in this and D3 are not +2760 eligible for the March Madness tournament, +2761 and are limited to 36 athletic scholarships +2762 for their football team. +2763 - "iii": NCAA Division III. The largest single division within the +2764 NCAA football pyramid. +2765 D3 schools have the distinction of being part of +2766 the only NCAA division that cannot give out scholarships solely +2767 for athletic ability. +2768 +2769 `conference` (str, optional): +2770 Optional argument. +2771 If you only want live scoreboard data from games +2772 involving teams a specific conference, +2773 set `conference` to the abbreviation +2774 of the conference you want live scoreboard data from. +2775 +2776 `api_key` (str, optional): +2777 Semi-optional argument. +2778 If `api_key` is null, this function will attempt to load a CFBD API key +2779 from the python environment, or from a file on this computer. +2780 If `api_key` is not null, +2781 this function will automatically assume that the +2782 inputted `api_key` is a valid CFBD API key. +2783 +2784 `api_key_dir` (str, optional): +2785 Optional argument. +2786 If `api_key` is set to am empty string, this variable is ignored. +2787 If `api_key_dir` is null, and `api_key` is null, +2788 this function will try to find +2789 a CFBD API key file in this user's home directory. +2790 If `api_key_dir` is set to a string, and `api_key` is null, +2791 this function will assume that `api_key_dir` is a directory, +2792 and will try to find a CFBD API key file in that directory. 2793 -2794 if rebuilt_json.get(player_id) is None: -2795 rebuilt_json[player_id] = {} -2796 -2797 rebuilt_json[player_id]["game_id"] = game_id -2798 rebuilt_json[player_id][ -2799 "team_name" -2800 ] = team_name -2801 rebuilt_json[player_id][ -2802 "team_conference" -2803 ] = team_conference -2804 rebuilt_json[player_id][ -2805 "player_id" -2806 ] = player_id -2807 rebuilt_json[player_id][ -2808 "player_name" -2809 ] = player_name -2810 rebuilt_json[player_id][ -2811 "home_away" -2812 ] = home_away -2813 rebuilt_json[player_id][ -2814 "defensive_TFL" -2815 ] = player_stat -2816 -2817 elif stat["name"] == "QB HUR": # defensive_QB HUR -2818 for i in stat["athletes"]: -2819 player_id = int(i["id"]) -2820 player_name = i["name"] -2821 player_stat = int(i["stat"]) -2822 -2823 if rebuilt_json.get(player_id) is None: -2824 rebuilt_json[player_id] = {} +2794 `return_as_dict` (bool, semi-optional): +2795 Semi-optional argument. +2796 If you want this function to return +2797 the data as a dictionary (read: JSON object), +2798 instead of a pandas `DataFrame` object, +2799 set `return_as_dict` to `True`. +2800 Usage +2801 ---------- +2802 ``` +2803 import time +2804 +2805 from cfbd_json_py.games import get_cfbd_live_scoreboard +2806 +2807 +2808 cfbd_key = "tigersAreAwesome" # placeholder for your CFBD API Key. +2809 +2810 if cfbd_key != "tigersAreAwesome": +2811 print( +2812 "Using the user's API key declared " + +2813 "in this script for this example." +2814 ) +2815 +2816 # Get live scoreboard data from the CFBD API. +2817 print( +2818 "Get live scoreboard data from the CFBD API." +2819 ) +2820 json_data = get_cfbd_live_scoreboard( +2821 api_key=cfbd_key +2822 ) +2823 print(json_data) +2824 time.sleep(5) 2825 -2826 rebuilt_json[player_id]["game_id"] = game_id -2827 rebuilt_json[player_id][ -2828 "team_name" -2829 ] = team_name -2830 rebuilt_json[player_id][ -2831 "team_conference" -2832 ] = team_conference -2833 rebuilt_json[player_id][ -2834 "player_id" -2835 ] = player_id -2836 rebuilt_json[player_id][ -2837 "player_name" -2838 ] = player_name -2839 rebuilt_json[player_id][ -2840 "home_away" -2841 ] = home_away -2842 rebuilt_json[player_id][ -2843 "defensive_QB HUR" -2844 ] = player_stat -2845 -2846 elif stat["name"] == "SACKS": # defensive_SACKS -2847 for i in stat["athletes"]: -2848 player_id = int(i["id"]) -2849 player_name = i["name"] -2850 player_stat = float(i["stat"]) +2826 # Get live scoreboard data from the CFBD API, +2827 # but only from the FCS ranks. +2828 print( +2829 "Get live scoreboard data from the CFBD API, " + +2830 "but only from the FCS ranks." +2831 ) +2832 json_data = get_cfbd_live_scoreboard( +2833 ncaa_division="fcs", +2834 api_key=cfbd_key +2835 ) +2836 print(json_data) +2837 time.sleep(5) +2838 +2839 # Get live scoreboard data from the CFBD API, +2840 # but only from the Atlantic Coast Conference. +2841 print( +2842 "Get live scoreboard data from the CFBD API, " + +2843 "but only from the Atlantic Coast Conference." +2844 ) +2845 json_data = get_cfbd_live_scoreboard( +2846 conference="ACC", +2847 api_key=cfbd_key +2848 ) +2849 print(json_data) +2850 time.sleep(5) 2851 -2852 if rebuilt_json.get(player_id) is None: -2853 rebuilt_json[player_id] = {} -2854 -2855 rebuilt_json[player_id]["game_id"] = game_id -2856 rebuilt_json[player_id][ -2857 "team_name" -2858 ] = team_name -2859 rebuilt_json[player_id][ -2860 "team_conference" -2861 ] = team_conference -2862 rebuilt_json[player_id][ -2863 "player_id" -2864 ] = player_id -2865 rebuilt_json[player_id][ -2866 "player_name" -2867 ] = player_name -2868 rebuilt_json[player_id][ -2869 "home_away" -2870 ] = home_away -2871 rebuilt_json[player_id][ -2872 "defensive_SACKS" -2873 ] = player_stat -2874 -2875 elif stat["name"] == "PD": # defensive_PD -2876 for i in stat["athletes"]: -2877 player_id = int(i["id"]) -2878 player_name = i["name"] -2879 player_stat = int(i["stat"]) -2880 -2881 if rebuilt_json.get(player_id) is None: -2882 rebuilt_json[player_id] = {} -2883 -2884 rebuilt_json[player_id]["game_id"] = game_id -2885 rebuilt_json[player_id][ -2886 "team_name" -2887 ] = team_name -2888 rebuilt_json[player_id][ -2889 "team_conference" -2890 ] = team_conference -2891 rebuilt_json[player_id][ -2892 "player_id" -2893 ] = player_id -2894 rebuilt_json[player_id][ -2895 "player_name" -2896 ] = player_name -2897 rebuilt_json[player_id][ -2898 "home_away" -2899 ] = home_away -2900 rebuilt_json[player_id][ -2901 "defensive_PD" -2902 ] = player_stat -2903 -2904 elif stat["name"] == "TD": # defensive_TD -2905 for i in stat["athletes"]: -2906 player_id = int(i["id"]) -2907 player_name = i["name"] -2908 player_stat = int(i["stat"]) -2909 -2910 if rebuilt_json.get(player_id) is None: -2911 rebuilt_json[player_id] = {} -2912 -2913 rebuilt_json[player_id]["game_id"] = game_id -2914 rebuilt_json[player_id][ -2915 "team_name" -2916 ] = team_name -2917 rebuilt_json[player_id][ -2918 "team_conference" -2919 ] = team_conference -2920 rebuilt_json[player_id][ -2921 "player_id" -2922 ] = player_id -2923 rebuilt_json[player_id][ -2924 "player_name" -2925 ] = player_name -2926 rebuilt_json[player_id][ -2927 "home_away" -2928 ] = home_away -2929 rebuilt_json[player_id][ -2930 "defensive_TD" -2931 ] = player_stat -2932 -2933 else: -2934 raise IndexError( -2935 f"Unhandled stat: \t{stat['name']}" -2936 ) -2937 -2938 elif s_category["name"] == "interceptions": -2939 for stat in s_category["types"]: -2940 if stat["name"] == "INT": # interceptions_INT -2941 for i in stat["athletes"]: -2942 player_id = int(i["id"]) -2943 player_name = i["name"] -2944 player_stat = int(i["stat"]) -2945 -2946 if rebuilt_json.get(player_id) is None: -2947 rebuilt_json[player_id] = {} -2948 -2949 rebuilt_json[player_id]["game_id"] = game_id -2950 rebuilt_json[player_id][ -2951 "team_name" -2952 ] = team_name -2953 rebuilt_json[player_id][ -2954 "team_conference" -2955 ] = team_conference -2956 rebuilt_json[player_id][ -2957 "player_id" -2958 ] = player_id -2959 rebuilt_json[player_id][ -2960 "player_name" -2961 ] = player_name -2962 rebuilt_json[player_id][ -2963 "home_away" -2964 ] = home_away -2965 rebuilt_json[player_id][ -2966 "interceptions_INT" -2967 ] = player_stat -2968 -2969 elif stat["name"] == "YDS": # interceptions_YDS -2970 for i in stat["athletes"]: -2971 player_id = int(i["id"]) -2972 player_name = i["name"] -2973 player_stat = int(i["stat"]) -2974 -2975 if rebuilt_json.get(player_id) is None: -2976 rebuilt_json[player_id] = {} -2977 -2978 rebuilt_json[player_id]["game_id"] = game_id -2979 rebuilt_json[player_id][ -2980 "team_name" -2981 ] = team_name -2982 rebuilt_json[player_id][ -2983 "team_conference" -2984 ] = team_conference -2985 rebuilt_json[player_id][ -2986 "player_id" -2987 ] = player_id -2988 rebuilt_json[player_id][ -2989 "player_name" -2990 ] = player_name -2991 rebuilt_json[player_id][ -2992 "home_away" -2993 ] = home_away -2994 rebuilt_json[player_id][ -2995 "interceptions_YDS" -2996 ] = player_stat -2997 -2998 elif stat["name"] == "TD": # interceptions_TD -2999 for i in stat["athletes"]: -3000 player_id = int(i["id"]) -3001 player_name = i["name"] -3002 player_stat = int(i["stat"]) -3003 -3004 if rebuilt_json.get(player_id) is None: -3005 rebuilt_json[player_id] = {} -3006 -3007 rebuilt_json[player_id]["game_id"] = game_id -3008 rebuilt_json[player_id][ -3009 "team_name" -3010 ] = team_name -3011 rebuilt_json[player_id][ -3012 "team_conference" -3013 ] = team_conference -3014 rebuilt_json[player_id][ -3015 "player_id" -3016 ] = player_id -3017 rebuilt_json[player_id][ -3018 "player_name" -3019 ] = player_name -3020 rebuilt_json[player_id][ -3021 "home_away" -3022 ] = home_away -3023 rebuilt_json[player_id][ -3024 "interceptions_TD" -3025 ] = player_stat -3026 -3027 else: -3028 raise IndexError( -3029 f"Unhandled stat: \t{stat['name']}" -3030 ) -3031 -3032 elif s_category["name"] == "punting": -3033 for stat in s_category["types"]: -3034 if stat["name"] == "NO": # punting_NO -3035 for i in stat["athletes"]: -3036 player_id = int(i["id"]) -3037 player_name = i["name"] -3038 player_stat = int(i["stat"]) -3039 -3040 if rebuilt_json.get(player_id) is None: -3041 rebuilt_json[player_id] = {} -3042 -3043 rebuilt_json[player_id]["game_id"] = game_id -3044 rebuilt_json[player_id][ -3045 "team_name" -3046 ] = team_name -3047 rebuilt_json[player_id][ -3048 "team_conference" -3049 ] = team_conference -3050 rebuilt_json[player_id][ -3051 "player_id" -3052 ] = player_id -3053 rebuilt_json[player_id][ -3054 "player_name" -3055 ] = player_name -3056 rebuilt_json[player_id][ -3057 "home_away" -3058 ] = home_away -3059 rebuilt_json[player_id][ -3060 "punting_NO" -3061 ] = player_stat -3062 -3063 elif stat["name"] == "YDS": # punting_YDS -3064 for i in stat["athletes"]: -3065 player_id = int(i["id"]) -3066 player_name = i["name"] -3067 player_stat = int(i["stat"]) -3068 -3069 if rebuilt_json.get(player_id) is None: -3070 rebuilt_json[player_id] = {} +2852 # You can also tell this function to just return the API call as +2853 # a Dictionary (read: JSON) object. +2854 print( +2855 "You can also tell this function to just return the API call " + +2856 "as a Dictionary (read: JSON) object." +2857 ) +2858 json_data = get_cfbd_live_scoreboard( +2859 api_key=cfbd_key, +2860 return_as_dict=True +2861 ) +2862 print(json_data) +2863 +2864 else: +2865 # Alternatively, if the CFBD API key exists in this python environment, +2866 # or it's been set by cfbd_json_py.utls.set_cfbd_api_token(), +2867 # you could just call these functions directly, +2868 # without setting the API key in the script. +2869 print( +2870 "Using the user's API key supposedly loaded " + +2871 "into this python environment for this example." +2872 ) +2873 +2874 # Get live scoreboard data from the CFBD API. +2875 print( +2876 "Get live scoreboard data from the CFBD API." +2877 ) +2878 json_data = get_cfbd_live_scoreboard() +2879 print(json_data) +2880 time.sleep(5) +2881 +2882 # Get live scoreboard data from the CFBD API, +2883 # but only from the FCS ranks. +2884 print( +2885 "Get live scoreboard data from the CFBD API, " + +2886 "but only from the FCS ranks." +2887 ) +2888 json_data = get_cfbd_live_scoreboard( +2889 ncaa_division="fcs", +2890 ) +2891 print(json_data) +2892 time.sleep(5) +2893 +2894 # Get live scoreboard data from the CFBD API, +2895 # but only from the Atlantic Coast Conference. +2896 print( +2897 "Get live scoreboard data from the CFBD API, " + +2898 "but only from the Atlantic Coast Conference." +2899 ) +2900 json_data = get_cfbd_live_scoreboard( +2901 conference="ACC", +2902 ) +2903 print(json_data) +2904 time.sleep(5) +2905 +2906 # You can also tell this function to just return the API call as +2907 # a Dictionary (read: JSON) object. +2908 print( +2909 "You can also tell this function to just return the API call " + +2910 "as a Dictionary (read: JSON) object." +2911 ) +2912 json_data = get_cfbd_live_scoreboard( +2913 return_as_dict=True +2914 ) +2915 print(json_data) +2916 +2917 ``` +2918 +2919 Returns +2920 ---------- +2921 A pandas `DataFrame` object with live scoreboard data, +2922 or (if `return_as_dict` is set to `True`) +2923 a dictionary object with live scoreboard data. +2924 +2925 """ +2926 # real_api_key = "" +2927 scoreboard_df = pd.DataFrame() +2928 url = "https://api.collegefootballdata.com/scoreboard" +2929 +2930 if api_key is not None: +2931 real_api_key = api_key +2932 del api_key +2933 else: +2934 real_api_key = get_cfbd_api_token(api_key_dir=api_key_dir) +2935 +2936 if real_api_key == "tigersAreAwesome": +2937 raise ValueError( +2938 "You actually need to change `cfbd_key` to your CFBD API key." +2939 ) +2940 elif "Bearer " in real_api_key: +2941 pass +2942 elif "Bearer" in real_api_key: +2943 real_api_key = real_api_key.replace("Bearer", "Bearer ") +2944 else: +2945 real_api_key = "Bearer " + real_api_key +2946 +2947 if ( +2948 ncaa_division.lower() == "fbs" +2949 or ncaa_division.lower() == "fcs" +2950 or ncaa_division.lower() == "ii" +2951 or ncaa_division.lower() == "iii" +2952 ): +2953 pass +2954 else: +2955 raise ValueError( +2956 "An invalid NCAA Division was inputted when calling this function." +2957 + '\nValid inputs are:\n-"fbs"\n-"fcs"\n-"ii"\n-"iii"' +2958 + f"\n\nYou entered:\n{ncaa_division}" +2959 ) +2960 +2961 url += f"?classification={ncaa_division}" +2962 +2963 if conference is not None and len(conference) > 0: +2964 url += f"&conference={conference}" +2965 +2966 headers = { +2967 "Authorization": f"{real_api_key}", +2968 "accept": "application/json" +2969 } +2970 +2971 response = requests.get(url, headers=headers) +2972 +2973 if response.status_code == 200: +2974 pass +2975 elif response.status_code == 401: +2976 raise ConnectionRefusedError( +2977 "Could not connect. The connection was refused.\n" + +2978 "HTTP Status Code 401." +2979 ) +2980 else: +2981 raise ConnectionError( +2982 f"Could not connect.\nHTTP Status code {response.status_code}" +2983 ) +2984 +2985 json_data = response.json() +2986 +2987 if return_as_dict is True: +2988 return json_data +2989 +2990 scoreboard_df = pd.json_normalize(json_data) +2991 +2992 if len(scoreboard_df) > 0: +2993 scoreboard_df.rename( +2994 columns={ +2995 "id": "game_id", +2996 "startDate": "start_datetime", +2997 "startTimeTBD": "is_start_time_tbd", +2998 "tv": "tv_network", +2999 "neutralSite": "is_neutral_site_game", +3000 "conferenceGame": "is_conference_game", +3001 "venue.name": "stadium_name", +3002 "venue.city": "stadium_city", +3003 "venue.state": "stadium_state", +3004 "homeTeam.id": "home_team_id", +3005 "homeTeam.name": "home_team_name", +3006 "homeTeam.conference": "home_team_conference", +3007 "awayTeam.id": "away_team_id", +3008 "awayTeam.name": "away_team_name", +3009 "awayTeam.conference": "away_team_conference", +3010 "weather.temperature": "weather_temperature", +3011 "weather.description": "weather_description", +3012 "weather.windSpeed": "weather_wind_speed", +3013 "weather.windDirection": "weather_wind_direction", +3014 "betting.spread": "betting_spread", +3015 "betting.overUnder": "betting_over_under", +3016 "betting.homeMoneyline": "betting_home_moneyline", +3017 "betting.awayMoneyline": "betting_away_moneyline", +3018 }, +3019 inplace=True, +3020 ) +3021 +3022 return scoreboard_df +3023 +3024 +3025def get_cfbd_weather_info( +3026 # game_id: int = None, +3027 season: int = None, +3028 # `game_id` and/or `season` must be not null for this function to work. +3029 week: int = None, +3030 season_type: str = "both", # "regular", "postseason", or "both" +3031 conference: str = None, +3032 team_name: str = None, +3033 ncaa_division: str = "fbs", +3034 api_key: str = None, +3035 api_key_dir: str = None, +3036 return_as_dict: bool = False, +3037): +3038 """ +3039 YOU MUST BE SUBSCRIBED TO THE CFBD PATREON FOR THIS FUNCTION TO WORK! +3040 To view the CFBD Patreon, visit https://www.patreon.com/collegefootballdata +3041 +3042 Parameters +3043 ---------- +3044 Retrieves live scoreboard data from the CFBD API, +3045 assuming the API key is an API key from a Patreon supporter. +3046 +3047 Parameters +3048 ---------- +3049 +3050 `game_id` (int, mandatory): +3051 DEPRECATED FROM V1. +3052 Specifies the game you want weather data from. +3053 This or `season` must be set to a valid non-null value. +3054 +3055 `season` (int, mandatory): +3056 Mandatory requirement. +3057 Specifies the season you want weather data from. +3058 This or `season` must be set to a valid non-null value. +3059 +3060 `week` (int, optional): +3061 Optional argument. +3062 If `week` is set to an integer, this function will attempt +3063 to load weather data from games in that season, and in that week. +3064 +3065 `season_type` (str, semi-optional): +3066 Semi-optional argument. +3067 By default, this will be set to "both", for the CFB regular season. +3068 If you want postseason betting data, set `season_type` to "postseason". +3069 If `season_type` is set to anything but "regular" or "postseason", +3070 a `ValueError()` will be raised. 3071 -3072 rebuilt_json[player_id]["game_id"] = game_id -3073 rebuilt_json[player_id][ -3074 "team_name" -3075 ] = team_name -3076 rebuilt_json[player_id][ -3077 "team_conference" -3078 ] = team_conference -3079 rebuilt_json[player_id][ -3080 "player_id" -3081 ] = player_id -3082 rebuilt_json[player_id][ -3083 "player_name" -3084 ] = player_name -3085 rebuilt_json[player_id][ -3086 "home_away" -3087 ] = home_away -3088 rebuilt_json[player_id][ -3089 "punting_YDS" -3090 ] = player_stat -3091 -3092 elif stat["name"] == "AVG": # punting_AVG -3093 for i in stat["athletes"]: -3094 player_id = int(i["id"]) -3095 player_name = i["name"] -3096 player_stat = float(i["stat"]) -3097 -3098 if rebuilt_json.get(player_id) is None: -3099 rebuilt_json[player_id] = {} -3100 -3101 rebuilt_json[player_id]["game_id"] = game_id -3102 rebuilt_json[player_id][ -3103 "team_name" -3104 ] = team_name -3105 rebuilt_json[player_id][ -3106 "team_conference" -3107 ] = team_conference -3108 rebuilt_json[player_id][ -3109 "player_id" -3110 ] = player_id -3111 rebuilt_json[player_id][ -3112 "player_name" -3113 ] = player_name -3114 rebuilt_json[player_id][ -3115 "home_away" -3116 ] = home_away -3117 rebuilt_json[player_id][ -3118 "punting_AVG" -3119 ] = player_stat -3120 -3121 elif stat["name"] == "TB": # punting_TB -3122 for i in stat["athletes"]: -3123 player_id = int(i["id"]) -3124 player_name = i["name"] -3125 player_stat = int(i["stat"]) -3126 -3127 if rebuilt_json.get(player_id) is None: -3128 rebuilt_json[player_id] = {} -3129 -3130 rebuilt_json[player_id]["game_id"] = game_id -3131 rebuilt_json[player_id][ -3132 "team_name" -3133 ] = team_name -3134 rebuilt_json[player_id][ -3135 "team_conference" -3136 ] = team_conference -3137 rebuilt_json[player_id][ -3138 "player_id" -3139 ] = player_id -3140 rebuilt_json[player_id][ -3141 "player_name" -3142 ] = player_name -3143 rebuilt_json[player_id][ -3144 "home_away" -3145 ] = home_away -3146 rebuilt_json[player_id][ -3147 "punting_TB" -3148 ] = player_stat -3149 -3150 elif stat["name"] == "In 20": # punting_In 20 -3151 for i in stat["athletes"]: -3152 player_id = int(i["id"]) -3153 player_name = i["name"] -3154 player_stat = int(i["stat"]) -3155 -3156 if rebuilt_json.get(player_id) is None: -3157 rebuilt_json[player_id] = {} -3158 -3159 rebuilt_json[player_id]["game_id"] = game_id -3160 rebuilt_json[player_id][ -3161 "team_name" -3162 ] = team_name -3163 rebuilt_json[player_id][ -3164 "team_conference" -3165 ] = team_conference -3166 rebuilt_json[player_id][ -3167 "player_id" -3168 ] = player_id -3169 rebuilt_json[player_id][ -3170 "player_name" -3171 ] = player_name -3172 rebuilt_json[player_id][ -3173 "home_away" -3174 ] = home_away -3175 rebuilt_json[player_id][ -3176 "punting_In 20" -3177 ] = player_stat -3178 -3179 elif stat["name"] == "LONG": # punting_LONG -3180 for i in stat["athletes"]: -3181 player_id = int(i["id"]) -3182 player_name = i["name"] -3183 player_stat = int(i["stat"]) -3184 -3185 if rebuilt_json.get(player_id) is None: -3186 rebuilt_json[player_id] = {} -3187 -3188 rebuilt_json[player_id]["game_id"] = game_id -3189 rebuilt_json[player_id][ -3190 "team_name" -3191 ] = team_name -3192 rebuilt_json[player_id][ -3193 "team_conference" -3194 ] = team_conference -3195 rebuilt_json[player_id][ -3196 "player_id" -3197 ] = player_id -3198 rebuilt_json[player_id][ -3199 "player_name" -3200 ] = player_name -3201 rebuilt_json[player_id][ -3202 "home_away" -3203 ] = home_away -3204 rebuilt_json[player_id][ -3205 "punting_LONG" -3206 ] = player_stat -3207 -3208 else: -3209 raise IndexError( -3210 f"Unhandled stat: \t{stat['name']}" -3211 ) +3072 `conference` (str, optional): +3073 Optional argument. +3074 If you only want weather data from games +3075 involving teams a specific conference, +3076 set `conference` to the abbreviation +3077 of the conference you want weather data from. +3078 +3079 `team_name` (str, optional): +3080 Optional argument. +3081 If you only want weather data for a team, +3082 regardless if they are the home/away team, +3083 set `team` to the name of the team +3084 you want weather data from. +3085 +3086 `ncaa_division` (str, semi-optional): +3087 Semi-optional argument. +3088 By default, `ncaa_division` will be set to "fbs", +3089 short for the Football Bowl Subdivision (FBS), +3090 formerly known as D1-A (read as "division one single A"), +3091 the highest level in the NCAA football pyramid, +3092 where teams can scholarship up to 85 players +3093 on their football team solely for athletic ability, +3094 and often have the largest athletics budgets +3095 within the NCAA. +3096 +3097 Other valid inputs are: +3098 - "fcs": Football Championship Subdivision (FCS), +3099 formerly known as D1-AA (read as "division one double A"). +3100 An FCS school is still in the 1st division of the NCAA, +3101 making them eligible for the March Madness tournament, +3102 but may not have the resources to compete at the FBS level +3103 at this time. FCS schools are limited to 63 athletic scholarships +3104 for football. +3105 - "ii": NCAA Division II. Schools in this and D3 are not +3106 eligible for the March Madness tournament, +3107 and are limited to 36 athletic scholarships +3108 for their football team. +3109 - "iii": NCAA Division III. The largest single division within the +3110 NCAA football pyramid. +3111 D3 schools have the distinction of being part of +3112 the only NCAA division that cannot give out scholarships solely +3113 for athletic ability. +3114 +3115 `api_key` (str, optional): +3116 Semi-optional argument. +3117 If `api_key` is null, this function will attempt to load a CFBD API key +3118 from the python environment, or from a file on this computer. +3119 If `api_key` is not null, +3120 this function will automatically assume that the +3121 inputted `api_key` is a valid CFBD API key. +3122 +3123 `api_key_dir` (str, optional): +3124 Optional argument. +3125 If `api_key` is set to am empty string, this variable is ignored. +3126 If `api_key_dir` is null, and `api_key` is null, +3127 this function will try to find +3128 a CFBD API key file in this user's home directory. +3129 If `api_key_dir` is set to a string, and `api_key` is null, +3130 this function will assume that `api_key_dir` is a directory, +3131 and will try to find a CFBD API key file in that directory. +3132 +3133 `return_as_dict` (bool, semi-optional): +3134 Semi-optional argument. +3135 If you want this function to return +3136 the data as a dictionary (read: JSON object), +3137 instead of a pandas `DataFrame` object, +3138 set `return_as_dict` to `True`. +3139 Usage +3140 ---------- +3141 ``` +3142 import time +3143 +3144 from cfbd_json_py.games import get_cfbd_weather_info +3145 +3146 +3147 cfbd_key = "tigersAreAwesome" # placeholder for your CFBD API Key. +3148 +3149 if cfbd_key != "tigersAreAwesome": +3150 print( +3151 "Using the user's API key declared " + +3152 "in this script for this example." +3153 ) +3154 +3155 # Get weather data for the 2024 CFB season +3156 print( +3157 "Get weather data for the 2024 CFB season." +3158 ) +3159 json_data = get_cfbd_weather_info( +3160 season=2024, +3161 api_key=cfbd_key +3162 ) +3163 print(json_data) +3164 time.sleep(5) +3165 +3166 # Get weather data for the 2024 Rose Bowl (game ID #401551786). +3167 print( +3168 "Get weather data for the 2024 Rose Bowl (game ID #401551786)." +3169 ) +3170 json_data = get_cfbd_weather_info( +3171 game_id=401551786, +3172 api_key=cfbd_key +3173 ) +3174 print(json_data) +3175 time.sleep(5) +3176 +3177 # Get weather data for week 1 of the 2024 CFB season +3178 print( +3179 "Get weather data for week 1 of the 2024 CFB season." +3180 ) +3181 json_data = get_cfbd_weather_info( +3182 season=2024, +3183 week=1, +3184 api_key=cfbd_key +3185 ) +3186 print(json_data) +3187 time.sleep(5) +3188 +3189 # Get weather data for postseason games of the 2023 CFB season. +3190 print( +3191 "Get weather data for postseason games of the 2023 CFB season." +3192 ) +3193 json_data = get_cfbd_weather_info( +3194 season=2023, +3195 season_type="postseason", +3196 api_key=cfbd_key +3197 ) +3198 print(json_data) +3199 time.sleep(5) +3200 +3201 # Get weather data for postseason games of the 2023 CFB season. +3202 print( +3203 "Get weather data for postseason games of the 2023 CFB season." +3204 ) +3205 json_data = get_cfbd_weather_info( +3206 season=2023, +3207 season_type="postseason", +3208 api_key=cfbd_key +3209 ) +3210 print(json_data) +3211 time.sleep(5) 3212 -3213 elif s_category["name"] == "kicking": -3214 for stat in s_category["types"]: -3215 if stat["name"] == "FG": # kicking_FG -3216 for i in stat["athletes"]: -3217 player_id = int(i["id"]) -3218 player_name = i["name"] -3219 player_stat = i["stat"] -3220 -3221 if rebuilt_json.get(player_id) is None: -3222 rebuilt_json[player_id] = {} -3223 -3224 rebuilt_json[player_id]["game_id"] = game_id -3225 rebuilt_json[player_id][ -3226 "team_name" -3227 ] = team_name -3228 rebuilt_json[player_id][ -3229 "team_conference" -3230 ] = team_conference -3231 rebuilt_json[player_id][ -3232 "player_id" -3233 ] = player_id -3234 rebuilt_json[player_id][ -3235 "player_name" -3236 ] = player_name -3237 rebuilt_json[player_id][ -3238 "home_away" -3239 ] = home_away -3240 rebuilt_json[player_id][ -3241 "kicking_FG" -3242 ] = player_stat -3243 -3244 elif stat["name"] == "TOT": # kicking_FG, special case -3245 for i in stat["athletes"]: -3246 player_id = int(i["id"]) -3247 player_name = i["name"] -3248 player_stat = i["stat"] +3213 # Get weather data for Big 10 (B1G) games of the 2024 CFB season. +3214 print( +3215 "Get weather data for Big 10 (B1G) games of the 2024 CFB season." +3216 ) +3217 json_data = get_cfbd_weather_info( +3218 season=2024, +3219 conference="B1G", +3220 api_key=cfbd_key +3221 ) +3222 print(json_data) +3223 time.sleep(5) +3224 +3225 # Get weather data for FCS games of the 2024 CFB season. +3226 print( +3227 "Get weather data for FCS games of the 2024 CFB season." +3228 ) +3229 json_data = get_cfbd_weather_info( +3230 season=2024, +3231 ncaa_division="fcs", +3232 api_key=cfbd_key +3233 ) +3234 print(json_data) +3235 time.sleep(5) +3236 +3237 # Get weather data for University of Cincinnati games +3238 # of the 2024 CFB season. +3239 print( +3240 "Get weather data for Big 10 (B1G) games of the 2024 CFB season." +3241 ) +3242 json_data = get_cfbd_weather_info( +3243 season=2024, +3244 team_name="Cincinnati", +3245 api_key=cfbd_key +3246 ) +3247 print(json_data) +3248 time.sleep(5) 3249 -3250 if rebuilt_json.get(player_id) is None: -3251 rebuilt_json[player_id] = {} -3252 -3253 rebuilt_json[player_id]["game_id"] = game_id -3254 rebuilt_json[player_id][ -3255 "team_name" -3256 ] = team_name -3257 rebuilt_json[player_id][ -3258 "team_conference" -3259 ] = team_conference -3260 rebuilt_json[player_id][ -3261 "player_id" -3262 ] = player_id -3263 rebuilt_json[player_id][ -3264 "player_name" -3265 ] = player_name -3266 rebuilt_json[player_id][ -3267 "home_away" -3268 ] = home_away -3269 rebuilt_json[player_id][ -3270 "kicking_FG" -3271 ] = player_stat +3250 # You can also tell this function to just return the API call +3251 # as a Dictionary (read: JSON) object. +3252 print( +3253 "You can also tell this function to just return the API call " + +3254 "as a Dictionary (read: JSON) object." +3255 ) +3256 json_data = get_cfbd_weather_info( +3257 api_key=cfbd_key, +3258 season=2023, +3259 return_as_dict=True +3260 ) +3261 print(json_data) +3262 +3263 else: +3264 # Alternatively, if the CFBD API key exists in this python environment, +3265 # or it's been set by cfbd_json_py.utls.set_cfbd_api_token(), +3266 # you could just call these functions directly, +3267 # without setting the API key in the script. +3268 print( +3269 "Using the user's API key supposedly loaded " + +3270 "into this python environment for this example." +3271 ) 3272 -3273 elif stat["name"] == "PCT": # kicking_PCT -3274 for i in stat["athletes"]: -3275 player_id = int(i["id"]) -3276 player_name = i["name"] -3277 player_stat = float(i["stat"]) -3278 -3279 if rebuilt_json.get(player_id) is None: -3280 rebuilt_json[player_id] = {} -3281 -3282 rebuilt_json[player_id]["game_id"] = game_id -3283 rebuilt_json[player_id][ -3284 "team_name" -3285 ] = team_name -3286 rebuilt_json[player_id][ -3287 "team_conference" -3288 ] = team_conference -3289 rebuilt_json[player_id][ -3290 "player_id" -3291 ] = player_id -3292 rebuilt_json[player_id][ -3293 "player_name" -3294 ] = player_name -3295 rebuilt_json[player_id][ -3296 "home_away" -3297 ] = home_away -3298 rebuilt_json[player_id][ -3299 "kicking_PCT" -3300 ] = player_stat -3301 -3302 elif stat["name"] == "LONG": # kicking_LONG -3303 for i in stat["athletes"]: -3304 player_id = int(i["id"]) -3305 player_name = i["name"] -3306 player_stat = int(i["stat"]) -3307 -3308 if rebuilt_json.get(player_id) is None: -3309 rebuilt_json[player_id] = {} -3310 -3311 rebuilt_json[player_id]["game_id"] = game_id -3312 rebuilt_json[player_id][ -3313 "team_name" -3314 ] = team_name -3315 rebuilt_json[player_id][ -3316 "team_conference" -3317 ] = team_conference -3318 rebuilt_json[player_id][ -3319 "player_id" -3320 ] = player_id -3321 rebuilt_json[player_id][ -3322 "player_name" -3323 ] = player_name -3324 rebuilt_json[player_id][ -3325 "home_away" -3326 ] = home_away -3327 rebuilt_json[player_id][ -3328 "kicking_LONG" -3329 ] = player_stat -3330 -3331 elif stat["name"] == "XP": # kicking_XP -3332 for i in stat["athletes"]: -3333 player_id = int(i["id"]) -3334 player_name = i["name"] -3335 player_stat = i["stat"] +3273 # Get weather data for the 2024 CFB season +3274 print( +3275 "Get weather data for the 2024 CFB season." +3276 ) +3277 json_data = get_cfbd_weather_info( +3278 season=2024 +3279 ) +3280 print(json_data) +3281 time.sleep(5) +3282 +3283 # Get weather data for the 2024 Rose Bowl (game ID #401551786). +3284 print( +3285 "Get weather data for the 2024 Rose Bowl (game ID #401551786)." +3286 ) +3287 json_data = get_cfbd_weather_info( +3288 game_id=401551786 +3289 ) +3290 print(json_data) +3291 time.sleep(5) +3292 +3293 # Get weather data for week 1 of the 2024 CFB season +3294 print( +3295 "Get weather data for week 1 of the 2024 CFB season." +3296 ) +3297 json_data = get_cfbd_weather_info( +3298 season=2024, +3299 week=1 +3300 ) +3301 print(json_data) +3302 time.sleep(5) +3303 +3304 # Get weather data for postseason games of the 2023 CFB season. +3305 print( +3306 "Get weather data for postseason games of the 2023 CFB season." +3307 ) +3308 json_data = get_cfbd_weather_info( +3309 season=2023, +3310 season_type="postseason" +3311 ) +3312 print(json_data) +3313 time.sleep(5) +3314 +3315 # Get weather data for postseason games of the 2023 CFB season. +3316 print( +3317 "Get weather data for postseason games of the 2023 CFB season." +3318 ) +3319 json_data = get_cfbd_weather_info( +3320 season=2023, +3321 season_type="postseason" +3322 ) +3323 print(json_data) +3324 time.sleep(5) +3325 +3326 # Get weather data for Big 10 (B1G) games of the 2024 CFB season. +3327 print( +3328 "Get weather data for Big 10 (B1G) games of the 2024 CFB season." +3329 ) +3330 json_data = get_cfbd_weather_info( +3331 season=2024, +3332 conference="B1G" +3333 ) +3334 print(json_data) +3335 time.sleep(5) 3336 -3337 if rebuilt_json.get(player_id) is None: -3338 rebuilt_json[player_id] = {} -3339 -3340 rebuilt_json[player_id]["game_id"] = game_id -3341 rebuilt_json[player_id][ -3342 "team_name" -3343 ] = team_name -3344 rebuilt_json[player_id][ -3345 "team_conference" -3346 ] = team_conference -3347 rebuilt_json[player_id][ -3348 "player_id" -3349 ] = player_id -3350 rebuilt_json[player_id][ -3351 "player_name" -3352 ] = player_name -3353 rebuilt_json[player_id][ -3354 "home_away" -3355 ] = home_away -3356 rebuilt_json[player_id][ -3357 "kicking_XP" -3358 ] = player_stat +3337 # Get weather data for FCS games of the 2024 CFB season. +3338 print( +3339 "Get weather data for FCS games of the 2024 CFB season." +3340 ) +3341 json_data = get_cfbd_weather_info( +3342 season=2024, +3343 ncaa_division="fcs" +3344 ) +3345 print(json_data) +3346 time.sleep(5) +3347 +3348 # Get weather data for University of Cincinnati games +3349 # of the 2024 CFB season. +3350 print( +3351 "Get weather data for Big 10 (B1G) games of the 2024 CFB season." +3352 ) +3353 json_data = get_cfbd_weather_info( +3354 season=2024, +3355 team_name="Cincinnati" +3356 ) +3357 print(json_data) +3358 time.sleep(5) 3359 -3360 elif stat["name"] == "PTS": # kicking_PTS -3361 for i in stat["athletes"]: -3362 player_id = int(i["id"]) -3363 player_name = i["name"] -3364 player_stat = int(i["stat"]) -3365 -3366 if rebuilt_json.get(player_id) is None: -3367 rebuilt_json[player_id] = {} -3368 -3369 rebuilt_json[player_id]["game_id"] = game_id -3370 rebuilt_json[player_id][ -3371 "team_name" -3372 ] = team_name -3373 rebuilt_json[player_id][ -3374 "team_conference" -3375 ] = team_conference -3376 rebuilt_json[player_id][ -3377 "player_id" -3378 ] = player_id -3379 rebuilt_json[player_id][ -3380 "player_name" -3381 ] = player_name -3382 rebuilt_json[player_id][ -3383 "home_away" -3384 ] = home_away -3385 rebuilt_json[player_id][ -3386 "kicking_PTS" -3387 ] = player_stat -3388 -3389 else: -3390 raise IndexError( -3391 f"Unhandled stat: \t{stat['name']}" -3392 ) -3393 -3394 elif s_category["name"] == "kickReturns": -3395 for stat in s_category["types"]: -3396 if stat["name"] == "NO": # kickReturns_NO -3397 for i in stat["athletes"]: -3398 player_id = int(i["id"]) -3399 player_name = i["name"] -3400 player_stat = int(i["stat"]) -3401 -3402 if rebuilt_json.get(player_id) is None: -3403 rebuilt_json[player_id] = {} -3404 -3405 rebuilt_json[player_id]["game_id"] = game_id -3406 rebuilt_json[player_id][ -3407 "team_name" -3408 ] = team_name -3409 rebuilt_json[player_id][ -3410 "team_conference" -3411 ] = team_conference -3412 rebuilt_json[player_id][ -3413 "player_id" -3414 ] = player_id -3415 rebuilt_json[player_id][ -3416 "player_name" -3417 ] = player_name -3418 rebuilt_json[player_id][ -3419 "home_away" -3420 ] = home_away -3421 rebuilt_json[player_id][ -3422 "kickReturns_NO" -3423 ] = player_stat -3424 -3425 elif stat["name"] == "YDS": # kickReturns_YDS -3426 for i in stat["athletes"]: -3427 player_id = int(i["id"]) -3428 player_name = i["name"] -3429 player_stat = int(i["stat"]) -3430 -3431 if rebuilt_json.get(player_id) is None: -3432 rebuilt_json[player_id] = {} +3360 # You can also tell this function to just return the API call +3361 # as a Dictionary (read: JSON) object. +3362 print( +3363 "You can also tell this function to just return the API call " + +3364 "as a Dictionary (read: JSON) object." +3365 ) +3366 json_data = get_cfbd_weather_info( +3367 season=2023, +3368 return_as_dict=True +3369 ) +3370 print(json_data) +3371 +3372 ``` +3373 Returns +3374 ---------- +3375 A pandas `DataFrame` object with live weather data, +3376 or (if `return_as_dict` is set to `True`) +3377 a dictionary object with live weather data. +3378 +3379 """ +3380 +3381 weather_df = pd.DataFrame() +3382 url = "https://api.collegefootballdata.com/games/weather" +3383 +3384 if api_key is not None: +3385 real_api_key = api_key +3386 del api_key +3387 else: +3388 real_api_key = get_cfbd_api_token(api_key_dir=api_key_dir) +3389 +3390 if real_api_key == "tigersAreAwesome": +3391 raise ValueError( +3392 "You actually need to change `cfbd_key` to your CFBD API key." +3393 ) +3394 elif "Bearer " in real_api_key: +3395 pass +3396 elif "Bearer" in real_api_key: +3397 real_api_key = real_api_key.replace("Bearer", "Bearer ") +3398 else: +3399 real_api_key = "Bearer " + real_api_key +3400 +3401 # if (game_id is None) and (season is None): +3402 # raise ValueError( +3403 # "`game_id` and/or `season` must be set to " + +3404 # "valid, non-null values." +3405 # ) +3406 # elif (game_id is not None) and (season is not None): +3407 # url += f"?gameId={game_id}&year={season}" +3408 # elif game_id is not None: +3409 # url += f"?gameId={game_id}" +3410 # elif season is not None: +3411 # url += f"?year={season}" +3412 if season is None: +3413 raise ValueError( +3414 "`season` must be set to a valid, non-null value." +3415 ) +3416 elif season is not None: +3417 url += f"?year={season}" +3418 +3419 if (ncaa_division is not None) and ( +3420 ncaa_division.lower() == "fbs" +3421 or ncaa_division.lower() == "fcs" +3422 or ncaa_division.lower() == "ii" +3423 or ncaa_division.lower() == "iii" +3424 ): +3425 ncaa_division = ncaa_division.lower() +3426 url += f"&classification={ncaa_division}" +3427 else: +3428 raise ValueError( +3429 "An invalid NCAA Division was inputted when calling this function." +3430 + '\nValid inputs are:\n-"fbs"\n-"fcs"\n-"ii"\n-"iii"' +3431 + f"\n\nYou entered:\n{ncaa_division}" +3432 ) 3433 -3434 rebuilt_json[player_id]["game_id"] = game_id -3435 rebuilt_json[player_id][ -3436 "team_name" -3437 ] = team_name -3438 rebuilt_json[player_id][ -3439 "team_conference" -3440 ] = team_conference -3441 rebuilt_json[player_id][ -3442 "player_id" -3443 ] = player_id -3444 rebuilt_json[player_id][ -3445 "player_name" -3446 ] = player_name -3447 rebuilt_json[player_id][ -3448 "home_away" -3449 ] = home_away -3450 rebuilt_json[player_id][ -3451 "kickReturns_YDS" -3452 ] = player_stat -3453 -3454 elif stat["name"] == "AVG": # kickReturns_AVG -3455 for i in stat["athletes"]: -3456 player_id = int(i["id"]) -3457 player_name = i["name"] -3458 player_stat = float(i["stat"]) -3459 -3460 if rebuilt_json.get(player_id) is None: -3461 rebuilt_json[player_id] = {} +3434 if week is not None: +3435 url += f"&week={week}" +3436 +3437 if ( +3438 season_type == "regular" or +3439 season_type == "postseason" or +3440 season_type == "both" +3441 ): +3442 url += f"&seasonType={season_type}" +3443 elif season_type is not None: +3444 raise ValueError( +3445 '`season_type` must be set to either "regular", ' +3446 + '"postseason", or "both" if you want to specify ' +3447 + "a part of the season." +3448 ) +3449 +3450 if team_name is not None: +3451 url += f"&team={team_name}" +3452 +3453 if conference is not None: +3454 url += f"&conference={conference}" +3455 +3456 headers = { +3457 "Authorization": f"{real_api_key}", +3458 "accept": "application/json" +3459 } +3460 +3461 response = requests.get(url, headers=headers) 3462 -3463 rebuilt_json[player_id]["game_id"] = game_id -3464 rebuilt_json[player_id][ -3465 "team_name" -3466 ] = team_name -3467 rebuilt_json[player_id][ -3468 "team_conference" -3469 ] = team_conference -3470 rebuilt_json[player_id][ -3471 "player_id" -3472 ] = player_id -3473 rebuilt_json[player_id][ -3474 "player_name" -3475 ] = player_name -3476 rebuilt_json[player_id][ -3477 "home_away" -3478 ] = home_away -3479 rebuilt_json[player_id][ -3480 "kickReturns_AVG" -3481 ] = player_stat +3463 if response.status_code == 200: +3464 pass +3465 elif response.status_code == 401: +3466 raise ConnectionRefusedError( +3467 "Could not connect. The connection was refused.\n" + +3468 "HTTP Status Code 401." +3469 ) +3470 else: +3471 raise ConnectionError( +3472 f"Could not connect.\nHTTP Status code {response.status_code}" +3473 ) +3474 +3475 json_data = response.json() +3476 +3477 if return_as_dict is True: +3478 return json_data +3479 +3480 weather_df = pd.json_normalize(json_data) +3481 # print(weather_df.columns) 3482 -3483 elif stat["name"] == "TD": # kickReturns_TD -3484 for i in stat["athletes"]: -3485 player_id = int(i["id"]) -3486 player_name = i["name"] -3487 player_stat = int(i["stat"]) -3488 -3489 if rebuilt_json.get(player_id) is None: -3490 rebuilt_json[player_id] = {} -3491 -3492 rebuilt_json[player_id]["game_id"] = game_id -3493 rebuilt_json[player_id][ -3494 "team_name" -3495 ] = team_name -3496 rebuilt_json[player_id][ -3497 "team_conference" -3498 ] = team_conference -3499 rebuilt_json[player_id][ -3500 "player_id" -3501 ] = player_id -3502 rebuilt_json[player_id][ -3503 "player_name" -3504 ] = player_name -3505 rebuilt_json[player_id][ -3506 "home_away" -3507 ] = home_away -3508 rebuilt_json[player_id][ -3509 "kickReturns_TD" -3510 ] = player_stat -3511 -3512 elif stat["name"] == "LONG": # kickReturns_LONG -3513 for i in stat["athletes"]: -3514 player_id = int(i["id"]) -3515 player_name = i["name"] -3516 player_stat = int(i["stat"]) -3517 -3518 if rebuilt_json.get(player_id) is None: -3519 rebuilt_json[player_id] = {} -3520 -3521 rebuilt_json[player_id]["game_id"] = game_id -3522 rebuilt_json[player_id][ -3523 "team_name" -3524 ] = team_name -3525 rebuilt_json[player_id][ -3526 "team_conference" -3527 ] = team_conference -3528 rebuilt_json[player_id][ -3529 "player_id" -3530 ] = player_id -3531 rebuilt_json[player_id][ -3532 "player_name" -3533 ] = player_name -3534 rebuilt_json[player_id][ -3535 "home_away" -3536 ] = home_away -3537 rebuilt_json[player_id][ -3538 "kickReturns_LONG" -3539 ] = player_stat -3540 -3541 else: -3542 raise IndexError( -3543 f"Unhandled stat: \t{stat['name']}" -3544 ) -3545 -3546 elif s_category["name"] == "puntReturns": -3547 for stat in s_category["types"]: -3548 if stat["name"] == "NO": # puntReturns_NO -3549 for i in stat["athletes"]: -3550 player_id = int(i["id"]) -3551 player_name = i["name"] -3552 player_stat = int(i["stat"]) -3553 -3554 if rebuilt_json.get(player_id) is None: -3555 rebuilt_json[player_id] = {} -3556 -3557 rebuilt_json[player_id]["game_id"] = game_id -3558 rebuilt_json[player_id][ -3559 "team_name" -3560 ] = team_name -3561 rebuilt_json[player_id][ -3562 "team_conference" -3563 ] = team_conference -3564 rebuilt_json[player_id][ -3565 "player_id" -3566 ] = player_id -3567 rebuilt_json[player_id][ -3568 "player_name" -3569 ] = player_name -3570 rebuilt_json[player_id][ -3571 "home_away" -3572 ] = home_away -3573 rebuilt_json[player_id][ -3574 "puntReturns_NO" -3575 ] = player_stat -3576 -3577 elif stat["name"] == "YDS": # puntReturns_YDS -3578 for i in stat["athletes"]: -3579 player_id = int(i["id"]) -3580 player_name = i["name"] -3581 player_stat = int(i["stat"]) -3582 -3583 if rebuilt_json.get(player_id) is None: -3584 rebuilt_json[player_id] = {} -3585 -3586 rebuilt_json[player_id]["game_id"] = game_id -3587 rebuilt_json[player_id][ -3588 "team_name" -3589 ] = team_name -3590 rebuilt_json[player_id][ -3591 "team_conference" -3592 ] = team_conference -3593 rebuilt_json[player_id][ -3594 "player_id" -3595 ] = player_id -3596 rebuilt_json[player_id][ -3597 "player_name" -3598 ] = player_name -3599 rebuilt_json[player_id][ -3600 "home_away" -3601 ] = home_away -3602 rebuilt_json[player_id][ -3603 "puntReturns_YDS" -3604 ] = player_stat -3605 -3606 elif stat["name"] == "AVG": # puntReturns_AVG -3607 for i in stat["athletes"]: -3608 player_id = int(i["id"]) -3609 player_name = i["name"] -3610 player_stat = float(i["stat"]) -3611 -3612 if rebuilt_json.get(player_id) is None: -3613 rebuilt_json[player_id] = {} -3614 -3615 rebuilt_json[player_id]["game_id"] = game_id -3616 rebuilt_json[player_id][ -3617 "team_name" -3618 ] = team_name -3619 rebuilt_json[player_id][ -3620 "team_conference" -3621 ] = team_conference -3622 rebuilt_json[player_id][ -3623 "player_id" -3624 ] = player_id -3625 rebuilt_json[player_id][ -3626 "player_name" -3627 ] = player_name -3628 rebuilt_json[player_id][ -3629 "home_away" -3630 ] = home_away -3631 rebuilt_json[player_id][ -3632 "puntReturns_AVG" -3633 ] = player_stat -3634 -3635 elif stat["name"] == "TD": # puntReturns_TD -3636 for i in stat["athletes"]: -3637 player_id = int(i["id"]) -3638 player_name = i["name"] -3639 player_stat = int(i["stat"]) -3640 -3641 if rebuilt_json.get(player_id) is None: -3642 rebuilt_json[player_id] = {} -3643 -3644 rebuilt_json[player_id]["game_id"] = game_id -3645 rebuilt_json[player_id][ -3646 "team_name" -3647 ] = team_name -3648 rebuilt_json[player_id][ -3649 "team_conference" -3650 ] = team_conference -3651 rebuilt_json[player_id][ -3652 "player_id" -3653 ] = player_id -3654 rebuilt_json[player_id][ -3655 "player_name" -3656 ] = player_name -3657 rebuilt_json[player_id][ -3658 "home_away" -3659 ] = home_away -3660 rebuilt_json[player_id][ -3661 "puntReturns_TD" -3662 ] = player_stat -3663 -3664 elif stat["name"] == "LONG": # puntReturns_LONG -3665 for i in stat["athletes"]: -3666 player_id = int(i["id"]) -3667 player_name = i["name"] -3668 player_stat = int(i["stat"]) -3669 -3670 if rebuilt_json.get(player_id) is None: -3671 rebuilt_json[player_id] = {} -3672 -3673 rebuilt_json[player_id]["game_id"] = game_id -3674 rebuilt_json[player_id][ -3675 "team_name" -3676 ] = team_name -3677 rebuilt_json[player_id][ -3678 "team_conference" -3679 ] = team_conference -3680 rebuilt_json[player_id][ -3681 "player_id" -3682 ] = player_id -3683 rebuilt_json[player_id][ -3684 "player_name" -3685 ] = player_name -3686 rebuilt_json[player_id][ -3687 "home_away" -3688 ] = home_away -3689 rebuilt_json[player_id][ -3690 "puntReturns_LONG" -3691 ] = player_stat -3692 -3693 else: -3694 raise IndexError( -3695 f"Unhandled stat: \t{stat['name']}" -3696 ) -3697 -3698 else: -3699 raise IndexError( -3700 f"Unhandled stat category: \t{s_category['name']}" -3701 ) -3702 -3703 for key, value in tqdm(rebuilt_json.items()): -3704 row_df = pd.json_normalize(value) -3705 cfb_games_df = pd.concat([cfb_games_df, row_df], ignore_index=True) -3706 del row_df -3707 -3708 cfb_games_df[["passing_COMP", "passing_ATT"]] = cfb_games_df[ -3709 "passing_C/ATT" -3710 ].str.split("/", expand=True) -3711 -3712 cfb_games_df[["kicking_FGM", "kicking_FGA"]] = cfb_games_df[ -3713 "kicking_FG" -3714 ].str.split( -3715 "/", expand=True -3716 ) -3717 cfb_games_df[["kicking_XPM", "kicking_XPA"]] = cfb_games_df[ -3718 "kicking_XP" -3719 ].str.split( -3720 "/", expand=True -3721 ) -3722 -3723 cfb_games_df = cfb_games_df.fillna(0) -3724 -3725 cfb_games_df = cfb_games_df.astype( -3726 { -3727 "passing_COMP": "int", -3728 "passing_ATT": "int", -3729 "kicking_FGM": "int", -3730 "kicking_FGA": "int", -3731 "kicking_XPM": "int", -3732 "kicking_XPA": "int", -3733 } -3734 ) -3735 # print(cfb_games_df.columns) -3736 cfb_games_df["season"] = season -3737 -3738 if filter_by_stat_category is False: -3739 cfb_games_df = cfb_games_df.reindex(columns=stat_columns) -3740 -3741 elif filter_by_stat_category is True and stat_category == "passing": -3742 cfb_games_df = cfb_games_df[ -3743 [ -3744 "season", -3745 "game_id", -3746 "team_name", -3747 "team_conference", -3748 "player_id", -3749 "player_name", -3750 "home_away", -3751 # PASS -3752 "passing_C/ATT", -3753 "passing_COMP", -3754 "passing_ATT", -3755 "passing_YDS", -3756 "passing_AVG", -3757 "passing_TD", -3758 "passing_INT", -3759 "passing_QBR", -3760 ] -3761 ] -3762 -3763 elif filter_by_stat_category is True and stat_category == "rushing": -3764 cfb_games_df = cfb_games_df[ -3765 [ -3766 "season", -3767 "game_id", -3768 "team_name", -3769 "team_conference", -3770 "player_id", -3771 "player_name", -3772 "home_away", -3773 # RUSH -3774 "rushing_CAR", -3775 "rushing_YDS", -3776 "rushing_AVG", -3777 "rushing_TD", -3778 "rushing_LONG", -3779 ] -3780 ] -3781 -3782 elif filter_by_stat_category is True and stat_category == "receiving": -3783 cfb_games_df = cfb_games_df[ -3784 [ -3785 "season", -3786 "game_id", -3787 "team_name", -3788 "team_conference", -3789 "player_id", -3790 "player_name", -3791 "home_away", -3792 # REC -3793 "receiving_REC", -3794 "receiving_YDS", -3795 "receiving_AVG", -3796 "receiving_TD", -3797 "receiving_LONG", -3798 ] -3799 ] -3800 -3801 elif filter_by_stat_category is True and stat_category == "fumbles": -3802 cfb_games_df = cfb_games_df[ -3803 [ -3804 "season", -3805 "game_id", -3806 "team_name", -3807 "team_conference", -3808 "player_id", -3809 "player_name", -3810 "home_away", -3811 # FUM -3812 "fumbles_FUM", -3813 "fumbles_LOST", -3814 "fumbles_REC", -3815 ] -3816 ] -3817 -3818 elif filter_by_stat_category is True and stat_category == "defensive": -3819 cfb_games_df = cfb_games_df[ -3820 [ -3821 "season", -3822 "game_id", -3823 "team_name", -3824 "team_conference", -3825 "player_id", -3826 "player_name", -3827 "home_away", -3828 # DEFENSE -3829 "defensive_TOT", -3830 "defensive_SOLO", -3831 "defensive_TFL", -3832 "defensive_QB HUR", -3833 "defensive_SACKS", -3834 "defensive_PD", -3835 "defensive_TD", -3836 ] -3837 ] -3838 -3839 elif filter_by_stat_category is True and stat_category == "interceptions": -3840 cfb_games_df = cfb_games_df[ -3841 [ -3842 "season", -3843 "game_id", -3844 "team_name", -3845 "team_conference", -3846 "player_id", -3847 "player_name", -3848 "home_away", -3849 # INT -3850 "interceptions_INT", -3851 "interceptions_YDS", -3852 "interceptions_TD", -3853 ] -3854 ] -3855 -3856 elif filter_by_stat_category is True and stat_category == "punting": -3857 cfb_games_df = cfb_games_df[ -3858 [ -3859 "season", -3860 "game_id", -3861 "team_name", -3862 "team_conference", -3863 "player_id", -3864 "player_name", -3865 "home_away", -3866 # PUNT -3867 "punting_NO", -3868 "punting_YDS", -3869 "punting_AVG", -3870 "punting_TB", -3871 "punting_In 20", -3872 "punting_LONG", -3873 ] -3874 ] -3875 -3876 elif filter_by_stat_category is True and stat_category == "kicking": -3877 cfb_games_df = cfb_games_df[ -3878 [ -3879 "season", -3880 "game_id", -3881 "team_name", -3882 "team_conference", -3883 "player_id", -3884 "player_name", -3885 "home_away", -3886 # KICK -3887 "kicking_FG", -3888 "kicking_FGM", -3889 "kicking_FGA", -3890 "kicking_PCT", -3891 "kicking_LONG", -3892 "kicking_XP", -3893 "kicking_XPM", -3894 "kicking_XPA", -3895 "kicking_PTS", -3896 ] -3897 ] -3898 -3899 elif filter_by_stat_category is True and stat_category == "kickReturns": -3900 cfb_games_df = cfb_games_df[ -3901 [ -3902 "season", -3903 "game_id", -3904 "team_name", -3905 "team_conference", -3906 "player_id", -3907 "player_name", -3908 "home_away", -3909 # KR -3910 "kickReturns_NO", -3911 "kickReturns_YDS", -3912 "kickReturns_AVG", -3913 "kickReturns_TD", -3914 "kickReturns_LONG", -3915 ] -3916 ] -3917 -3918 elif filter_by_stat_category is True and stat_category == "puntReturns": -3919 cfb_games_df = cfb_games_df[ -3920 [ -3921 "season", -3922 "game_id", -3923 "team_name", -3924 "team_conference", -3925 "player_id", -3926 "player_name", -3927 "home_away", -3928 # KR -3929 "puntReturns_NO", -3930 "puntReturns_YDS", -3931 "puntReturns_AVG", -3932 "puntReturns_TD", -3933 "puntReturns_LONG", -3934 ] -3935 ] -3936 -3937 return cfb_games_df -3938 -3939 -3940def get_cfbd_player_advanced_game_stats( -3941 game_id: int, -3942 api_key: str = None, -3943 api_key_dir: str = None, -3944 return_as_dict: bool = False, -3945): -3946 """ -3947 Retrieves advanced game stats from the CFBD API. -3948 -3949 Parameters -3950 ---------- -3951 `game_id` (int, mandatory): -3952 Mandatory requirement. -3953 Specifies the game you want advanced game stats from. -3954 -3955 `api_key` (str, optional): -3956 Semi-optional argument. -3957 If `api_key` is null, this function will attempt to load a CFBD API key -3958 from the python environment, or from a file on this computer. -3959 If `api_key` is not null, -3960 this function will automatically assume that the -3961 inputted `api_key` is a valid CFBD API key. -3962 -3963 `api_key_dir` (str, optional): -3964 Optional argument. -3965 If `api_key` is set to am empty string, this variable is ignored. -3966 If `api_key_dir` is null, and `api_key` is null, -3967 this function will try to find -3968 a CFBD API key file in this user's home directory. -3969 If `api_key_dir` is set to a string, and `api_key` is null, -3970 this function will assume that `api_key_dir` is a directory, -3971 and will try to find a CFBD API key file in that directory. -3972 -3973 `return_as_dict` (bool, semi-optional): -3974 Semi-optional argument. -3975 If you want this function to return -3976 the data as a dictionary (read: JSON object), -3977 instead of a pandas `DataFrame` object, -3978 set `return_as_dict` to `True`. -3979 -3980 Usage -3981 ---------- -3982 ``` -3983 import time -3984 -3985 from cfbd_json_py.games import get_cfbd_player_advanced_game_stats -3986 -3987 -3988 cfbd_key = "tigersAreAwesome" # placeholder for your CFBD API Key. -3989 -3990 if cfbd_key is not "tigersAreAwesome": -3991 print( -3992 "Using the user's API key declared in this script " + -3993 "for this example." -3994 ) -3995 -3996 # Get advanced player stats for a 2019 CFB game -3997 # between the LSU Tigers Football Program, -3998 # and the Oklahoma Sooners Football Program. -3999 print( -4000 "Get advanced player stats for a 2019 CFB game between " + -4001 "the LSU Tigers Football Program, " + -4002 "and the Oklahoma Sooners Football Program." -4003 ) -4004 json_data = get_cfbd_player_advanced_game_stats( -4005 api_key=cfbd_key, -4006 game_id=401135278 -4007 ) -4008 print(json_data) -4009 time.sleep(5) -4010 -4011 -4012 # You can also tell this function to just return the API call as -4013 # a Dictionary (read: JSON) object. -4014 print( -4015 "You can also tell this function to just return the API call " + -4016 "as a Dictionary (read: JSON) object." -4017 ) -4018 json_data = get_cfbd_player_advanced_game_stats( -4019 api_key=cfbd_key, -4020 game_id=401135278, -4021 return_as_dict=True -4022 ) -4023 print(json_data) -4024 -4025 else: -4026 # Alternatively, if the CFBD API key exists in this python environment, -4027 # or it's been set by cfbd_json_py.utls.set_cfbd_api_token(), -4028 # you could just call these functions directly, -4029 # without setting the API key in the script. -4030 print( -4031 "Using the user's API key supposedly loaded " + -4032 "into this python environment for this example." -4033 ) -4034 -4035 # Get advanced player stats for a 2019 CFB game -4036 # between the LSU Tigers Football Program, -4037 # and the Oklahoma Sooners Football Program. -4038 print( -4039 "Get advanced player stats for a 2019 CFB game " + -4040 "between the LSU Tigers Football Program, " + -4041 "and the Oklahoma Sooners Football Program." -4042 ) -4043 json_data = get_cfbd_player_advanced_game_stats( -4044 game_id=401135278 -4045 ) -4046 print(json_data) -4047 time.sleep(5) -4048 -4049 -4050 # You can also tell this function to just return the API call as -4051 # a Dictionary (read: JSON) object. -4052 print( -4053 "You can also tell this function to just return the API call " + -4054 "as a Dictionary (read: JSON) object." -4055 ) -4056 json_data = get_cfbd_player_advanced_game_stats( -4057 game_id=401135278, -4058 return_as_dict=True -4059 ) -4060 print(json_data) -4061 -4062 ``` -4063 Returns -4064 ---------- -4065 A pandas `DataFrame` object with college football game information, -4066 or (if `return_as_dict` is set to `True`) -4067 a dictionary object with college football game information. -4068 """ -4069 -4070 # now = datetime.now() -4071 usage_df = pd.DataFrame() -4072 ppa_df = pd.DataFrame() -4073 adv_stats_df = pd.DataFrame() -4074 row_df = pd.DataFrame() -4075 url = "https://api.collegefootballdata.com/game/box/advanced" -4076 -4077 ########################################################################## -4078 -4079 if api_key is not None: -4080 real_api_key = api_key -4081 del api_key -4082 else: -4083 real_api_key = get_cfbd_api_token(api_key_dir=api_key_dir) -4084 -4085 if real_api_key == "tigersAreAwesome": -4086 raise ValueError( -4087 "You actually need to change `cfbd_key` to your CFBD API key." -4088 ) -4089 elif "Bearer " in real_api_key: -4090 pass -4091 elif "Bearer" in real_api_key: -4092 real_api_key = real_api_key.replace("Bearer", "Bearer ") -4093 else: -4094 real_api_key = "Bearer " + real_api_key -4095 -4096 # URL builder -4097 ########################################################################## -4098 -4099 # Required by API -4100 url += f"?gameId={game_id}" -4101 -4102 headers = { -4103 "Authorization": f"{real_api_key}", -4104 "accept": "application/json" -4105 } -4106 response = requests.get(url, headers=headers) -4107 -4108 if response.status_code == 200: -4109 pass -4110 elif response.status_code == 401: -4111 raise ConnectionRefusedError( -4112 "Could not connect. The connection was refused." + -4113 "\nHTTP Status Code 401." -4114 ) -4115 else: -4116 raise ConnectionError( -4117 f"Could not connect.\nHTTP Status code {response.status_code}" -4118 ) -4119 -4120 json_data = response.json() -4121 -4122 if return_as_dict is True: -4123 return json_data -4124 -4125 home_team_name = json_data["gameInfo"]["homeTeam"] -4126 home_points = json_data["gameInfo"]["homePoints"] -4127 home_win_prob = json_data["gameInfo"]["homeWinProb"] -4128 away_team_name = json_data["gameInfo"]["awayTeam"] -4129 away_points = json_data["gameInfo"]["awayPoints"] -4130 away_win_prob = json_data["gameInfo"]["awayWinProb"] -4131 home_winner = json_data["gameInfo"]["homeWinner"] -4132 game_excitement_score = json_data["gameInfo"]["excitement"] -4133 -4134 # Parsing Usage -4135 print("Parsing player usage data.") -4136 for player in tqdm(json_data["players"]["usage"]): -4137 row_df = pd.DataFrame({"game_id": game_id}, index=[0]) -4138 row_df["player_name"] = player["player"] -4139 row_df["team"] = player["team"] -4140 row_df["position"] = player["position"] -4141 -4142 row_df["total_usage"] = player["total"] -4143 row_df["q1_usage"] = player["quarter1"] -4144 row_df["q2_usage"] = player["quarter2"] -4145 row_df["q3_usage"] = player["quarter3"] -4146 row_df["q4_usage"] = player["quarter4"] -4147 row_df["rushing_usage"] = player["rushing"] -4148 row_df["passing_usage"] = player["passing"] -4149 -4150 usage_df = pd.concat([usage_df, row_df], ignore_index=True) -4151 del row_df -4152 -4153 # Parsing PPA -4154 print("Parsing player PPA data.") -4155 for player in tqdm(json_data["players"]["ppa"]): -4156 row_df = pd.DataFrame({"game_id": game_id}, index=[0]) -4157 row_df["player_name"] = player["player"] -4158 row_df["team"] = player["team"] -4159 row_df["position"] = player["position"] -4160 -4161 row_df["average_ppa_total"] = player["average"]["total"] -4162 row_df["average_ppa_q1"] = player["average"]["quarter1"] -4163 row_df["average_ppa_q2"] = player["average"]["quarter2"] -4164 row_df["average_ppa_q3"] = player["average"]["quarter3"] -4165 row_df["average_ppa_q4"] = player["average"]["quarter4"] -4166 row_df["average_ppa_rushing"] = player["average"]["rushing"] -4167 row_df["average_ppa_passing"] = player["average"]["passing"] -4168 -4169 row_df["cumulative_ppa_total"] = player["cumulative"]["total"] -4170 row_df["cumulative_ppa_q1"] = player["cumulative"]["quarter1"] -4171 row_df["cumulative_ppa_q2"] = player["cumulative"]["quarter2"] -4172 row_df["cumulative_ppa_q3"] = player["cumulative"]["quarter3"] -4173 row_df["cumulative_ppa_q4"] = player["cumulative"]["quarter4"] -4174 row_df["cumulative_ppa_rushing"] = player["cumulative"]["rushing"] -4175 row_df["cumulative_ppa_passing"] = player["cumulative"]["passing"] -4176 -4177 ppa_df = pd.concat([ppa_df, row_df], ignore_index=True) -4178 -4179 # Join `usage_df` and `ppa_df` together -4180 adv_stats_df = pd.merge( -4181 left=usage_df, -4182 right=ppa_df, -4183 how="outer", -4184 on=["game_id", "player_name", "team", "position"], -4185 ) -4186 -4187 # Add in these columns for completeness. -4188 -4189 adv_stats_df.loc[ -4190 adv_stats_df["team"] == home_team_name, "home_away" -4191 ] = "home" -4192 adv_stats_df.loc[adv_stats_df["team"] == home_team_name, "opponent"] = ( -4193 away_team_name -4194 ) -4195 -4196 adv_stats_df.loc[ -4197 adv_stats_df["team"] == away_team_name, "home_away" -4198 ] = "away" -4199 adv_stats_df.loc[adv_stats_df["team"] == away_team_name, "opponent"] = ( -4200 home_team_name -4201 ) -4202 -4203 adv_stats_df["home_team"] = home_team_name -4204 adv_stats_df["away_team"] = away_team_name -4205 -4206 adv_stats_df["home_win_prob"] = home_win_prob -4207 adv_stats_df["away_win_prob"] = away_win_prob -4208 -4209 adv_stats_df["home_points"] = home_points -4210 adv_stats_df["away_points"] = away_points -4211 -4212 adv_stats_df["home_winner"] = home_winner -4213 adv_stats_df["game_excitement_score"] = game_excitement_score -4214 -4215 return adv_stats_df -4216 -4217 -4218############################################################################### -4219# Patreon Only Functions. -4220# No caching, because the entire point of these functions are to get people -4221# data ASAP, and right before kickoff. -4222############################################################################### -4223 -4224 -4225def get_cfbd_live_scoreboard( -4226 ncaa_division: str = "fbs", -4227 conference: str = None, -4228 api_key: str = None, -4229 api_key_dir: str = None, -4230 return_as_dict: bool = False, -4231): -4232 """ -4233 YOU MUST BE SUBSCRIBED TO THE CFBD PATREON FOR THIS FUNCTION TO WORK! -4234 To view the CFBD Patreon, visit https://www.patreon.com/collegefootballdata -4235 -4236 Retrieves live scoreboard data from the CFBD API, -4237 assuming the API key is an API key from a Patreon supporter. -4238 -4239 Parameters -4240 ---------- -4241 `ncaa_division` (str, semi-optional): -4242 Semi-optional argument. -4243 By default, `ncaa_division` will be set to "fbs", -4244 short for the Football Bowl Subdivision (FBS), -4245 formerly known as D1-A (read as "division one single A"), -4246 the highest level in the NCAA football pyramid, -4247 where teams can scholarship up to 85 players -4248 on their football team solely for athletic ability, -4249 and often have the largest athletics budgets -4250 within the NCAA. -4251 -4252 Other valid inputs are: -4253 - "fcs": Football Championship Subdivision (FCS), -4254 formerly known as D1-AA (read as "division one double A"). -4255 An FCS school is still in the 1st division of the NCAA, -4256 making them eligible for the March Madness tournament, -4257 but may not have the resources to compete at the FBS level -4258 at this time. FCS schools are limited to 63 athletic scholarships -4259 for football. -4260 - "ii": NCAA Division II. Schools in this and D3 are not -4261 eligible for the March Madness tournament, -4262 and are limited to 36 athletic scholarships -4263 for their football team. -4264 - "iii": NCAA Division III. The largest single division within the -4265 NCAA football pyramid. -4266 D3 schools have the distinction of being part of -4267 the only NCAA division that cannot give out scholarships solely -4268 for athletic ability. -4269 -4270 `conference` (str, optional): -4271 Optional argument. -4272 If you only want live scoreboard data from games -4273 involving teams a specific conference, -4274 set `conference` to the abbreviation -4275 of the conference you want live scoreboard data from. -4276 -4277 `api_key` (str, optional): -4278 Semi-optional argument. -4279 If `api_key` is null, this function will attempt to load a CFBD API key -4280 from the python environment, or from a file on this computer. -4281 If `api_key` is not null, -4282 this function will automatically assume that the -4283 inputted `api_key` is a valid CFBD API key. -4284 -4285 `api_key_dir` (str, optional): -4286 Optional argument. -4287 If `api_key` is set to am empty string, this variable is ignored. -4288 If `api_key_dir` is null, and `api_key` is null, -4289 this function will try to find -4290 a CFBD API key file in this user's home directory. -4291 If `api_key_dir` is set to a string, and `api_key` is null, -4292 this function will assume that `api_key_dir` is a directory, -4293 and will try to find a CFBD API key file in that directory. -4294 -4295 `return_as_dict` (bool, semi-optional): -4296 Semi-optional argument. -4297 If you want this function to return -4298 the data as a dictionary (read: JSON object), -4299 instead of a pandas `DataFrame` object, -4300 set `return_as_dict` to `True`. -4301 Usage -4302 ---------- -4303 ``` -4304 import time -4305 -4306 from cfbd_json_py.games import get_cfbd_live_scoreboard -4307 -4308 -4309 cfbd_key = "tigersAreAwesome" # placeholder for your CFBD API Key. -4310 -4311 if cfbd_key != "tigersAreAwesome": -4312 print( -4313 "Using the user's API key declared " + -4314 "in this script for this example." -4315 ) -4316 -4317 # Get live scoreboard data from the CFBD API. -4318 print( -4319 "Get live scoreboard data from the CFBD API." -4320 ) -4321 json_data = get_cfbd_live_scoreboard( -4322 api_key=cfbd_key -4323 ) -4324 print(json_data) -4325 time.sleep(5) -4326 -4327 # Get live scoreboard data from the CFBD API, -4328 # but only from the FCS ranks. -4329 print( -4330 "Get live scoreboard data from the CFBD API, " + -4331 "but only from the FCS ranks." -4332 ) -4333 json_data = get_cfbd_live_scoreboard( -4334 ncaa_division="fcs", -4335 api_key=cfbd_key -4336 ) -4337 print(json_data) -4338 time.sleep(5) -4339 -4340 # Get live scoreboard data from the CFBD API, -4341 # but only from the Atlantic Coast Conference. -4342 print( -4343 "Get live scoreboard data from the CFBD API, " + -4344 "but only from the Atlantic Coast Conference." -4345 ) -4346 json_data = get_cfbd_live_scoreboard( -4347 conference="ACC", -4348 api_key=cfbd_key -4349 ) -4350 print(json_data) -4351 time.sleep(5) -4352 -4353 # You can also tell this function to just return the API call as -4354 # a Dictionary (read: JSON) object. -4355 print( -4356 "You can also tell this function to just return the API call " + -4357 "as a Dictionary (read: JSON) object." -4358 ) -4359 json_data = get_cfbd_live_scoreboard( -4360 api_key=cfbd_key, -4361 return_as_dict=True -4362 ) -4363 print(json_data) -4364 -4365 else: -4366 # Alternatively, if the CFBD API key exists in this python environment, -4367 # or it's been set by cfbd_json_py.utls.set_cfbd_api_token(), -4368 # you could just call these functions directly, -4369 # without setting the API key in the script. -4370 print( -4371 "Using the user's API key supposedly loaded " + -4372 "into this python environment for this example." -4373 ) -4374 -4375 # Get live scoreboard data from the CFBD API. -4376 print( -4377 "Get live scoreboard data from the CFBD API." -4378 ) -4379 json_data = get_cfbd_live_scoreboard() -4380 print(json_data) -4381 time.sleep(5) -4382 -4383 # Get live scoreboard data from the CFBD API, -4384 # but only from the FCS ranks. -4385 print( -4386 "Get live scoreboard data from the CFBD API, " + -4387 "but only from the FCS ranks." -4388 ) -4389 json_data = get_cfbd_live_scoreboard( -4390 ncaa_division="fcs", -4391 ) -4392 print(json_data) -4393 time.sleep(5) -4394 -4395 # Get live scoreboard data from the CFBD API, -4396 # but only from the Atlantic Coast Conference. -4397 print( -4398 "Get live scoreboard data from the CFBD API, " + -4399 "but only from the Atlantic Coast Conference." -4400 ) -4401 json_data = get_cfbd_live_scoreboard( -4402 conference="ACC", -4403 ) -4404 print(json_data) -4405 time.sleep(5) -4406 -4407 # You can also tell this function to just return the API call as -4408 # a Dictionary (read: JSON) object. -4409 print( -4410 "You can also tell this function to just return the API call " + -4411 "as a Dictionary (read: JSON) object." -4412 ) -4413 json_data = get_cfbd_live_scoreboard( -4414 return_as_dict=True -4415 ) -4416 print(json_data) -4417 -4418 ``` -4419 -4420 Returns -4421 ---------- -4422 A pandas `DataFrame` object with live scoreboard data, -4423 or (if `return_as_dict` is set to `True`) -4424 a dictionary object with live scoreboard data. -4425 -4426 """ -4427 # real_api_key = "" -4428 scoreboard_df = pd.DataFrame() -4429 url = "https://api.collegefootballdata.com/scoreboard" -4430 -4431 if api_key is not None: -4432 real_api_key = api_key -4433 del api_key -4434 else: -4435 real_api_key = get_cfbd_api_token(api_key_dir=api_key_dir) -4436 -4437 if real_api_key == "tigersAreAwesome": -4438 raise ValueError( -4439 "You actually need to change `cfbd_key` to your CFBD API key." -4440 ) -4441 elif "Bearer " in real_api_key: -4442 pass -4443 elif "Bearer" in real_api_key: -4444 real_api_key = real_api_key.replace("Bearer", "Bearer ") -4445 else: -4446 real_api_key = "Bearer " + real_api_key -4447 -4448 if ( -4449 ncaa_division.lower() == "fbs" -4450 or ncaa_division.lower() == "fcs" -4451 or ncaa_division.lower() == "ii" -4452 or ncaa_division.lower() == "iii" -4453 ): -4454 pass -4455 else: -4456 raise ValueError( -4457 "An invalid NCAA Division was inputted when calling this function." -4458 + '\nValid inputs are:\n-"fbs"\n-"fcs"\n-"ii"\n-"iii"' -4459 + f"\n\nYou entered:\n{ncaa_division}" -4460 ) -4461 -4462 url += f"?classification={ncaa_division}" -4463 -4464 if conference is not None and len(conference) > 0: -4465 url += f"&conference={conference}" -4466 -4467 headers = { -4468 "Authorization": f"{real_api_key}", -4469 "accept": "application/json" -4470 } -4471 -4472 response = requests.get(url, headers=headers) -4473 -4474 if response.status_code == 200: -4475 pass -4476 elif response.status_code == 401: -4477 raise ConnectionRefusedError( -4478 "Could not connect. The connection was refused.\n" + -4479 "HTTP Status Code 401." -4480 ) -4481 else: -4482 raise ConnectionError( -4483 f"Could not connect.\nHTTP Status code {response.status_code}" -4484 ) -4485 -4486 json_data = response.json() -4487 -4488 if return_as_dict is True: -4489 return json_data -4490 -4491 scoreboard_df = pd.json_normalize(json_data) -4492 -4493 if len(scoreboard_df) > 0: -4494 scoreboard_df.rename( -4495 columns={ -4496 "id": "game_id", -4497 "startDate": "start_datetime", -4498 "startTimeTBD": "is_start_time_tbd", -4499 "tv": "tv_network", -4500 "neutralSite": "is_neutral_site_game", -4501 "conferenceGame": "is_conference_game", -4502 "venue.name": "stadium_name", -4503 "venue.city": "stadium_city", -4504 "venue.state": "stadium_state", -4505 "homeTeam.id": "home_team_id", -4506 "homeTeam.name": "home_team_name", -4507 "homeTeam.conference": "home_team_conference", -4508 "awayTeam.id": "away_team_id", -4509 "awayTeam.name": "away_team_name", -4510 "awayTeam.conference": "away_team_conference", -4511 "weather.temperature": "weather_temperature", -4512 "weather.description": "weather_description", -4513 "weather.windSpeed": "weather_wind_speed", -4514 "weather.windDirection": "weather_wind_direction", -4515 "betting.spread": "betting_spread", -4516 "betting.overUnder": "betting_over_under", -4517 "betting.homeMoneyline": "betting_home_moneyline", -4518 "betting.awayMoneyline": "betting_away_moneyline", -4519 }, -4520 inplace=True, -4521 ) -4522 -4523 return scoreboard_df -4524 -4525 -4526def get_cfbd_weather_info( -4527 game_id: int = None, -4528 season: int = None, -4529 # `game_id` and/or `season` must be not null for this function to work. -4530 week: int = None, -4531 season_type: str = "both", # "regular", "postseason", or "both" -4532 conference: str = None, -4533 team_name: str = None, -4534 ncaa_division: str = "fbs", -4535 api_key: str = None, -4536 api_key_dir: str = None, -4537 return_as_dict: bool = False, -4538): -4539 """ -4540 YOU MUST BE SUBSCRIBED TO THE CFBD PATREON FOR THIS FUNCTION TO WORK! -4541 To view the CFBD Patreon, visit https://www.patreon.com/collegefootballdata -4542 -4543 Parameters -4544 ---------- -4545 Retrieves live scoreboard data from the CFBD API, -4546 assuming the API key is an API key from a Patreon supporter. -4547 -4548 Parameters -4549 ---------- -4550 -4551 `game_id` (int, mandatory): -4552 Mandatory requirement. -4553 Specifies the game you want weather data from. -4554 This or `season` must be set to a valid non-null value. -4555 -4556 `season` (int, mandatory): -4557 Mandatory requirement. -4558 Specifies the season you want weather data from. -4559 This or `season` must be set to a valid non-null value. -4560 -4561 `week` (int, optional): -4562 Optional argument. -4563 If `week` is set to an integer, this function will attempt -4564 to load weather data from games in that season, and in that week. -4565 -4566 `season_type` (str, semi-optional): -4567 Semi-optional argument. -4568 By default, this will be set to "both", for the CFB regular season. -4569 If you want postseason betting data, set `season_type` to "postseason". -4570 If `season_type` is set to anything but "regular" or "postseason", -4571 a `ValueError()` will be raised. -4572 -4573 `conference` (str, optional): -4574 Optional argument. -4575 If you only want weather data from games -4576 involving teams a specific conference, -4577 set `conference` to the abbreviation -4578 of the conference you want weather data from. -4579 -4580 `team_name` (str, optional): -4581 Optional argument. -4582 If you only want weather data for a team, -4583 regardless if they are the home/away team, -4584 set `team` to the name of the team -4585 you want weather data from. -4586 -4587 `ncaa_division` (str, semi-optional): -4588 Semi-optional argument. -4589 By default, `ncaa_division` will be set to "fbs", -4590 short for the Football Bowl Subdivision (FBS), -4591 formerly known as D1-A (read as "division one single A"), -4592 the highest level in the NCAA football pyramid, -4593 where teams can scholarship up to 85 players -4594 on their football team solely for athletic ability, -4595 and often have the largest athletics budgets -4596 within the NCAA. -4597 -4598 Other valid inputs are: -4599 - "fcs": Football Championship Subdivision (FCS), -4600 formerly known as D1-AA (read as "division one double A"). -4601 An FCS school is still in the 1st division of the NCAA, -4602 making them eligible for the March Madness tournament, -4603 but may not have the resources to compete at the FBS level -4604 at this time. FCS schools are limited to 63 athletic scholarships -4605 for football. -4606 - "ii": NCAA Division II. Schools in this and D3 are not -4607 eligible for the March Madness tournament, -4608 and are limited to 36 athletic scholarships -4609 for their football team. -4610 - "iii": NCAA Division III. The largest single division within the -4611 NCAA football pyramid. -4612 D3 schools have the distinction of being part of -4613 the only NCAA division that cannot give out scholarships solely -4614 for athletic ability. -4615 -4616 `api_key` (str, optional): -4617 Semi-optional argument. -4618 If `api_key` is null, this function will attempt to load a CFBD API key -4619 from the python environment, or from a file on this computer. -4620 If `api_key` is not null, -4621 this function will automatically assume that the -4622 inputted `api_key` is a valid CFBD API key. -4623 -4624 `api_key_dir` (str, optional): -4625 Optional argument. -4626 If `api_key` is set to am empty string, this variable is ignored. -4627 If `api_key_dir` is null, and `api_key` is null, -4628 this function will try to find -4629 a CFBD API key file in this user's home directory. -4630 If `api_key_dir` is set to a string, and `api_key` is null, -4631 this function will assume that `api_key_dir` is a directory, -4632 and will try to find a CFBD API key file in that directory. -4633 -4634 `return_as_dict` (bool, semi-optional): -4635 Semi-optional argument. -4636 If you want this function to return -4637 the data as a dictionary (read: JSON object), -4638 instead of a pandas `DataFrame` object, -4639 set `return_as_dict` to `True`. -4640 Usage -4641 ---------- -4642 ``` -4643 import time -4644 -4645 from cfbd_json_py.games import get_cfbd_weather_info -4646 -4647 -4648 cfbd_key = "tigersAreAwesome" # placeholder for your CFBD API Key. -4649 -4650 if cfbd_key != "tigersAreAwesome": -4651 print( -4652 "Using the user's API key declared " + -4653 "in this script for this example." -4654 ) -4655 -4656 # Get weather data for the 2024 CFB season -4657 print( -4658 "Get weather data for the 2024 CFB season." -4659 ) -4660 json_data = get_cfbd_weather_info( -4661 season=2024, -4662 api_key=cfbd_key -4663 ) -4664 print(json_data) -4665 time.sleep(5) -4666 -4667 # Get weather data for the 2024 Rose Bowl (game ID #401551786). -4668 print( -4669 "Get weather data for the 2024 Rose Bowl (game ID #401551786)." -4670 ) -4671 json_data = get_cfbd_weather_info( -4672 game_id=401551786, -4673 api_key=cfbd_key -4674 ) -4675 print(json_data) -4676 time.sleep(5) -4677 -4678 # Get weather data for week 1 of the 2024 CFB season -4679 print( -4680 "Get weather data for week 1 of the 2024 CFB season." -4681 ) -4682 json_data = get_cfbd_weather_info( -4683 season=2024, -4684 week=1, -4685 api_key=cfbd_key -4686 ) -4687 print(json_data) -4688 time.sleep(5) -4689 -4690 # Get weather data for postseason games of the 2023 CFB season. -4691 print( -4692 "Get weather data for postseason games of the 2023 CFB season." -4693 ) -4694 json_data = get_cfbd_weather_info( -4695 season=2023, -4696 season_type="postseason", -4697 api_key=cfbd_key -4698 ) -4699 print(json_data) -4700 time.sleep(5) -4701 -4702 # Get weather data for postseason games of the 2023 CFB season. -4703 print( -4704 "Get weather data for postseason games of the 2023 CFB season." -4705 ) -4706 json_data = get_cfbd_weather_info( -4707 season=2023, -4708 season_type="postseason", -4709 api_key=cfbd_key -4710 ) -4711 print(json_data) -4712 time.sleep(5) -4713 -4714 # Get weather data for Big 10 (B1G) games of the 2024 CFB season. -4715 print( -4716 "Get weather data for Big 10 (B1G) games of the 2024 CFB season." -4717 ) -4718 json_data = get_cfbd_weather_info( -4719 season=2024, -4720 conference="B1G", -4721 api_key=cfbd_key -4722 ) -4723 print(json_data) -4724 time.sleep(5) -4725 -4726 # Get weather data for FCS games of the 2024 CFB season. -4727 print( -4728 "Get weather data for FCS games of the 2024 CFB season." -4729 ) -4730 json_data = get_cfbd_weather_info( -4731 season=2024, -4732 ncaa_division="fcs", -4733 api_key=cfbd_key -4734 ) -4735 print(json_data) -4736 time.sleep(5) -4737 -4738 # Get weather data for University of Cincinnati games -4739 # of the 2024 CFB season. -4740 print( -4741 "Get weather data for Big 10 (B1G) games of the 2024 CFB season." -4742 ) -4743 json_data = get_cfbd_weather_info( -4744 season=2024, -4745 team_name="Cincinnati", -4746 api_key=cfbd_key -4747 ) -4748 print(json_data) -4749 time.sleep(5) -4750 -4751 # You can also tell this function to just return the API call -4752 # as a Dictionary (read: JSON) object. -4753 print( -4754 "You can also tell this function to just return the API call " + -4755 "as a Dictionary (read: JSON) object." -4756 ) -4757 json_data = get_cfbd_weather_info( -4758 api_key=cfbd_key, -4759 season=2023, -4760 return_as_dict=True -4761 ) -4762 print(json_data) -4763 -4764 else: -4765 # Alternatively, if the CFBD API key exists in this python environment, -4766 # or it's been set by cfbd_json_py.utls.set_cfbd_api_token(), -4767 # you could just call these functions directly, -4768 # without setting the API key in the script. -4769 print( -4770 "Using the user's API key supposedly loaded " + -4771 "into this python environment for this example." -4772 ) -4773 -4774 # Get weather data for the 2024 CFB season -4775 print( -4776 "Get weather data for the 2024 CFB season." -4777 ) -4778 json_data = get_cfbd_weather_info( -4779 season=2024 -4780 ) -4781 print(json_data) -4782 time.sleep(5) -4783 -4784 # Get weather data for the 2024 Rose Bowl (game ID #401551786). -4785 print( -4786 "Get weather data for the 2024 Rose Bowl (game ID #401551786)." -4787 ) -4788 json_data = get_cfbd_weather_info( -4789 game_id=401551786 -4790 ) -4791 print(json_data) -4792 time.sleep(5) -4793 -4794 # Get weather data for week 1 of the 2024 CFB season -4795 print( -4796 "Get weather data for week 1 of the 2024 CFB season." -4797 ) -4798 json_data = get_cfbd_weather_info( -4799 season=2024, -4800 week=1 -4801 ) -4802 print(json_data) -4803 time.sleep(5) -4804 -4805 # Get weather data for postseason games of the 2023 CFB season. -4806 print( -4807 "Get weather data for postseason games of the 2023 CFB season." -4808 ) -4809 json_data = get_cfbd_weather_info( -4810 season=2023, -4811 season_type="postseason" -4812 ) -4813 print(json_data) -4814 time.sleep(5) -4815 -4816 # Get weather data for postseason games of the 2023 CFB season. -4817 print( -4818 "Get weather data for postseason games of the 2023 CFB season." -4819 ) -4820 json_data = get_cfbd_weather_info( -4821 season=2023, -4822 season_type="postseason" -4823 ) -4824 print(json_data) -4825 time.sleep(5) -4826 -4827 # Get weather data for Big 10 (B1G) games of the 2024 CFB season. -4828 print( -4829 "Get weather data for Big 10 (B1G) games of the 2024 CFB season." -4830 ) -4831 json_data = get_cfbd_weather_info( -4832 season=2024, -4833 conference="B1G" -4834 ) -4835 print(json_data) -4836 time.sleep(5) -4837 -4838 # Get weather data for FCS games of the 2024 CFB season. -4839 print( -4840 "Get weather data for FCS games of the 2024 CFB season." -4841 ) -4842 json_data = get_cfbd_weather_info( -4843 season=2024, -4844 ncaa_division="fcs" -4845 ) -4846 print(json_data) -4847 time.sleep(5) -4848 -4849 # Get weather data for University of Cincinnati games -4850 # of the 2024 CFB season. -4851 print( -4852 "Get weather data for Big 10 (B1G) games of the 2024 CFB season." -4853 ) -4854 json_data = get_cfbd_weather_info( -4855 season=2024, -4856 team_name="Cincinnati" -4857 ) -4858 print(json_data) -4859 time.sleep(5) -4860 -4861 # You can also tell this function to just return the API call -4862 # as a Dictionary (read: JSON) object. -4863 print( -4864 "You can also tell this function to just return the API call " + -4865 "as a Dictionary (read: JSON) object." -4866 ) -4867 json_data = get_cfbd_weather_info( -4868 season=2023, -4869 return_as_dict=True -4870 ) -4871 print(json_data) -4872 -4873 ``` -4874 Returns -4875 ---------- -4876 A pandas `DataFrame` object with live weather data, -4877 or (if `return_as_dict` is set to `True`) -4878 a dictionary object with live weather data. -4879 -4880 """ -4881 -4882 weather_df = pd.DataFrame() -4883 url = "https://api.collegefootballdata.com/games/weather" -4884 -4885 if api_key is not None: -4886 real_api_key = api_key -4887 del api_key -4888 else: -4889 real_api_key = get_cfbd_api_token(api_key_dir=api_key_dir) -4890 -4891 if real_api_key == "tigersAreAwesome": -4892 raise ValueError( -4893 "You actually need to change `cfbd_key` to your CFBD API key." -4894 ) -4895 elif "Bearer " in real_api_key: -4896 pass -4897 elif "Bearer" in real_api_key: -4898 real_api_key = real_api_key.replace("Bearer", "Bearer ") -4899 else: -4900 real_api_key = "Bearer " + real_api_key -4901 -4902 if (game_id is None) and (season is None): -4903 raise ValueError( -4904 "`game_id` and/or `season` must be set to valid, non-null values." -4905 ) -4906 elif (game_id is not None) and (season is not None): -4907 url += f"?gameId={game_id}&year={season}" -4908 elif game_id is not None: -4909 url += f"?gameId={game_id}" -4910 elif season is not None: -4911 url += f"?year={season}" -4912 -4913 if (ncaa_division is not None) and ( -4914 ncaa_division.lower() == "fbs" -4915 or ncaa_division.lower() == "fcs" -4916 or ncaa_division.lower() == "ii" -4917 or ncaa_division.lower() == "iii" -4918 ): -4919 ncaa_division = ncaa_division.lower() -4920 url += f"&classification={ncaa_division}" -4921 else: -4922 raise ValueError( -4923 "An invalid NCAA Division was inputted when calling this function." -4924 + '\nValid inputs are:\n-"fbs"\n-"fcs"\n-"ii"\n-"iii"' -4925 + f"\n\nYou entered:\n{ncaa_division}" -4926 ) -4927 -4928 if week is not None: -4929 url += f"&week={week}" -4930 -4931 if ( -4932 season_type == "regular" or -4933 season_type == "postseason" or -4934 season_type == "both" -4935 ): -4936 url += f"&seasonType={season_type}" -4937 elif season_type is not None: -4938 raise ValueError( -4939 '`season_type` must be set to either "regular", ' -4940 + '"postseason", or "both" if you want to specify ' -4941 + "a part of the season." -4942 ) -4943 -4944 if team_name is not None: -4945 url += f"&team={team_name}" -4946 -4947 if conference is not None: -4948 url += f"&conference={conference}" -4949 -4950 headers = { -4951 "Authorization": f"{real_api_key}", -4952 "accept": "application/json" -4953 } -4954 -4955 response = requests.get(url, headers=headers) -4956 -4957 if response.status_code == 200: -4958 pass -4959 elif response.status_code == 401: -4960 raise ConnectionRefusedError( -4961 "Could not connect. The connection was refused.\n" + -4962 "HTTP Status Code 401." -4963 ) -4964 else: -4965 raise ConnectionError( -4966 f"Could not connect.\nHTTP Status code {response.status_code}" -4967 ) -4968 -4969 json_data = response.json() -4970 -4971 if return_as_dict is True: -4972 return json_data -4973 -4974 weather_df = pd.json_normalize(json_data) -4975 # print(weather_df.columns) -4976 -4977 [ -4978 "weatherConditionCode", -4979 "weatherCondition", -4980 ] -4981 if len(weather_df) > 0: -4982 weather_df.rename( -4983 columns={ -4984 "id": "game_id", -4985 "startTime": "start_datetime", -4986 "seasonType": "season_type", -4987 "gameIndoors": "is_game_indoors", -4988 "homeTeam": "home_team_name", -4989 "homeConference": "home_team_conference", -4990 "awayTeam": "away_team_name", -4991 "awayConference": "away_team_conference", -4992 "venueId": "venue_id", -4993 "venue": "venue_name", -4994 "windDirection": "wind_direction", -4995 "windSpeed": "wind_speed", -4996 "weatherConditionCode": "weather_condition_code", -4997 "weatherCondition": "weather_condition", -4998 }, -4999 inplace=True, -5000 ) -5001 -5002 return weather_df +3483 [ +3484 "weatherConditionCode", +3485 "weatherCondition", +3486 ] +3487 if len(weather_df) > 0: +3488 weather_df.rename( +3489 columns={ +3490 "id": "game_id", +3491 "startTime": "start_datetime", +3492 "seasonType": "season_type", +3493 "gameIndoors": "is_game_indoors", +3494 "homeTeam": "home_team_name", +3495 "homeConference": "home_team_conference", +3496 "awayTeam": "away_team_name", +3497 "awayConference": "away_team_conference", +3498 "venueId": "venue_id", +3499 "venue": "venue_name", +3500 "windDirection": "wind_direction", +3501 "windSpeed": "wind_speed", +3502 "weatherConditionCode": "weather_condition_code", +3503 "weatherCondition": "weather_condition", +3504 }, +3505 inplace=True, +3506 ) +3507 +3508 return weather_df @@ -6541,515 +5047,515 @@

-
 19def get_cfbd_games(
- 20    api_key: str = None,
- 21    api_key_dir: str = None,
- 22    season: int = None,
- 23    season_type: str = "regular",
- 24    week: int = None,
- 25    team: str = None,
- 26    home_team: str = None,
- 27    away_team: str = None,
- 28    conference: str = None,
- 29    ncaa_division: str = "fbs",
- 30    game_id: int = None,
- 31    return_as_dict: bool = False,
- 32):
- 33    """
- 34    Retrieves game schedule data from the CFBD API.
- 35
- 36    Parameters
- 37    ----------
- 38    `season` (int, mandatory):
- 39        Required argument.
- 40        Specifies the season you want CFB game information from.
- 41        This must be specified, otherwise this package, and by extension
- 42        the CFBD API, will not accept the request to get CFB game information.
- 43
- 44    `api_key` (str, optional):
- 45        Semi-optional argument.
- 46        If `api_key` is null, this function will attempt to load a CFBD API key
- 47        from the python environment, or from a file on this computer.
- 48        If `api_key` is not null,
- 49        this function will automatically assume that the
- 50        inputted `api_key` is a valid CFBD API key.
- 51
- 52    `api_key_dir` (str, optional):
- 53        Optional argument.
- 54        If `api_key` is set to am empty string, this variable is ignored.
- 55        If `api_key_dir` is null, and `api_key` is null,
- 56        this function will try to find
- 57        a CFBD API key file in this user's home directory.
- 58        If `api_key_dir` is set to a string, and `api_key` is null,
- 59        this function will assume that `api_key_dir` is a directory,
- 60        and will try to find a CFBD API key file in that directory.
- 61
- 62    `season_type` (str, semi-optional):
- 63        Semi-optional argument.
- 64        By default, this will be set to "regular", for the CFB regular season.
- 65        If you want CFB game information for non-regular season games,
- 66        set `season_type` to "postseason".
- 67        If `season_type` is set to anything but "regular" or "postseason",
- 68        a `ValueError()` will be raised.
- 69
- 70    `week` (int, optional):
- 71        Optional argument.
- 72        If `week` is set to an integer, this function will attempt
- 73        to load CFB game data from games in that season, and in that week.
- 74
- 75    `team` (str, optional):
- 76        Optional argument.
- 77        If you only want CFB game information for a team,
- 78        regardless if they are the home/away team,
- 79        set `team` to the name of the team you want CFB game information from.
- 80
- 81    `home_team` (str, optional):
- 82        Optional argument.
- 83        If you only want game information for a team,
- 84        where that team was the home team in this season,
- 85        set `home_team` to the name of the team you want game information for.
- 86
- 87    `away_team` (str, optional):
- 88        Optional argument.
- 89        If you only want game information for a team,
- 90        where that team was the away team in this season,
- 91        set `away_team` to the name of the team you want game information for.
- 92
- 93    `conference` (str, optional):
- 94        Optional argument.
- 95        If you only want game information from games
- 96        involving teams a specific conference,
- 97        set `conference` to the abbreviation
- 98        of the conference you want game information from.
- 99
-100    `ncaa_division` (str, semi-optional):
-101        Semi-optional argument.
-102        By default, `ncaa_division` will be set to "fbs",
-103        short for the Football Bowl Subdivision (FBS),
-104        formerly known as D1-A (read as "division one single A"),
-105        the highest level in the NCAA football pyramid,
-106        where teams can scholarship up to 85 players
-107        on their football team solely for athletic ability,
-108        and often have the largest athletics budgets
-109        within the NCAA.
-110
-111        Other valid inputs are:
-112        - "fcs": Football Championship Subdivision (FCS),
-113            formerly known as D1-AA (read as "division one double A").
-114            An FCS school is still in the 1st division of the NCAA,
-115            making them eligible for the March Madness tournament,
-116            but may not have the resources to compete at the FBS level
-117            at this time. FCS schools are limited to 63 athletic scholarships
-118            for football.
-119        - "ii": NCAA Division II. Schools in this and D3 are not
-120            eligible for the March Madness tournament,
-121            and are limited to 36 athletic scholarships
-122            for their football team.
-123        - "iii": NCAA Division III. The largest single division within the
-124            NCAA football pyramid.
-125            D3 schools have the distinction of being part of
-126            the only NCAA division that cannot give out scholarships solely
-127            for athletic ability.
-128
-129    `game_id` (int, optional):
-130        Optional argument.
-131        If `game_id` is set to a game ID,
-132        `get_cfb_betting_lines()` will try to get
-133        game information just for that game ID.
-134
-135    `return_as_dict` (bool, semi-optional):
-136        Semi-optional argument.
-137        If you want this function to return
-138        the data as a dictionary (read: JSON object),
-139        instead of a pandas `DataFrame` object,
-140        set `return_as_dict` to `True`.
-141
-142    Usage
-143    ----------
-144    ```
-145    import time
-146
-147    from cfbd_json_py.games import get_cfbd_games
-148
+                
 20def get_cfbd_games(
+ 21    api_key: str = None,
+ 22    api_key_dir: str = None,
+ 23    season: int = None,
+ 24    season_type: str = "regular",
+ 25    week: int = None,
+ 26    team: str = None,
+ 27    home_team: str = None,
+ 28    away_team: str = None,
+ 29    conference: str = None,
+ 30    ncaa_division: str = "fbs",
+ 31    game_id: int = None,
+ 32    return_as_dict: bool = False,
+ 33):
+ 34    """
+ 35    Retrieves game schedule data from the CFBD API.
+ 36
+ 37    Parameters
+ 38    ----------
+ 39    `season` (int, mandatory):
+ 40        Required argument.
+ 41        Specifies the season you want CFB game information from.
+ 42        This must be specified, otherwise this package, and by extension
+ 43        the CFBD API, will not accept the request to get CFB game information.
+ 44
+ 45    `api_key` (str, optional):
+ 46        Semi-optional argument.
+ 47        If `api_key` is null, this function will attempt to load a CFBD API key
+ 48        from the python environment, or from a file on this computer.
+ 49        If `api_key` is not null,
+ 50        this function will automatically assume that the
+ 51        inputted `api_key` is a valid CFBD API key.
+ 52
+ 53    `api_key_dir` (str, optional):
+ 54        Optional argument.
+ 55        If `api_key` is set to am empty string, this variable is ignored.
+ 56        If `api_key_dir` is null, and `api_key` is null,
+ 57        this function will try to find
+ 58        a CFBD API key file in this user's home directory.
+ 59        If `api_key_dir` is set to a string, and `api_key` is null,
+ 60        this function will assume that `api_key_dir` is a directory,
+ 61        and will try to find a CFBD API key file in that directory.
+ 62
+ 63    `season_type` (str, semi-optional):
+ 64        Semi-optional argument.
+ 65        By default, this will be set to "regular", for the CFB regular season.
+ 66        If you want CFB game information for non-regular season games,
+ 67        set `season_type` to "postseason".
+ 68        If `season_type` is set to anything but "regular" or "postseason",
+ 69        a `ValueError()` will be raised.
+ 70
+ 71    `week` (int, optional):
+ 72        Optional argument.
+ 73        If `week` is set to an integer, this function will attempt
+ 74        to load CFB game data from games in that season, and in that week.
+ 75
+ 76    `team` (str, optional):
+ 77        Optional argument.
+ 78        If you only want CFB game information for a team,
+ 79        regardless if they are the home/away team,
+ 80        set `team` to the name of the team you want CFB game information from.
+ 81
+ 82    `home_team` (str, optional):
+ 83        Optional argument.
+ 84        If you only want game information for a team,
+ 85        where that team was the home team in this season,
+ 86        set `home_team` to the name of the team you want game information for.
+ 87
+ 88    `away_team` (str, optional):
+ 89        Optional argument.
+ 90        If you only want game information for a team,
+ 91        where that team was the away team in this season,
+ 92        set `away_team` to the name of the team you want game information for.
+ 93
+ 94    `conference` (str, optional):
+ 95        Optional argument.
+ 96        If you only want game information from games
+ 97        involving teams a specific conference,
+ 98        set `conference` to the abbreviation
+ 99        of the conference you want game information from.
+100
+101    `ncaa_division` (str, semi-optional):
+102        Semi-optional argument.
+103        By default, `ncaa_division` will be set to "fbs",
+104        short for the Football Bowl Subdivision (FBS),
+105        formerly known as D1-A (read as "division one single A"),
+106        the highest level in the NCAA football pyramid,
+107        where teams can scholarship up to 85 players
+108        on their football team solely for athletic ability,
+109        and often have the largest athletics budgets
+110        within the NCAA.
+111
+112        Other valid inputs are:
+113        - "fcs": Football Championship Subdivision (FCS),
+114            formerly known as D1-AA (read as "division one double A").
+115            An FCS school is still in the 1st division of the NCAA,
+116            making them eligible for the March Madness tournament,
+117            but may not have the resources to compete at the FBS level
+118            at this time. FCS schools are limited to 63 athletic scholarships
+119            for football.
+120        - "ii": NCAA Division II. Schools in this and D3 are not
+121            eligible for the March Madness tournament,
+122            and are limited to 36 athletic scholarships
+123            for their football team.
+124        - "iii": NCAA Division III. The largest single division within the
+125            NCAA football pyramid.
+126            D3 schools have the distinction of being part of
+127            the only NCAA division that cannot give out scholarships solely
+128            for athletic ability.
+129
+130    `game_id` (int, optional):
+131        Optional argument.
+132        If `game_id` is set to a game ID,
+133        `get_cfb_betting_lines()` will try to get
+134        game information just for that game ID.
+135
+136    `return_as_dict` (bool, semi-optional):
+137        Semi-optional argument.
+138        If you want this function to return
+139        the data as a dictionary (read: JSON object),
+140        instead of a pandas `DataFrame` object,
+141        set `return_as_dict` to `True`.
+142
+143    Usage
+144    ----------
+145    ```
+146    import time
+147
+148    from cfbd_json_py.games import get_cfbd_games
 149
-150    cfbd_key = "tigersAreAwesome"  # placeholder for your CFBD API Key.
-151
-152    if cfbd_key is not "tigersAreAwesome":
-153        print(
-154            "Using the user's API key declared in this script " +
-155            "for this example."
-156        )
-157
-158        # Get CFB games from the 2020 CFB season.
-159        print("Get CFB games from the 2020 CFB season.")
-160        json_data = get_cfbd_games(
-161            api_key=cfbd_key,
-162            season=2020
-163        )
-164        print(json_data)
-165        time.sleep(5)
-166
-167        # Get CFB games from week 10 of the 2020 CFB season.
-168        print("Get CFB games from week 10 of the 2020 CFB season.")
-169        json_data = get_cfbd_games(
-170            api_key=cfbd_key,
-171            season=2020,
-172            week=10
-173        )
-174        print(json_data)
-175        time.sleep(5)
-176
-177        # Get CFB games from the 2019 CFB season
-178        # that involved the 2019 LSU Tigers.
-179        print(
-180            "Get CFB games from the 2019 CFB season " +
-181            "that involved the 2019 LSU Tigers."
-182        )
-183        json_data = get_cfbd_games(
-184            api_key=cfbd_key,
-185            season=2019,
-186            team="LSU"
-187        )
-188        print(json_data)
-189        time.sleep(5)
-190
-191        # Get 2021 Cincinnati Bearcats Football games
-192        # where the Bearcats were the home team.
-193        print(
-194            "Get 2021 Cincinnati Bearcats Football games " +
-195            "where the Bearcats were the home team."
-196        )
-197        json_data = get_cfbd_games(
-198            api_key=cfbd_key,
-199            season=2021,
-200            home_team="Cincinnati"
-201        )
-202        print(json_data)
-203        time.sleep(5)
-204
-205        # Get 2018 Ohio Bobcats Football games
-206        # where the Bobcats were the away team.
-207        print(
-208            "Get 2018 Ohio Bobcats Football games " +
-209            "where the Bobcats were the away team."
-210        )
-211        json_data = get_cfbd_games(
-212            api_key=cfbd_key,
-213            season=2019,
-214            away_team="Ohio"
-215        )
-216        print(json_data)
-217        time.sleep(5)
-218
-219        # Get 2022 college football games where one or more teams competing
-220        # was a Football Championship Subdivision team.
-221        print(
-222            "Get 2022 college football games where one or more " +
-223            "teams competing was a Football Championship Subdivision team."
-224        )
-225        json_data = get_cfbd_games(
-226            api_key=cfbd_key,
-227            season=2018,
-228            away_team="Ohio"
-229        )
-230        print(json_data)
-231        time.sleep(5)
-232
-233        # Get game information for the
-234        # 2021 American Athletic conference (AAC) Championship Game.
-235        print(
-236            "Get game information for " +
-237            "the 2021 American Athletic conference (AAC) Championship Game."
-238        )
-239        json_data = get_cfbd_games(
-240            api_key=cfbd_key,
-241            season=2018,
-242            game_id=401331162
-243        )
-244        print(json_data)
-245        time.sleep(5)
-246
-247        # You can also tell this function to just return the API call as
-248        # a Dictionary (read: JSON) object.
-249        print(
-250            "You can also tell this function to just return the API call " +
-251            "as a Dictionary (read: JSON) object."
-252        )
-253        json_data = get_cfbd_games(
-254            season=2020,
-255            week=10,
-256            api_key=cfbd_key,
-257            return_as_dict=True
-258        )
-259        print(json_data)
-260
-261    else:
-262        # Alternatively, if the CFBD API key exists in this python environment,
-263        # or it's been set by cfbd_json_py.utls.set_cfbd_api_token(),
-264        # you could just call these functions directly,
-265        # without setting the API key in the script.
-266        print(
-267            "Using the user's API key supposedly loaded " +
-268            "into this python environment for this example."
-269        )
-270
-271        # Get CFB games from the 2020 CFB season.
-272        print("Get CFB games from the 2020 CFB season.")
-273        json_data = get_cfbd_games(
-274            season=2020
-275        )
-276        print(json_data)
-277        time.sleep(5)
-278
-279        # Get CFB games from week 10 of the 2020 CFB season.
-280        print("Get CFB games from week 10 of the 2020 CFB season.")
-281        json_data = get_cfbd_games(
-282            season=2020,
-283            week=10
-284        )
-285        print(json_data)
-286        time.sleep(5)
-287
-288        # Get CFB games from the 2019 CFB season
-289        # that involved the 2019 LSU Tigers.
-290        print(
-291            "Get CFB games from the 2019 CFB season " +
-292            "that involved the 2019 LSU Tigers."
-293        )
-294        json_data = get_cfbd_games(
-295            season=2019,
-296            team="LSU"
-297        )
-298        print(json_data)
-299        time.sleep(5)
-300
-301        # Get 2021 Cincinnati Bearcats Football games
-302        # where the Bearcats were the home team.
-303        print(
-304            "Get 2021 Cincinnati Bearcats Football games " +
-305            "where the Bearcats were the home team."
-306        )
-307        json_data = get_cfbd_games(
-308            season=2021,
-309            home_team="Cincinnati"
-310        )
-311        print(json_data)
-312        time.sleep(5)
-313
-314        # Get 2018 Ohio Bobcats Football games
-315        # where the Bobcats were the away team.
-316        print(
-317            "Get 2018 Ohio Bobcats Football games " +
-318            "where the Bobcats were the away team."
-319        )
-320        json_data = get_cfbd_games(
-321            season=2019,
-322            away_team="Ohio"
-323        )
-324        print(json_data)
-325        time.sleep(5)
-326
-327        # Get 2018 Ohio Bobcats Football games
-328        # where the Bobcats were the away team.
-329        print(
-330            "Get 2018 Ohio Bobcats Football games " +
-331            "where the Bobcats were the away team."
-332        )
-333        json_data = get_cfbd_games(
-334            season=2018,
-335            away_team="Ohio"
-336        )
-337        print(json_data)
-338        time.sleep(5)
-339
-340        # Get 2022 college football games where one or more teams competing
-341        # was a Football Championship Subdivision team.
-342        print(
-343            "Get 2022 college football games where one or more " +
-344            "teams competing was a Football Championship Subdivision team."
-345        )
-346        json_data = get_cfbd_games(
-347            season=2018,
-348            away_team="Ohio"
-349        )
-350        print(json_data)
-351        time.sleep(5)
-352
-353        # Get game information for the
-354        # 2021 American Athletic conference (AAC) Championship Game.
-355        print(
-356            "Get game information for " +
-357            "the 2021 American Athletic conference (AAC) Championship Game."
-358        )
-359        json_data = get_cfbd_games(
-360            season=2018,
-361            game_id=401331162
-362        )
-363        print(json_data)
-364        time.sleep(5)
-365
-366        # You can also tell this function to just return the API call as
-367        # a Dictionary (read: JSON) object.
-368        print(
-369            "You can also tell this function to just return the API call " +
-370            "as a Dictionary (read: JSON) object."
-371        )
-372        json_data = get_cfbd_games(
-373            season=2020,
-374            week=10,
-375            return_as_dict=True
-376        )
-377        print(json_data)
-378
-379    ```
-380    Returns
-381    ----------
-382    A pandas `DataFrame` object with college football game information,
-383    or (if `return_as_dict` is set to `True`)
-384    a dictionary object with college football game information.
-385    """
-386
-387    now = datetime.now()
-388    cfb_games_df = pd.DataFrame()
-389    url = "https://api.collegefootballdata.com/games"
-390
-391    ##########################################################################
-392
-393    if api_key is not None:
-394        real_api_key = api_key
-395        del api_key
-396    else:
-397        real_api_key = get_cfbd_api_token(api_key_dir=api_key_dir)
-398
-399    if real_api_key == "tigersAreAwesome":
-400        raise ValueError(
-401            "You actually need to change `cfbd_key` to your CFBD API key."
-402        )
-403    elif "Bearer " in real_api_key:
-404        pass
-405    elif "Bearer" in real_api_key:
-406        real_api_key = real_api_key.replace("Bearer", "Bearer ")
-407    else:
-408        real_api_key = "Bearer " + real_api_key
-409
-410    if season is None:
-411        # This should never happen without user tampering, but if it does,
-412        # we need to raise an error,
-413        # because the CFBD API will refuse this call without a valid season.
-414        raise SystemError(
-415            "I don't know how, I don't know why, "
-416            + "but you managed to call this function "
-417            + "while `season` was `None` (NULL),"
-418            + " and the function got to this point in the code."
-419            + "\nIf you have a GitHub account, "
-420            + "please raise an issue on this python package's GitHub page:\n"
-421            + "https://github.com/armstjc/cfbd-json-py/issues"
-422        )
-423    elif season > (now.year + 1):
-424        raise ValueError(f"`season` cannot be greater than {season}.")
-425    elif season < 1869:
-426        raise ValueError("`season` cannot be less than 1869.")
-427
-428    if season_type != "regular" and season_type != "postseason":
-429        raise ValueError(
-430            "`season_type` must be set to either "
-431            + '"regular" or "postseason" for this function to work.'
-432        )
-433
-434    if (
-435        ncaa_division.lower() == "fbs"
-436        or ncaa_division.lower() == "fcs"
-437        or ncaa_division.lower() == "ii"
-438        or ncaa_division.lower() == "iii"
-439    ):
-440        pass
-441    else:
-442        raise ValueError(
-443            "An invalid NCAA Division was inputted when calling this function."
-444            + '\nValid inputs are:\n-"fbs"\n-"fcs"\n-"ii"\n-"iii"'
-445            + f"\n\nYou entered: \n{ncaa_division}"
-446        )
-447
-448    # URL builder
-449    ##########################################################################
-450
-451    # Required by API
-452    url += f"?seasonType={season_type}"
-453
-454    if game_id is not None:
-455        url += f"&year={season}"
-456        url += f"&id={game_id}"
-457
-458        if (
-459            team is not None
-460            or home_team is not None
-461            or away_team is not None
-462            or conference is not None
-463            or week is not None
-464        ):
-465            logging.warning(
-466                "When calling `cfbd_json_py.games.get_cfbd_games()`, "
-467                + "and setting `game_id` to a non-null value, "
-468                + "only `season` and `game_id` are considered "
-469                + "when calling the CFBD API."
-470            )
-471
-472    else:
-473        url += f"&year={season}"
-474
-475        # Optional for the API
-476        if week is not None:
-477            url += f"&week={week}"
-478
-479        if team is not None:
-480            url += f"&team={team}"
-481
-482        if home_team is not None:
-483            url += f"&home={home_team}"
-484
-485        if away_team is not None:
-486            url += f"&away={away_team}"
-487
-488        if conference is not None:
-489            url += f"&conference={conference}"
-490
-491        if ncaa_division is not None:
-492            url += f"&division={ncaa_division}"
-493
-494    headers = {
-495        "Authorization": f"{real_api_key}",
-496        "accept": "application/json"
-497    }
-498
-499    response = requests.get(url, headers=headers)
-500
-501    if response.status_code == 200:
-502        pass
-503    elif response.status_code == 401:
-504        raise ConnectionRefusedError(
-505            "Could not connect. The connection was refused." +
-506            "\nHTTP Status Code 401."
-507        )
-508    else:
-509        raise ConnectionError(
-510            f"Could not connect.\nHTTP Status code {response.status_code}"
-511        )
-512
-513    json_data = response.json()
-514
-515    if return_as_dict is True:
-516        return json_data
-517
-518    cfb_games_df = pd.json_normalize(json_data)
-519    # print(cfb_games_df.columns)
-520    if len(cfb_games_df) == 0:
-521        logging.error(
-522            "The CFBD API accepted your inputs, "
-523            + "but found no data within your specified input parameters."
-524            + " Please double check your input parameters."
-525        )
-526
-527    return cfb_games_df
+150
+151    cfbd_key = "tigersAreAwesome"  # placeholder for your CFBD API Key.
+152
+153    if cfbd_key is not "tigersAreAwesome":
+154        print(
+155            "Using the user's API key declared in this script " +
+156            "for this example."
+157        )
+158
+159        # Get CFB games from the 2020 CFB season.
+160        print("Get CFB games from the 2020 CFB season.")
+161        json_data = get_cfbd_games(
+162            api_key=cfbd_key,
+163            season=2020
+164        )
+165        print(json_data)
+166        time.sleep(5)
+167
+168        # Get CFB games from week 10 of the 2020 CFB season.
+169        print("Get CFB games from week 10 of the 2020 CFB season.")
+170        json_data = get_cfbd_games(
+171            api_key=cfbd_key,
+172            season=2020,
+173            week=10
+174        )
+175        print(json_data)
+176        time.sleep(5)
+177
+178        # Get CFB games from the 2019 CFB season
+179        # that involved the 2019 LSU Tigers.
+180        print(
+181            "Get CFB games from the 2019 CFB season " +
+182            "that involved the 2019 LSU Tigers."
+183        )
+184        json_data = get_cfbd_games(
+185            api_key=cfbd_key,
+186            season=2019,
+187            team="LSU"
+188        )
+189        print(json_data)
+190        time.sleep(5)
+191
+192        # Get 2021 Cincinnati Bearcats Football games
+193        # where the Bearcats were the home team.
+194        print(
+195            "Get 2021 Cincinnati Bearcats Football games " +
+196            "where the Bearcats were the home team."
+197        )
+198        json_data = get_cfbd_games(
+199            api_key=cfbd_key,
+200            season=2021,
+201            home_team="Cincinnati"
+202        )
+203        print(json_data)
+204        time.sleep(5)
+205
+206        # Get 2018 Ohio Bobcats Football games
+207        # where the Bobcats were the away team.
+208        print(
+209            "Get 2018 Ohio Bobcats Football games " +
+210            "where the Bobcats were the away team."
+211        )
+212        json_data = get_cfbd_games(
+213            api_key=cfbd_key,
+214            season=2019,
+215            away_team="Ohio"
+216        )
+217        print(json_data)
+218        time.sleep(5)
+219
+220        # Get 2022 college football games where one or more teams competing
+221        # was a Football Championship Subdivision team.
+222        print(
+223            "Get 2022 college football games where one or more " +
+224            "teams competing was a Football Championship Subdivision team."
+225        )
+226        json_data = get_cfbd_games(
+227            api_key=cfbd_key,
+228            season=2018,
+229            away_team="Ohio"
+230        )
+231        print(json_data)
+232        time.sleep(5)
+233
+234        # Get game information for the
+235        # 2021 American Athletic conference (AAC) Championship Game.
+236        print(
+237            "Get game information for " +
+238            "the 2021 American Athletic conference (AAC) Championship Game."
+239        )
+240        json_data = get_cfbd_games(
+241            api_key=cfbd_key,
+242            season=2018,
+243            game_id=401331162
+244        )
+245        print(json_data)
+246        time.sleep(5)
+247
+248        # You can also tell this function to just return the API call as
+249        # a Dictionary (read: JSON) object.
+250        print(
+251            "You can also tell this function to just return the API call " +
+252            "as a Dictionary (read: JSON) object."
+253        )
+254        json_data = get_cfbd_games(
+255            season=2020,
+256            week=10,
+257            api_key=cfbd_key,
+258            return_as_dict=True
+259        )
+260        print(json_data)
+261
+262    else:
+263        # Alternatively, if the CFBD API key exists in this python environment,
+264        # or it's been set by cfbd_json_py.utls.set_cfbd_api_token(),
+265        # you could just call these functions directly,
+266        # without setting the API key in the script.
+267        print(
+268            "Using the user's API key supposedly loaded " +
+269            "into this python environment for this example."
+270        )
+271
+272        # Get CFB games from the 2020 CFB season.
+273        print("Get CFB games from the 2020 CFB season.")
+274        json_data = get_cfbd_games(
+275            season=2020
+276        )
+277        print(json_data)
+278        time.sleep(5)
+279
+280        # Get CFB games from week 10 of the 2020 CFB season.
+281        print("Get CFB games from week 10 of the 2020 CFB season.")
+282        json_data = get_cfbd_games(
+283            season=2020,
+284            week=10
+285        )
+286        print(json_data)
+287        time.sleep(5)
+288
+289        # Get CFB games from the 2019 CFB season
+290        # that involved the 2019 LSU Tigers.
+291        print(
+292            "Get CFB games from the 2019 CFB season " +
+293            "that involved the 2019 LSU Tigers."
+294        )
+295        json_data = get_cfbd_games(
+296            season=2019,
+297            team="LSU"
+298        )
+299        print(json_data)
+300        time.sleep(5)
+301
+302        # Get 2021 Cincinnati Bearcats Football games
+303        # where the Bearcats were the home team.
+304        print(
+305            "Get 2021 Cincinnati Bearcats Football games " +
+306            "where the Bearcats were the home team."
+307        )
+308        json_data = get_cfbd_games(
+309            season=2021,
+310            home_team="Cincinnati"
+311        )
+312        print(json_data)
+313        time.sleep(5)
+314
+315        # Get 2018 Ohio Bobcats Football games
+316        # where the Bobcats were the away team.
+317        print(
+318            "Get 2018 Ohio Bobcats Football games " +
+319            "where the Bobcats were the away team."
+320        )
+321        json_data = get_cfbd_games(
+322            season=2019,
+323            away_team="Ohio"
+324        )
+325        print(json_data)
+326        time.sleep(5)
+327
+328        # Get 2018 Ohio Bobcats Football games
+329        # where the Bobcats were the away team.
+330        print(
+331            "Get 2018 Ohio Bobcats Football games " +
+332            "where the Bobcats were the away team."
+333        )
+334        json_data = get_cfbd_games(
+335            season=2018,
+336            away_team="Ohio"
+337        )
+338        print(json_data)
+339        time.sleep(5)
+340
+341        # Get 2022 college football games where one or more teams competing
+342        # was a Football Championship Subdivision team.
+343        print(
+344            "Get 2022 college football games where one or more " +
+345            "teams competing was a Football Championship Subdivision team."
+346        )
+347        json_data = get_cfbd_games(
+348            season=2018,
+349            away_team="Ohio"
+350        )
+351        print(json_data)
+352        time.sleep(5)
+353
+354        # Get game information for the
+355        # 2021 American Athletic conference (AAC) Championship Game.
+356        print(
+357            "Get game information for " +
+358            "the 2021 American Athletic conference (AAC) Championship Game."
+359        )
+360        json_data = get_cfbd_games(
+361            season=2018,
+362            game_id=401331162
+363        )
+364        print(json_data)
+365        time.sleep(5)
+366
+367        # You can also tell this function to just return the API call as
+368        # a Dictionary (read: JSON) object.
+369        print(
+370            "You can also tell this function to just return the API call " +
+371            "as a Dictionary (read: JSON) object."
+372        )
+373        json_data = get_cfbd_games(
+374            season=2020,
+375            week=10,
+376            return_as_dict=True
+377        )
+378        print(json_data)
+379
+380    ```
+381    Returns
+382    ----------
+383    A pandas `DataFrame` object with college football game information,
+384    or (if `return_as_dict` is set to `True`)
+385    a dictionary object with college football game information.
+386    """
+387
+388    now = datetime.now()
+389    cfb_games_df = pd.DataFrame()
+390    url = "https://api.collegefootballdata.com/games"
+391
+392    ##########################################################################
+393
+394    if api_key is not None:
+395        real_api_key = api_key
+396        del api_key
+397    else:
+398        real_api_key = get_cfbd_api_token(api_key_dir=api_key_dir)
+399
+400    if real_api_key == "tigersAreAwesome":
+401        raise ValueError(
+402            "You actually need to change `cfbd_key` to your CFBD API key."
+403        )
+404    elif "Bearer " in real_api_key:
+405        pass
+406    elif "Bearer" in real_api_key:
+407        real_api_key = real_api_key.replace("Bearer", "Bearer ")
+408    else:
+409        real_api_key = "Bearer " + real_api_key
+410
+411    if season is None:
+412        # This should never happen without user tampering, but if it does,
+413        # we need to raise an error,
+414        # because the CFBD API will refuse this call without a valid season.
+415        raise SystemError(
+416            "I don't know how, I don't know why, "
+417            + "but you managed to call this function "
+418            + "while `season` was `None` (NULL),"
+419            + " and the function got to this point in the code."
+420            + "\nIf you have a GitHub account, "
+421            + "please raise an issue on this python package's GitHub page:\n"
+422            + "https://github.com/armstjc/cfbd-json-py/issues"
+423        )
+424    elif season > (now.year + 1):
+425        raise ValueError(f"`season` cannot be greater than {season}.")
+426    elif season < 1869:
+427        raise ValueError("`season` cannot be less than 1869.")
+428
+429    if season_type != "regular" and season_type != "postseason":
+430        raise ValueError(
+431            "`season_type` must be set to either "
+432            + '"regular" or "postseason" for this function to work.'
+433        )
+434
+435    if (
+436        ncaa_division.lower() == "fbs"
+437        or ncaa_division.lower() == "fcs"
+438        or ncaa_division.lower() == "ii"
+439        or ncaa_division.lower() == "iii"
+440    ):
+441        pass
+442    else:
+443        raise ValueError(
+444            "An invalid NCAA Division was inputted when calling this function."
+445            + '\nValid inputs are:\n-"fbs"\n-"fcs"\n-"ii"\n-"iii"'
+446            + f"\n\nYou entered: \n{ncaa_division}"
+447        )
+448
+449    # URL builder
+450    ##########################################################################
+451
+452    # Required by API
+453    url += f"?seasonType={season_type}"
+454
+455    if game_id is not None:
+456        url += f"&year={season}"
+457        url += f"&id={game_id}"
+458
+459        if (
+460            team is not None
+461            or home_team is not None
+462            or away_team is not None
+463            or conference is not None
+464            or week is not None
+465        ):
+466            logging.warning(
+467                "When calling `cfbd_json_py.games.get_cfbd_games()`, "
+468                + "and setting `game_id` to a non-null value, "
+469                + "only `season` and `game_id` are considered "
+470                + "when calling the CFBD API."
+471            )
+472
+473    else:
+474        url += f"&year={season}"
+475
+476        # Optional for the API
+477        if week is not None:
+478            url += f"&week={week}"
+479
+480        if team is not None:
+481            url += f"&team={team}"
+482
+483        if home_team is not None:
+484            url += f"&home={home_team}"
+485
+486        if away_team is not None:
+487            url += f"&away={away_team}"
+488
+489        if conference is not None:
+490            url += f"&conference={conference}"
+491
+492        if ncaa_division is not None:
+493            url += f"&division={ncaa_division}"
+494
+495    headers = {
+496        "Authorization": f"{real_api_key}",
+497        "accept": "application/json"
+498    }
+499
+500    response = requests.get(url, headers=headers)
+501
+502    if response.status_code == 200:
+503        pass
+504    elif response.status_code == 401:
+505        raise ConnectionRefusedError(
+506            "Could not connect. The connection was refused." +
+507            "\nHTTP Status Code 401."
+508        )
+509    else:
+510        raise ConnectionError(
+511            f"Could not connect.\nHTTP Status code {response.status_code}"
+512        )
+513
+514    json_data = response.json()
+515
+516    if return_as_dict is True:
+517        return json_data
+518
+519    cfb_games_df = pd.json_normalize(json_data)
+520    # print(cfb_games_df.columns)
+521    if len(cfb_games_df) == 0:
+522        logging.error(
+523            "The CFBD API accepted your inputs, "
+524            + "but found no data within your specified input parameters."
+525            + " Please double check your input parameters."
+526        )
+527
+528    return cfb_games_df
 
@@ -7439,317 +5945,317 @@

Returns

-
530def get_cfbd_team_records(
-531    api_key: str = None,
-532    api_key_dir: str = None,
-533    season: int = None,
-534    team: str = None,  # Must specify either a year or team
-535    conference: str = None,
-536    return_as_dict: bool = False,
-537):
-538    """
-539    Get a team, or multiple team's record (wins, losses, ties)
-540    for home games, away games,
-541    conference games, and the team's record for that season.
-542
-543    Parameters
-544    ----------
-545
-546    `api_key` (str, optional):
-547        Semi-optional argument.
-548        If `api_key` is null, this function will attempt to load a CFBD API key
-549        from the python environment, or from a file on this computer.
-550        If `api_key` is not null,
-551        this function will automatically assume that the
-552        inputted `api_key` is a valid CFBD API key.
-553
-554    `api_key_dir` (str, optional):
-555        Optional argument.
-556        If `api_key` is set to am empty string, this variable is ignored.
-557        If `api_key_dir` is null, and `api_key` is null,
-558        this function will try to find
-559        a CFBD API key file in this user's home directory.
-560        If `api_key_dir` is set to a string, and `api_key` is null,
-561        this function will assume that `api_key_dir` is a directory,
-562        and will try to find a CFBD API key file in that directory.
-563
-564    `season` (int, optional):
-565        Semi-optional argument.
-566        Specifies the season you want CFB team records data from.
-567        You MUST set `season` or `team` to a non-null value for
-568        this function to work. If you don't, a `ValueError()`
-569        will be raised.
-570
-571    `team` (str, optional):
-572        Semi-optional argument.
-573        If you only want CFB team records data for a specific team,
-574        set `team` to the name of the team you want CFB drive data from.
-575        You MUST set `season` or `team` to a non-null value for
-576        this function to work. If you don't, a `ValueError()`
-577        will be raised.
-578
-579    `conference` (str, optional):
-580        Optional argument.
-581        If you only want CFB team records data from games
-582        involving teams from a specific conference,
-583        set `conference` to the abbreviation
-584        of the conference you want CFB team records data from.
-585        For a list of conferences,
-586        use the `cfbd_json_py.conferences.get_cfbd_conference_info()`
-587        function.
-588
-589    `return_as_dict` (bool, semi-optional):
-590        Semi-optional argument.
-591        If you want this function to return
-592        the data as a dictionary (read: JSON object),
-593        instead of a pandas `DataFrame` object,
-594        set `return_as_dict` to `True`.
-595
-596    Usage
-597    ----------
-598    ```
-599    import time
-600
-601    from cfbd_json_py.games import get_cfbd_team_records
-602
+                
531def get_cfbd_team_records(
+532    api_key: str = None,
+533    api_key_dir: str = None,
+534    season: int = None,
+535    team: str = None,  # Must specify either a year or team
+536    conference: str = None,
+537    return_as_dict: bool = False,
+538):
+539    """
+540    Get a team, or multiple team's record (wins, losses, ties)
+541    for home games, away games,
+542    conference games, and the team's record for that season.
+543
+544    Parameters
+545    ----------
+546
+547    `api_key` (str, optional):
+548        Semi-optional argument.
+549        If `api_key` is null, this function will attempt to load a CFBD API key
+550        from the python environment, or from a file on this computer.
+551        If `api_key` is not null,
+552        this function will automatically assume that the
+553        inputted `api_key` is a valid CFBD API key.
+554
+555    `api_key_dir` (str, optional):
+556        Optional argument.
+557        If `api_key` is set to am empty string, this variable is ignored.
+558        If `api_key_dir` is null, and `api_key` is null,
+559        this function will try to find
+560        a CFBD API key file in this user's home directory.
+561        If `api_key_dir` is set to a string, and `api_key` is null,
+562        this function will assume that `api_key_dir` is a directory,
+563        and will try to find a CFBD API key file in that directory.
+564
+565    `season` (int, optional):
+566        Semi-optional argument.
+567        Specifies the season you want CFB team records data from.
+568        You MUST set `season` or `team` to a non-null value for
+569        this function to work. If you don't, a `ValueError()`
+570        will be raised.
+571
+572    `team` (str, optional):
+573        Semi-optional argument.
+574        If you only want CFB team records data for a specific team,
+575        set `team` to the name of the team you want CFB drive data from.
+576        You MUST set `season` or `team` to a non-null value for
+577        this function to work. If you don't, a `ValueError()`
+578        will be raised.
+579
+580    `conference` (str, optional):
+581        Optional argument.
+582        If you only want CFB team records data from games
+583        involving teams from a specific conference,
+584        set `conference` to the abbreviation
+585        of the conference you want CFB team records data from.
+586        For a list of conferences,
+587        use the `cfbd_json_py.conferences.get_cfbd_conference_info()`
+588        function.
+589
+590    `return_as_dict` (bool, semi-optional):
+591        Semi-optional argument.
+592        If you want this function to return
+593        the data as a dictionary (read: JSON object),
+594        instead of a pandas `DataFrame` object,
+595        set `return_as_dict` to `True`.
+596
+597    Usage
+598    ----------
+599    ```
+600    import time
+601
+602    from cfbd_json_py.games import get_cfbd_team_records
 603
-604    cfbd_key = "tigersAreAwesome"  # placeholder for your CFBD API Key.
-605
-606    if cfbd_key is not "tigersAreAwesome":
-607        print(
-608            "Using the user's API key declared in this script " +
-609            "for this example."
-610        )
-611
-612        # Get CFB team records from the 2020 CFB season.
-613        print("Get CFB team records from the 2020 CFB season.")
-614        json_data = get_cfbd_team_records(
-615            api_key=cfbd_key,
-616            season=2020
-617        )
-618        print(json_data)
-619        time.sleep(5)
-620
-621        # Get team records from football teams
-622        # fielded by the University of Cincinnati.
-623        print(
-624            "Get team records from football teams fielded " +
-625            "by the University of Cincinnati."
-626        )
-627        json_data = get_cfbd_team_records(
-628            api_key=cfbd_key,
-629            team="Cincinnati"
-630        )
-631        print(json_data)
-632        time.sleep(5)
-633
-634        # Get team records from football teams that played
-635        # in the Big 10 (B1G) conference in the 2017 CFB season
-636        print(
-637            "Get team records from football teams that played " +
-638            "in the Big 10 (B1G) conference in the 2017 CFB season"
-639        )
-640        json_data = get_cfbd_team_records(
-641            api_key=cfbd_key,
-642            season=2017,
-643            conference="B1G"
-644        )
-645        print(json_data)
-646        time.sleep(5)
-647
+604
+605    cfbd_key = "tigersAreAwesome"  # placeholder for your CFBD API Key.
+606
+607    if cfbd_key is not "tigersAreAwesome":
+608        print(
+609            "Using the user's API key declared in this script " +
+610            "for this example."
+611        )
+612
+613        # Get CFB team records from the 2020 CFB season.
+614        print("Get CFB team records from the 2020 CFB season.")
+615        json_data = get_cfbd_team_records(
+616            api_key=cfbd_key,
+617            season=2020
+618        )
+619        print(json_data)
+620        time.sleep(5)
+621
+622        # Get team records from football teams
+623        # fielded by the University of Cincinnati.
+624        print(
+625            "Get team records from football teams fielded " +
+626            "by the University of Cincinnati."
+627        )
+628        json_data = get_cfbd_team_records(
+629            api_key=cfbd_key,
+630            team="Cincinnati"
+631        )
+632        print(json_data)
+633        time.sleep(5)
+634
+635        # Get team records from football teams that played
+636        # in the Big 10 (B1G) conference in the 2017 CFB season
+637        print(
+638            "Get team records from football teams that played " +
+639            "in the Big 10 (B1G) conference in the 2017 CFB season"
+640        )
+641        json_data = get_cfbd_team_records(
+642            api_key=cfbd_key,
+643            season=2017,
+644            conference="B1G"
+645        )
+646        print(json_data)
+647        time.sleep(5)
 648
-649        # You can also tell this function to just return the API call as
-650        # a Dictionary (read: JSON) object.
-651        print(
-652            "You can also tell this function to just return the API call " +
-653            "as a Dictionary (read: JSON) object."
-654        )
-655        json_data = get_cfbd_team_records(
-656            season=2020,
-657            api_key=cfbd_key,
-658            return_as_dict=True
-659        )
-660        print(json_data)
-661
-662    else:
-663        # Alternatively, if the CFBD API key exists in this python environment,
-664        # or it's been set by cfbd_json_py.utls.set_cfbd_api_token(),
-665        # you could just call these functions directly,
-666        # without setting the API key in the script.
-667        print(
-668            "Using the user's API key supposedly loaded " +
-669            "into this python environment for this example."
-670        )
-671
-672        # Get CFB team records from the 2020 CFB season.
-673        print("Get CFB team records from the 2020 CFB season.")
-674        json_data = get_cfbd_team_records(
-675            season=2020
-676        )
-677        print(json_data)
-678        time.sleep(5)
-679
-680        # Get team records from football teams
-681        # fielded by the University of Cincinnati.
-682        print(
-683            "Get team records from football teams " +
-684            "fielded by the University of Cincinnati."
-685        )
-686        json_data = get_cfbd_team_records(
-687            team="Cincinnati"
-688        )
-689        print(json_data)
-690        time.sleep(5)
-691
-692        # Get team records from football teams that played
-693        # in the Big 10 (B1G) conference in the 2017 CFB season
-694        print(
-695            "Get team records from football teams that played " +
-696            "in the Big 10 (B1G) conference in the 2017 CFB season"
-697        )
-698        json_data = get_cfbd_team_records(
-699            season=2017,
-700            conference="B1G"
-701        )
-702        print(json_data)
-703        time.sleep(5)
-704
-705        # You can also tell this function to just return the API call as
-706        # a Dictionary (read: JSON) object.
-707        print(
-708            "You can also tell this function to just return the API call " +
-709            "as a Dictionary (read: JSON) object."
-710        )
-711        json_data = get_cfbd_team_records(
-712            season=2020,
-713            return_as_dict=True
-714        )
-715        print(json_data)
-716
-717    ```
-718
-719    Returns
-720    ----------
-721    A pandas `DataFrame` object with CFB team records data,
-722    or (if `return_as_dict` is set to `True`)
-723    a dictionary object with CFB team records data.
-724
-725    """
-726
-727    now = datetime.now()
-728    cfb_records_df = pd.DataFrame()
-729    # row_df = pd.DataFrame()
-730    url = "https://api.collegefootballdata.com/records"
-731
-732    ##########################################################################
-733
-734    if api_key is not None:
-735        real_api_key = api_key
-736        del api_key
-737    else:
-738        real_api_key = get_cfbd_api_token(api_key_dir=api_key_dir)
-739
-740    if real_api_key == "tigersAreAwesome":
-741        raise ValueError(
-742            "You actually need to change `cfbd_key` to your CFBD API key."
-743        )
-744    elif "Bearer " in real_api_key:
-745        pass
-746    elif "Bearer" in real_api_key:
-747        real_api_key = real_api_key.replace("Bearer", "Bearer ")
-748    else:
-749        real_api_key = "Bearer " + real_api_key
-750
-751    if season is not None and season > now.year:
-752        raise ValueError(f"`season` cannot be greater than {season}.")
-753    elif season is not None and season < 1869:
-754        raise ValueError("`season` cannot be less than 1869.")
-755
-756    if season is None and team is None:
-757        raise ValueError(
-758            "If you call `cfbd_json_py.games.get_cfbd_team_records()`, "
-759            + "you must specify at least a team or CFB season."
-760        )
-761
-762    # URL builder
-763    ##########################################################################
-764
-765    url_elements = 0
-766
-767    if season is not None and url_elements == 0:
-768        url += f"?year={season}"
-769        url_elements += 1
-770    elif season is not None:
-771        url += f"&year={season}"
-772        url_elements += 1
-773
-774    if team is not None and url_elements == 0:
-775        url += f"?team={team}"
-776        url_elements += 1
-777    elif team is not None:
-778        url += f"&team={team}"
-779        url_elements += 1
-780
-781    if conference is not None and url_elements == 0:
-782        url += f"?conference={conference}"
-783        url_elements += 1
-784    elif conference is not None:
-785        url += f"&conference={conference}"
-786        url_elements += 1
-787
-788    headers = {
-789        "Authorization": f"{real_api_key}",
-790        "accept": "application/json"
-791    }
-792    response = requests.get(url, headers=headers)
-793
-794    if response.status_code == 200:
-795        pass
-796    elif response.status_code == 401:
-797        raise ConnectionRefusedError(
-798            "Could not connect. The connection was refused." +
-799            "\nHTTP Status Code 401."
-800        )
-801    else:
-802        raise ConnectionError(
-803            f"Could not connect.\nHTTP Status code {response.status_code}"
-804        )
-805
-806    json_data = response.json()
-807
-808    if return_as_dict is True:
-809        return json_data
-810
-811    cfb_records_df = pd.json_normalize(json_data)
-812    # print(cfb_records_df.columns)
-813    cfb_records_df.rename(
-814        columns={
-815            "year": "season",
-816            "teamId": "team_id",
-817            "team": "team_name",
-818            "conference": "conference_name",
-819            "division": "division_name",
-820            "expectedWins": "expected_wins",
-821            "total.games": "games",
-822            "total.wins": "wins",
-823            "total.losses": "losses",
-824            "total.ties": "ties",
-825            "conferenceGames.games": "conf_games",
-826            "conferenceGames.wins": "conf_wins",
-827            "conferenceGames.losses": "conf_losses",
-828            "conferenceGames.ties": "conf_ties",
-829            "homeGames.games": "home_games",
-830            "homeGames.wins": "home_wins",
-831            "homeGames.losses": "home_losses",
-832            "homeGames.ties": "home_ties",
-833            "awayGames.games": "away_games",
-834            "awayGames.wins": "away_wins",
-835            "awayGames.losses": "away_losses",
-836            "awayGames.ties": "away_ties",
-837        },
-838        inplace=True,
-839    )
-840    return cfb_records_df
+649
+650        # You can also tell this function to just return the API call as
+651        # a Dictionary (read: JSON) object.
+652        print(
+653            "You can also tell this function to just return the API call " +
+654            "as a Dictionary (read: JSON) object."
+655        )
+656        json_data = get_cfbd_team_records(
+657            season=2020,
+658            api_key=cfbd_key,
+659            return_as_dict=True
+660        )
+661        print(json_data)
+662
+663    else:
+664        # Alternatively, if the CFBD API key exists in this python environment,
+665        # or it's been set by cfbd_json_py.utls.set_cfbd_api_token(),
+666        # you could just call these functions directly,
+667        # without setting the API key in the script.
+668        print(
+669            "Using the user's API key supposedly loaded " +
+670            "into this python environment for this example."
+671        )
+672
+673        # Get CFB team records from the 2020 CFB season.
+674        print("Get CFB team records from the 2020 CFB season.")
+675        json_data = get_cfbd_team_records(
+676            season=2020
+677        )
+678        print(json_data)
+679        time.sleep(5)
+680
+681        # Get team records from football teams
+682        # fielded by the University of Cincinnati.
+683        print(
+684            "Get team records from football teams " +
+685            "fielded by the University of Cincinnati."
+686        )
+687        json_data = get_cfbd_team_records(
+688            team="Cincinnati"
+689        )
+690        print(json_data)
+691        time.sleep(5)
+692
+693        # Get team records from football teams that played
+694        # in the Big 10 (B1G) conference in the 2017 CFB season
+695        print(
+696            "Get team records from football teams that played " +
+697            "in the Big 10 (B1G) conference in the 2017 CFB season"
+698        )
+699        json_data = get_cfbd_team_records(
+700            season=2017,
+701            conference="B1G"
+702        )
+703        print(json_data)
+704        time.sleep(5)
+705
+706        # You can also tell this function to just return the API call as
+707        # a Dictionary (read: JSON) object.
+708        print(
+709            "You can also tell this function to just return the API call " +
+710            "as a Dictionary (read: JSON) object."
+711        )
+712        json_data = get_cfbd_team_records(
+713            season=2020,
+714            return_as_dict=True
+715        )
+716        print(json_data)
+717
+718    ```
+719
+720    Returns
+721    ----------
+722    A pandas `DataFrame` object with CFB team records data,
+723    or (if `return_as_dict` is set to `True`)
+724    a dictionary object with CFB team records data.
+725
+726    """
+727
+728    now = datetime.now()
+729    cfb_records_df = pd.DataFrame()
+730    # row_df = pd.DataFrame()
+731    url = "https://api.collegefootballdata.com/records"
+732
+733    ##########################################################################
+734
+735    if api_key is not None:
+736        real_api_key = api_key
+737        del api_key
+738    else:
+739        real_api_key = get_cfbd_api_token(api_key_dir=api_key_dir)
+740
+741    if real_api_key == "tigersAreAwesome":
+742        raise ValueError(
+743            "You actually need to change `cfbd_key` to your CFBD API key."
+744        )
+745    elif "Bearer " in real_api_key:
+746        pass
+747    elif "Bearer" in real_api_key:
+748        real_api_key = real_api_key.replace("Bearer", "Bearer ")
+749    else:
+750        real_api_key = "Bearer " + real_api_key
+751
+752    if season is not None and season > now.year:
+753        raise ValueError(f"`season` cannot be greater than {season}.")
+754    elif season is not None and season < 1869:
+755        raise ValueError("`season` cannot be less than 1869.")
+756
+757    if season is None and team is None:
+758        raise ValueError(
+759            "If you call `cfbd_json_py.games.get_cfbd_team_records()`, "
+760            + "you must specify at least a team or CFB season."
+761        )
+762
+763    # URL builder
+764    ##########################################################################
+765
+766    url_elements = 0
+767
+768    if season is not None and url_elements == 0:
+769        url += f"?year={season}"
+770        url_elements += 1
+771    elif season is not None:
+772        url += f"&year={season}"
+773        url_elements += 1
+774
+775    if team is not None and url_elements == 0:
+776        url += f"?team={team}"
+777        url_elements += 1
+778    elif team is not None:
+779        url += f"&team={team}"
+780        url_elements += 1
+781
+782    if conference is not None and url_elements == 0:
+783        url += f"?conference={conference}"
+784        url_elements += 1
+785    elif conference is not None:
+786        url += f"&conference={conference}"
+787        url_elements += 1
+788
+789    headers = {
+790        "Authorization": f"{real_api_key}",
+791        "accept": "application/json"
+792    }
+793    response = requests.get(url, headers=headers)
+794
+795    if response.status_code == 200:
+796        pass
+797    elif response.status_code == 401:
+798        raise ConnectionRefusedError(
+799            "Could not connect. The connection was refused." +
+800            "\nHTTP Status Code 401."
+801        )
+802    else:
+803        raise ConnectionError(
+804            f"Could not connect.\nHTTP Status code {response.status_code}"
+805        )
+806
+807    json_data = response.json()
+808
+809    if return_as_dict is True:
+810        return json_data
+811
+812    cfb_records_df = pd.json_normalize(json_data)
+813    # print(cfb_records_df.columns)
+814    cfb_records_df.rename(
+815        columns={
+816            "year": "season",
+817            "teamId": "team_id",
+818            "team": "team_name",
+819            "conference": "conference_name",
+820            "division": "division_name",
+821            "expectedWins": "expected_wins",
+822            "total.games": "games",
+823            "total.wins": "wins",
+824            "total.losses": "losses",
+825            "total.ties": "ties",
+826            "conferenceGames.games": "conf_games",
+827            "conferenceGames.wins": "conf_wins",
+828            "conferenceGames.losses": "conf_losses",
+829            "conferenceGames.ties": "conf_ties",
+830            "homeGames.games": "home_games",
+831            "homeGames.wins": "home_wins",
+832            "homeGames.losses": "home_losses",
+833            "homeGames.ties": "home_ties",
+834            "awayGames.games": "away_games",
+835            "awayGames.wins": "away_wins",
+836            "awayGames.losses": "away_losses",
+837            "awayGames.ties": "away_ties",
+838        },
+839        inplace=True,
+840    )
+841    return cfb_records_df
 
@@ -7966,209 +6472,209 @@

Returns

-
 843def get_cfbd_season_weeks(
- 844    season: int,
- 845    api_key: str = None,
- 846    api_key_dir: str = None,
- 847    return_as_dict: bool = False,
- 848):
- 849    """
- 850    Retrieves a list of weeks that occurred in a given CFB season.
- 851
- 852    Parameters
- 853    ----------
- 854    `season` (int, mandatory):
- 855        Required argument.
- 856        Specifies the season you want a list of weeks that occurred
- 857        in a given CFB season information from.
- 858        This must be specified, otherwise this package, and by extension
- 859        the CFBD API, will not accept the request
- 860        to get a list of weeks that occurred in a given CFB season information.
- 861
- 862    `api_key` (str, optional):
- 863        Semi-optional argument.
- 864        If `api_key` is null, this function will attempt to load a CFBD API key
- 865        from the python environment, or from a file on this computer.
- 866        If `api_key` is not null,
- 867        this function will automatically assume that the
- 868        inputted `api_key` is a valid CFBD API key.
- 869
- 870    `api_key_dir` (str, optional):
- 871        Optional argument.
- 872        If `api_key` is set to am empty string, this variable is ignored.
- 873        If `api_key_dir` is null, and `api_key` is null,
- 874        this function will try to find
- 875        a CFBD API key file in this user's home directory.
- 876        If `api_key_dir` is set to a string, and `api_key` is null,
- 877        this function will assume that `api_key_dir` is a directory,
- 878        and will try to find a CFBD API key file in that directory.
- 879
- 880    `return_as_dict` (bool, semi-optional):
- 881        Semi-optional argument.
- 882        If you want this function to return
- 883        the data as a dictionary (read: JSON object),
- 884        instead of a pandas `DataFrame` object,
- 885        set `return_as_dict` to `True`.
- 886
+                
 844def get_cfbd_season_weeks(
+ 845    season: int,
+ 846    api_key: str = None,
+ 847    api_key_dir: str = None,
+ 848    return_as_dict: bool = False,
+ 849):
+ 850    """
+ 851    Retrieves a list of weeks that occurred in a given CFB season.
+ 852
+ 853    Parameters
+ 854    ----------
+ 855    `season` (int, mandatory):
+ 856        Required argument.
+ 857        Specifies the season you want a list of weeks that occurred
+ 858        in a given CFB season information from.
+ 859        This must be specified, otherwise this package, and by extension
+ 860        the CFBD API, will not accept the request
+ 861        to get a list of weeks that occurred in a given CFB season information.
+ 862
+ 863    `api_key` (str, optional):
+ 864        Semi-optional argument.
+ 865        If `api_key` is null, this function will attempt to load a CFBD API key
+ 866        from the python environment, or from a file on this computer.
+ 867        If `api_key` is not null,
+ 868        this function will automatically assume that the
+ 869        inputted `api_key` is a valid CFBD API key.
+ 870
+ 871    `api_key_dir` (str, optional):
+ 872        Optional argument.
+ 873        If `api_key` is set to am empty string, this variable is ignored.
+ 874        If `api_key_dir` is null, and `api_key` is null,
+ 875        this function will try to find
+ 876        a CFBD API key file in this user's home directory.
+ 877        If `api_key_dir` is set to a string, and `api_key` is null,
+ 878        this function will assume that `api_key_dir` is a directory,
+ 879        and will try to find a CFBD API key file in that directory.
+ 880
+ 881    `return_as_dict` (bool, semi-optional):
+ 882        Semi-optional argument.
+ 883        If you want this function to return
+ 884        the data as a dictionary (read: JSON object),
+ 885        instead of a pandas `DataFrame` object,
+ 886        set `return_as_dict` to `True`.
  887
- 888    Usage
- 889    ----------
- 890    ```
- 891    import time
- 892
- 893    from cfbd_json_py.games import get_cfbd_season_weeks
- 894
+ 888
+ 889    Usage
+ 890    ----------
+ 891    ```
+ 892    import time
+ 893
+ 894    from cfbd_json_py.games import get_cfbd_season_weeks
  895
- 896    cfbd_key = "tigersAreAwesome"  # placeholder for your CFBD API Key.
- 897
- 898    if cfbd_key is not "tigersAreAwesome":
- 899        print(
- 900            "Using the user's API key declared in this script " +
- 901            "for this example."
- 902        )
- 903
- 904        # Get a list of weeks in the 2020 CFB season.
- 905        print("Get a list of weeks in the 2020 CFB season.")
- 906        json_data = get_cfbd_season_weeks(
- 907            api_key=cfbd_key,
- 908            season=2020
- 909        )
- 910        print(json_data)
- 911        time.sleep(5)
- 912
+ 896
+ 897    cfbd_key = "tigersAreAwesome"  # placeholder for your CFBD API Key.
+ 898
+ 899    if cfbd_key is not "tigersAreAwesome":
+ 900        print(
+ 901            "Using the user's API key declared in this script " +
+ 902            "for this example."
+ 903        )
+ 904
+ 905        # Get a list of weeks in the 2020 CFB season.
+ 906        print("Get a list of weeks in the 2020 CFB season.")
+ 907        json_data = get_cfbd_season_weeks(
+ 908            api_key=cfbd_key,
+ 909            season=2020
+ 910        )
+ 911        print(json_data)
+ 912        time.sleep(5)
  913
- 914        # You can also tell this function to just return the API call as
- 915        # a Dictionary (read: JSON) object.
- 916        print(
- 917            "You can also tell this function to just return the API call " +
- 918            "as a Dictionary (read: JSON) object."
- 919        )
- 920        json_data = get_cfbd_season_weeks(
- 921            season=2020,
- 922            api_key=cfbd_key,
- 923            return_as_dict=True
- 924        )
- 925        print(json_data)
- 926
- 927    else:
- 928        # Alternatively, if the CFBD API key exists in this python environment,
- 929        # or it's been set by cfbd_json_py.utls.set_cfbd_api_token(),
- 930        # you could just call these functions directly,
- 931        # without setting the API key in the script.
- 932        print(
- 933            "Using the user's API key supposedly loaded " +
- 934            "into this python environment for this example."
- 935        )
- 936
- 937        # Get a list of weeks in the 2020 CFB season.
- 938        print("Get a list of weeks in the 2020 CFB season.")
- 939        json_data = get_cfbd_season_weeks(
- 940            season=2020
- 941        )
- 942        print(json_data)
- 943        time.sleep(5)
- 944
+ 914
+ 915        # You can also tell this function to just return the API call as
+ 916        # a Dictionary (read: JSON) object.
+ 917        print(
+ 918            "You can also tell this function to just return the API call " +
+ 919            "as a Dictionary (read: JSON) object."
+ 920        )
+ 921        json_data = get_cfbd_season_weeks(
+ 922            season=2020,
+ 923            api_key=cfbd_key,
+ 924            return_as_dict=True
+ 925        )
+ 926        print(json_data)
+ 927
+ 928    else:
+ 929        # Alternatively, if the CFBD API key exists in this python environment,
+ 930        # or it's been set by cfbd_json_py.utls.set_cfbd_api_token(),
+ 931        # you could just call these functions directly,
+ 932        # without setting the API key in the script.
+ 933        print(
+ 934            "Using the user's API key supposedly loaded " +
+ 935            "into this python environment for this example."
+ 936        )
+ 937
+ 938        # Get a list of weeks in the 2020 CFB season.
+ 939        print("Get a list of weeks in the 2020 CFB season.")
+ 940        json_data = get_cfbd_season_weeks(
+ 941            season=2020
+ 942        )
+ 943        print(json_data)
+ 944        time.sleep(5)
  945
- 946        # You can also tell this function to just return the API call as
- 947        # a Dictionary (read: JSON) object.
- 948        print(
- 949            "You can also tell this function to just return the API call " +
- 950            "as a Dictionary (read: JSON) object."
- 951        )
- 952        json_data = get_cfbd_season_weeks(
- 953            season=2020,
- 954            return_as_dict=True
- 955        )
- 956        print(json_data)
- 957    ```
- 958    Returns
- 959    ----------
- 960    A pandas `DataFrame` object
- 961    with a list of valid weeks in a given CFB season,
- 962    or (if `return_as_dict` is set to `True`)
- 963    a dictionary object with a list of valid weeks in a given CFB season.
- 964    """
- 965
- 966    now = datetime.now()
- 967    cfb_weeks_df = pd.DataFrame()
- 968    # row_df = pd.DataFrame()
- 969    url = "https://api.collegefootballdata.com/calendar"
- 970
- 971    ##########################################################################
- 972
- 973    if api_key is not None:
- 974        real_api_key = api_key
- 975        del api_key
- 976    else:
- 977        real_api_key = get_cfbd_api_token(api_key_dir=api_key_dir)
- 978
- 979    if real_api_key == "tigersAreAwesome":
- 980        raise ValueError(
- 981            "You actually need to change `cfbd_key` to your CFBD API key."
- 982        )
- 983    elif "Bearer " in real_api_key:
- 984        pass
- 985    elif "Bearer" in real_api_key:
- 986        real_api_key = real_api_key.replace("Bearer", "Bearer ")
- 987    else:
- 988        real_api_key = "Bearer " + real_api_key
- 989
- 990    if season is None:
- 991        # This should never happen without user tampering, but if it does,
- 992        # we need to raise an error,
- 993        # because the CFBD API will refuse this call without a valid season.
- 994        raise SystemError(
- 995            "I don't know how, I don't know why, "
- 996            + "but you managed to call this function "
- 997            + "while `season` was `None` (NULL),"
- 998            + " and the function got to this point in the code."
- 999            + "\nIf you have a GitHub account, "
-1000            + "please raise an issue on this python package's GitHub page:\n"
-1001            + "https://github.com/armstjc/cfbd-json-py/issues"
-1002        )
-1003    elif season > (now.year + 1):
-1004        raise ValueError(f"`season` cannot be greater than {season}.")
-1005    elif season < 1869:
-1006        raise ValueError("`season` cannot be less than 1869.")
-1007
-1008    # URL builder
-1009    ##########################################################################
-1010
-1011    # Required by API
-1012    url += f"?year={season}"
-1013
-1014    headers = {
-1015        "Authorization": f"{real_api_key}",
-1016        "accept": "application/json"
-1017    }
-1018    response = requests.get(url, headers=headers)
-1019
-1020    if response.status_code == 200:
-1021        pass
-1022    elif response.status_code == 401:
-1023        raise ConnectionRefusedError(
-1024            "Could not connect. The connection was refused." +
-1025            "\nHTTP Status Code 401."
-1026        )
-1027    else:
-1028        raise ConnectionError(
-1029            f"Could not connect.\nHTTP Status code {response.status_code}"
-1030        )
-1031
-1032    json_data = response.json()
-1033
-1034    if return_as_dict is True:
-1035        return json_data
-1036
-1037    cfb_weeks_df = pd.json_normalize(json_data)
-1038    # print(cfb_weeks_df.columns)
-1039    cfb_weeks_df.rename(
-1040        columns={
-1041            "firstGameStart": "first_game_start",
-1042            "lastGameStart": "last_game_start",
-1043        }
-1044    )
-1045    return cfb_weeks_df
+ 946
+ 947        # You can also tell this function to just return the API call as
+ 948        # a Dictionary (read: JSON) object.
+ 949        print(
+ 950            "You can also tell this function to just return the API call " +
+ 951            "as a Dictionary (read: JSON) object."
+ 952        )
+ 953        json_data = get_cfbd_season_weeks(
+ 954            season=2020,
+ 955            return_as_dict=True
+ 956        )
+ 957        print(json_data)
+ 958    ```
+ 959    Returns
+ 960    ----------
+ 961    A pandas `DataFrame` object
+ 962    with a list of valid weeks in a given CFB season,
+ 963    or (if `return_as_dict` is set to `True`)
+ 964    a dictionary object with a list of valid weeks in a given CFB season.
+ 965    """
+ 966
+ 967    now = datetime.now()
+ 968    cfb_weeks_df = pd.DataFrame()
+ 969    # row_df = pd.DataFrame()
+ 970    url = "https://api.collegefootballdata.com/calendar"
+ 971
+ 972    ##########################################################################
+ 973
+ 974    if api_key is not None:
+ 975        real_api_key = api_key
+ 976        del api_key
+ 977    else:
+ 978        real_api_key = get_cfbd_api_token(api_key_dir=api_key_dir)
+ 979
+ 980    if real_api_key == "tigersAreAwesome":
+ 981        raise ValueError(
+ 982            "You actually need to change `cfbd_key` to your CFBD API key."
+ 983        )
+ 984    elif "Bearer " in real_api_key:
+ 985        pass
+ 986    elif "Bearer" in real_api_key:
+ 987        real_api_key = real_api_key.replace("Bearer", "Bearer ")
+ 988    else:
+ 989        real_api_key = "Bearer " + real_api_key
+ 990
+ 991    if season is None:
+ 992        # This should never happen without user tampering, but if it does,
+ 993        # we need to raise an error,
+ 994        # because the CFBD API will refuse this call without a valid season.
+ 995        raise SystemError(
+ 996            "I don't know how, I don't know why, "
+ 997            + "but you managed to call this function "
+ 998            + "while `season` was `None` (NULL),"
+ 999            + " and the function got to this point in the code."
+1000            + "\nIf you have a GitHub account, "
+1001            + "please raise an issue on this python package's GitHub page:\n"
+1002            + "https://github.com/armstjc/cfbd-json-py/issues"
+1003        )
+1004    elif season > (now.year + 1):
+1005        raise ValueError(f"`season` cannot be greater than {season}.")
+1006    elif season < 1869:
+1007        raise ValueError("`season` cannot be less than 1869.")
+1008
+1009    # URL builder
+1010    ##########################################################################
+1011
+1012    # Required by API
+1013    url += f"?year={season}"
+1014
+1015    headers = {
+1016        "Authorization": f"{real_api_key}",
+1017        "accept": "application/json"
+1018    }
+1019    response = requests.get(url, headers=headers)
+1020
+1021    if response.status_code == 200:
+1022        pass
+1023    elif response.status_code == 401:
+1024        raise ConnectionRefusedError(
+1025            "Could not connect. The connection was refused." +
+1026            "\nHTTP Status Code 401."
+1027        )
+1028    else:
+1029        raise ConnectionError(
+1030            f"Could not connect.\nHTTP Status code {response.status_code}"
+1031        )
+1032
+1033    json_data = response.json()
+1034
+1035    if return_as_dict is True:
+1036        return json_data
+1037
+1038    cfb_weeks_df = pd.json_normalize(json_data)
+1039    # print(cfb_weeks_df.columns)
+1040    cfb_weeks_df.rename(
+1041        columns={
+1042            "firstGameStart": "first_game_start",
+1043            "lastGameStart": "last_game_start",
+1044        }
+1045    )
+1046    return cfb_weeks_df
 
@@ -8326,537 +6832,537 @@

Returns

-
1048def get_cfbd_game_media_info(
-1049    season: int,
-1050    api_key: str = None,
-1051    api_key_dir: str = None,
-1052    season_type: str = "regular",  # "regular", "postseason", or "both"
-1053    week: int = None,
-1054    team: str = None,
-1055    conference: str = None,
-1056    media_type: str = "all",  # "tv", "radio", "web", "ppv", or "mobile"
-1057    ncaa_division: str = "fbs",
-1058    return_as_dict: bool = False,
-1059):
-1060    """
-1061    Gets known media information for CFB games in a given CFB season.
-1062
-1063    Parameters
-1064    ----------
-1065    `season` (int, mandatory):
-1066        Required argument.
-1067        Specifies the season you want CFB media information from.
-1068        This must be specified, otherwise this package, and by extension
-1069        the CFBD API, will not accept the request to get CFB media information.
-1070
-1071    `api_key` (str, optional):
-1072        Semi-optional argument.
-1073        If `api_key` is null, this function will attempt to load a CFBD API key
-1074        from the python environment, or from a file on this computer.
-1075        If `api_key` is not null,
-1076        this function will automatically assume that the
-1077        inputted `api_key` is a valid CFBD API key.
-1078
-1079    `api_key_dir` (str, optional):
-1080        Optional argument.
-1081        If `api_key` is set to am empty string, this variable is ignored.
-1082        If `api_key_dir` is null, and `api_key` is null,
-1083        this function will try to find
-1084        a CFBD API key file in this user's home directory.
-1085        If `api_key_dir` is set to a string, and `api_key` is null,
-1086        this function will assume that `api_key_dir` is a directory,
-1087        and will try to find a CFBD API key file in that directory.
-1088
-1089    `season_type` (str, semi-optional):
-1090        Semi-optional argument.
-1091        By default, this will be set to "regular", for the CFB regular season.
-1092        If you want CFB media information for non-regular season games,
-1093        set `season_type` to "postseason".
-1094        If you want both "regular" and "postseason" games returned,
-1095        set `season_type` to "both"
-1096        If `season_type` is set to anything but "regular" or "postseason",
-1097        a `ValueError()` will be raised.
-1098
-1099    `week` (int, optional):
-1100        Optional argument.
-1101        If `week` is set to an integer, this function will attempt
-1102        to load CFB media information from games in that season,
-1103        and in that week.
-1104
-1105    `team` (str, optional):
-1106        Optional argument.
-1107        If you only want CFB media information for a team,
-1108        regardless if they are the home/away team,
-1109        set `team` to the name of the team you want CFB media information from.
-1110
-1111    `conference` (str, optional):
-1112        Optional argument.
-1113        If you only want media information from games
-1114        involving teams a specific conference,
-1115        set `conference` to the abbreviation
-1116        of the conference you want game information from.
-1117
-1118    `media_type` (str, semi-optional):
-1119        Semi-optional argument.
-1120        If you only want game broadcast information
-1121        for a specific type of broadcast,
-1122        set this to the type of broadcast.
-1123
-1124        Valid inputs are:
-1125        - `all` (default): Returns all games,
-1126            and all known broadcasters for those games.
-1127        - `tv`: Returns all known TV broadcasters for CFB games
-1128            in the requested time frame.
-1129        - `radio`: Returns all known radio broadcasters
-1130            for CFB games in the requested time frame.
-1131        - `web`: Returns all known web broadcasts (like ESPN+)
-1132            for CFB games in the requested time frame.
-1133        - `ppv`: Returns all known Pay Per View (PPV) broadcasts
-1134            for CFB games in the requested time frame.
-1135        - `mobile`: Returns all known broadcasters that only broadcasted
-1136            games on mobile devices (?)
-1137
-1138    `ncaa_division` (str, semi-optional):
-1139        Semi-optional argument.
-1140        By default, `ncaa_division` will be set to "fbs",
-1141        short for the Football Bowl Subdivision (FBS),
-1142        formerly known as D1-A (read as "division one single A"),
-1143        the highest level in the NCAA football pyramid,
-1144        where teams can scholarship up to 85 players
-1145        on their football team solely for athletic ability,
-1146        and often have the largest athletics budgets
-1147        within the NCAA.
-1148
-1149        Other valid inputs are:
-1150        - "fcs": Football Championship Subdivision (FCS),
-1151            formerly known as D1-AA (read as "division one double A").
-1152            An FCS school is still in the 1st division of the NCAA,
-1153            making them eligible for the March Madness tournament,
-1154            but may not have the resources to compete at the FBS level
-1155            at this time. FCS schools are limited to 63 athletic scholarships
-1156            for football.
-1157        - "ii": NCAA Division II. Schools in this and D3 are not
-1158            eligible for the March Madness tournament,
-1159            and are limited to 36 athletic scholarships
-1160            for their football team.
-1161        - "iii": NCAA Division III. The largest single division within the
-1162            NCAA football pyramid.
-1163            D3 schools have the distinction of being part of
-1164            the only NCAA division that cannot give out scholarships solely
-1165            for athletic ability.
-1166
-1167    `return_as_dict` (bool, semi-optional):
-1168        Semi-optional argument.
-1169        If you want this function to return
-1170        the data as a dictionary (read: JSON object),
-1171        instead of a pandas `DataFrame` object,
-1172        set `return_as_dict` to `True`.
-1173
-1174    Usage
-1175    ----------
-1176    ```
-1177    import time
-1178
-1179    from cfbd_json_py.games import get_cfbd_game_media_info
-1180
+                
1049def get_cfbd_game_media_info(
+1050    season: int,
+1051    api_key: str = None,
+1052    api_key_dir: str = None,
+1053    season_type: str = "regular",  # "regular", "postseason", or "both"
+1054    week: int = None,
+1055    team: str = None,
+1056    conference: str = None,
+1057    media_type: str = "all",  # "tv", "radio", "web", "ppv", or "mobile"
+1058    ncaa_division: str = "fbs",
+1059    return_as_dict: bool = False,
+1060):
+1061    """
+1062    Gets known media information for CFB games in a given CFB season.
+1063
+1064    Parameters
+1065    ----------
+1066    `season` (int, mandatory):
+1067        Required argument.
+1068        Specifies the season you want CFB media information from.
+1069        This must be specified, otherwise this package, and by extension
+1070        the CFBD API, will not accept the request to get CFB media information.
+1071
+1072    `api_key` (str, optional):
+1073        Semi-optional argument.
+1074        If `api_key` is null, this function will attempt to load a CFBD API key
+1075        from the python environment, or from a file on this computer.
+1076        If `api_key` is not null,
+1077        this function will automatically assume that the
+1078        inputted `api_key` is a valid CFBD API key.
+1079
+1080    `api_key_dir` (str, optional):
+1081        Optional argument.
+1082        If `api_key` is set to am empty string, this variable is ignored.
+1083        If `api_key_dir` is null, and `api_key` is null,
+1084        this function will try to find
+1085        a CFBD API key file in this user's home directory.
+1086        If `api_key_dir` is set to a string, and `api_key` is null,
+1087        this function will assume that `api_key_dir` is a directory,
+1088        and will try to find a CFBD API key file in that directory.
+1089
+1090    `season_type` (str, semi-optional):
+1091        Semi-optional argument.
+1092        By default, this will be set to "regular", for the CFB regular season.
+1093        If you want CFB media information for non-regular season games,
+1094        set `season_type` to "postseason".
+1095        If you want both "regular" and "postseason" games returned,
+1096        set `season_type` to "both"
+1097        If `season_type` is set to anything but "regular" or "postseason",
+1098        a `ValueError()` will be raised.
+1099
+1100    `week` (int, optional):
+1101        Optional argument.
+1102        If `week` is set to an integer, this function will attempt
+1103        to load CFB media information from games in that season,
+1104        and in that week.
+1105
+1106    `team` (str, optional):
+1107        Optional argument.
+1108        If you only want CFB media information for a team,
+1109        regardless if they are the home/away team,
+1110        set `team` to the name of the team you want CFB media information from.
+1111
+1112    `conference` (str, optional):
+1113        Optional argument.
+1114        If you only want media information from games
+1115        involving teams a specific conference,
+1116        set `conference` to the abbreviation
+1117        of the conference you want game information from.
+1118
+1119    `media_type` (str, semi-optional):
+1120        Semi-optional argument.
+1121        If you only want game broadcast information
+1122        for a specific type of broadcast,
+1123        set this to the type of broadcast.
+1124
+1125        Valid inputs are:
+1126        - `all` (default): Returns all games,
+1127            and all known broadcasters for those games.
+1128        - `tv`: Returns all known TV broadcasters for CFB games
+1129            in the requested time frame.
+1130        - `radio`: Returns all known radio broadcasters
+1131            for CFB games in the requested time frame.
+1132        - `web`: Returns all known web broadcasts (like ESPN+)
+1133            for CFB games in the requested time frame.
+1134        - `ppv`: Returns all known Pay Per View (PPV) broadcasts
+1135            for CFB games in the requested time frame.
+1136        - `mobile`: Returns all known broadcasters that only broadcasted
+1137            games on mobile devices (?)
+1138
+1139    `ncaa_division` (str, semi-optional):
+1140        Semi-optional argument.
+1141        By default, `ncaa_division` will be set to "fbs",
+1142        short for the Football Bowl Subdivision (FBS),
+1143        formerly known as D1-A (read as "division one single A"),
+1144        the highest level in the NCAA football pyramid,
+1145        where teams can scholarship up to 85 players
+1146        on their football team solely for athletic ability,
+1147        and often have the largest athletics budgets
+1148        within the NCAA.
+1149
+1150        Other valid inputs are:
+1151        - "fcs": Football Championship Subdivision (FCS),
+1152            formerly known as D1-AA (read as "division one double A").
+1153            An FCS school is still in the 1st division of the NCAA,
+1154            making them eligible for the March Madness tournament,
+1155            but may not have the resources to compete at the FBS level
+1156            at this time. FCS schools are limited to 63 athletic scholarships
+1157            for football.
+1158        - "ii": NCAA Division II. Schools in this and D3 are not
+1159            eligible for the March Madness tournament,
+1160            and are limited to 36 athletic scholarships
+1161            for their football team.
+1162        - "iii": NCAA Division III. The largest single division within the
+1163            NCAA football pyramid.
+1164            D3 schools have the distinction of being part of
+1165            the only NCAA division that cannot give out scholarships solely
+1166            for athletic ability.
+1167
+1168    `return_as_dict` (bool, semi-optional):
+1169        Semi-optional argument.
+1170        If you want this function to return
+1171        the data as a dictionary (read: JSON object),
+1172        instead of a pandas `DataFrame` object,
+1173        set `return_as_dict` to `True`.
+1174
+1175    Usage
+1176    ----------
+1177    ```
+1178    import time
+1179
+1180    from cfbd_json_py.games import get_cfbd_game_media_info
 1181
-1182    cfbd_key = "tigersAreAwesome"  # placeholder for your CFBD API Key.
-1183
-1184    if cfbd_key is not "tigersAreAwesome":
-1185        print(
-1186            "Using the user's API key declared in this script " +
-1187            "for this example."
-1188        )
-1189
-1190        # Get a media information for the 2020 CFB season.
-1191        print("Get a media information for the 2020 CFB season.")
-1192        json_data = get_cfbd_game_media_info(
-1193            api_key=cfbd_key,
-1194            season=2020
-1195        )
-1196        print(json_data)
-1197        time.sleep(5)
-1198
-1199        # Get a media information for postseason games in the 2020 CFB season.
-1200        print("Get a media information for the 2020 CFB season.")
-1201        json_data = get_cfbd_game_media_info(
-1202            api_key=cfbd_key,
-1203            season=2020,
-1204            season_type="postseason"
-1205        )
-1206        print(json_data)
-1207        time.sleep(5)
-1208
-1209        # Get a media information for week 10 games in the 2020 CFB season.
-1210        print(
-1211            "Get a media information for week 10 games in the 2020 CFB season."
-1212        )
-1213        json_data = get_cfbd_game_media_info(
-1214            api_key=cfbd_key,
-1215            season=2020,
-1216            week=10
-1217        )
-1218        print(json_data)
-1219        time.sleep(5)
-1220
-1221        # Get all known broadcasters for games played by
-1222        # the Ohio State Football Program in the the 2019 CFB season.
-1223        print(
-1224            "Get all known broadcasters for games played by " +
-1225            "the Ohio State Football Program in the the 2019 CFB season."
-1226        )
-1227        json_data = get_cfbd_game_media_info(
-1228            api_key=cfbd_key,
-1229            season=2020,
-1230            team="Ohio State"
-1231        )
-1232        print(json_data)
-1233        time.sleep(5)
-1234
-1235        # Get all known radio broadcasters for games played by teams
-1236        # within the American Athletic conference (AAC)
-1237        # in the the 2021 CFB season.
-1238        print(
-1239            "Get all known radio broadcasters for games played " +
-1240            "by teams within the American Athletic conference (AAC) " +
-1241            "in the the 2021 CFB season."
-1242        )
-1243        json_data = get_cfbd_game_media_info(
-1244            api_key=cfbd_key,
-1245            season=2020,
-1246            conference="AAC"
-1247        )
-1248        print(json_data)
-1249        time.sleep(5)
-1250
-1251        # Get all known radio broadcasters
-1252        # for games in the the 2020 CFB season.
-1253        print(
-1254            "Get all known radio broadcasters " +
-1255            "for games in the the 2020 CFB season."
-1256        )
-1257        json_data = get_cfbd_game_media_info(
-1258            api_key=cfbd_key,
-1259            season=2020,
-1260            media_type="radio"
-1261        )
-1262        print(json_data)
-1263        time.sleep(5)
-1264
-1265        # Get all known broadcasters for
-1266        # the Football Championship Subdivision (FCS) games
-1267        # in the 2020 CFB season.
-1268        print(
-1269            "Get all known broadcasters for " +
-1270            "the Football Championship Subdivision (FCS) games " +
-1271            "in the 2020 CFB season."
-1272        )
-1273        json_data = get_cfbd_game_media_info(
-1274            api_key=cfbd_key,
-1275            season=2020,
-1276            ncaa_division="fcs"
-1277        )
-1278        print(json_data)
-1279        time.sleep(5)
-1280
-1281        # You can also tell this function to just return the API call as
-1282        # a Dictionary (read: JSON) object.
-1283        print(
-1284            "You can also tell this function to just return the API call " +
-1285            "as a Dictionary (read: JSON) object."
-1286        )
-1287        json_data = get_cfbd_game_media_info(
-1288            season=2020,
-1289            api_key=cfbd_key,
-1290            return_as_dict=True
-1291        )
-1292        print(json_data)
-1293
-1294    else:
-1295        # Alternatively, if the CFBD API key exists in this python environment,
-1296        # or it's been set by cfbd_json_py.utls.set_cfbd_api_token(),
-1297        # you could just call these functions directly,
-1298        # without setting the API key in the script.
-1299        print(
-1300            "Using the user's API key supposedly loaded " +
-1301            "into this python environment for this example."
-1302        )
-1303
-1304        # Get a media information for the 2020 CFB season.
-1305        print("Get a media information for the 2020 CFB season.")
-1306        json_data = get_cfbd_game_media_info(
-1307            season=2020
-1308        )
-1309        print(json_data)
-1310        time.sleep(5)
-1311
-1312        # Get a media information for postseason games in the 2020 CFB season.
-1313        print("Get a media information for the 2020 CFB season.")
-1314        json_data = get_cfbd_game_media_info(
-1315            season=2020,
-1316            season_type="postseason"
-1317        )
-1318        print(json_data)
-1319        time.sleep(5)
-1320
-1321        # Get a media information for week 10 games in the 2020 CFB season.
-1322        print(
-1323            "Get a media information for week 10 games in the 2020 CFB season."
-1324        )
-1325        json_data = get_cfbd_game_media_info(
-1326            season=2020,
-1327            week=10
-1328        )
-1329        print(json_data)
-1330        time.sleep(5)
-1331
-1332        # Get all known broadcasters for games played by
-1333        # the Ohio State Football Program in the the 2019 CFB season.
-1334        print(
-1335            "Get all known broadcasters for games played by " +
-1336            "the Ohio State Football Program in the the 2019 CFB season."
-1337        )
-1338        json_data = get_cfbd_game_media_info(
-1339            season=2020,
-1340            team="Ohio State"
-1341        )
-1342        print(json_data)
-1343        time.sleep(5)
-1344
-1345        # Get all known radio broadcasters for games played by teams
-1346        # within the American Athletic conference (AAC)
-1347        # in the the 2021 CFB season.
-1348        print(
-1349            "Get all known radio broadcasters for games played " +
-1350            "by teams within the American Athletic conference (AAC) " +
-1351            "in the the 2021 CFB season."
-1352        )
-1353        json_data = get_cfbd_game_media_info(
-1354            season=2020,
-1355            conference="AAC"
-1356        )
-1357        print(json_data)
-1358        time.sleep(5)
-1359
-1360        # Get all known radio broadcasters
-1361        # for games in the the 2020 CFB season.
-1362        print(
-1363            "Get all known radio broadcasters " +
-1364            "for games in the the 2020 CFB season."
-1365        )
-1366        json_data = get_cfbd_game_media_info(
-1367            season=2020,
-1368            media_type="radio"
-1369        )
-1370        print(json_data)
-1371        time.sleep(5)
-1372
-1373        # Get all known broadcasters for
-1374        # the Football Championship Subdivision (FCS) games
-1375        # in the 2020 CFB season.
-1376        print(
-1377            "Get all known broadcasters for " +
-1378            "the Football Championship Subdivision (FCS) games " +
-1379            "in the 2020 CFB season."
-1380        )
-1381        json_data = get_cfbd_game_media_info(
-1382            season=2020,
-1383            ncaa_division="fcs"
-1384        )
-1385        print(json_data)
-1386        time.sleep(5)
-1387
+1182
+1183    cfbd_key = "tigersAreAwesome"  # placeholder for your CFBD API Key.
+1184
+1185    if cfbd_key is not "tigersAreAwesome":
+1186        print(
+1187            "Using the user's API key declared in this script " +
+1188            "for this example."
+1189        )
+1190
+1191        # Get a media information for the 2020 CFB season.
+1192        print("Get a media information for the 2020 CFB season.")
+1193        json_data = get_cfbd_game_media_info(
+1194            api_key=cfbd_key,
+1195            season=2020
+1196        )
+1197        print(json_data)
+1198        time.sleep(5)
+1199
+1200        # Get a media information for postseason games in the 2020 CFB season.
+1201        print("Get a media information for the 2020 CFB season.")
+1202        json_data = get_cfbd_game_media_info(
+1203            api_key=cfbd_key,
+1204            season=2020,
+1205            season_type="postseason"
+1206        )
+1207        print(json_data)
+1208        time.sleep(5)
+1209
+1210        # Get a media information for week 10 games in the 2020 CFB season.
+1211        print(
+1212            "Get a media information for week 10 games in the 2020 CFB season."
+1213        )
+1214        json_data = get_cfbd_game_media_info(
+1215            api_key=cfbd_key,
+1216            season=2020,
+1217            week=10
+1218        )
+1219        print(json_data)
+1220        time.sleep(5)
+1221
+1222        # Get all known broadcasters for games played by
+1223        # the Ohio State Football Program in the the 2019 CFB season.
+1224        print(
+1225            "Get all known broadcasters for games played by " +
+1226            "the Ohio State Football Program in the the 2019 CFB season."
+1227        )
+1228        json_data = get_cfbd_game_media_info(
+1229            api_key=cfbd_key,
+1230            season=2020,
+1231            team="Ohio State"
+1232        )
+1233        print(json_data)
+1234        time.sleep(5)
+1235
+1236        # Get all known radio broadcasters for games played by teams
+1237        # within the American Athletic conference (AAC)
+1238        # in the the 2021 CFB season.
+1239        print(
+1240            "Get all known radio broadcasters for games played " +
+1241            "by teams within the American Athletic conference (AAC) " +
+1242            "in the the 2021 CFB season."
+1243        )
+1244        json_data = get_cfbd_game_media_info(
+1245            api_key=cfbd_key,
+1246            season=2020,
+1247            conference="AAC"
+1248        )
+1249        print(json_data)
+1250        time.sleep(5)
+1251
+1252        # Get all known radio broadcasters
+1253        # for games in the the 2020 CFB season.
+1254        print(
+1255            "Get all known radio broadcasters " +
+1256            "for games in the the 2020 CFB season."
+1257        )
+1258        json_data = get_cfbd_game_media_info(
+1259            api_key=cfbd_key,
+1260            season=2020,
+1261            media_type="radio"
+1262        )
+1263        print(json_data)
+1264        time.sleep(5)
+1265
+1266        # Get all known broadcasters for
+1267        # the Football Championship Subdivision (FCS) games
+1268        # in the 2020 CFB season.
+1269        print(
+1270            "Get all known broadcasters for " +
+1271            "the Football Championship Subdivision (FCS) games " +
+1272            "in the 2020 CFB season."
+1273        )
+1274        json_data = get_cfbd_game_media_info(
+1275            api_key=cfbd_key,
+1276            season=2020,
+1277            ncaa_division="fcs"
+1278        )
+1279        print(json_data)
+1280        time.sleep(5)
+1281
+1282        # You can also tell this function to just return the API call as
+1283        # a Dictionary (read: JSON) object.
+1284        print(
+1285            "You can also tell this function to just return the API call " +
+1286            "as a Dictionary (read: JSON) object."
+1287        )
+1288        json_data = get_cfbd_game_media_info(
+1289            season=2020,
+1290            api_key=cfbd_key,
+1291            return_as_dict=True
+1292        )
+1293        print(json_data)
+1294
+1295    else:
+1296        # Alternatively, if the CFBD API key exists in this python environment,
+1297        # or it's been set by cfbd_json_py.utls.set_cfbd_api_token(),
+1298        # you could just call these functions directly,
+1299        # without setting the API key in the script.
+1300        print(
+1301            "Using the user's API key supposedly loaded " +
+1302            "into this python environment for this example."
+1303        )
+1304
+1305        # Get a media information for the 2020 CFB season.
+1306        print("Get a media information for the 2020 CFB season.")
+1307        json_data = get_cfbd_game_media_info(
+1308            season=2020
+1309        )
+1310        print(json_data)
+1311        time.sleep(5)
+1312
+1313        # Get a media information for postseason games in the 2020 CFB season.
+1314        print("Get a media information for the 2020 CFB season.")
+1315        json_data = get_cfbd_game_media_info(
+1316            season=2020,
+1317            season_type="postseason"
+1318        )
+1319        print(json_data)
+1320        time.sleep(5)
+1321
+1322        # Get a media information for week 10 games in the 2020 CFB season.
+1323        print(
+1324            "Get a media information for week 10 games in the 2020 CFB season."
+1325        )
+1326        json_data = get_cfbd_game_media_info(
+1327            season=2020,
+1328            week=10
+1329        )
+1330        print(json_data)
+1331        time.sleep(5)
+1332
+1333        # Get all known broadcasters for games played by
+1334        # the Ohio State Football Program in the the 2019 CFB season.
+1335        print(
+1336            "Get all known broadcasters for games played by " +
+1337            "the Ohio State Football Program in the the 2019 CFB season."
+1338        )
+1339        json_data = get_cfbd_game_media_info(
+1340            season=2020,
+1341            team="Ohio State"
+1342        )
+1343        print(json_data)
+1344        time.sleep(5)
+1345
+1346        # Get all known radio broadcasters for games played by teams
+1347        # within the American Athletic conference (AAC)
+1348        # in the the 2021 CFB season.
+1349        print(
+1350            "Get all known radio broadcasters for games played " +
+1351            "by teams within the American Athletic conference (AAC) " +
+1352            "in the the 2021 CFB season."
+1353        )
+1354        json_data = get_cfbd_game_media_info(
+1355            season=2020,
+1356            conference="AAC"
+1357        )
+1358        print(json_data)
+1359        time.sleep(5)
+1360
+1361        # Get all known radio broadcasters
+1362        # for games in the the 2020 CFB season.
+1363        print(
+1364            "Get all known radio broadcasters " +
+1365            "for games in the the 2020 CFB season."
+1366        )
+1367        json_data = get_cfbd_game_media_info(
+1368            season=2020,
+1369            media_type="radio"
+1370        )
+1371        print(json_data)
+1372        time.sleep(5)
+1373
+1374        # Get all known broadcasters for
+1375        # the Football Championship Subdivision (FCS) games
+1376        # in the 2020 CFB season.
+1377        print(
+1378            "Get all known broadcasters for " +
+1379            "the Football Championship Subdivision (FCS) games " +
+1380            "in the 2020 CFB season."
+1381        )
+1382        json_data = get_cfbd_game_media_info(
+1383            season=2020,
+1384            ncaa_division="fcs"
+1385        )
+1386        print(json_data)
+1387        time.sleep(5)
 1388
-1389        # You can also tell this function to just return the API call as
-1390        # a Dictionary (read: JSON) object.
-1391        print(
-1392            "You can also tell this function to just return the API call " +
-1393            "as a Dictionary (read: JSON) object."
-1394        )
-1395        json_data = get_cfbd_game_media_info(
-1396            season=2020,
-1397            return_as_dict=True
-1398        )
-1399        print(json_data)
-1400
-1401    ```
-1402    Returns
-1403    ----------
-1404    A pandas `DataFrame` object with college football media information,
-1405    or (if `return_as_dict` is set to `True`)
-1406    a dictionary object with college football media information.
-1407
-1408    """
-1409
-1410    now = datetime.now()
-1411    cfb_games_df = pd.DataFrame()
-1412    # row_df = pd.DataFrame()
-1413    url = "https://api.collegefootballdata.com/games/media"
-1414
-1415    ##########################################################################
-1416
-1417    if api_key is not None:
-1418        real_api_key = api_key
-1419        del api_key
-1420    else:
-1421        real_api_key = get_cfbd_api_token(api_key_dir=api_key_dir)
-1422
-1423    if real_api_key == "tigersAreAwesome":
-1424        raise ValueError(
-1425            "You actually need to change `cfbd_key` to your CFBD API key."
-1426        )
-1427    elif "Bearer " in real_api_key:
-1428        pass
-1429    elif "Bearer" in real_api_key:
-1430        real_api_key = real_api_key.replace("Bearer", "Bearer ")
-1431    else:
-1432        real_api_key = "Bearer " + real_api_key
-1433
-1434    if season is None:
-1435        # This should never happen without user tampering, but if it does,
-1436        # we need to raise an error,
-1437        # because the CFBD API will refuse this call without a valid season.
-1438        raise SystemError(
-1439            "I don't know how, I don't know why, "
-1440            + "but you managed to call this function "
-1441            + "while `season` was `None` (NULL),"
-1442            + " and the function got to this point in the code."
-1443            + "\nIf you have a GitHub account, "
-1444            + "please raise an issue on this python package's GitHub page:\n"
-1445            + "https://github.com/armstjc/cfbd-json-py/issues"
-1446        )
-1447    elif season > (now.year + 1):
-1448        raise ValueError(f"`season` cannot be greater than {season}.")
-1449    elif season < 1869:
-1450        raise ValueError("`season` cannot be less than 1869.")
-1451
-1452    if (
-1453        season_type != "both"
-1454        and season_type != "regular"
-1455        and season_type != "postseason"
-1456    ):
-1457        raise ValueError(
-1458            "`season_type` must be set to "
-1459            + '"both", "regular", or "postseason" for this function to work.'
-1460        )
-1461
-1462    if (
-1463        media_type != "all"
-1464        and media_type != "tv"
-1465        and media_type != "radio"
-1466        and media_type != "web"
-1467        and media_type != "ppv"
-1468        and media_type != "mobile"
-1469    ):
-1470        raise ValueError(
-1471            "`media_type` must be set "
-1472            + "to one of the following values for this function to work:"
-1473            + "\n\t- `all`"
-1474            + "\n\t- `tv`"
-1475            + "\n\t- `radio`"
-1476            + "\n\t- `web`"
-1477            + "\n\t- `ppv`"
-1478            + "\n\t- `mobile`"
-1479        )
-1480
-1481    if (
-1482        ncaa_division.lower() == "fbs"
-1483        or ncaa_division.lower() == "fcs"
-1484        or ncaa_division.lower() == "ii"
-1485        or ncaa_division.lower() == "iii"
-1486    ):
-1487        pass
-1488    else:
-1489        raise ValueError(
-1490            "An invalid NCAA Division was inputted when calling this function."
-1491            + '\nValid inputs are:\n-"fbs"\n-"fcs"\n-"ii"\n-"iii"'
-1492            + f"\n\nYou entered: \n{ncaa_division}"
-1493        )
-1494
-1495    # URL builder
-1496    ##########################################################################
-1497
-1498    # Required by API
-1499    url += f"?year={season}"
-1500
-1501    if week is not None:
-1502        url += f"&week={week}"
-1503
-1504    if team is not None:
-1505        url += f"&team={team}"
-1506
-1507    if conference is not None:
-1508        url += f"&conference={conference}"
-1509
-1510    if season_type is not None:
-1511        url += f"&seasonType={season_type}"
-1512
-1513    if media_type == "all":
-1514        # If we don't care about what media type we want back,
-1515        # we don't need to add anything to the URL.
-1516        pass
-1517    elif media_type is not None:
-1518        url += f"&mediaType={media_type}"
-1519
-1520    if ncaa_division is not None:
-1521        url += f"&classification={ncaa_division}"
-1522
-1523    headers = {
-1524        "Authorization": f"{real_api_key}",
-1525        "accept": "application/json"
-1526    }
-1527    response = requests.get(url, headers=headers)
-1528
-1529    if response.status_code == 200:
-1530        pass
-1531    elif response.status_code == 401:
-1532        raise ConnectionRefusedError(
-1533            "Could not connect. The connection was refused." +
-1534            "\nHTTP Status Code 401."
-1535        )
-1536    else:
-1537        raise ConnectionError(
-1538            f"Could not connect.\nHTTP Status code {response.status_code}"
-1539        )
-1540
-1541    json_data = response.json()
-1542
-1543    if return_as_dict is True:
-1544        return json_data
-1545
-1546    # for game in tqdm(json_data):
-1547    #     row_df = pd.DataFrame({"season": season}, index=[0])
-1548    #     row_df["week"] = game["week"]
-1549    #     row_df["game_id"] = game["id"]
-1550    #     row_df["season_type"] = game["seasonType"]
-1551    #     row_df["game_start_time"] = game["startTime"]
-1552    #     row_df["is_start_time_tbd"] = game["isStartTimeTBD"]
-1553    #     row_df["home_team"] = game["homeTeam"]
-1554    #     row_df["home_conference"] = game["homeConference"]
-1555    #     row_df["away_team"] = game["awayTeam"]
-1556    #     row_df["away_conference"] = game["awayConference"]
-1557    #     row_df["media_type"] = game["mediaType"]
-1558    #     row_df["outlet"] = game["outlet"]
-1559
-1560    #     cfb_games_df = pd.concat([cfb_games_df, row_df], ignore_index=True)
-1561    #     del row_df
-1562
-1563    cfb_games_df = pd.json_normalize(json_data)
-1564    # print(cfb_games_df.columns)
-1565    cfb_games_df.rename(
-1566        columns={
-1567            "seasonType": "season_type",
-1568            "startTime": "start_time",
-1569            "isStartTimeTBD": "is_start_time_tbd",
-1570            "homeTeam": "home_team_name",
-1571            "homeConference": "home_conference_name",
-1572            "awayTeam": "away_team_name",
-1573            "awayConference": "away_conference_name",
-1574            "mediaType": "media_type",
-1575        },
-1576        inplace=True,
-1577    )
-1578    return cfb_games_df
+1389
+1390        # You can also tell this function to just return the API call as
+1391        # a Dictionary (read: JSON) object.
+1392        print(
+1393            "You can also tell this function to just return the API call " +
+1394            "as a Dictionary (read: JSON) object."
+1395        )
+1396        json_data = get_cfbd_game_media_info(
+1397            season=2020,
+1398            return_as_dict=True
+1399        )
+1400        print(json_data)
+1401
+1402    ```
+1403    Returns
+1404    ----------
+1405    A pandas `DataFrame` object with college football media information,
+1406    or (if `return_as_dict` is set to `True`)
+1407    a dictionary object with college football media information.
+1408
+1409    """
+1410
+1411    now = datetime.now()
+1412    cfb_games_df = pd.DataFrame()
+1413    # row_df = pd.DataFrame()
+1414    url = "https://api.collegefootballdata.com/games/media"
+1415
+1416    ##########################################################################
+1417
+1418    if api_key is not None:
+1419        real_api_key = api_key
+1420        del api_key
+1421    else:
+1422        real_api_key = get_cfbd_api_token(api_key_dir=api_key_dir)
+1423
+1424    if real_api_key == "tigersAreAwesome":
+1425        raise ValueError(
+1426            "You actually need to change `cfbd_key` to your CFBD API key."
+1427        )
+1428    elif "Bearer " in real_api_key:
+1429        pass
+1430    elif "Bearer" in real_api_key:
+1431        real_api_key = real_api_key.replace("Bearer", "Bearer ")
+1432    else:
+1433        real_api_key = "Bearer " + real_api_key
+1434
+1435    if season is None:
+1436        # This should never happen without user tampering, but if it does,
+1437        # we need to raise an error,
+1438        # because the CFBD API will refuse this call without a valid season.
+1439        raise SystemError(
+1440            "I don't know how, I don't know why, "
+1441            + "but you managed to call this function "
+1442            + "while `season` was `None` (NULL),"
+1443            + " and the function got to this point in the code."
+1444            + "\nIf you have a GitHub account, "
+1445            + "please raise an issue on this python package's GitHub page:\n"
+1446            + "https://github.com/armstjc/cfbd-json-py/issues"
+1447        )
+1448    elif season > (now.year + 1):
+1449        raise ValueError(f"`season` cannot be greater than {season}.")
+1450    elif season < 1869:
+1451        raise ValueError("`season` cannot be less than 1869.")
+1452
+1453    if (
+1454        season_type != "both"
+1455        and season_type != "regular"
+1456        and season_type != "postseason"
+1457    ):
+1458        raise ValueError(
+1459            "`season_type` must be set to "
+1460            + '"both", "regular", or "postseason" for this function to work.'
+1461        )
+1462
+1463    if (
+1464        media_type != "all"
+1465        and media_type != "tv"
+1466        and media_type != "radio"
+1467        and media_type != "web"
+1468        and media_type != "ppv"
+1469        and media_type != "mobile"
+1470    ):
+1471        raise ValueError(
+1472            "`media_type` must be set "
+1473            + "to one of the following values for this function to work:"
+1474            + "\n\t- `all`"
+1475            + "\n\t- `tv`"
+1476            + "\n\t- `radio`"
+1477            + "\n\t- `web`"
+1478            + "\n\t- `ppv`"
+1479            + "\n\t- `mobile`"
+1480        )
+1481
+1482    if (
+1483        ncaa_division.lower() == "fbs"
+1484        or ncaa_division.lower() == "fcs"
+1485        or ncaa_division.lower() == "ii"
+1486        or ncaa_division.lower() == "iii"
+1487    ):
+1488        pass
+1489    else:
+1490        raise ValueError(
+1491            "An invalid NCAA Division was inputted when calling this function."
+1492            + '\nValid inputs are:\n-"fbs"\n-"fcs"\n-"ii"\n-"iii"'
+1493            + f"\n\nYou entered: \n{ncaa_division}"
+1494        )
+1495
+1496    # URL builder
+1497    ##########################################################################
+1498
+1499    # Required by API
+1500    url += f"?year={season}"
+1501
+1502    if week is not None:
+1503        url += f"&week={week}"
+1504
+1505    if team is not None:
+1506        url += f"&team={team}"
+1507
+1508    if conference is not None:
+1509        url += f"&conference={conference}"
+1510
+1511    if season_type is not None:
+1512        url += f"&seasonType={season_type}"
+1513
+1514    if media_type == "all":
+1515        # If we don't care about what media type we want back,
+1516        # we don't need to add anything to the URL.
+1517        pass
+1518    elif media_type is not None:
+1519        url += f"&mediaType={media_type}"
+1520
+1521    if ncaa_division is not None:
+1522        url += f"&classification={ncaa_division}"
+1523
+1524    headers = {
+1525        "Authorization": f"{real_api_key}",
+1526        "accept": "application/json"
+1527    }
+1528    response = requests.get(url, headers=headers)
+1529
+1530    if response.status_code == 200:
+1531        pass
+1532    elif response.status_code == 401:
+1533        raise ConnectionRefusedError(
+1534            "Could not connect. The connection was refused." +
+1535            "\nHTTP Status Code 401."
+1536        )
+1537    else:
+1538        raise ConnectionError(
+1539            f"Could not connect.\nHTTP Status code {response.status_code}"
+1540        )
+1541
+1542    json_data = response.json()
+1543
+1544    if return_as_dict is True:
+1545        return json_data
+1546
+1547    # for game in tqdm(json_data):
+1548    #     row_df = pd.DataFrame({"season": season}, index=[0])
+1549    #     row_df["week"] = game["week"]
+1550    #     row_df["game_id"] = game["id"]
+1551    #     row_df["season_type"] = game["seasonType"]
+1552    #     row_df["game_start_time"] = game["startTime"]
+1553    #     row_df["is_start_time_tbd"] = game["isStartTimeTBD"]
+1554    #     row_df["home_team"] = game["homeTeam"]
+1555    #     row_df["home_conference"] = game["homeConference"]
+1556    #     row_df["away_team"] = game["awayTeam"]
+1557    #     row_df["away_conference"] = game["awayConference"]
+1558    #     row_df["media_type"] = game["mediaType"]
+1559    #     row_df["outlet"] = game["outlet"]
+1560
+1561    #     cfb_games_df = pd.concat([cfb_games_df, row_df], ignore_index=True)
+1562    #     del row_df
+1563
+1564    cfb_games_df = pd.json_normalize(json_data)
+1565    # print(cfb_games_df.columns)
+1566    cfb_games_df.rename(
+1567        columns={
+1568            "seasonType": "season_type",
+1569            "startTime": "start_time",
+1570            "isStartTimeTBD": "is_start_time_tbd",
+1571            "homeTeam": "home_team_name",
+1572            "homeConference": "home_conference_name",
+1573            "awayTeam": "away_team_name",
+1574            "awayConference": "away_conference_name",
+1575            "mediaType": "media_type",
+1576        },
+1577        inplace=True,
+1578    )
+1579    return cfb_games_df
 
@@ -9235,7 +7741,7 @@

Returns

class="o">=
None, conference: str = None, stat_category: str s_category: str = None, game_id: int = None, Returns

-
1581def get_cfbd_player_game_stats(
-1582    season: int,
-1583    api_key: str = None,
-1584    api_key_dir: str = None,
-1585    season_type: str = "regular",  # "regular" or "postseason"
-1586    week: int = None,
-1587    team: str = None,
-1588    conference: str = None,
-1589    # `week`, `team`, and/or `conference`
-1590    # must be not null for this function to work.
-1591    stat_category: str = None,
-1592    game_id: int = None,
-1593    return_as_dict: bool = False,
-1594):
-1595    """
-1596    Retrieves player game stats for a given time frame.
-1597
-1598    Parameters
-1599    ----------
-1600    `season` (int, mandatory):
-1601        Required argument.
-1602        Specifies the season you want CFB player game stats from.
-1603        This must be specified, otherwise this package, and by extension
-1604        the CFBD API, will not accept the request to get CFB player game stats.
-1605
-1606    `api_key` (str, optional):
-1607        Semi-optional argument.
-1608        If `api_key` is null, this function will attempt to load a CFBD API key
-1609        from the python environment, or from a file on this computer.
-1610        If `api_key` is not null,
-1611        this function will automatically assume that the
-1612        inputted `api_key` is a valid CFBD API key.
-1613
-1614    `api_key_dir` (str, optional):
-1615        Optional argument.
-1616        If `api_key` is set to am empty string, this variable is ignored.
-1617        If `api_key_dir` is null, and `api_key` is null,
-1618        this function will try to find
-1619        a CFBD API key file in this user's home directory.
-1620        If `api_key_dir` is set to a string, and `api_key` is null,
-1621        this function will assume that `api_key_dir` is a directory,
-1622        and will try to find a CFBD API key file in that directory.
-1623
-1624    `season_type` (str, semi-optional):
-1625        Semi-optional argument.
-1626        By default, this will be set to "regular", for the CFB regular season.
-1627        If you want CFB player game stats for non-regular season games,
-1628        set `season_type` to "postseason".
-1629        If `season_type` is set to anything but "regular" or "postseason",
-1630        a `ValueError()` will be raised.
-1631
-1632    **For the following three variables,
-1633    at least one must be set to
-1634    a non-null variable when calling this function.**
-1635
-1636    `week` (int, optional):
-1637        Optional argument.
-1638        If `week` is set to an integer, this function will attempt
-1639        to load CFB player game stats from games in that season,
-1640        and in that week.
-1641
-1642    `team` (str, optional):
-1643        Optional argument.
-1644        If you only want CFB player game stats for a team,
-1645        regardless if they are the home/away team,
-1646        set `team` to the name of the team you want CFB player game stats from.
-1647
-1648    `conference` (str, optional):
-1649        Optional argument.
-1650        If you only want player game stats from games
-1651        involving teams a specific conference,
-1652        set `conference` to the abbreviation
-1653        of the conference you want stats from.
-1654
-1655    `stat_category` (str, optional):
-1656        Optional argument.
-1657        If only want stats for a specific stat category,
-1658        set this variable to that category.
-1659
-1660        Valid inputs are:
-1661        - `passing`
-1662        - `rushing`
-1663        - `receiving`
-1664        - `fumbles`
-1665        - `defensive`
-1666        - `interceptions`
-1667        - `punting`
-1668        - `kicking`
-1669        - `kickReturns`
-1670        - `puntReturns`
-1671
-1672    `game_id` (int, optional):
-1673        Optional argument.
-1674        If `game_id` is set to a game ID, `get_cfbd_player_game_stats()`
-1675        will try to get player game stats just for that game ID.
-1676
-1677    `return_as_dict` (bool, semi-optional):
-1678        Semi-optional argument.
-1679        If you want this function to return
-1680        the data as a dictionary (read: JSON object),
-1681        instead of a pandas `DataFrame` object,
-1682        set `return_as_dict` to `True`.
-1683
-1684    Usage
-1685    ----------
-1686    ```
-1687    import time
-1688
-1689    from cfbd_json_py.games import get_cfbd_player_game_stats
-1690
+                
1582def get_cfbd_player_game_stats(
+1583    season: int,
+1584    api_key: str = None,
+1585    api_key_dir: str = None,
+1586    season_type: str = "regular",  # "regular" or "postseason"
+1587    week: int = None,
+1588    team: str = None,
+1589    conference: str = None,
+1590    # `week`, `team`, and/or `conference`
+1591    # must be not null for this function to work.
+1592    s_category: str = None,
+1593    game_id: int = None,
+1594    return_as_dict: bool = False,
+1595):
+1596    """
+1597    Retrieves player game stats for a given time frame.
+1598
+1599    Parameters
+1600    ----------
+1601    `season` (int, mandatory):
+1602        Required argument.
+1603        Specifies the season you want CFB player game stats from.
+1604        This must be specified, otherwise this package, and by extension
+1605        the CFBD API, will not accept the request to get CFB player game stats.
+1606
+1607    `api_key` (str, optional):
+1608        Semi-optional argument.
+1609        If `api_key` is null, this function will attempt to load a CFBD API key
+1610        from the python environment, or from a file on this computer.
+1611        If `api_key` is not null,
+1612        this function will automatically assume that the
+1613        inputted `api_key` is a valid CFBD API key.
+1614
+1615    `api_key_dir` (str, optional):
+1616        Optional argument.
+1617        If `api_key` is set to am empty string, this variable is ignored.
+1618        If `api_key_dir` is null, and `api_key` is null,
+1619        this function will try to find
+1620        a CFBD API key file in this user's home directory.
+1621        If `api_key_dir` is set to a string, and `api_key` is null,
+1622        this function will assume that `api_key_dir` is a directory,
+1623        and will try to find a CFBD API key file in that directory.
+1624
+1625    `season_type` (str, semi-optional):
+1626        Semi-optional argument.
+1627        By default, this will be set to "regular", for the CFB regular season.
+1628        If you want CFB player game stats for non-regular season games,
+1629        set `season_type` to "postseason".
+1630        If `season_type` is set to anything but "regular" or "postseason",
+1631        a `ValueError()` will be raised.
+1632
+1633    **For the following three variables,
+1634    at least one must be set to
+1635    a non-null variable when calling this function.**
+1636
+1637    `week` (int, optional):
+1638        Optional argument.
+1639        If `week` is set to an integer, this function will attempt
+1640        to load CFB player game stats from games in that season,
+1641        and in that week.
+1642
+1643    `team` (str, optional):
+1644        Optional argument.
+1645        If you only want CFB player game stats for a team,
+1646        regardless if they are the home/away team,
+1647        set `team` to the name of the team you want CFB player game stats from.
+1648
+1649    `conference` (str, optional):
+1650        Optional argument.
+1651        If you only want player game stats from games
+1652        involving teams a specific conference,
+1653        set `conference` to the abbreviation
+1654        of the conference you want stats from.
+1655
+1656    `stat_category` (str, optional):
+1657        Optional argument.
+1658        If only want stats for a specific stat category,
+1659        set this variable to that category.
+1660
+1661        Valid inputs are:
+1662        - `passing`
+1663        - `rushing`
+1664        - `receiving`
+1665        - `fumbles`
+1666        - `defensive`
+1667        - `interceptions`
+1668        - `punting`
+1669        - `kicking`
+1670        - `kickReturns`
+1671        - `puntReturns`
+1672
+1673    `game_id` (int, optional):
+1674        Optional argument.
+1675        If `game_id` is set to a game ID, `get_cfbd_player_game_stats()`
+1676        will try to get player game stats just for that game ID.
+1677
+1678    `return_as_dict` (bool, semi-optional):
+1679        Semi-optional argument.
+1680        If you want this function to return
+1681        the data as a dictionary (read: JSON object),
+1682        instead of a pandas `DataFrame` object,
+1683        set `return_as_dict` to `True`.
+1684
+1685    Usage
+1686    ----------
+1687    ```
+1688    import time
+1689
+1690    from cfbd_json_py.games import get_cfbd_player_game_stats
 1691
-1692    cfbd_key = "tigersAreAwesome"  # placeholder for your CFBD API Key.
-1693
-1694    if cfbd_key is not "tigersAreAwesome":
-1695        print(
-1696            "Using the user's API key declared in this script " +
-1697            "for this example."
-1698        )
-1699
-1700        # Get player game stats for week 10 of the 2020 CFB season.
-1701        print("Get player game stats for week 10 of the 2020 CFB season.")
-1702        json_data = get_cfbd_player_game_stats(
-1703            api_key=cfbd_key,
-1704            season=2020,
-1705            week=10
-1706        )
-1707        print(json_data)
-1708        time.sleep(5)
-1709
-1710        # Get postseason player game stats for the 2020 CFB season.
-1711        print("Get postseason player game stats for the 2020 CFB season.")
-1712        json_data = get_cfbd_player_game_stats(
-1713            api_key=cfbd_key,
-1714            season=2020,
-1715            season_type="postseason",
-1716            week=1
-1717        )
-1718        print(json_data)
-1719        time.sleep(5)
-1720
-1721        # Get player game stats for
-1722        # the Alabama Crimson Tide Football Team for the 2018 CFB season.
-1723        print(
-1724            "Get player game stats for " +
-1725            "the Alabama Crimson Tide Football Team for the 2018 CFB season."
-1726        )
-1727        json_data = get_cfbd_player_game_stats(
-1728            api_key=cfbd_key,
-1729            season=2018,
-1730            team="Alabama"
-1731        )
-1732        print(json_data)
-1733        time.sleep(5)
-1734
-1735        # Get player game stats for players of teams in
-1736        # the Atlantic Coast Conference (ACC) in the 2020 CFB season.
-1737        print(
-1738            "Get player game stats for players of teams in " +
-1739            "the Atlantic Coast Conference (ACC) in the 2020 CFB season."
-1740        )
-1741        json_data = get_cfbd_player_game_stats(
-1742            api_key=cfbd_key,
-1743            season=2020,
-1744            conference="ACC"
-1745        )
-1746        print(json_data)
-1747        time.sleep(5)
-1748
-1749        # Get get passing stats from players who played
-1750        # in week 7 of the 2017 CFB season.
-1751        print(
-1752            "Get get passing stats from players who played " +
-1753            "in week 7 of the 2017 CFB season."
-1754        )
-1755        json_data = get_cfbd_player_game_stats(
-1756            api_key=cfbd_key,
-1757            season=2017,
-1758            week=7,
-1759            stat_category="passing"
-1760        )
-1761        print(json_data)
-1762        time.sleep(5)
-1763
-1764        # Get player game stats from the 2021 Virbo Citrus Bowl,
-1765        # a bowl game that happened in the 2020 CFB season.
-1766        print(
-1767            "Get player game stats from the 2021 Virbo Citrus Bowl, " +
-1768            "a bowl game that happened in the 2020 CFB season."
-1769        )
-1770        json_data = get_cfbd_player_game_stats(
-1771            api_key=cfbd_key,
-1772            season=2020,
-1773            game_id=401256199
-1774        )
-1775        print(json_data)
-1776        time.sleep(5)
-1777
-1778        # You can also tell this function to just return the API call as
-1779        # a Dictionary (read: JSON) object.
-1780        print(
-1781            "You can also tell this function to just return the API call " +
-1782            "as a Dictionary (read: JSON) object."
-1783        )
-1784        json_data = get_cfbd_player_game_stats(
-1785            season=2020,
-1786            week=10,
-1787            api_key=cfbd_key,
-1788            return_as_dict=True
-1789        )
-1790        print(json_data)
-1791
-1792    else:
-1793        # Alternatively, if the CFBD API key exists in this python environment,
-1794        # or it's been set by cfbd_json_py.utls.set_cfbd_api_token(),
-1795        # you could just call these functions directly,
-1796        # without setting the API key in the script.
-1797        print(
-1798            "Using the user's API key supposedly loaded " +
-1799            "into this python environment for this example."
-1800        )
-1801
-1802        # Get player game stats for week 10 of the 2020 CFB season.
-1803        print("Get player game stats for week 10 of the 2020 CFB season.")
-1804        json_data = get_cfbd_player_game_stats(
-1805            season=2020,
-1806            week=10
-1807        )
-1808        print(json_data)
-1809        time.sleep(5)
-1810
-1811        # Get postseason player game stats for the 2020 CFB season.
-1812        print("Get postseason player game stats for the 2020 CFB season.")
-1813        json_data = get_cfbd_player_game_stats(
-1814            season=2020,
-1815            season_type="postseason",
-1816            week=1
-1817        )
-1818        print(json_data)
-1819        time.sleep(5)
-1820
-1821        # Get player game stats for
-1822        # the Alabama Crimson Tide Football Team for the 2018 CFB season.
-1823        print(
-1824            "Get player game stats for " +
-1825            "the Alabama Crimson Tide Football Team for the 2018 CFB season."
-1826        )
-1827        json_data = get_cfbd_player_game_stats(
-1828            season=2018,
-1829            team="Alabama"
-1830        )
-1831        print(json_data)
-1832        time.sleep(5)
-1833
-1834        # Get player game stats for players of teams in
-1835        # the Atlantic Coast Conference (ACC) in the 2020 CFB season.
-1836        print(
-1837            "Get player game stats for players of teams in " +
-1838            "the Atlantic Coast Conference (ACC) in the 2020 CFB season."
-1839        )
-1840        json_data = get_cfbd_player_game_stats(
-1841            season=2020,
-1842            conference="ACC"
-1843        )
-1844        print(json_data)
-1845        time.sleep(5)
-1846
-1847        # Get get passing stats from players who played
-1848        # in week 7 of the 2017 CFB season.
-1849        print(
-1850            "Get get passing stats from players who played " +
-1851            "in week 7 of the 2017 CFB season."
-1852        )
-1853        json_data = get_cfbd_player_game_stats(
-1854            season=2017,
-1855            week=7,
-1856            stat_category="passing"
-1857        )
-1858        print(json_data)
-1859        time.sleep(5)
-1860
-1861        # Get player game stats from the 2021 Virbo Citrus Bowl,
-1862        # a bowl game that happened in the 2020 CFB season,
-1863        # between the Aubrun Tigers, and the Northwestern Wildcats.
-1864        print("Get player game stats from the 2021 Virbo Citrus Bowl, "+
-1865            "a bowl game that happened in the 2020 CFB season " +
-1866            "between the Aubrun Tigers, and the Northwestern Wildcats."
-1867        )
-1868        json_data = get_cfbd_player_game_stats(
-1869            season=2020,
-1870            game_id=401256199
-1871        )
-1872        print(json_data)
-1873        time.sleep(5)
-1874
+1692
+1693    cfbd_key = "tigersAreAwesome"  # placeholder for your CFBD API Key.
+1694
+1695    if cfbd_key is not "tigersAreAwesome":
+1696        print(
+1697            "Using the user's API key declared in this script " +
+1698            "for this example."
+1699        )
+1700
+1701        # Get player game stats for week 10 of the 2020 CFB season.
+1702        print("Get player game stats for week 10 of the 2020 CFB season.")
+1703        json_data = get_cfbd_player_game_stats(
+1704            api_key=cfbd_key,
+1705            season=2020,
+1706            week=10
+1707        )
+1708        print(json_data)
+1709        time.sleep(5)
+1710
+1711        # Get postseason player game stats for the 2020 CFB season.
+1712        print("Get postseason player game stats for the 2020 CFB season.")
+1713        json_data = get_cfbd_player_game_stats(
+1714            api_key=cfbd_key,
+1715            season=2020,
+1716            season_type="postseason",
+1717            week=1
+1718        )
+1719        print(json_data)
+1720        time.sleep(5)
+1721
+1722        # Get player game stats for
+1723        # the Alabama Crimson Tide Football Team for the 2018 CFB season.
+1724        print(
+1725            "Get player game stats for " +
+1726            "the Alabama Crimson Tide Football Team for the 2018 CFB season."
+1727        )
+1728        json_data = get_cfbd_player_game_stats(
+1729            api_key=cfbd_key,
+1730            season=2018,
+1731            team="Alabama"
+1732        )
+1733        print(json_data)
+1734        time.sleep(5)
+1735
+1736        # Get player game stats for players of teams in
+1737        # the Atlantic Coast Conference (ACC) in the 2020 CFB season.
+1738        print(
+1739            "Get player game stats for players of teams in " +
+1740            "the Atlantic Coast Conference (ACC) in the 2020 CFB season."
+1741        )
+1742        json_data = get_cfbd_player_game_stats(
+1743            api_key=cfbd_key,
+1744            season=2020,
+1745            conference="ACC"
+1746        )
+1747        print(json_data)
+1748        time.sleep(5)
+1749
+1750        # Get get passing stats from players who played
+1751        # in week 7 of the 2017 CFB season.
+1752        print(
+1753            "Get get passing stats from players who played " +
+1754            "in week 7 of the 2017 CFB season."
+1755        )
+1756        json_data = get_cfbd_player_game_stats(
+1757            api_key=cfbd_key,
+1758            season=2017,
+1759            week=7,
+1760            stat_category="passing"
+1761        )
+1762        print(json_data)
+1763        time.sleep(5)
+1764
+1765        # Get player game stats from the 2021 Virbo Citrus Bowl,
+1766        # a bowl game that happened in the 2020 CFB season.
+1767        print(
+1768            "Get player game stats from the 2021 Virbo Citrus Bowl, " +
+1769            "a bowl game that happened in the 2020 CFB season."
+1770        )
+1771        json_data = get_cfbd_player_game_stats(
+1772            api_key=cfbd_key,
+1773            season=2020,
+1774            game_id=401256199
+1775        )
+1776        print(json_data)
+1777        time.sleep(5)
+1778
+1779        # You can also tell this function to just return the API call as
+1780        # a Dictionary (read: JSON) object.
+1781        print(
+1782            "You can also tell this function to just return the API call " +
+1783            "as a Dictionary (read: JSON) object."
+1784        )
+1785        json_data = get_cfbd_player_game_stats(
+1786            season=2020,
+1787            week=10,
+1788            api_key=cfbd_key,
+1789            return_as_dict=True
+1790        )
+1791        print(json_data)
+1792
+1793    else:
+1794        # Alternatively, if the CFBD API key exists in this python environment,
+1795        # or it's been set by cfbd_json_py.utls.set_cfbd_api_token(),
+1796        # you could just call these functions directly,
+1797        # without setting the API key in the script.
+1798        print(
+1799            "Using the user's API key supposedly loaded " +
+1800            "into this python environment for this example."
+1801        )
+1802
+1803        # Get player game stats for week 10 of the 2020 CFB season.
+1804        print("Get player game stats for week 10 of the 2020 CFB season.")
+1805        json_data = get_cfbd_player_game_stats(
+1806            season=2020,
+1807            week=10
+1808        )
+1809        print(json_data)
+1810        time.sleep(5)
+1811
+1812        # Get postseason player game stats for the 2020 CFB season.
+1813        print("Get postseason player game stats for the 2020 CFB season.")
+1814        json_data = get_cfbd_player_game_stats(
+1815            season=2020,
+1816            season_type="postseason",
+1817            week=1
+1818        )
+1819        print(json_data)
+1820        time.sleep(5)
+1821
+1822        # Get player game stats for
+1823        # the Alabama Crimson Tide Football Team for the 2018 CFB season.
+1824        print(
+1825            "Get player game stats for " +
+1826            "the Alabama Crimson Tide Football Team for the 2018 CFB season."
+1827        )
+1828        json_data = get_cfbd_player_game_stats(
+1829            season=2018,
+1830            team="Alabama"
+1831        )
+1832        print(json_data)
+1833        time.sleep(5)
+1834
+1835        # Get player game stats for players of teams in
+1836        # the Atlantic Coast Conference (ACC) in the 2020 CFB season.
+1837        print(
+1838            "Get player game stats for players of teams in " +
+1839            "the Atlantic Coast Conference (ACC) in the 2020 CFB season."
+1840        )
+1841        json_data = get_cfbd_player_game_stats(
+1842            season=2020,
+1843            conference="ACC"
+1844        )
+1845        print(json_data)
+1846        time.sleep(5)
+1847
+1848        # Get get passing stats from players who played
+1849        # in week 7 of the 2017 CFB season.
+1850        print(
+1851            "Get get passing stats from players who played " +
+1852            "in week 7 of the 2017 CFB season."
+1853        )
+1854        json_data = get_cfbd_player_game_stats(
+1855            season=2017,
+1856            week=7,
+1857            stat_category="passing"
+1858        )
+1859        print(json_data)
+1860        time.sleep(5)
+1861
+1862        # Get player game stats from the 2021 Virbo Citrus Bowl,
+1863        # a bowl game that happened in the 2020 CFB season,
+1864        # between the Aubrun Tigers, and the Northwestern Wildcats.
+1865        print("Get player game stats from the 2021 Virbo Citrus Bowl, "+
+1866            "a bowl game that happened in the 2020 CFB season " +
+1867            "between the Aubrun Tigers, and the Northwestern Wildcats."
+1868        )
+1869        json_data = get_cfbd_player_game_stats(
+1870            season=2020,
+1871            game_id=401256199
+1872        )
+1873        print(json_data)
+1874        time.sleep(5)
 1875
-1876        # You can also tell this function to just return the API call as
-1877        # a Dictionary (read: JSON) object.
-1878        print(
-1879            "You can also tell this function to just return the API call " +
-1880            "as a Dictionary (read: JSON) object."
-1881        )
-1882        json_data = get_cfbd_player_game_stats(
-1883            season=2020,
-1884            week=10,
-1885            return_as_dict=True
-1886        )
-1887        print(json_data)
-1888
-1889    ```
-1890    Returns
-1891    ----------
-1892    A pandas `DataFrame` object with player game stats data,
-1893    or (if `return_as_dict` is set to `True`)
-1894    a dictionary object with player game stats data.
-1895
-1896    """
-1897
-1898    rebuilt_json = {}
+1876
+1877        # You can also tell this function to just return the API call as
+1878        # a Dictionary (read: JSON) object.
+1879        print(
+1880            "You can also tell this function to just return the API call " +
+1881            "as a Dictionary (read: JSON) object."
+1882        )
+1883        json_data = get_cfbd_player_game_stats(
+1884            season=2020,
+1885            week=10,
+1886            return_as_dict=True
+1887        )
+1888        print(json_data)
+1889
+1890    ```
+1891    Returns
+1892    ----------
+1893    A pandas `DataFrame` object with player game stats data,
+1894    or (if `return_as_dict` is set to `True`)
+1895    a dictionary object with player game stats data.
+1896
+1897    """
+1898
 1899    now = datetime.now()
-1900    cfb_games_df = pd.DataFrame()
-1901    row_df = pd.DataFrame()
-1902    url = "https://api.collegefootballdata.com/games/players"
-1903    stat_columns = [
-1904        "season",
-1905        "game_id",
-1906        "team_name",
-1907        "team_conference",
-1908        "player_id",
-1909        "player_name",
-1910        "home_away",
-1911        # PASS
-1912        "passing_C/ATT",
-1913        "passing_COMP",
-1914        "passing_ATT",
-1915        "passing_YDS",
-1916        "passing_AVG",
-1917        "passing_TD",
-1918        "passing_INT",
-1919        "passing_QBR",
-1920        # RUSH
-1921        "rushing_CAR",
-1922        "rushing_YDS",
-1923        "rushing_AVG",
-1924        "rushing_TD",
-1925        "rushing_LONG",
-1926        # REC
-1927        "receiving_REC",
-1928        "receiving_YDS",
-1929        "receiving_AVG",
-1930        "receiving_TD",
-1931        "receiving_LONG",
-1932        # FUM
-1933        "fumbles_FUM",
-1934        "fumbles_LOST",
-1935        "fumbles_REC",
-1936        # DEFENSE
-1937        "defensive_TOT",
-1938        "defensive_SOLO",
-1939        "defensive_TFL",
-1940        "defensive_QB HUR",
-1941        "defensive_SACKS",
-1942        "defensive_PD",
-1943        "defensive_TD",
-1944        # INT
-1945        "interceptions_INT",
-1946        "interceptions_YDS",
-1947        "interceptions_TD",
-1948        # PUNT
-1949        "punting_NO",
-1950        "punting_YDS",
-1951        "punting_AVG",
-1952        "punting_TB",
-1953        "punting_In 20",
-1954        "punting_LONG",
-1955        # KICK
-1956        "kicking_FG",
-1957        "kicking_FGM",
-1958        "kicking_FGA",
-1959        "kicking_PCT",
-1960        "kicking_LONG",
-1961        "kicking_XP",
-1962        "kicking_XPM",
-1963        "kicking_XPA",
-1964        "kicking_PTS",
-1965        # KR
-1966        "kickReturns_NO",
-1967        "kickReturns_YDS",
-1968        "kickReturns_AVG",
-1969        "kickReturns_TD",
-1970        "kickReturns_LONG",
-1971        # PR
-1972        "puntReturns_NO",
-1973        "puntReturns_YDS",
-1974        "puntReturns_AVG",
-1975        "puntReturns_TD",
-1976        "puntReturns_LONG",
-1977    ]
-1978
-1979    ##########################################################################
-1980
-1981    if api_key is not None:
-1982        real_api_key = api_key
-1983        del api_key
-1984    else:
-1985        real_api_key = get_cfbd_api_token(api_key_dir=api_key_dir)
-1986
-1987    if real_api_key == "tigersAreAwesome":
-1988        raise ValueError(
-1989            "You actually need to change `cfbd_key` to your CFBD API key."
-1990        )
-1991    elif "Bearer " in real_api_key:
-1992        pass
-1993    elif "Bearer" in real_api_key:
-1994        real_api_key = real_api_key.replace("Bearer", "Bearer ")
-1995    else:
-1996        real_api_key = "Bearer " + real_api_key
-1997
-1998    if season is None:
-1999        # This should never happen without user tampering, but if it does,
-2000        # we need to raise an error,
-2001        # because the CFBD API will refuse this call without a valid season.
-2002        raise SystemError(
-2003            "I don't know how, I don't know why, "
-2004            + "but you managed to call this function "
-2005            + "while `season` was `None` (NULL),"
-2006            + " and the function got to this point in the code."
-2007            + "\nIf you have a GitHub account, "
-2008            + "please raise an issue on this python package's GitHub page:\n"
-2009            + "https://github.com/armstjc/cfbd-json-py/issues"
-2010        )
-2011    elif season > (now.year + 1):
-2012        raise ValueError(f"`season` cannot be greater than {season}.")
-2013    elif season < 1869:
-2014        raise ValueError("`season` cannot be less than 1869.")
-2015
-2016    if season_type != "regular" and season_type != "postseason":
-2017        raise ValueError(
-2018            '`season_type` must be set to either "regular" or '
-2019            + '"postseason" for this function to work.'
-2020        )
-2021
-2022    # `week`, `team`, and/or `conference`
-2023    # must be not null for this function to work.
-2024
-2025    if (
-2026        week is None and
-2027        team is None and
-2028        conference is None and
-2029        game_id is None
-2030    ):
-2031        raise ValueError(
-2032            "To use `get_cfbd_player_game_stats()`,"
-2033            + " `week`, `team`, and/or `conference` "
-2034            + "need to be set to a non-null value."
-2035        )
-2036
-2037    filter_by_stat_category = False
-2038
-2039    if stat_category is None:
-2040        pass
-2041    elif stat_category == "passing":
-2042        filter_by_stat_category = True
-2043    elif stat_category == "rushing":
-2044        filter_by_stat_category = True
-2045    elif stat_category == "receiving":
+1900
+1901    rebuilt_json = {}
+1902    rebuilt_json_list = []
+1903
+1904    cfb_games_df = pd.DataFrame()
+1905    # row_df = pd.DataFrame()
+1906    url = "https://api.collegefootballdata.com/games/players"
+1907    stat_columns = [
+1908        "season",
+1909        "game_id",
+1910        "team_name",
+1911        "team_conference",
+1912        "player_id",
+1913        "player_name",
+1914        "home_away",
+1915        # PASS
+1916        "passing_C/ATT",
+1917        "passing_COMP",
+1918        "passing_ATT",
+1919        "passing_YDS",
+1920        "passing_AVG",
+1921        "passing_TD",
+1922        "passing_INT",
+1923        "passing_QBR",
+1924        # RUSH
+1925        "rushing_CAR",
+1926        "rushing_YDS",
+1927        "rushing_AVG",
+1928        "rushing_TD",
+1929        "rushing_LONG",
+1930        # REC
+1931        "receiving_REC",
+1932        "receiving_YDS",
+1933        "receiving_AVG",
+1934        "receiving_TD",
+1935        "receiving_LONG",
+1936        # FUM
+1937        "fumbles_FUM",
+1938        "fumbles_LOST",
+1939        "fumbles_REC",
+1940        # DEFENSE
+1941        "defensive_TOT",
+1942        "defensive_SOLO",
+1943        "defensive_TFL",
+1944        "defensive_QB HUR",
+1945        "defensive_SACKS",
+1946        "defensive_PD",
+1947        "defensive_TD",
+1948        # INT
+1949        "interceptions_INT",
+1950        "interceptions_YDS",
+1951        "interceptions_TD",
+1952        # PUNT
+1953        "punting_NO",
+1954        "punting_YDS",
+1955        "punting_AVG",
+1956        "punting_TB",
+1957        "punting_In 20",
+1958        "punting_LONG",
+1959        # KICK
+1960        "kicking_FG",
+1961        "kicking_FGM",
+1962        "kicking_FGA",
+1963        "kicking_PCT",
+1964        "kicking_LONG",
+1965        "kicking_XP",
+1966        "kicking_XPM",
+1967        "kicking_XPA",
+1968        "kicking_PTS",
+1969        # KR
+1970        "kickReturns_NO",
+1971        "kickReturns_YDS",
+1972        "kickReturns_AVG",
+1973        "kickReturns_TD",
+1974        "kickReturns_LONG",
+1975        # PR
+1976        "puntReturns_NO",
+1977        "puntReturns_YDS",
+1978        "puntReturns_AVG",
+1979        "puntReturns_TD",
+1980        "puntReturns_LONG",
+1981    ]
+1982
+1983    ##########################################################################
+1984
+1985    if api_key is not None:
+1986        real_api_key = api_key
+1987        del api_key
+1988    else:
+1989        real_api_key = get_cfbd_api_token(api_key_dir=api_key_dir)
+1990
+1991    if real_api_key == "tigersAreAwesome":
+1992        raise ValueError(
+1993            "You actually need to change `cfbd_key` to your CFBD API key."
+1994        )
+1995    elif "Bearer " in real_api_key:
+1996        pass
+1997    elif "Bearer" in real_api_key:
+1998        real_api_key = real_api_key.replace("Bearer", "Bearer ")
+1999    else:
+2000        real_api_key = "Bearer " + real_api_key
+2001
+2002    if season is None:
+2003        # This should never happen without user tampering, but if it does,
+2004        # we need to raise an error,
+2005        # because the CFBD API will refuse this call without a valid season.
+2006        raise SystemError(
+2007            "I don't know how, I don't know why, "
+2008            + "but you managed to call this function "
+2009            + "while `season` was `None` (NULL),"
+2010            + " and the function got to this point in the code."
+2011            + "\nIf you have a GitHub account, "
+2012            + "please raise an issue on this python package's GitHub page:\n"
+2013            + "https://github.com/armstjc/cfbd-json-py/issues"
+2014        )
+2015    elif season > (now.year + 1):
+2016        raise ValueError(f"`season` cannot be greater than {season}.")
+2017    elif season < 1869:
+2018        raise ValueError("`season` cannot be less than 1869.")
+2019
+2020    if season_type != "regular" and season_type != "postseason":
+2021        raise ValueError(
+2022            '`season_type` must be set to either "regular" or '
+2023            + '"postseason" for this function to work.'
+2024        )
+2025
+2026    # `week`, `team`, and/or `conference`
+2027    # must be not null for this function to work.
+2028
+2029    if (
+2030        week is None and
+2031        team is None and
+2032        conference is None and
+2033        game_id is None
+2034    ):
+2035        raise ValueError(
+2036            "To use `get_cfbd_player_game_stats()`,"
+2037            + " `week`, `team`, and/or `conference` "
+2038            + "need to be set to a non-null value."
+2039        )
+2040
+2041    filter_by_stat_category = False
+2042
+2043    if s_category is None:
+2044        pass
+2045    elif s_category == "passing":
 2046        filter_by_stat_category = True
-2047    elif stat_category == "fumbles":
+2047    elif s_category == "rushing":
 2048        filter_by_stat_category = True
-2049    elif stat_category == "passing":
+2049    elif s_category == "receiving":
 2050        filter_by_stat_category = True
-2051    elif stat_category == "defensive":
+2051    elif s_category == "fumbles":
 2052        filter_by_stat_category = True
-2053    elif stat_category == "interceptions":
+2053    elif s_category == "passing":
 2054        filter_by_stat_category = True
-2055    elif stat_category == "punting":
+2055    elif s_category == "defensive":
 2056        filter_by_stat_category = True
-2057    elif stat_category == "kicking":
+2057    elif s_category == "interceptions":
 2058        filter_by_stat_category = True
-2059    elif stat_category == "kickReturns":
+2059    elif s_category == "punting":
 2060        filter_by_stat_category = True
-2061    elif stat_category == "puntReturns":
+2061    elif s_category == "kicking":
 2062        filter_by_stat_category = True
-2063    else:
-2064        raise ValueError(
-2065            "Invalid input for `stat_category`."
-2066            + "\nValid inputs are:"
-2067            + """
-2068            - `passing`
-2069            - `rushing`
-2070            - `receiving`
-2071            - `fumbles`
-2072            - `defensive`
-2073            - `interceptions`
-2074            - `punting`
-2075            - `kicking`
-2076            - `kickReturns`
-2077            - `puntReturns`
-2078            """
-2079        )
-2080
-2081    # URL builder
-2082    ##########################################################################
-2083
-2084    # Required by the API
-2085    url += f"?year={season}"
-2086
-2087    if game_id is not None:
-2088        url += f"&gameId={game_id}"
-2089
-2090        if stat_category is not None:
-2091            url += f"&category={stat_category}"
-2092
-2093        if week is not None or team is not None or conference is not None:
-2094            logging.warning(
-2095                "When calling "
-2096                + "`cfbd_json_py.games.get_cfbd_player_game_stats()`"
-2097                + ", and setting `game_id` to a non-null value, "
-2098                + "only `season`, `stat_category`, "
-2099                + "and `game_id` are considered "
-2100                + "when calling the CFBD API."
-2101            )
-2102    else:
-2103        if season_type is not None:
-2104            url += f"&seasonType={season_type}"
-2105
-2106        if week is not None:
-2107            url += f"&week={week}"
-2108
-2109        if team is not None:
-2110            url += f"&team={team}"
-2111
-2112        if conference is not None:
-2113            url += f"&conference={conference}"
-2114
-2115    headers = {
-2116        "Authorization": f"{real_api_key}",
-2117        "accept": "application/json"
-2118    }
-2119    response = requests.get(url, headers=headers)
-2120
-2121    if response.status_code == 200:
-2122        pass
-2123    elif response.status_code == 401:
-2124        raise ConnectionRefusedError(
-2125            "Could not connect. The connection was refused." +
-2126            "\nHTTP Status Code 401."
-2127        )
-2128    else:
-2129        raise ConnectionError(
-2130            f"Could not connect.\nHTTP Status code {response.status_code}"
+2063    elif s_category == "kickReturns":
+2064        filter_by_stat_category = True
+2065    elif s_category == "puntReturns":
+2066        filter_by_stat_category = True
+2067    else:
+2068        raise ValueError(
+2069            "Invalid input for `stat_category`."
+2070            + "\nValid inputs are:"
+2071            + """
+2072            - `passing`
+2073            - `rushing`
+2074            - `receiving`
+2075            - `fumbles`
+2076            - `defensive`
+2077            - `interceptions`
+2078            - `punting`
+2079            - `kicking`
+2080            - `kickReturns`
+2081            - `puntReturns`
+2082            """
+2083        )
+2084
+2085    # URL builder
+2086    ##########################################################################
+2087
+2088    # Required by the API
+2089    url += f"?year={season}"
+2090
+2091    if game_id is not None:
+2092        url += f"&gameId={game_id}"
+2093
+2094        if s_category is not None:
+2095            url += f"&category={s_category}"
+2096
+2097        if week is not None or team is not None or conference is not None:
+2098            logging.warning(
+2099                "When calling "
+2100                + "`cfbd_json_py.games.get_cfbd_player_game_stats()`"
+2101                + ", and setting `game_id` to a non-null value, "
+2102                + "only `season`, `stat_category`, "
+2103                + "and `game_id` are considered "
+2104                + "when calling the CFBD API."
+2105            )
+2106    else:
+2107        if season_type is not None:
+2108            url += f"&seasonType={season_type}"
+2109
+2110        if week is not None:
+2111            url += f"&week={week}"
+2112
+2113        if team is not None:
+2114            url += f"&team={team}"
+2115
+2116        if conference is not None:
+2117            url += f"&conference={conference}"
+2118
+2119    headers = {
+2120        "Authorization": f"{real_api_key}",
+2121        "accept": "application/json"
+2122    }
+2123    response = requests.get(url, headers=headers)
+2124
+2125    if response.status_code == 200:
+2126        pass
+2127    elif response.status_code == 401:
+2128        raise ConnectionRefusedError(
+2129            "Could not connect. The connection was refused." +
+2130            "\nHTTP Status Code 401."
 2131        )
-2132
-2133    json_data = response.json()
-2134
-2135    if return_as_dict is True:
-2136        return json_data
-2137
-2138    for game in tqdm(json_data):
-2139        game_id = game["id"]
-2140
-2141        for team in game["teams"]:
-2142            team_name = team["school"]
-2143            team_conference = team["conference"]
-2144            home_away = team["homeAway"]
-2145
-2146            for s_category in team["categories"]:
-2147                if s_category["name"] == "passing":
-2148                    for stat in s_category["types"]:
-2149                        if stat["name"] == "C/ATT":  # passing_C/ATT
-2150                            for i in stat["athletes"]:
-2151                                player_id = int(i["id"])
-2152                                player_name = i["name"]
-2153                                player_stat = i["stat"]
-2154
-2155                                if rebuilt_json.get(player_id) is None:
-2156                                    rebuilt_json[player_id] = {}
-2157
-2158                                rebuilt_json[player_id]["game_id"] = game_id
-2159                                rebuilt_json[player_id][
-2160                                    "team_name"
-2161                                ] = team_name
-2162                                rebuilt_json[player_id][
-2163                                    "team_conference"
-2164                                ] = team_conference
-2165                                rebuilt_json[player_id][
-2166                                    "player_id"
-2167                                ] = player_id
-2168                                rebuilt_json[player_id][
-2169                                    "player_name"
-2170                                ] = player_name
-2171                                rebuilt_json[player_id][
-2172                                    "home_away"
-2173                                ] = home_away
-2174                                rebuilt_json[player_id][
-2175                                    "passing_C/ATT"
-2176                                ] = player_stat
-2177
-2178                        elif stat["name"] == "YDS":  # passing_YDS
-2179                            for i in stat["athletes"]:
-2180                                player_id = int(i["id"])
-2181                                player_name = i["name"]
-2182                                player_stat = int(i["stat"])
-2183
-2184                                if rebuilt_json.get(player_id) is None:
-2185                                    rebuilt_json[player_id] = {}
-2186
-2187                                rebuilt_json[player_id]["game_id"] = game_id
-2188                                rebuilt_json[player_id][
-2189                                    "team_name"
-2190                                ] = team_name
-2191                                rebuilt_json[player_id][
-2192                                    "team_conference"
-2193                                ] = team_conference
-2194                                rebuilt_json[player_id][
-2195                                    "player_id"
-2196                                ] = player_id
-2197                                rebuilt_json[player_id][
-2198                                    "player_name"
-2199                                ] = player_name
-2200                                rebuilt_json[player_id][
-2201                                    "home_away"
-2202                                ] = home_away
-2203                                rebuilt_json[player_id][
-2204                                    "passing_YDS"
-2205                                ] = player_stat
-2206
-2207                        elif stat["name"] == "AVG":  # passing_AVG
-2208                            for i in stat["athletes"]:
-2209                                player_id = int(i["id"])
-2210                                player_name = i["name"]
-2211                                player_stat = float(i["stat"])
+2132    else:
+2133        raise ConnectionError(
+2134            f"Could not connect.\nHTTP Status code {response.status_code}"
+2135        )
+2136
+2137    json_data = response.json()
+2138
+2139    if return_as_dict is True:
+2140        return json_data
+2141
+2142    for game in tqdm(json_data):
+2143        game_id = game["id"]
+2144
+2145        for team in game["teams"]:
+2146            team_name = team["school"]
+2147            team_conference = team["conference"]
+2148            home_away = team["homeAway"]
+2149
+2150            for s_category in team["categories"]:
+2151                stat_category = s_category["name"]
+2152                for s_type in s_category["types"]:
+2153                    stat_name = s_type["name"]
+2154                    for player in s_type["athletes"]:
+2155                        p_id = player["id"]
+2156                        p_name = player["name"]
+2157                        full_stat_name = f"{stat_category}_{stat_name}"
+2158                        stat_value = player["stat"]
+2159
+2160                        if rebuilt_json.get(p_id) is None:
+2161                            rebuilt_json[p_id] = {}
+2162                        rebuilt_json[p_id]["player_id"] = p_id
+2163                        rebuilt_json[p_id]["game_id"] = game_id
+2164                        rebuilt_json[p_id]["team_name"] = team_name
+2165                        rebuilt_json[p_id]["team_conference"] = team_conference
+2166                        rebuilt_json[p_id]["home_away"] = home_away
+2167                        rebuilt_json[p_id]["player_name"] = p_name
+2168                        rebuilt_json[p_id][full_stat_name] = stat_value
+2169
+2170    for _, value in rebuilt_json.items():
+2171        rebuilt_json_list.append(value)
+2172    cfb_games_df = pd.DataFrame(rebuilt_json_list)
+2173    cfb_games_df["season"] = season
+2174
+2175    cfb_games_df[["passing_COMP", "passing_ATT"]] = cfb_games_df[
+2176        "passing_C/ATT"
+2177    ].str.split("/", expand=True)
+2178
+2179    cfb_games_df[["kicking_FGM", "kicking_FGA"]] = cfb_games_df[
+2180        "kicking_FG"
+2181    ].str.split(
+2182        "/", expand=True
+2183    )
+2184
+2185    cfb_games_df[["kicking_XP", "kicking_XPM"]] = cfb_games_df[
+2186        "kicking_XP"
+2187    ].str.split(
+2188        "/", expand=True
+2189    )
+2190
+2191    cfb_games_df = cfb_games_df.reindex(
+2192        columns=stat_columns
+2193    )
+2194
+2195    cfb_games_df = cfb_games_df.replace(np.nan, 0)
+2196    cfb_games_df = cfb_games_df.astype(
+2197        {
+2198            "season": "uint16",
+2199            "game_id": "int64",
+2200            "team_name": "str",
+2201            "team_conference": "str",
+2202            "player_id": "int64",
+2203            "player_name": "str",
+2204            "home_away": "str",
+2205
+2206            "passing_COMP": "uint16",
+2207            "passing_ATT": "uint16",
+2208            "passing_YDS": "int16",
+2209            "passing_TD": "uint16",
+2210            "passing_INT": "uint16",
+2211            "passing_AVG": "float16",
 2212
-2213                                if rebuilt_json.get(player_id) is None:
-2214                                    rebuilt_json[player_id] = {}
-2215
-2216                                rebuilt_json[player_id]["game_id"] = game_id
-2217                                rebuilt_json[player_id][
-2218                                    "team_name"
-2219                                ] = team_name
-2220                                rebuilt_json[player_id][
-2221                                    "team_conference"
-2222                                ] = team_conference
-2223                                rebuilt_json[player_id][
-2224                                    "player_id"
-2225                                ] = player_id
-2226                                rebuilt_json[player_id][
-2227                                    "player_name"
-2228                                ] = player_name
-2229                                rebuilt_json[player_id][
-2230                                    "home_away"
-2231                                ] = home_away
-2232                                rebuilt_json[player_id][
-2233                                    "passing_AVG"
-2234                                ] = player_stat
-2235
-2236                        elif stat["name"] == "TD":  # passing_TD
-2237                            for i in stat["athletes"]:
-2238                                player_id = int(i["id"])
-2239                                player_name = i["name"]
-2240                                player_stat = int(i["stat"])
-2241
-2242                                if rebuilt_json.get(player_id) is None:
-2243                                    rebuilt_json[player_id] = {}
-2244
-2245                                rebuilt_json[player_id]["game_id"] = game_id
-2246                                rebuilt_json[player_id][
-2247                                    "team_name"
-2248                                ] = team_name
-2249                                rebuilt_json[player_id][
-2250                                    "team_conference"
-2251                                ] = team_conference
-2252                                rebuilt_json[player_id][
-2253                                    "player_id"
-2254                                ] = player_id
-2255                                rebuilt_json[player_id][
-2256                                    "player_name"
-2257                                ] = player_name
-2258                                rebuilt_json[player_id][
-2259                                    "home_away"
-2260                                ] = home_away
-2261                                rebuilt_json[player_id][
-2262                                    "passing_TD"
-2263                                ] = player_stat
-2264
-2265                        elif stat["name"] == "INT":  # passing_INT
-2266                            for i in stat["athletes"]:
-2267                                player_id = int(i["id"])
-2268                                player_name = i["name"]
-2269                                player_stat = int(i["stat"])
-2270
-2271                                if rebuilt_json.get(player_id) is None:
-2272                                    rebuilt_json[player_id] = {}
-2273
-2274                                rebuilt_json[player_id]["game_id"] = game_id
-2275                                rebuilt_json[player_id][
-2276                                    "team_name"
-2277                                ] = team_name
-2278                                rebuilt_json[player_id][
-2279                                    "team_conference"
-2280                                ] = team_conference
-2281                                rebuilt_json[player_id][
-2282                                    "player_id"
-2283                                ] = player_id
-2284                                rebuilt_json[player_id][
-2285                                    "player_name"
-2286                                ] = player_name
-2287                                rebuilt_json[player_id][
-2288                                    "home_away"
-2289                                ] = home_away
-2290                                rebuilt_json[player_id][
-2291                                    "passing_INT"
-2292                                ] = player_stat
-2293
-2294                        elif stat["name"] == "QBR":  # passing_QBR
-2295                            for i in stat["athletes"]:
-2296                                player_id = int(i["id"])
-2297                                player_name = i["name"]
-2298                                try:
-2299                                    player_stat = float(i["stat"])
-2300                                except:  # noqa: E722
-2301                                    player_stat = None
-2302
-2303                                if rebuilt_json.get(player_id) is None:
-2304                                    rebuilt_json[player_id] = {}
-2305
-2306                                rebuilt_json[player_id]["game_id"] = game_id
-2307                                rebuilt_json[player_id][
-2308                                    "team_name"
-2309                                ] = team_name
-2310                                rebuilt_json[player_id][
-2311                                    "team_conference"
-2312                                ] = team_conference
-2313                                rebuilt_json[player_id][
-2314                                    "player_id"
-2315                                ] = player_id
-2316                                rebuilt_json[player_id][
-2317                                    "player_name"
-2318                                ] = player_name
-2319                                rebuilt_json[player_id][
-2320                                    "home_away"
-2321                                ] = home_away
-2322                                rebuilt_json[player_id][
-2323                                    "passing_QBR"
-2324                                ] = player_stat
-2325
-2326                        else:
-2327                            raise IndexError(
-2328                                f"Unhandled stat: \t{stat['name']}"
-2329                            )
-2330                    # passing_df = pd.DataFrame(s_category['types'])
-2331                elif s_category["name"] == "rushing":
-2332                    for stat in s_category["types"]:
-2333                        if stat["name"] == "CAR":  # rushing_CAR
-2334                            for i in stat["athletes"]:
-2335                                player_id = int(i["id"])
-2336                                player_name = i["name"]
-2337                                player_stat = int(i["stat"])
-2338
-2339                                if rebuilt_json.get(player_id) is None:
-2340                                    rebuilt_json[player_id] = {}
-2341
-2342                                rebuilt_json[player_id]["game_id"] = game_id
-2343                                rebuilt_json[player_id][
-2344                                    "team_name"
-2345                                ] = team_name
-2346                                rebuilt_json[player_id][
-2347                                    "team_conference"
-2348                                ] = team_conference
-2349                                rebuilt_json[player_id][
-2350                                    "player_id"
-2351                                ] = player_id
-2352                                rebuilt_json[player_id][
-2353                                    "player_name"
-2354                                ] = player_name
-2355                                rebuilt_json[player_id][
-2356                                    "home_away"
-2357                                ] = home_away
-2358                                rebuilt_json[player_id][
-2359                                    "rushing_CAR"
-2360                                ] = player_stat
-2361
-2362                        elif stat["name"] == "YDS":  # rushing_YDS
-2363                            for i in stat["athletes"]:
-2364                                player_id = int(i["id"])
-2365                                player_name = i["name"]
-2366                                player_stat = int(i["stat"])
-2367
-2368                                if rebuilt_json.get(player_id) is None:
-2369                                    rebuilt_json[player_id] = {}
-2370
-2371                                rebuilt_json[player_id]["game_id"] = game_id
-2372                                rebuilt_json[player_id][
-2373                                    "team_name"
-2374                                ] = team_name
-2375                                rebuilt_json[player_id][
-2376                                    "team_conference"
-2377                                ] = team_conference
-2378                                rebuilt_json[player_id][
-2379                                    "player_id"
-2380                                ] = player_id
-2381                                rebuilt_json[player_id][
-2382                                    "player_name"
-2383                                ] = player_name
-2384                                rebuilt_json[player_id][
-2385                                    "home_away"
-2386                                ] = home_away
-2387                                rebuilt_json[player_id][
-2388                                    "rushing_YDS"
-2389                                ] = player_stat
-2390
-2391                        elif stat["name"] == "AVG":  # rushing_AVG
-2392                            for i in stat["athletes"]:
-2393                                player_id = int(i["id"])
-2394                                player_name = i["name"]
-2395                                player_stat = float(i["stat"])
-2396
-2397                                if rebuilt_json.get(player_id) is None:
-2398                                    rebuilt_json[player_id] = {}
-2399
-2400                                rebuilt_json[player_id]["game_id"] = game_id
-2401                                rebuilt_json[player_id][
-2402                                    "team_name"
-2403                                ] = team_name
-2404                                rebuilt_json[player_id][
-2405                                    "team_conference"
-2406                                ] = team_conference
-2407                                rebuilt_json[player_id][
-2408                                    "player_id"
-2409                                ] = player_id
-2410                                rebuilt_json[player_id][
-2411                                    "player_name"
-2412                                ] = player_name
-2413                                rebuilt_json[player_id][
-2414                                    "home_away"
-2415                                ] = home_away
-2416                                rebuilt_json[player_id][
-2417                                    "rushing_AVG"
-2418                                ] = player_stat
-2419
-2420                        elif stat["name"] == "TD":  # rushing_TD
-2421                            for i in stat["athletes"]:
-2422                                player_id = int(i["id"])
-2423                                player_name = i["name"]
-2424                                player_stat = int(i["stat"])
-2425
-2426                                if rebuilt_json.get(player_id) is None:
-2427                                    rebuilt_json[player_id] = {}
-2428
-2429                                rebuilt_json[player_id]["game_id"] = game_id
-2430                                rebuilt_json[player_id][
-2431                                    "team_name"
-2432                                ] = team_name
-2433                                rebuilt_json[player_id][
-2434                                    "team_conference"
-2435                                ] = team_conference
-2436                                rebuilt_json[player_id][
-2437                                    "player_id"
-2438                                ] = player_id
-2439                                rebuilt_json[player_id][
-2440                                    "player_name"
-2441                                ] = player_name
-2442                                rebuilt_json[player_id][
-2443                                    "home_away"
-2444                                ] = home_away
-2445                                rebuilt_json[player_id][
-2446                                    "rushing_TD"
-2447                                ] = player_stat
-2448
-2449                        elif stat["name"] == "LONG":  # rushing_LONG
-2450                            for i in stat["athletes"]:
-2451                                player_id = int(i["id"])
-2452                                player_name = i["name"]
-2453                                player_stat = int(i["stat"])
-2454
-2455                                if rebuilt_json.get(player_id) is None:
-2456                                    rebuilt_json[player_id] = {}
-2457
-2458                                rebuilt_json[player_id]["game_id"] = game_id
-2459                                rebuilt_json[player_id][
-2460                                    "team_name"
-2461                                ] = team_name
-2462                                rebuilt_json[player_id][
-2463                                    "team_conference"
-2464                                ] = team_conference
-2465                                rebuilt_json[player_id][
-2466                                    "player_id"
-2467                                ] = player_id
-2468                                rebuilt_json[player_id][
-2469                                    "player_name"
-2470                                ] = player_name
-2471                                rebuilt_json[player_id][
-2472                                    "home_away"
-2473                                ] = home_away
-2474                                rebuilt_json[player_id][
-2475                                    "rushing_LONG"
-2476                                ] = player_stat
-2477
-2478                        else:
-2479                            raise IndexError(
-2480                                f"Unhandled stat: \t{stat['name']}"
-2481                            )
-2482
-2483                elif s_category["name"] == "receiving":
-2484                    for stat in s_category["types"]:
-2485                        if stat["name"] == "REC":  # receiving_REC
-2486                            for i in stat["athletes"]:
-2487                                player_id = int(i["id"])
-2488                                player_name = i["name"]
-2489                                player_stat = int(i["stat"])
-2490
-2491                                if rebuilt_json.get(player_id) is None:
-2492                                    rebuilt_json[player_id] = {}
-2493
-2494                                rebuilt_json[player_id]["game_id"] = game_id
-2495                                rebuilt_json[player_id][
-2496                                    "team_name"
-2497                                ] = team_name
-2498                                rebuilt_json[player_id][
-2499                                    "team_conference"
-2500                                ] = team_conference
-2501                                rebuilt_json[player_id][
-2502                                    "player_id"
-2503                                ] = player_id
-2504                                rebuilt_json[player_id][
-2505                                    "player_name"
-2506                                ] = player_name
-2507                                rebuilt_json[player_id][
-2508                                    "home_away"
-2509                                ] = home_away
-2510                                rebuilt_json[player_id][
-2511                                    "receiving_REC"
-2512                                ] = player_stat
-2513
-2514                        elif stat["name"] == "YDS":  # receiving_YDS
-2515                            for i in stat["athletes"]:
-2516                                player_id = int(i["id"])
-2517                                player_name = i["name"]
-2518                                player_stat = int(i["stat"])
-2519
-2520                                if rebuilt_json.get(player_id) is None:
-2521                                    rebuilt_json[player_id] = {}
-2522
-2523                                rebuilt_json[player_id]["game_id"] = game_id
-2524                                rebuilt_json[player_id][
-2525                                    "team_name"
-2526                                ] = team_name
-2527                                rebuilt_json[player_id][
-2528                                    "team_conference"
-2529                                ] = team_conference
-2530                                rebuilt_json[player_id][
-2531                                    "player_id"
-2532                                ] = player_id
-2533                                rebuilt_json[player_id][
-2534                                    "player_name"
-2535                                ] = player_name
-2536                                rebuilt_json[player_id][
-2537                                    "home_away"
-2538                                ] = home_away
-2539                                rebuilt_json[player_id][
-2540                                    "receiving_YDS"
-2541                                ] = player_stat
-2542
-2543                        elif stat["name"] == "AVG":  # receiving_AVG
-2544                            for i in stat["athletes"]:
-2545                                player_id = int(i["id"])
-2546                                player_name = i["name"]
-2547                                player_stat = float(i["stat"])
-2548
-2549                                if rebuilt_json.get(player_id) is None:
-2550                                    rebuilt_json[player_id] = {}
-2551
-2552                                rebuilt_json[player_id]["game_id"] = game_id
-2553                                rebuilt_json[player_id][
-2554                                    "team_name"
-2555                                ] = team_name
-2556                                rebuilt_json[player_id][
-2557                                    "team_conference"
-2558                                ] = team_conference
-2559                                rebuilt_json[player_id][
-2560                                    "player_id"
-2561                                ] = player_id
-2562                                rebuilt_json[player_id][
-2563                                    "player_name"
-2564                                ] = player_name
-2565                                rebuilt_json[player_id][
-2566                                    "home_away"
-2567                                ] = home_away
-2568                                rebuilt_json[player_id][
-2569                                    "receiving_AVG"
-2570                                ] = player_stat
-2571
-2572                        elif stat["name"] == "TD":  # receiving_TD
-2573                            for i in stat["athletes"]:
-2574                                player_id = int(i["id"])
-2575                                player_name = i["name"]
-2576                                player_stat = int(i["stat"])
-2577
-2578                                if rebuilt_json.get(player_id) is None:
-2579                                    rebuilt_json[player_id] = {}
-2580
-2581                                rebuilt_json[player_id]["game_id"] = game_id
-2582                                rebuilt_json[player_id][
-2583                                    "team_name"
-2584                                ] = team_name
-2585                                rebuilt_json[player_id][
-2586                                    "team_conference"
-2587                                ] = team_conference
-2588                                rebuilt_json[player_id][
-2589                                    "player_id"
-2590                                ] = player_id
-2591                                rebuilt_json[player_id][
-2592                                    "player_name"
-2593                                ] = player_name
-2594                                rebuilt_json[player_id][
-2595                                    "home_away"
-2596                                ] = home_away
-2597                                rebuilt_json[player_id][
-2598                                    "receiving_TD"
-2599                                ] = player_stat
-2600
-2601                        elif stat["name"] == "LONG":  # receiving_LONG
-2602                            for i in stat["athletes"]:
-2603                                player_id = int(i["id"])
-2604                                player_name = i["name"]
-2605                                player_stat = int(i["stat"])
-2606
-2607                                if rebuilt_json.get(player_id) is None:
-2608                                    rebuilt_json[player_id] = {}
-2609
-2610                                rebuilt_json[player_id]["game_id"] = game_id
-2611                                rebuilt_json[player_id][
-2612                                    "team_name"
-2613                                ] = team_name
-2614                                rebuilt_json[player_id][
-2615                                    "team_conference"
-2616                                ] = team_conference
-2617                                rebuilt_json[player_id][
-2618                                    "player_id"
-2619                                ] = player_id
-2620                                rebuilt_json[player_id][
-2621                                    "player_name"
-2622                                ] = player_name
-2623                                rebuilt_json[player_id][
-2624                                    "home_away"
-2625                                ] = home_away
-2626                                rebuilt_json[player_id][
-2627                                    "receiving_LONG"
-2628                                ] = player_stat
-2629
-2630                        else:
-2631                            raise IndexError(
-2632                                f"Unhandled stat: \t{stat['name']}"
-2633                            )
-2634
-2635                elif s_category["name"] == "fumbles":
-2636                    for stat in s_category["types"]:
-2637                        if stat["name"] == "FUM":  # fumbles_FUM
-2638                            for i in stat["athletes"]:
-2639                                player_id = int(i["id"])
-2640                                player_name = i["name"]
-2641                                player_stat = int(i["stat"])
-2642
-2643                                if rebuilt_json.get(player_id) is None:
-2644                                    rebuilt_json[player_id] = {}
-2645
-2646                                rebuilt_json[player_id]["game_id"] = game_id
-2647                                rebuilt_json[player_id][
-2648                                    "team_name"
-2649                                ] = team_name
-2650                                rebuilt_json[player_id][
-2651                                    "team_conference"
-2652                                ] = team_conference
-2653                                rebuilt_json[player_id][
-2654                                    "player_id"
-2655                                ] = player_id
-2656                                rebuilt_json[player_id][
-2657                                    "player_name"
-2658                                ] = player_name
-2659                                rebuilt_json[player_id][
-2660                                    "home_away"
-2661                                ] = home_away
-2662                                rebuilt_json[player_id][
-2663                                    "fumbles_FUM"
-2664                                ] = player_stat
-2665
-2666                        elif stat["name"] == "LOST":  # fumbles_LOST
-2667                            for i in stat["athletes"]:
-2668                                player_id = int(i["id"])
-2669                                player_name = i["name"]
-2670                                player_stat = int(i["stat"])
-2671
-2672                                if rebuilt_json.get(player_id) is None:
-2673                                    rebuilt_json[player_id] = {}
-2674
-2675                                rebuilt_json[player_id]["game_id"] = game_id
-2676                                rebuilt_json[player_id][
-2677                                    "team_name"
-2678                                ] = team_name
-2679                                rebuilt_json[player_id][
-2680                                    "team_conference"
-2681                                ] = team_conference
-2682                                rebuilt_json[player_id][
-2683                                    "player_id"
-2684                                ] = player_id
-2685                                rebuilt_json[player_id][
-2686                                    "player_name"
-2687                                ] = player_name
-2688                                rebuilt_json[player_id][
-2689                                    "home_away"
-2690                                ] = home_away
-2691                                rebuilt_json[player_id][
-2692                                    "fumbles_LOST"
-2693                                ] = player_stat
-2694
-2695                        elif stat["name"] == "REC":  # fumbles_REC
-2696                            for i in stat["athletes"]:
-2697                                player_id = int(i["id"])
-2698                                player_name = i["name"]
-2699                                player_stat = int(i["stat"])
-2700
-2701                                if rebuilt_json.get(player_id) is None:
-2702                                    rebuilt_json[player_id] = {}
-2703
-2704                                rebuilt_json[player_id]["game_id"] = game_id
-2705                                rebuilt_json[player_id][
-2706                                    "team_name"
-2707                                ] = team_name
-2708                                rebuilt_json[player_id][
-2709                                    "team_conference"
-2710                                ] = team_conference
-2711                                rebuilt_json[player_id][
-2712                                    "player_id"
-2713                                ] = player_id
-2714                                rebuilt_json[player_id][
-2715                                    "player_name"
-2716                                ] = player_name
-2717                                rebuilt_json[player_id][
-2718                                    "home_away"
-2719                                ] = home_away
-2720                                rebuilt_json[player_id][
-2721                                    "fumbles_REC"
-2722                                ] = player_stat
-2723
-2724                        else:
-2725                            raise IndexError(
-2726                                f"Unhandled stat: \t{stat['name']}"
-2727                            )
-2728
-2729                elif s_category["name"] == "defensive":
-2730                    for stat in s_category["types"]:
-2731                        if stat["name"] == "TOT":  # defensive_TOT
-2732                            for i in stat["athletes"]:
-2733                                player_id = int(i["id"])
-2734                                player_name = i["name"]
-2735                                player_stat = int(i["stat"])
-2736
-2737                                if rebuilt_json.get(player_id) is None:
-2738                                    rebuilt_json[player_id] = {}
-2739
-2740                                rebuilt_json[player_id]["game_id"] = game_id
-2741                                rebuilt_json[player_id][
-2742                                    "team_name"
-2743                                ] = team_name
-2744                                rebuilt_json[player_id][
-2745                                    "team_conference"
-2746                                ] = team_conference
-2747                                rebuilt_json[player_id][
-2748                                    "player_id"
-2749                                ] = player_id
-2750                                rebuilt_json[player_id][
-2751                                    "player_name"
-2752                                ] = player_name
-2753                                rebuilt_json[player_id][
-2754                                    "home_away"
-2755                                ] = home_away
-2756                                rebuilt_json[player_id][
-2757                                    "defensive_TOT"
-2758                                ] = player_stat
-2759
-2760                        elif stat["name"] == "SOLO":  # defensive_SOLO
-2761                            for i in stat["athletes"]:
-2762                                player_id = int(i["id"])
-2763                                player_name = i["name"]
-2764                                player_stat = int(i["stat"])
-2765
-2766                                if rebuilt_json.get(player_id) is None:
-2767                                    rebuilt_json[player_id] = {}
-2768
-2769                                rebuilt_json[player_id]["game_id"] = game_id
-2770                                rebuilt_json[player_id][
-2771                                    "team_name"
-2772                                ] = team_name
-2773                                rebuilt_json[player_id][
-2774                                    "team_conference"
-2775                                ] = team_conference
-2776                                rebuilt_json[player_id][
-2777                                    "player_id"
-2778                                ] = player_id
-2779                                rebuilt_json[player_id][
-2780                                    "player_name"
-2781                                ] = player_name
-2782                                rebuilt_json[player_id][
-2783                                    "home_away"
-2784                                ] = home_away
-2785                                rebuilt_json[player_id][
-2786                                    "defensive_SOLO"
-2787                                ] = player_stat
-2788
-2789                        elif stat["name"] == "TFL":  # defensive_TFL
-2790                            for i in stat["athletes"]:
-2791                                player_id = int(i["id"])
-2792                                player_name = i["name"]
-2793                                player_stat = float(i["stat"])
-2794
-2795                                if rebuilt_json.get(player_id) is None:
-2796                                    rebuilt_json[player_id] = {}
-2797
-2798                                rebuilt_json[player_id]["game_id"] = game_id
-2799                                rebuilt_json[player_id][
-2800                                    "team_name"
-2801                                ] = team_name
-2802                                rebuilt_json[player_id][
-2803                                    "team_conference"
-2804                                ] = team_conference
-2805                                rebuilt_json[player_id][
-2806                                    "player_id"
-2807                                ] = player_id
-2808                                rebuilt_json[player_id][
-2809                                    "player_name"
-2810                                ] = player_name
-2811                                rebuilt_json[player_id][
-2812                                    "home_away"
-2813                                ] = home_away
-2814                                rebuilt_json[player_id][
-2815                                    "defensive_TFL"
-2816                                ] = player_stat
-2817
-2818                        elif stat["name"] == "QB HUR":  # defensive_QB HUR
-2819                            for i in stat["athletes"]:
-2820                                player_id = int(i["id"])
-2821                                player_name = i["name"]
-2822                                player_stat = int(i["stat"])
-2823
-2824                                if rebuilt_json.get(player_id) is None:
-2825                                    rebuilt_json[player_id] = {}
-2826
-2827                                rebuilt_json[player_id]["game_id"] = game_id
-2828                                rebuilt_json[player_id][
-2829                                    "team_name"
-2830                                ] = team_name
-2831                                rebuilt_json[player_id][
-2832                                    "team_conference"
-2833                                ] = team_conference
-2834                                rebuilt_json[player_id][
-2835                                    "player_id"
-2836                                ] = player_id
-2837                                rebuilt_json[player_id][
-2838                                    "player_name"
-2839                                ] = player_name
-2840                                rebuilt_json[player_id][
-2841                                    "home_away"
-2842                                ] = home_away
-2843                                rebuilt_json[player_id][
-2844                                    "defensive_QB HUR"
-2845                                ] = player_stat
-2846
-2847                        elif stat["name"] == "SACKS":  # defensive_SACKS
-2848                            for i in stat["athletes"]:
-2849                                player_id = int(i["id"])
-2850                                player_name = i["name"]
-2851                                player_stat = float(i["stat"])
-2852
-2853                                if rebuilt_json.get(player_id) is None:
-2854                                    rebuilt_json[player_id] = {}
-2855
-2856                                rebuilt_json[player_id]["game_id"] = game_id
-2857                                rebuilt_json[player_id][
-2858                                    "team_name"
-2859                                ] = team_name
-2860                                rebuilt_json[player_id][
-2861                                    "team_conference"
-2862                                ] = team_conference
-2863                                rebuilt_json[player_id][
-2864                                    "player_id"
-2865                                ] = player_id
-2866                                rebuilt_json[player_id][
-2867                                    "player_name"
-2868                                ] = player_name
-2869                                rebuilt_json[player_id][
-2870                                    "home_away"
-2871                                ] = home_away
-2872                                rebuilt_json[player_id][
-2873                                    "defensive_SACKS"
-2874                                ] = player_stat
-2875
-2876                        elif stat["name"] == "PD":  # defensive_PD
-2877                            for i in stat["athletes"]:
-2878                                player_id = int(i["id"])
-2879                                player_name = i["name"]
-2880                                player_stat = int(i["stat"])
-2881
-2882                                if rebuilt_json.get(player_id) is None:
-2883                                    rebuilt_json[player_id] = {}
-2884
-2885                                rebuilt_json[player_id]["game_id"] = game_id
-2886                                rebuilt_json[player_id][
-2887                                    "team_name"
-2888                                ] = team_name
-2889                                rebuilt_json[player_id][
-2890                                    "team_conference"
-2891                                ] = team_conference
-2892                                rebuilt_json[player_id][
-2893                                    "player_id"
-2894                                ] = player_id
-2895                                rebuilt_json[player_id][
-2896                                    "player_name"
-2897                                ] = player_name
-2898                                rebuilt_json[player_id][
-2899                                    "home_away"
-2900                                ] = home_away
-2901                                rebuilt_json[player_id][
-2902                                    "defensive_PD"
-2903                                ] = player_stat
-2904
-2905                        elif stat["name"] == "TD":  # defensive_TD
-2906                            for i in stat["athletes"]:
-2907                                player_id = int(i["id"])
-2908                                player_name = i["name"]
-2909                                player_stat = int(i["stat"])
-2910
-2911                                if rebuilt_json.get(player_id) is None:
-2912                                    rebuilt_json[player_id] = {}
-2913
-2914                                rebuilt_json[player_id]["game_id"] = game_id
-2915                                rebuilt_json[player_id][
-2916                                    "team_name"
-2917                                ] = team_name
-2918                                rebuilt_json[player_id][
-2919                                    "team_conference"
-2920                                ] = team_conference
-2921                                rebuilt_json[player_id][
-2922                                    "player_id"
-2923                                ] = player_id
-2924                                rebuilt_json[player_id][
-2925                                    "player_name"
-2926                                ] = player_name
-2927                                rebuilt_json[player_id][
-2928                                    "home_away"
-2929                                ] = home_away
-2930                                rebuilt_json[player_id][
-2931                                    "defensive_TD"
-2932                                ] = player_stat
-2933
-2934                        else:
-2935                            raise IndexError(
-2936                                f"Unhandled stat: \t{stat['name']}"
-2937                            )
-2938
-2939                elif s_category["name"] == "interceptions":
-2940                    for stat in s_category["types"]:
-2941                        if stat["name"] == "INT":  # interceptions_INT
-2942                            for i in stat["athletes"]:
-2943                                player_id = int(i["id"])
-2944                                player_name = i["name"]
-2945                                player_stat = int(i["stat"])
-2946
-2947                                if rebuilt_json.get(player_id) is None:
-2948                                    rebuilt_json[player_id] = {}
-2949
-2950                                rebuilt_json[player_id]["game_id"] = game_id
-2951                                rebuilt_json[player_id][
-2952                                    "team_name"
-2953                                ] = team_name
-2954                                rebuilt_json[player_id][
-2955                                    "team_conference"
-2956                                ] = team_conference
-2957                                rebuilt_json[player_id][
-2958                                    "player_id"
-2959                                ] = player_id
-2960                                rebuilt_json[player_id][
-2961                                    "player_name"
-2962                                ] = player_name
-2963                                rebuilt_json[player_id][
-2964                                    "home_away"
-2965                                ] = home_away
-2966                                rebuilt_json[player_id][
-2967                                    "interceptions_INT"
-2968                                ] = player_stat
-2969
-2970                        elif stat["name"] == "YDS":  # interceptions_YDS
-2971                            for i in stat["athletes"]:
-2972                                player_id = int(i["id"])
-2973                                player_name = i["name"]
-2974                                player_stat = int(i["stat"])
-2975
-2976                                if rebuilt_json.get(player_id) is None:
-2977                                    rebuilt_json[player_id] = {}
-2978
-2979                                rebuilt_json[player_id]["game_id"] = game_id
-2980                                rebuilt_json[player_id][
-2981                                    "team_name"
-2982                                ] = team_name
-2983                                rebuilt_json[player_id][
-2984                                    "team_conference"
-2985                                ] = team_conference
-2986                                rebuilt_json[player_id][
-2987                                    "player_id"
-2988                                ] = player_id
-2989                                rebuilt_json[player_id][
-2990                                    "player_name"
-2991                                ] = player_name
-2992                                rebuilt_json[player_id][
-2993                                    "home_away"
-2994                                ] = home_away
-2995                                rebuilt_json[player_id][
-2996                                    "interceptions_YDS"
-2997                                ] = player_stat
-2998
-2999                        elif stat["name"] == "TD":  # interceptions_TD
-3000                            for i in stat["athletes"]:
-3001                                player_id = int(i["id"])
-3002                                player_name = i["name"]
-3003                                player_stat = int(i["stat"])
-3004
-3005                                if rebuilt_json.get(player_id) is None:
-3006                                    rebuilt_json[player_id] = {}
-3007
-3008                                rebuilt_json[player_id]["game_id"] = game_id
-3009                                rebuilt_json[player_id][
-3010                                    "team_name"
-3011                                ] = team_name
-3012                                rebuilt_json[player_id][
-3013                                    "team_conference"
-3014                                ] = team_conference
-3015                                rebuilt_json[player_id][
-3016                                    "player_id"
-3017                                ] = player_id
-3018                                rebuilt_json[player_id][
-3019                                    "player_name"
-3020                                ] = player_name
-3021                                rebuilt_json[player_id][
-3022                                    "home_away"
-3023                                ] = home_away
-3024                                rebuilt_json[player_id][
-3025                                    "interceptions_TD"
-3026                                ] = player_stat
-3027
-3028                        else:
-3029                            raise IndexError(
-3030                                f"Unhandled stat: \t{stat['name']}"
-3031                            )
-3032
-3033                elif s_category["name"] == "punting":
-3034                    for stat in s_category["types"]:
-3035                        if stat["name"] == "NO":  # punting_NO
-3036                            for i in stat["athletes"]:
-3037                                player_id = int(i["id"])
-3038                                player_name = i["name"]
-3039                                player_stat = int(i["stat"])
-3040
-3041                                if rebuilt_json.get(player_id) is None:
-3042                                    rebuilt_json[player_id] = {}
-3043
-3044                                rebuilt_json[player_id]["game_id"] = game_id
-3045                                rebuilt_json[player_id][
-3046                                    "team_name"
-3047                                ] = team_name
-3048                                rebuilt_json[player_id][
-3049                                    "team_conference"
-3050                                ] = team_conference
-3051                                rebuilt_json[player_id][
-3052                                    "player_id"
-3053                                ] = player_id
-3054                                rebuilt_json[player_id][
-3055                                    "player_name"
-3056                                ] = player_name
-3057                                rebuilt_json[player_id][
-3058                                    "home_away"
-3059                                ] = home_away
-3060                                rebuilt_json[player_id][
-3061                                    "punting_NO"
-3062                                ] = player_stat
-3063
-3064                        elif stat["name"] == "YDS":  # punting_YDS
-3065                            for i in stat["athletes"]:
-3066                                player_id = int(i["id"])
-3067                                player_name = i["name"]
-3068                                player_stat = int(i["stat"])
-3069
-3070                                if rebuilt_json.get(player_id) is None:
-3071                                    rebuilt_json[player_id] = {}
-3072
-3073                                rebuilt_json[player_id]["game_id"] = game_id
-3074                                rebuilt_json[player_id][
-3075                                    "team_name"
-3076                                ] = team_name
-3077                                rebuilt_json[player_id][
-3078                                    "team_conference"
-3079                                ] = team_conference
-3080                                rebuilt_json[player_id][
-3081                                    "player_id"
-3082                                ] = player_id
-3083                                rebuilt_json[player_id][
-3084                                    "player_name"
-3085                                ] = player_name
-3086                                rebuilt_json[player_id][
-3087                                    "home_away"
-3088                                ] = home_away
-3089                                rebuilt_json[player_id][
-3090                                    "punting_YDS"
-3091                                ] = player_stat
-3092
-3093                        elif stat["name"] == "AVG":  # punting_AVG
-3094                            for i in stat["athletes"]:
-3095                                player_id = int(i["id"])
-3096                                player_name = i["name"]
-3097                                player_stat = float(i["stat"])
-3098
-3099                                if rebuilt_json.get(player_id) is None:
-3100                                    rebuilt_json[player_id] = {}
-3101
-3102                                rebuilt_json[player_id]["game_id"] = game_id
-3103                                rebuilt_json[player_id][
-3104                                    "team_name"
-3105                                ] = team_name
-3106                                rebuilt_json[player_id][
-3107                                    "team_conference"
-3108                                ] = team_conference
-3109                                rebuilt_json[player_id][
-3110                                    "player_id"
-3111                                ] = player_id
-3112                                rebuilt_json[player_id][
-3113                                    "player_name"
-3114                                ] = player_name
-3115                                rebuilt_json[player_id][
-3116                                    "home_away"
-3117                                ] = home_away
-3118                                rebuilt_json[player_id][
-3119                                    "punting_AVG"
-3120                                ] = player_stat
-3121
-3122                        elif stat["name"] == "TB":  # punting_TB
-3123                            for i in stat["athletes"]:
-3124                                player_id = int(i["id"])
-3125                                player_name = i["name"]
-3126                                player_stat = int(i["stat"])
-3127
-3128                                if rebuilt_json.get(player_id) is None:
-3129                                    rebuilt_json[player_id] = {}
-3130
-3131                                rebuilt_json[player_id]["game_id"] = game_id
-3132                                rebuilt_json[player_id][
-3133                                    "team_name"
-3134                                ] = team_name
-3135                                rebuilt_json[player_id][
-3136                                    "team_conference"
-3137                                ] = team_conference
-3138                                rebuilt_json[player_id][
-3139                                    "player_id"
-3140                                ] = player_id
-3141                                rebuilt_json[player_id][
-3142                                    "player_name"
-3143                                ] = player_name
-3144                                rebuilt_json[player_id][
-3145                                    "home_away"
-3146                                ] = home_away
-3147                                rebuilt_json[player_id][
-3148                                    "punting_TB"
-3149                                ] = player_stat
-3150
-3151                        elif stat["name"] == "In 20":  # punting_In 20
-3152                            for i in stat["athletes"]:
-3153                                player_id = int(i["id"])
-3154                                player_name = i["name"]
-3155                                player_stat = int(i["stat"])
-3156
-3157                                if rebuilt_json.get(player_id) is None:
-3158                                    rebuilt_json[player_id] = {}
-3159
-3160                                rebuilt_json[player_id]["game_id"] = game_id
-3161                                rebuilt_json[player_id][
-3162                                    "team_name"
-3163                                ] = team_name
-3164                                rebuilt_json[player_id][
-3165                                    "team_conference"
-3166                                ] = team_conference
-3167                                rebuilt_json[player_id][
-3168                                    "player_id"
-3169                                ] = player_id
-3170                                rebuilt_json[player_id][
-3171                                    "player_name"
-3172                                ] = player_name
-3173                                rebuilt_json[player_id][
-3174                                    "home_away"
-3175                                ] = home_away
-3176                                rebuilt_json[player_id][
-3177                                    "punting_In 20"
-3178                                ] = player_stat
-3179
-3180                        elif stat["name"] == "LONG":  # punting_LONG
-3181                            for i in stat["athletes"]:
-3182                                player_id = int(i["id"])
-3183                                player_name = i["name"]
-3184                                player_stat = int(i["stat"])
-3185
-3186                                if rebuilt_json.get(player_id) is None:
-3187                                    rebuilt_json[player_id] = {}
-3188
-3189                                rebuilt_json[player_id]["game_id"] = game_id
-3190                                rebuilt_json[player_id][
-3191                                    "team_name"
-3192                                ] = team_name
-3193                                rebuilt_json[player_id][
-3194                                    "team_conference"
-3195                                ] = team_conference
-3196                                rebuilt_json[player_id][
-3197                                    "player_id"
-3198                                ] = player_id
-3199                                rebuilt_json[player_id][
-3200                                    "player_name"
-3201                                ] = player_name
-3202                                rebuilt_json[player_id][
-3203                                    "home_away"
-3204                                ] = home_away
-3205                                rebuilt_json[player_id][
-3206                                    "punting_LONG"
-3207                                ] = player_stat
-3208
-3209                        else:
-3210                            raise IndexError(
-3211                                f"Unhandled stat: \t{stat['name']}"
-3212                            )
-3213
-3214                elif s_category["name"] == "kicking":
-3215                    for stat in s_category["types"]:
-3216                        if stat["name"] == "FG":  # kicking_FG
-3217                            for i in stat["athletes"]:
-3218                                player_id = int(i["id"])
-3219                                player_name = i["name"]
-3220                                player_stat = i["stat"]
-3221
-3222                                if rebuilt_json.get(player_id) is None:
-3223                                    rebuilt_json[player_id] = {}
-3224
-3225                                rebuilt_json[player_id]["game_id"] = game_id
-3226                                rebuilt_json[player_id][
-3227                                    "team_name"
-3228                                ] = team_name
-3229                                rebuilt_json[player_id][
-3230                                    "team_conference"
-3231                                ] = team_conference
-3232                                rebuilt_json[player_id][
-3233                                    "player_id"
-3234                                ] = player_id
-3235                                rebuilt_json[player_id][
-3236                                    "player_name"
-3237                                ] = player_name
-3238                                rebuilt_json[player_id][
-3239                                    "home_away"
-3240                                ] = home_away
-3241                                rebuilt_json[player_id][
-3242                                    "kicking_FG"
-3243                                ] = player_stat
-3244
-3245                        elif stat["name"] == "TOT":  # kicking_FG, special case
-3246                            for i in stat["athletes"]:
-3247                                player_id = int(i["id"])
-3248                                player_name = i["name"]
-3249                                player_stat = i["stat"]
-3250
-3251                                if rebuilt_json.get(player_id) is None:
-3252                                    rebuilt_json[player_id] = {}
-3253
-3254                                rebuilt_json[player_id]["game_id"] = game_id
-3255                                rebuilt_json[player_id][
-3256                                    "team_name"
-3257                                ] = team_name
-3258                                rebuilt_json[player_id][
-3259                                    "team_conference"
-3260                                ] = team_conference
-3261                                rebuilt_json[player_id][
-3262                                    "player_id"
-3263                                ] = player_id
-3264                                rebuilt_json[player_id][
-3265                                    "player_name"
-3266                                ] = player_name
-3267                                rebuilt_json[player_id][
-3268                                    "home_away"
-3269                                ] = home_away
-3270                                rebuilt_json[player_id][
-3271                                    "kicking_FG"
-3272                                ] = player_stat
-3273
-3274                        elif stat["name"] == "PCT":  # kicking_PCT
-3275                            for i in stat["athletes"]:
-3276                                player_id = int(i["id"])
-3277                                player_name = i["name"]
-3278                                player_stat = float(i["stat"])
-3279
-3280                                if rebuilt_json.get(player_id) is None:
-3281                                    rebuilt_json[player_id] = {}
-3282
-3283                                rebuilt_json[player_id]["game_id"] = game_id
-3284                                rebuilt_json[player_id][
-3285                                    "team_name"
-3286                                ] = team_name
-3287                                rebuilt_json[player_id][
-3288                                    "team_conference"
-3289                                ] = team_conference
-3290                                rebuilt_json[player_id][
-3291                                    "player_id"
-3292                                ] = player_id
-3293                                rebuilt_json[player_id][
-3294                                    "player_name"
-3295                                ] = player_name
-3296                                rebuilt_json[player_id][
-3297                                    "home_away"
-3298                                ] = home_away
-3299                                rebuilt_json[player_id][
-3300                                    "kicking_PCT"
-3301                                ] = player_stat
-3302
-3303                        elif stat["name"] == "LONG":  # kicking_LONG
-3304                            for i in stat["athletes"]:
-3305                                player_id = int(i["id"])
-3306                                player_name = i["name"]
-3307                                player_stat = int(i["stat"])
-3308
-3309                                if rebuilt_json.get(player_id) is None:
-3310                                    rebuilt_json[player_id] = {}
-3311
-3312                                rebuilt_json[player_id]["game_id"] = game_id
-3313                                rebuilt_json[player_id][
-3314                                    "team_name"
-3315                                ] = team_name
-3316                                rebuilt_json[player_id][
-3317                                    "team_conference"
-3318                                ] = team_conference
-3319                                rebuilt_json[player_id][
-3320                                    "player_id"
-3321                                ] = player_id
-3322                                rebuilt_json[player_id][
-3323                                    "player_name"
-3324                                ] = player_name
-3325                                rebuilt_json[player_id][
-3326                                    "home_away"
-3327                                ] = home_away
-3328                                rebuilt_json[player_id][
-3329                                    "kicking_LONG"
-3330                                ] = player_stat
-3331
-3332                        elif stat["name"] == "XP":  # kicking_XP
-3333                            for i in stat["athletes"]:
-3334                                player_id = int(i["id"])
-3335                                player_name = i["name"]
-3336                                player_stat = i["stat"]
-3337
-3338                                if rebuilt_json.get(player_id) is None:
-3339                                    rebuilt_json[player_id] = {}
-3340
-3341                                rebuilt_json[player_id]["game_id"] = game_id
-3342                                rebuilt_json[player_id][
-3343                                    "team_name"
-3344                                ] = team_name
-3345                                rebuilt_json[player_id][
-3346                                    "team_conference"
-3347                                ] = team_conference
-3348                                rebuilt_json[player_id][
-3349                                    "player_id"
-3350                                ] = player_id
-3351                                rebuilt_json[player_id][
-3352                                    "player_name"
-3353                                ] = player_name
-3354                                rebuilt_json[player_id][
-3355                                    "home_away"
-3356                                ] = home_away
-3357                                rebuilt_json[player_id][
-3358                                    "kicking_XP"
-3359                                ] = player_stat
-3360
-3361                        elif stat["name"] == "PTS":  # kicking_PTS
-3362                            for i in stat["athletes"]:
-3363                                player_id = int(i["id"])
-3364                                player_name = i["name"]
-3365                                player_stat = int(i["stat"])
-3366
-3367                                if rebuilt_json.get(player_id) is None:
-3368                                    rebuilt_json[player_id] = {}
-3369
-3370                                rebuilt_json[player_id]["game_id"] = game_id
-3371                                rebuilt_json[player_id][
-3372                                    "team_name"
-3373                                ] = team_name
-3374                                rebuilt_json[player_id][
-3375                                    "team_conference"
-3376                                ] = team_conference
-3377                                rebuilt_json[player_id][
-3378                                    "player_id"
-3379                                ] = player_id
-3380                                rebuilt_json[player_id][
-3381                                    "player_name"
-3382                                ] = player_name
-3383                                rebuilt_json[player_id][
-3384                                    "home_away"
-3385                                ] = home_away
-3386                                rebuilt_json[player_id][
-3387                                    "kicking_PTS"
-3388                                ] = player_stat
-3389
-3390                        else:
-3391                            raise IndexError(
-3392                                f"Unhandled stat: \t{stat['name']}"
-3393                            )
-3394
-3395                elif s_category["name"] == "kickReturns":
-3396                    for stat in s_category["types"]:
-3397                        if stat["name"] == "NO":  # kickReturns_NO
-3398                            for i in stat["athletes"]:
-3399                                player_id = int(i["id"])
-3400                                player_name = i["name"]
-3401                                player_stat = int(i["stat"])
-3402
-3403                                if rebuilt_json.get(player_id) is None:
-3404                                    rebuilt_json[player_id] = {}
-3405
-3406                                rebuilt_json[player_id]["game_id"] = game_id
-3407                                rebuilt_json[player_id][
-3408                                    "team_name"
-3409                                ] = team_name
-3410                                rebuilt_json[player_id][
-3411                                    "team_conference"
-3412                                ] = team_conference
-3413                                rebuilt_json[player_id][
-3414                                    "player_id"
-3415                                ] = player_id
-3416                                rebuilt_json[player_id][
-3417                                    "player_name"
-3418                                ] = player_name
-3419                                rebuilt_json[player_id][
-3420                                    "home_away"
-3421                                ] = home_away
-3422                                rebuilt_json[player_id][
-3423                                    "kickReturns_NO"
-3424                                ] = player_stat
-3425
-3426                        elif stat["name"] == "YDS":  # kickReturns_YDS
-3427                            for i in stat["athletes"]:
-3428                                player_id = int(i["id"])
-3429                                player_name = i["name"]
-3430                                player_stat = int(i["stat"])
-3431
-3432                                if rebuilt_json.get(player_id) is None:
-3433                                    rebuilt_json[player_id] = {}
-3434
-3435                                rebuilt_json[player_id]["game_id"] = game_id
-3436                                rebuilt_json[player_id][
-3437                                    "team_name"
-3438                                ] = team_name
-3439                                rebuilt_json[player_id][
-3440                                    "team_conference"
-3441                                ] = team_conference
-3442                                rebuilt_json[player_id][
-3443                                    "player_id"
-3444                                ] = player_id
-3445                                rebuilt_json[player_id][
-3446                                    "player_name"
-3447                                ] = player_name
-3448                                rebuilt_json[player_id][
-3449                                    "home_away"
-3450                                ] = home_away
-3451                                rebuilt_json[player_id][
-3452                                    "kickReturns_YDS"
-3453                                ] = player_stat
-3454
-3455                        elif stat["name"] == "AVG":  # kickReturns_AVG
-3456                            for i in stat["athletes"]:
-3457                                player_id = int(i["id"])
-3458                                player_name = i["name"]
-3459                                player_stat = float(i["stat"])
-3460
-3461                                if rebuilt_json.get(player_id) is None:
-3462                                    rebuilt_json[player_id] = {}
-3463
-3464                                rebuilt_json[player_id]["game_id"] = game_id
-3465                                rebuilt_json[player_id][
-3466                                    "team_name"
-3467                                ] = team_name
-3468                                rebuilt_json[player_id][
-3469                                    "team_conference"
-3470                                ] = team_conference
-3471                                rebuilt_json[player_id][
-3472                                    "player_id"
-3473                                ] = player_id
-3474                                rebuilt_json[player_id][
-3475                                    "player_name"
-3476                                ] = player_name
-3477                                rebuilt_json[player_id][
-3478                                    "home_away"
-3479                                ] = home_away
-3480                                rebuilt_json[player_id][
-3481                                    "kickReturns_AVG"
-3482                                ] = player_stat
-3483
-3484                        elif stat["name"] == "TD":  # kickReturns_TD
-3485                            for i in stat["athletes"]:
-3486                                player_id = int(i["id"])
-3487                                player_name = i["name"]
-3488                                player_stat = int(i["stat"])
-3489
-3490                                if rebuilt_json.get(player_id) is None:
-3491                                    rebuilt_json[player_id] = {}
-3492
-3493                                rebuilt_json[player_id]["game_id"] = game_id
-3494                                rebuilt_json[player_id][
-3495                                    "team_name"
-3496                                ] = team_name
-3497                                rebuilt_json[player_id][
-3498                                    "team_conference"
-3499                                ] = team_conference
-3500                                rebuilt_json[player_id][
-3501                                    "player_id"
-3502                                ] = player_id
-3503                                rebuilt_json[player_id][
-3504                                    "player_name"
-3505                                ] = player_name
-3506                                rebuilt_json[player_id][
-3507                                    "home_away"
-3508                                ] = home_away
-3509                                rebuilt_json[player_id][
-3510                                    "kickReturns_TD"
-3511                                ] = player_stat
-3512
-3513                        elif stat["name"] == "LONG":  # kickReturns_LONG
-3514                            for i in stat["athletes"]:
-3515                                player_id = int(i["id"])
-3516                                player_name = i["name"]
-3517                                player_stat = int(i["stat"])
-3518
-3519                                if rebuilt_json.get(player_id) is None:
-3520                                    rebuilt_json[player_id] = {}
-3521
-3522                                rebuilt_json[player_id]["game_id"] = game_id
-3523                                rebuilt_json[player_id][
-3524                                    "team_name"
-3525                                ] = team_name
-3526                                rebuilt_json[player_id][
-3527                                    "team_conference"
-3528                                ] = team_conference
-3529                                rebuilt_json[player_id][
-3530                                    "player_id"
-3531                                ] = player_id
-3532                                rebuilt_json[player_id][
-3533                                    "player_name"
-3534                                ] = player_name
-3535                                rebuilt_json[player_id][
-3536                                    "home_away"
-3537                                ] = home_away
-3538                                rebuilt_json[player_id][
-3539                                    "kickReturns_LONG"
-3540                                ] = player_stat
-3541
-3542                        else:
-3543                            raise IndexError(
-3544                                f"Unhandled stat: \t{stat['name']}"
-3545                            )
-3546
-3547                elif s_category["name"] == "puntReturns":
-3548                    for stat in s_category["types"]:
-3549                        if stat["name"] == "NO":  # puntReturns_NO
-3550                            for i in stat["athletes"]:
-3551                                player_id = int(i["id"])
-3552                                player_name = i["name"]
-3553                                player_stat = int(i["stat"])
-3554
-3555                                if rebuilt_json.get(player_id) is None:
-3556                                    rebuilt_json[player_id] = {}
-3557
-3558                                rebuilt_json[player_id]["game_id"] = game_id
-3559                                rebuilt_json[player_id][
-3560                                    "team_name"
-3561                                ] = team_name
-3562                                rebuilt_json[player_id][
-3563                                    "team_conference"
-3564                                ] = team_conference
-3565                                rebuilt_json[player_id][
-3566                                    "player_id"
-3567                                ] = player_id
-3568                                rebuilt_json[player_id][
-3569                                    "player_name"
-3570                                ] = player_name
-3571                                rebuilt_json[player_id][
-3572                                    "home_away"
-3573                                ] = home_away
-3574                                rebuilt_json[player_id][
-3575                                    "puntReturns_NO"
-3576                                ] = player_stat
-3577
-3578                        elif stat["name"] == "YDS":  # puntReturns_YDS
-3579                            for i in stat["athletes"]:
-3580                                player_id = int(i["id"])
-3581                                player_name = i["name"]
-3582                                player_stat = int(i["stat"])
-3583
-3584                                if rebuilt_json.get(player_id) is None:
-3585                                    rebuilt_json[player_id] = {}
-3586
-3587                                rebuilt_json[player_id]["game_id"] = game_id
-3588                                rebuilt_json[player_id][
-3589                                    "team_name"
-3590                                ] = team_name
-3591                                rebuilt_json[player_id][
-3592                                    "team_conference"
-3593                                ] = team_conference
-3594                                rebuilt_json[player_id][
-3595                                    "player_id"
-3596                                ] = player_id
-3597                                rebuilt_json[player_id][
-3598                                    "player_name"
-3599                                ] = player_name
-3600                                rebuilt_json[player_id][
-3601                                    "home_away"
-3602                                ] = home_away
-3603                                rebuilt_json[player_id][
-3604                                    "puntReturns_YDS"
-3605                                ] = player_stat
-3606
-3607                        elif stat["name"] == "AVG":  # puntReturns_AVG
-3608                            for i in stat["athletes"]:
-3609                                player_id = int(i["id"])
-3610                                player_name = i["name"]
-3611                                player_stat = float(i["stat"])
-3612
-3613                                if rebuilt_json.get(player_id) is None:
-3614                                    rebuilt_json[player_id] = {}
-3615
-3616                                rebuilt_json[player_id]["game_id"] = game_id
-3617                                rebuilt_json[player_id][
-3618                                    "team_name"
-3619                                ] = team_name
-3620                                rebuilt_json[player_id][
-3621                                    "team_conference"
-3622                                ] = team_conference
-3623                                rebuilt_json[player_id][
-3624                                    "player_id"
-3625                                ] = player_id
-3626                                rebuilt_json[player_id][
-3627                                    "player_name"
-3628                                ] = player_name
-3629                                rebuilt_json[player_id][
-3630                                    "home_away"
-3631                                ] = home_away
-3632                                rebuilt_json[player_id][
-3633                                    "puntReturns_AVG"
-3634                                ] = player_stat
-3635
-3636                        elif stat["name"] == "TD":  # puntReturns_TD
-3637                            for i in stat["athletes"]:
-3638                                player_id = int(i["id"])
-3639                                player_name = i["name"]
-3640                                player_stat = int(i["stat"])
-3641
-3642                                if rebuilt_json.get(player_id) is None:
-3643                                    rebuilt_json[player_id] = {}
-3644
-3645                                rebuilt_json[player_id]["game_id"] = game_id
-3646                                rebuilt_json[player_id][
-3647                                    "team_name"
-3648                                ] = team_name
-3649                                rebuilt_json[player_id][
-3650                                    "team_conference"
-3651                                ] = team_conference
-3652                                rebuilt_json[player_id][
-3653                                    "player_id"
-3654                                ] = player_id
-3655                                rebuilt_json[player_id][
-3656                                    "player_name"
-3657                                ] = player_name
-3658                                rebuilt_json[player_id][
-3659                                    "home_away"
-3660                                ] = home_away
-3661                                rebuilt_json[player_id][
-3662                                    "puntReturns_TD"
-3663                                ] = player_stat
-3664
-3665                        elif stat["name"] == "LONG":  # puntReturns_LONG
-3666                            for i in stat["athletes"]:
-3667                                player_id = int(i["id"])
-3668                                player_name = i["name"]
-3669                                player_stat = int(i["stat"])
-3670
-3671                                if rebuilt_json.get(player_id) is None:
-3672                                    rebuilt_json[player_id] = {}
-3673
-3674                                rebuilt_json[player_id]["game_id"] = game_id
-3675                                rebuilt_json[player_id][
-3676                                    "team_name"
-3677                                ] = team_name
-3678                                rebuilt_json[player_id][
-3679                                    "team_conference"
-3680                                ] = team_conference
-3681                                rebuilt_json[player_id][
-3682                                    "player_id"
-3683                                ] = player_id
-3684                                rebuilt_json[player_id][
-3685                                    "player_name"
-3686                                ] = player_name
-3687                                rebuilt_json[player_id][
-3688                                    "home_away"
-3689                                ] = home_away
-3690                                rebuilt_json[player_id][
-3691                                    "puntReturns_LONG"
-3692                                ] = player_stat
-3693
-3694                        else:
-3695                            raise IndexError(
-3696                                f"Unhandled stat: \t{stat['name']}"
-3697                            )
-3698
-3699                else:
-3700                    raise IndexError(
-3701                        f"Unhandled stat category: \t{s_category['name']}"
-3702                    )
-3703
-3704    for key, value in tqdm(rebuilt_json.items()):
-3705        row_df = pd.json_normalize(value)
-3706        cfb_games_df = pd.concat([cfb_games_df, row_df], ignore_index=True)
-3707        del row_df
-3708
-3709    cfb_games_df[["passing_COMP", "passing_ATT"]] = cfb_games_df[
-3710        "passing_C/ATT"
-3711    ].str.split("/", expand=True)
-3712
-3713    cfb_games_df[["kicking_FGM", "kicking_FGA"]] = cfb_games_df[
-3714        "kicking_FG"
-3715    ].str.split(
-3716        "/", expand=True
-3717    )
-3718    cfb_games_df[["kicking_XPM", "kicking_XPA"]] = cfb_games_df[
-3719        "kicking_XP"
-3720    ].str.split(
-3721        "/", expand=True
-3722    )
-3723
-3724    cfb_games_df = cfb_games_df.fillna(0)
-3725
-3726    cfb_games_df = cfb_games_df.astype(
-3727        {
-3728            "passing_COMP": "int",
-3729            "passing_ATT": "int",
-3730            "kicking_FGM": "int",
-3731            "kicking_FGA": "int",
-3732            "kicking_XPM": "int",
-3733            "kicking_XPA": "int",
-3734        }
-3735    )
-3736    # print(cfb_games_df.columns)
-3737    cfb_games_df["season"] = season
-3738
-3739    if filter_by_stat_category is False:
-3740        cfb_games_df = cfb_games_df.reindex(columns=stat_columns)
-3741
-3742    elif filter_by_stat_category is True and stat_category == "passing":
-3743        cfb_games_df = cfb_games_df[
-3744            [
-3745                "season",
-3746                "game_id",
-3747                "team_name",
-3748                "team_conference",
-3749                "player_id",
-3750                "player_name",
-3751                "home_away",
-3752                # PASS
-3753                "passing_C/ATT",
-3754                "passing_COMP",
-3755                "passing_ATT",
-3756                "passing_YDS",
-3757                "passing_AVG",
-3758                "passing_TD",
-3759                "passing_INT",
-3760                "passing_QBR",
-3761            ]
-3762        ]
-3763
-3764    elif filter_by_stat_category is True and stat_category == "rushing":
-3765        cfb_games_df = cfb_games_df[
-3766            [
-3767                "season",
-3768                "game_id",
-3769                "team_name",
-3770                "team_conference",
-3771                "player_id",
-3772                "player_name",
-3773                "home_away",
-3774                # RUSH
-3775                "rushing_CAR",
-3776                "rushing_YDS",
-3777                "rushing_AVG",
-3778                "rushing_TD",
-3779                "rushing_LONG",
-3780            ]
-3781        ]
-3782
-3783    elif filter_by_stat_category is True and stat_category == "receiving":
-3784        cfb_games_df = cfb_games_df[
-3785            [
-3786                "season",
-3787                "game_id",
-3788                "team_name",
-3789                "team_conference",
-3790                "player_id",
-3791                "player_name",
-3792                "home_away",
-3793                # REC
-3794                "receiving_REC",
-3795                "receiving_YDS",
-3796                "receiving_AVG",
-3797                "receiving_TD",
-3798                "receiving_LONG",
-3799            ]
-3800        ]
-3801
-3802    elif filter_by_stat_category is True and stat_category == "fumbles":
-3803        cfb_games_df = cfb_games_df[
-3804            [
-3805                "season",
-3806                "game_id",
-3807                "team_name",
-3808                "team_conference",
-3809                "player_id",
-3810                "player_name",
-3811                "home_away",
-3812                # FUM
-3813                "fumbles_FUM",
-3814                "fumbles_LOST",
-3815                "fumbles_REC",
-3816            ]
-3817        ]
-3818
-3819    elif filter_by_stat_category is True and stat_category == "defensive":
-3820        cfb_games_df = cfb_games_df[
-3821            [
-3822                "season",
-3823                "game_id",
-3824                "team_name",
-3825                "team_conference",
-3826                "player_id",
-3827                "player_name",
-3828                "home_away",
-3829                # DEFENSE
-3830                "defensive_TOT",
-3831                "defensive_SOLO",
-3832                "defensive_TFL",
-3833                "defensive_QB HUR",
-3834                "defensive_SACKS",
-3835                "defensive_PD",
-3836                "defensive_TD",
-3837            ]
-3838        ]
-3839
-3840    elif filter_by_stat_category is True and stat_category == "interceptions":
-3841        cfb_games_df = cfb_games_df[
-3842            [
-3843                "season",
-3844                "game_id",
-3845                "team_name",
-3846                "team_conference",
-3847                "player_id",
-3848                "player_name",
-3849                "home_away",
-3850                # INT
-3851                "interceptions_INT",
-3852                "interceptions_YDS",
-3853                "interceptions_TD",
-3854            ]
-3855        ]
-3856
-3857    elif filter_by_stat_category is True and stat_category == "punting":
-3858        cfb_games_df = cfb_games_df[
-3859            [
-3860                "season",
-3861                "game_id",
-3862                "team_name",
-3863                "team_conference",
-3864                "player_id",
-3865                "player_name",
-3866                "home_away",
-3867                # PUNT
-3868                "punting_NO",
-3869                "punting_YDS",
-3870                "punting_AVG",
-3871                "punting_TB",
-3872                "punting_In 20",
-3873                "punting_LONG",
-3874            ]
-3875        ]
-3876
-3877    elif filter_by_stat_category is True and stat_category == "kicking":
-3878        cfb_games_df = cfb_games_df[
-3879            [
-3880                "season",
-3881                "game_id",
-3882                "team_name",
-3883                "team_conference",
-3884                "player_id",
-3885                "player_name",
-3886                "home_away",
-3887                # KICK
-3888                "kicking_FG",
-3889                "kicking_FGM",
-3890                "kicking_FGA",
-3891                "kicking_PCT",
-3892                "kicking_LONG",
-3893                "kicking_XP",
-3894                "kicking_XPM",
-3895                "kicking_XPA",
-3896                "kicking_PTS",
-3897            ]
-3898        ]
-3899
-3900    elif filter_by_stat_category is True and stat_category == "kickReturns":
-3901        cfb_games_df = cfb_games_df[
-3902            [
-3903                "season",
-3904                "game_id",
-3905                "team_name",
-3906                "team_conference",
-3907                "player_id",
-3908                "player_name",
-3909                "home_away",
-3910                # KR
-3911                "kickReturns_NO",
-3912                "kickReturns_YDS",
-3913                "kickReturns_AVG",
-3914                "kickReturns_TD",
-3915                "kickReturns_LONG",
-3916            ]
-3917        ]
-3918
-3919    elif filter_by_stat_category is True and stat_category == "puntReturns":
-3920        cfb_games_df = cfb_games_df[
-3921            [
-3922                "season",
-3923                "game_id",
-3924                "team_name",
-3925                "team_conference",
-3926                "player_id",
-3927                "player_name",
-3928                "home_away",
-3929                # KR
-3930                "puntReturns_NO",
-3931                "puntReturns_YDS",
-3932                "puntReturns_AVG",
-3933                "puntReturns_TD",
-3934                "puntReturns_LONG",
-3935            ]
-3936        ]
-3937
-3938    return cfb_games_df
+2213            "rushing_CAR": "uint16",
+2214            "rushing_YDS": "int16",
+2215            "rushing_AVG": "float16",
+2216            "rushing_TD": "uint16",
+2217            "rushing_LONG": "int16",
+2218
+2219            "receiving_REC": "uint16",
+2220            "receiving_YDS": "int16",
+2221            "receiving_AVG": "float16",
+2222            "receiving_TD": "uint16",
+2223            "receiving_LONG": "int16",
+2224
+2225            "fumbles_FUM": "uint8",
+2226            "fumbles_LOST": "uint8",
+2227            "fumbles_REC": "uint8",
+2228
+2229            "defensive_TOT": "uint16",
+2230            "defensive_SOLO": "uint16",
+2231            "defensive_TFL": "float16",
+2232            "defensive_QB HUR": "uint16",
+2233            "defensive_SACKS": "float16",
+2234            "defensive_PD": "uint16",
+2235            "defensive_TD": "uint8",
+2236
+2237            "interceptions_INT": "uint8",
+2238            "interceptions_YDS": "int16",
+2239            "interceptions_TD": "uint8",
+2240
+2241            "punting_NO": "uint16",
+2242            "punting_YDS": "int16",
+2243            "punting_AVG": "float16",
+2244            "punting_TB": "uint8",
+2245            "punting_In 20": "uint8",
+2246            "punting_LONG": "int8",
+2247
+2248            "kicking_FGM": "uint16",
+2249            "kicking_FGA": "uint16",
+2250            "kicking_PCT": "float16",
+2251            "kicking_LONG": "uint8",
+2252            "kicking_XPM": "uint16",
+2253            "kicking_XPA": "uint16",
+2254            "kicking_PTS": "uint16",
+2255
+2256            "kickReturns_NO": "uint16",
+2257            "kickReturns_YDS": "int16",
+2258            "kickReturns_AVG": "float16",
+2259            "kickReturns_TD": "uint8",
+2260            "kickReturns_LONG": "int8",
+2261
+2262            "puntReturns_NO": "uint16",
+2263            "puntReturns_YDS": "int16",
+2264            "puntReturns_AVG": "float16",
+2265            "puntReturns_TD": "uint8",
+2266            "puntReturns_LONG": "int8",
+2267        }
+2268    )
+2269
+2270    if filter_by_stat_category is True and stat_category == "passing":
+2271        cfb_games_df = cfb_games_df[[
+2272            "season",
+2273            "game_id",
+2274            "team_name",
+2275            "team_conference",
+2276            "player_id",
+2277            "player_name",
+2278            "home_away",
+2279            # PASS
+2280            "passing_C/ATT",
+2281            "passing_COMP",
+2282            "passing_ATT",
+2283            "passing_YDS",
+2284            "passing_AVG",
+2285            "passing_TD",
+2286            "passing_INT",
+2287            "passing_QBR",
+2288        ]]
+2289    elif filter_by_stat_category is True and stat_category == "rushing":
+2290        cfb_games_df = cfb_games_df[[
+2291            "season",
+2292            "game_id",
+2293            "team_name",
+2294            "team_conference",
+2295            "player_id",
+2296            "player_name",
+2297            "home_away",
+2298            # RUSH
+2299            "rushing_CAR",
+2300            "rushing_YDS",
+2301            "rushing_AVG",
+2302            "rushing_TD",
+2303            "rushing_LONG",
+2304        ]]
+2305    elif filter_by_stat_category is True and stat_category == "receiving":
+2306        cfb_games_df = cfb_games_df[[
+2307            "season",
+2308            "game_id",
+2309            "team_name",
+2310            "team_conference",
+2311            "player_id",
+2312            "player_name",
+2313            "home_away",
+2314            # REC
+2315            "receiving_REC",
+2316            "receiving_YDS",
+2317            "receiving_AVG",
+2318            "receiving_TD",
+2319            "receiving_LONG",
+2320        ]]
+2321    elif filter_by_stat_category is True and stat_category == "fumbles":
+2322        cfb_games_df = cfb_games_df[[
+2323            "season",
+2324            "game_id",
+2325            "team_name",
+2326            "team_conference",
+2327            "player_id",
+2328            "player_name",
+2329            "home_away",
+2330            # FUM
+2331            "fumbles_FUM",
+2332            "fumbles_LOST",
+2333            "fumbles_REC",
+2334        ]]
+2335    elif filter_by_stat_category is True and stat_category == "defensive":
+2336        cfb_games_df = cfb_games_df[[
+2337            "season",
+2338            "game_id",
+2339            "team_name",
+2340            "team_conference",
+2341            "player_id",
+2342            "player_name",
+2343            "home_away",
+2344            # DEFENSE
+2345            "defensive_TOT",
+2346            "defensive_SOLO",
+2347            "defensive_TFL",
+2348            "defensive_QB HUR",
+2349            "defensive_SACKS",
+2350            "defensive_PD",
+2351            "defensive_TD",
+2352        ]]
+2353    elif filter_by_stat_category is True and stat_category == "interceptions":
+2354        cfb_games_df = cfb_games_df[[
+2355            "season",
+2356            "game_id",
+2357            "team_name",
+2358            "team_conference",
+2359            "player_id",
+2360            "player_name",
+2361            "home_away",
+2362            # INT
+2363            "interceptions_INT",
+2364            "interceptions_YDS",
+2365            "interceptions_TD",
+2366        ]]
+2367    elif filter_by_stat_category is True and stat_category == "punting":
+2368        cfb_games_df = cfb_games_df[[
+2369            "season",
+2370            "game_id",
+2371            "team_name",
+2372            "team_conference",
+2373            "player_id",
+2374            "player_name",
+2375            "home_away",
+2376            # PUNT
+2377            "punting_NO",
+2378            "punting_YDS",
+2379            "punting_AVG",
+2380            "punting_TB",
+2381            "punting_In 20",
+2382            "punting_LONG",
+2383        ]]
+2384    elif filter_by_stat_category is True and stat_category == "kicking":
+2385        cfb_games_df = cfb_games_df[[
+2386            "season",
+2387            "game_id",
+2388            "team_name",
+2389            "team_conference",
+2390            "player_id",
+2391            "player_name",
+2392            "home_away",
+2393            # KICK
+2394            "kicking_FG",
+2395            "kicking_FGM",
+2396            "kicking_FGA",
+2397            "kicking_PCT",
+2398            "kicking_LONG",
+2399            "kicking_XP",
+2400            "kicking_XPM",
+2401            "kicking_XPA",
+2402            "kicking_PTS",
+2403        ]]
+2404    elif filter_by_stat_category is True and stat_category == "kickReturns":
+2405        cfb_games_df = cfb_games_df[[
+2406            "season",
+2407            "game_id",
+2408            "team_name",
+2409            "team_conference",
+2410            "player_id",
+2411            "player_name",
+2412            "home_away",
+2413            # KR
+2414            "kickReturns_NO",
+2415            "kickReturns_YDS",
+2416            "kickReturns_AVG",
+2417            "kickReturns_TD",
+2418            "kickReturns_LONG",
+2419        ]]
+2420    elif filter_by_stat_category is True and stat_category == "puntReturns":
+2421        cfb_games_df = cfb_games_df[[
+2422            "season",
+2423            "game_id",
+2424            "team_name",
+2425            "team_conference",
+2426            "player_id",
+2427            "player_name",
+2428            "home_away",
+2429            # KR
+2430            "puntReturns_NO",
+2431            "puntReturns_YDS",
+2432            "puntReturns_AVG",
+2433            "puntReturns_TD",
+2434            "puntReturns_LONG",
+2435        ]]
+2436
+2437    return cfb_games_df
 
@@ -11940,282 +8944,282 @@

Returns

-
3941def get_cfbd_player_advanced_game_stats(
-3942    game_id: int,
-3943    api_key: str = None,
-3944    api_key_dir: str = None,
-3945    return_as_dict: bool = False,
-3946):
-3947    """
-3948    Retrieves advanced game stats from the CFBD API.
-3949
-3950    Parameters
-3951    ----------
-3952    `game_id` (int, mandatory):
-3953        Mandatory requirement.
-3954        Specifies the game you want advanced game stats from.
-3955
-3956    `api_key` (str, optional):
-3957        Semi-optional argument.
-3958        If `api_key` is null, this function will attempt to load a CFBD API key
-3959        from the python environment, or from a file on this computer.
-3960        If `api_key` is not null,
-3961        this function will automatically assume that the
-3962        inputted `api_key` is a valid CFBD API key.
-3963
-3964    `api_key_dir` (str, optional):
-3965        Optional argument.
-3966        If `api_key` is set to am empty string, this variable is ignored.
-3967        If `api_key_dir` is null, and `api_key` is null,
-3968        this function will try to find
-3969        a CFBD API key file in this user's home directory.
-3970        If `api_key_dir` is set to a string, and `api_key` is null,
-3971        this function will assume that `api_key_dir` is a directory,
-3972        and will try to find a CFBD API key file in that directory.
-3973
-3974    `return_as_dict` (bool, semi-optional):
-3975        Semi-optional argument.
-3976        If you want this function to return
-3977        the data as a dictionary (read: JSON object),
-3978        instead of a pandas `DataFrame` object,
-3979        set `return_as_dict` to `True`.
-3980
-3981    Usage
-3982    ----------
-3983    ```
-3984    import time
-3985
-3986    from cfbd_json_py.games import get_cfbd_player_advanced_game_stats
-3987
-3988
-3989    cfbd_key = "tigersAreAwesome"  # placeholder for your CFBD API Key.
-3990
-3991    if cfbd_key is not "tigersAreAwesome":
-3992        print(
-3993            "Using the user's API key declared in this script " +
-3994            "for this example."
-3995        )
-3996
-3997        # Get advanced player stats for a 2019 CFB game
-3998        # between the LSU Tigers Football Program,
-3999        # and the Oklahoma Sooners Football Program.
-4000        print(
-4001            "Get advanced player stats for a 2019 CFB game between " +
-4002            "the LSU Tigers Football Program, " +
-4003            "and the Oklahoma Sooners Football Program."
-4004        )
-4005        json_data = get_cfbd_player_advanced_game_stats(
-4006            api_key=cfbd_key,
-4007            game_id=401135278
-4008        )
-4009        print(json_data)
-4010        time.sleep(5)
-4011
-4012
-4013        # You can also tell this function to just return the API call as
-4014        # a Dictionary (read: JSON) object.
-4015        print(
-4016            "You can also tell this function to just return the API call " +
-4017            "as a Dictionary (read: JSON) object."
-4018        )
-4019        json_data = get_cfbd_player_advanced_game_stats(
-4020            api_key=cfbd_key,
-4021            game_id=401135278,
-4022            return_as_dict=True
-4023        )
-4024        print(json_data)
-4025
-4026    else:
-4027        # Alternatively, if the CFBD API key exists in this python environment,
-4028        # or it's been set by cfbd_json_py.utls.set_cfbd_api_token(),
-4029        # you could just call these functions directly,
-4030        # without setting the API key in the script.
-4031        print(
-4032            "Using the user's API key supposedly loaded " +
-4033            "into this python environment for this example."
-4034        )
-4035
-4036        # Get advanced player stats for a 2019 CFB game
-4037        # between the LSU Tigers Football Program,
-4038        # and the Oklahoma Sooners Football Program.
-4039        print(
-4040            "Get advanced player stats for a 2019 CFB game " +
-4041            "between the LSU Tigers Football Program, " +
-4042            "and the Oklahoma Sooners Football Program."
-4043        )
-4044        json_data = get_cfbd_player_advanced_game_stats(
-4045            game_id=401135278
-4046        )
-4047        print(json_data)
-4048        time.sleep(5)
-4049
-4050
-4051        # You can also tell this function to just return the API call as
-4052        # a Dictionary (read: JSON) object.
-4053        print(
-4054            "You can also tell this function to just return the API call " +
-4055            "as a Dictionary (read: JSON) object."
-4056        )
-4057        json_data = get_cfbd_player_advanced_game_stats(
-4058            game_id=401135278,
-4059            return_as_dict=True
-4060        )
-4061        print(json_data)
-4062
-4063    ```
-4064    Returns
-4065    ----------
-4066    A pandas `DataFrame` object with college football game information,
-4067    or (if `return_as_dict` is set to `True`)
-4068    a dictionary object with college football game information.
-4069    """
-4070
-4071    # now = datetime.now()
-4072    usage_df = pd.DataFrame()
-4073    ppa_df = pd.DataFrame()
-4074    adv_stats_df = pd.DataFrame()
-4075    row_df = pd.DataFrame()
-4076    url = "https://api.collegefootballdata.com/game/box/advanced"
-4077
-4078    ##########################################################################
-4079
-4080    if api_key is not None:
-4081        real_api_key = api_key
-4082        del api_key
-4083    else:
-4084        real_api_key = get_cfbd_api_token(api_key_dir=api_key_dir)
-4085
-4086    if real_api_key == "tigersAreAwesome":
-4087        raise ValueError(
-4088            "You actually need to change `cfbd_key` to your CFBD API key."
-4089        )
-4090    elif "Bearer " in real_api_key:
-4091        pass
-4092    elif "Bearer" in real_api_key:
-4093        real_api_key = real_api_key.replace("Bearer", "Bearer ")
-4094    else:
-4095        real_api_key = "Bearer " + real_api_key
-4096
-4097    # URL builder
-4098    ##########################################################################
-4099
-4100    # Required by API
-4101    url += f"?gameId={game_id}"
-4102
-4103    headers = {
-4104        "Authorization": f"{real_api_key}",
-4105        "accept": "application/json"
-4106    }
-4107    response = requests.get(url, headers=headers)
-4108
-4109    if response.status_code == 200:
-4110        pass
-4111    elif response.status_code == 401:
-4112        raise ConnectionRefusedError(
-4113            "Could not connect. The connection was refused." +
-4114            "\nHTTP Status Code 401."
-4115        )
-4116    else:
-4117        raise ConnectionError(
-4118            f"Could not connect.\nHTTP Status code {response.status_code}"
-4119        )
-4120
-4121    json_data = response.json()
-4122
-4123    if return_as_dict is True:
-4124        return json_data
-4125
-4126    home_team_name = json_data["gameInfo"]["homeTeam"]
-4127    home_points = json_data["gameInfo"]["homePoints"]
-4128    home_win_prob = json_data["gameInfo"]["homeWinProb"]
-4129    away_team_name = json_data["gameInfo"]["awayTeam"]
-4130    away_points = json_data["gameInfo"]["awayPoints"]
-4131    away_win_prob = json_data["gameInfo"]["awayWinProb"]
-4132    home_winner = json_data["gameInfo"]["homeWinner"]
-4133    game_excitement_score = json_data["gameInfo"]["excitement"]
-4134
-4135    # Parsing Usage
-4136    print("Parsing player usage data.")
-4137    for player in tqdm(json_data["players"]["usage"]):
-4138        row_df = pd.DataFrame({"game_id": game_id}, index=[0])
-4139        row_df["player_name"] = player["player"]
-4140        row_df["team"] = player["team"]
-4141        row_df["position"] = player["position"]
-4142
-4143        row_df["total_usage"] = player["total"]
-4144        row_df["q1_usage"] = player["quarter1"]
-4145        row_df["q2_usage"] = player["quarter2"]
-4146        row_df["q3_usage"] = player["quarter3"]
-4147        row_df["q4_usage"] = player["quarter4"]
-4148        row_df["rushing_usage"] = player["rushing"]
-4149        row_df["passing_usage"] = player["passing"]
-4150
-4151        usage_df = pd.concat([usage_df, row_df], ignore_index=True)
-4152        del row_df
-4153
-4154    # Parsing PPA
-4155    print("Parsing player PPA data.")
-4156    for player in tqdm(json_data["players"]["ppa"]):
-4157        row_df = pd.DataFrame({"game_id": game_id}, index=[0])
-4158        row_df["player_name"] = player["player"]
-4159        row_df["team"] = player["team"]
-4160        row_df["position"] = player["position"]
-4161
-4162        row_df["average_ppa_total"] = player["average"]["total"]
-4163        row_df["average_ppa_q1"] = player["average"]["quarter1"]
-4164        row_df["average_ppa_q2"] = player["average"]["quarter2"]
-4165        row_df["average_ppa_q3"] = player["average"]["quarter3"]
-4166        row_df["average_ppa_q4"] = player["average"]["quarter4"]
-4167        row_df["average_ppa_rushing"] = player["average"]["rushing"]
-4168        row_df["average_ppa_passing"] = player["average"]["passing"]
-4169
-4170        row_df["cumulative_ppa_total"] = player["cumulative"]["total"]
-4171        row_df["cumulative_ppa_q1"] = player["cumulative"]["quarter1"]
-4172        row_df["cumulative_ppa_q2"] = player["cumulative"]["quarter2"]
-4173        row_df["cumulative_ppa_q3"] = player["cumulative"]["quarter3"]
-4174        row_df["cumulative_ppa_q4"] = player["cumulative"]["quarter4"]
-4175        row_df["cumulative_ppa_rushing"] = player["cumulative"]["rushing"]
-4176        row_df["cumulative_ppa_passing"] = player["cumulative"]["passing"]
-4177
-4178        ppa_df = pd.concat([ppa_df, row_df], ignore_index=True)
-4179
-4180    # Join `usage_df` and `ppa_df` together
-4181    adv_stats_df = pd.merge(
-4182        left=usage_df,
-4183        right=ppa_df,
-4184        how="outer",
-4185        on=["game_id", "player_name", "team", "position"],
-4186    )
-4187
-4188    # Add in these columns for completeness.
-4189
-4190    adv_stats_df.loc[
-4191        adv_stats_df["team"] == home_team_name, "home_away"
-4192    ] = "home"
-4193    adv_stats_df.loc[adv_stats_df["team"] == home_team_name, "opponent"] = (
-4194        away_team_name
-4195    )
-4196
-4197    adv_stats_df.loc[
-4198        adv_stats_df["team"] == away_team_name, "home_away"
-4199    ] = "away"
-4200    adv_stats_df.loc[adv_stats_df["team"] == away_team_name, "opponent"] = (
-4201        home_team_name
-4202    )
-4203
-4204    adv_stats_df["home_team"] = home_team_name
-4205    adv_stats_df["away_team"] = away_team_name
-4206
-4207    adv_stats_df["home_win_prob"] = home_win_prob
-4208    adv_stats_df["away_win_prob"] = away_win_prob
-4209
-4210    adv_stats_df["home_points"] = home_points
-4211    adv_stats_df["away_points"] = away_points
-4212
-4213    adv_stats_df["home_winner"] = home_winner
-4214    adv_stats_df["game_excitement_score"] = game_excitement_score
-4215
-4216    return adv_stats_df
+                
2440def get_cfbd_player_advanced_game_stats(
+2441    game_id: int,
+2442    api_key: str = None,
+2443    api_key_dir: str = None,
+2444    return_as_dict: bool = False,
+2445):
+2446    """
+2447    Retrieves advanced game stats from the CFBD API.
+2448
+2449    Parameters
+2450    ----------
+2451    `game_id` (int, mandatory):
+2452        Mandatory requirement.
+2453        Specifies the game you want advanced game stats from.
+2454
+2455    `api_key` (str, optional):
+2456        Semi-optional argument.
+2457        If `api_key` is null, this function will attempt to load a CFBD API key
+2458        from the python environment, or from a file on this computer.
+2459        If `api_key` is not null,
+2460        this function will automatically assume that the
+2461        inputted `api_key` is a valid CFBD API key.
+2462
+2463    `api_key_dir` (str, optional):
+2464        Optional argument.
+2465        If `api_key` is set to am empty string, this variable is ignored.
+2466        If `api_key_dir` is null, and `api_key` is null,
+2467        this function will try to find
+2468        a CFBD API key file in this user's home directory.
+2469        If `api_key_dir` is set to a string, and `api_key` is null,
+2470        this function will assume that `api_key_dir` is a directory,
+2471        and will try to find a CFBD API key file in that directory.
+2472
+2473    `return_as_dict` (bool, semi-optional):
+2474        Semi-optional argument.
+2475        If you want this function to return
+2476        the data as a dictionary (read: JSON object),
+2477        instead of a pandas `DataFrame` object,
+2478        set `return_as_dict` to `True`.
+2479
+2480    Usage
+2481    ----------
+2482    ```
+2483    import time
+2484
+2485    from cfbd_json_py.games import get_cfbd_player_advanced_game_stats
+2486
+2487
+2488    cfbd_key = "tigersAreAwesome"  # placeholder for your CFBD API Key.
+2489
+2490    if cfbd_key is not "tigersAreAwesome":
+2491        print(
+2492            "Using the user's API key declared in this script " +
+2493            "for this example."
+2494        )
+2495
+2496        # Get advanced player stats for a 2019 CFB game
+2497        # between the LSU Tigers Football Program,
+2498        # and the Oklahoma Sooners Football Program.
+2499        print(
+2500            "Get advanced player stats for a 2019 CFB game between " +
+2501            "the LSU Tigers Football Program, " +
+2502            "and the Oklahoma Sooners Football Program."
+2503        )
+2504        json_data = get_cfbd_player_advanced_game_stats(
+2505            api_key=cfbd_key,
+2506            game_id=401135278
+2507        )
+2508        print(json_data)
+2509        time.sleep(5)
+2510
+2511
+2512        # You can also tell this function to just return the API call as
+2513        # a Dictionary (read: JSON) object.
+2514        print(
+2515            "You can also tell this function to just return the API call " +
+2516            "as a Dictionary (read: JSON) object."
+2517        )
+2518        json_data = get_cfbd_player_advanced_game_stats(
+2519            api_key=cfbd_key,
+2520            game_id=401135278,
+2521            return_as_dict=True
+2522        )
+2523        print(json_data)
+2524
+2525    else:
+2526        # Alternatively, if the CFBD API key exists in this python environment,
+2527        # or it's been set by cfbd_json_py.utls.set_cfbd_api_token(),
+2528        # you could just call these functions directly,
+2529        # without setting the API key in the script.
+2530        print(
+2531            "Using the user's API key supposedly loaded " +
+2532            "into this python environment for this example."
+2533        )
+2534
+2535        # Get advanced player stats for a 2019 CFB game
+2536        # between the LSU Tigers Football Program,
+2537        # and the Oklahoma Sooners Football Program.
+2538        print(
+2539            "Get advanced player stats for a 2019 CFB game " +
+2540            "between the LSU Tigers Football Program, " +
+2541            "and the Oklahoma Sooners Football Program."
+2542        )
+2543        json_data = get_cfbd_player_advanced_game_stats(
+2544            game_id=401135278
+2545        )
+2546        print(json_data)
+2547        time.sleep(5)
+2548
+2549
+2550        # You can also tell this function to just return the API call as
+2551        # a Dictionary (read: JSON) object.
+2552        print(
+2553            "You can also tell this function to just return the API call " +
+2554            "as a Dictionary (read: JSON) object."
+2555        )
+2556        json_data = get_cfbd_player_advanced_game_stats(
+2557            game_id=401135278,
+2558            return_as_dict=True
+2559        )
+2560        print(json_data)
+2561
+2562    ```
+2563    Returns
+2564    ----------
+2565    A pandas `DataFrame` object with college football game information,
+2566    or (if `return_as_dict` is set to `True`)
+2567    a dictionary object with college football game information.
+2568    """
+2569
+2570    # now = datetime.now()
+2571    usage_df = pd.DataFrame()
+2572    ppa_df = pd.DataFrame()
+2573    adv_stats_df = pd.DataFrame()
+2574    row_df = pd.DataFrame()
+2575    url = "https://api.collegefootballdata.com/game/box/advanced"
+2576
+2577    ##########################################################################
+2578
+2579    if api_key is not None:
+2580        real_api_key = api_key
+2581        del api_key
+2582    else:
+2583        real_api_key = get_cfbd_api_token(api_key_dir=api_key_dir)
+2584
+2585    if real_api_key == "tigersAreAwesome":
+2586        raise ValueError(
+2587            "You actually need to change `cfbd_key` to your CFBD API key."
+2588        )
+2589    elif "Bearer " in real_api_key:
+2590        pass
+2591    elif "Bearer" in real_api_key:
+2592        real_api_key = real_api_key.replace("Bearer", "Bearer ")
+2593    else:
+2594        real_api_key = "Bearer " + real_api_key
+2595
+2596    # URL builder
+2597    ##########################################################################
+2598
+2599    # Required by API
+2600    url += f"?gameId={game_id}"
+2601
+2602    headers = {
+2603        "Authorization": f"{real_api_key}",
+2604        "accept": "application/json"
+2605    }
+2606    response = requests.get(url, headers=headers)
+2607
+2608    if response.status_code == 200:
+2609        pass
+2610    elif response.status_code == 401:
+2611        raise ConnectionRefusedError(
+2612            "Could not connect. The connection was refused." +
+2613            "\nHTTP Status Code 401."
+2614        )
+2615    else:
+2616        raise ConnectionError(
+2617            f"Could not connect.\nHTTP Status code {response.status_code}"
+2618        )
+2619
+2620    json_data = response.json()
+2621
+2622    if return_as_dict is True:
+2623        return json_data
+2624
+2625    home_team_name = json_data["gameInfo"]["homeTeam"]
+2626    home_points = json_data["gameInfo"]["homePoints"]
+2627    home_win_prob = json_data["gameInfo"]["homeWinProb"]
+2628    away_team_name = json_data["gameInfo"]["awayTeam"]
+2629    away_points = json_data["gameInfo"]["awayPoints"]
+2630    away_win_prob = json_data["gameInfo"]["awayWinProb"]
+2631    home_winner = json_data["gameInfo"]["homeWinner"]
+2632    game_excitement_score = json_data["gameInfo"]["excitement"]
+2633
+2634    # Parsing Usage
+2635    logging.info("Parsing player usage data.")
+2636    for player in json_data["players"]["usage"]:
+2637        row_df = pd.DataFrame({"game_id": game_id}, index=[0])
+2638        row_df["player_name"] = player["player"]
+2639        row_df["team"] = player["team"]
+2640        row_df["position"] = player["position"]
+2641
+2642        row_df["total_usage"] = player["total"]
+2643        row_df["q1_usage"] = player["quarter1"]
+2644        row_df["q2_usage"] = player["quarter2"]
+2645        row_df["q3_usage"] = player["quarter3"]
+2646        row_df["q4_usage"] = player["quarter4"]
+2647        row_df["rushing_usage"] = player["rushing"]
+2648        row_df["passing_usage"] = player["passing"]
+2649
+2650        usage_df = pd.concat([usage_df, row_df], ignore_index=True)
+2651        del row_df
+2652
+2653    # Parsing PPA
+2654    logging.info("Parsing player PPA data.")
+2655    for player in json_data["players"]["ppa"]:
+2656        row_df = pd.DataFrame({"game_id": game_id}, index=[0])
+2657        row_df["player_name"] = player["player"]
+2658        row_df["team"] = player["team"]
+2659        row_df["position"] = player["position"]
+2660
+2661        row_df["average_ppa_total"] = player["average"]["total"]
+2662        row_df["average_ppa_q1"] = player["average"]["quarter1"]
+2663        row_df["average_ppa_q2"] = player["average"]["quarter2"]
+2664        row_df["average_ppa_q3"] = player["average"]["quarter3"]
+2665        row_df["average_ppa_q4"] = player["average"]["quarter4"]
+2666        row_df["average_ppa_rushing"] = player["average"]["rushing"]
+2667        row_df["average_ppa_passing"] = player["average"]["passing"]
+2668
+2669        row_df["cumulative_ppa_total"] = player["cumulative"]["total"]
+2670        row_df["cumulative_ppa_q1"] = player["cumulative"]["quarter1"]
+2671        row_df["cumulative_ppa_q2"] = player["cumulative"]["quarter2"]
+2672        row_df["cumulative_ppa_q3"] = player["cumulative"]["quarter3"]
+2673        row_df["cumulative_ppa_q4"] = player["cumulative"]["quarter4"]
+2674        row_df["cumulative_ppa_rushing"] = player["cumulative"]["rushing"]
+2675        row_df["cumulative_ppa_passing"] = player["cumulative"]["passing"]
+2676
+2677        ppa_df = pd.concat([ppa_df, row_df], ignore_index=True)
+2678
+2679    # Join `usage_df` and `ppa_df` together
+2680    adv_stats_df = pd.merge(
+2681        left=usage_df,
+2682        right=ppa_df,
+2683        how="outer",
+2684        on=["game_id", "player_name", "team", "position"],
+2685    )
+2686
+2687    # Add in these columns for completeness.
+2688
+2689    adv_stats_df.loc[
+2690        adv_stats_df["team"] == home_team_name, "home_away"
+2691    ] = "home"
+2692    adv_stats_df.loc[adv_stats_df["team"] == home_team_name, "opponent"] = (
+2693        away_team_name
+2694    )
+2695
+2696    adv_stats_df.loc[
+2697        adv_stats_df["team"] == away_team_name, "home_away"
+2698    ] = "away"
+2699    adv_stats_df.loc[adv_stats_df["team"] == away_team_name, "opponent"] = (
+2700        home_team_name
+2701    )
+2702
+2703    adv_stats_df["home_team"] = home_team_name
+2704    adv_stats_df["away_team"] = away_team_name
+2705
+2706    adv_stats_df["home_win_prob"] = home_win_prob
+2707    adv_stats_df["away_win_prob"] = away_win_prob
+2708
+2709    adv_stats_df["home_points"] = home_points
+2710    adv_stats_df["away_points"] = away_points
+2711
+2712    adv_stats_df["home_winner"] = home_winner
+2713    adv_stats_df["game_excitement_score"] = game_excitement_score
+2714
+2715    return adv_stats_df
 
@@ -12372,305 +9376,305 @@

Returns

-
4226def get_cfbd_live_scoreboard(
-4227    ncaa_division: str = "fbs",
-4228    conference: str = None,
-4229    api_key: str = None,
-4230    api_key_dir: str = None,
-4231    return_as_dict: bool = False,
-4232):
-4233    """
-4234    YOU MUST BE SUBSCRIBED TO THE CFBD PATREON FOR THIS FUNCTION TO WORK!
-4235    To view the CFBD Patreon, visit https://www.patreon.com/collegefootballdata
-4236
-4237    Retrieves live scoreboard data from the CFBD API,
-4238    assuming the API key is an API key from a Patreon supporter.
-4239
-4240    Parameters
-4241    ----------
-4242    `ncaa_division` (str, semi-optional):
-4243        Semi-optional argument.
-4244        By default, `ncaa_division` will be set to "fbs",
-4245        short for the Football Bowl Subdivision (FBS),
-4246        formerly known as D1-A (read as "division one single A"),
-4247        the highest level in the NCAA football pyramid,
-4248        where teams can scholarship up to 85 players
-4249        on their football team solely for athletic ability,
-4250        and often have the largest athletics budgets
-4251        within the NCAA.
-4252
-4253        Other valid inputs are:
-4254        - "fcs": Football Championship Subdivision (FCS),
-4255            formerly known as D1-AA (read as "division one double A").
-4256            An FCS school is still in the 1st division of the NCAA,
-4257            making them eligible for the March Madness tournament,
-4258            but may not have the resources to compete at the FBS level
-4259            at this time. FCS schools are limited to 63 athletic scholarships
-4260            for football.
-4261        - "ii": NCAA Division II. Schools in this and D3 are not
-4262            eligible for the March Madness tournament,
-4263            and are limited to 36 athletic scholarships
-4264            for their football team.
-4265        - "iii": NCAA Division III. The largest single division within the
-4266            NCAA football pyramid.
-4267            D3 schools have the distinction of being part of
-4268            the only NCAA division that cannot give out scholarships solely
-4269            for athletic ability.
-4270
-4271    `conference` (str, optional):
-4272        Optional argument.
-4273        If you only want live scoreboard data from games
-4274        involving teams a specific conference,
-4275        set `conference` to the abbreviation
-4276        of the conference you want live scoreboard data from.
-4277
-4278    `api_key` (str, optional):
-4279        Semi-optional argument.
-4280        If `api_key` is null, this function will attempt to load a CFBD API key
-4281        from the python environment, or from a file on this computer.
-4282        If `api_key` is not null,
-4283        this function will automatically assume that the
-4284        inputted `api_key` is a valid CFBD API key.
-4285
-4286    `api_key_dir` (str, optional):
-4287        Optional argument.
-4288        If `api_key` is set to am empty string, this variable is ignored.
-4289        If `api_key_dir` is null, and `api_key` is null,
-4290        this function will try to find
-4291        a CFBD API key file in this user's home directory.
-4292        If `api_key_dir` is set to a string, and `api_key` is null,
-4293        this function will assume that `api_key_dir` is a directory,
-4294        and will try to find a CFBD API key file in that directory.
-4295
-4296    `return_as_dict` (bool, semi-optional):
-4297        Semi-optional argument.
-4298        If you want this function to return
-4299        the data as a dictionary (read: JSON object),
-4300        instead of a pandas `DataFrame` object,
-4301        set `return_as_dict` to `True`.
-4302    Usage
-4303    ----------
-4304    ```
-4305    import time
-4306
-4307    from cfbd_json_py.games import get_cfbd_live_scoreboard
-4308
-4309
-4310    cfbd_key = "tigersAreAwesome"  # placeholder for your CFBD API Key.
-4311
-4312    if cfbd_key != "tigersAreAwesome":
-4313        print(
-4314            "Using the user's API key declared " +
-4315            "in this script for this example."
-4316        )
-4317
-4318        # Get live scoreboard data from the CFBD API.
-4319        print(
-4320            "Get live scoreboard data from the CFBD API."
-4321        )
-4322        json_data = get_cfbd_live_scoreboard(
-4323            api_key=cfbd_key
-4324        )
-4325        print(json_data)
-4326        time.sleep(5)
-4327
-4328        # Get live scoreboard data from the CFBD API,
-4329        # but only from the FCS ranks.
-4330        print(
-4331            "Get live scoreboard data from the CFBD API, " +
-4332            "but only from the FCS ranks."
-4333        )
-4334        json_data = get_cfbd_live_scoreboard(
-4335            ncaa_division="fcs",
-4336            api_key=cfbd_key
-4337        )
-4338        print(json_data)
-4339        time.sleep(5)
-4340
-4341        # Get live scoreboard data from the CFBD API,
-4342        # but only from the Atlantic Coast Conference.
-4343        print(
-4344            "Get live scoreboard data from the CFBD API, " +
-4345            "but only from the Atlantic Coast Conference."
-4346        )
-4347        json_data = get_cfbd_live_scoreboard(
-4348            conference="ACC",
-4349            api_key=cfbd_key
-4350        )
-4351        print(json_data)
-4352        time.sleep(5)
-4353
-4354        # You can also tell this function to just return the API call as
-4355        # a Dictionary (read: JSON) object.
-4356        print(
-4357            "You can also tell this function to just return the API call " +
-4358            "as a Dictionary (read: JSON) object."
-4359        )
-4360        json_data = get_cfbd_live_scoreboard(
-4361            api_key=cfbd_key,
-4362            return_as_dict=True
-4363        )
-4364        print(json_data)
-4365
-4366    else:
-4367        # Alternatively, if the CFBD API key exists in this python environment,
-4368        # or it's been set by cfbd_json_py.utls.set_cfbd_api_token(),
-4369        # you could just call these functions directly,
-4370        # without setting the API key in the script.
-4371        print(
-4372            "Using the user's API key supposedly loaded " +
-4373            "into this python environment for this example."
-4374        )
-4375
-4376        # Get live scoreboard data from the CFBD API.
-4377        print(
-4378            "Get live scoreboard data from the CFBD API."
-4379        )
-4380        json_data = get_cfbd_live_scoreboard()
-4381        print(json_data)
-4382        time.sleep(5)
-4383
-4384        # Get live scoreboard data from the CFBD API,
-4385        # but only from the FCS ranks.
-4386        print(
-4387            "Get live scoreboard data from the CFBD API, " +
-4388            "but only from the FCS ranks."
-4389        )
-4390        json_data = get_cfbd_live_scoreboard(
-4391            ncaa_division="fcs",
-4392        )
-4393        print(json_data)
-4394        time.sleep(5)
-4395
-4396        # Get live scoreboard data from the CFBD API,
-4397        # but only from the Atlantic Coast Conference.
-4398        print(
-4399            "Get live scoreboard data from the CFBD API, " +
-4400            "but only from the Atlantic Coast Conference."
-4401        )
-4402        json_data = get_cfbd_live_scoreboard(
-4403            conference="ACC",
-4404        )
-4405        print(json_data)
-4406        time.sleep(5)
-4407
-4408        # You can also tell this function to just return the API call as
-4409        # a Dictionary (read: JSON) object.
-4410        print(
-4411            "You can also tell this function to just return the API call " +
-4412            "as a Dictionary (read: JSON) object."
-4413        )
-4414        json_data = get_cfbd_live_scoreboard(
-4415            return_as_dict=True
-4416        )
-4417        print(json_data)
-4418
-4419    ```
-4420
-4421    Returns
-4422    ----------
-4423    A pandas `DataFrame` object with live scoreboard data,
-4424    or (if `return_as_dict` is set to `True`)
-4425    a dictionary object with live scoreboard data.
-4426
-4427    """
-4428    # real_api_key = ""
-4429    scoreboard_df = pd.DataFrame()
-4430    url = "https://api.collegefootballdata.com/scoreboard"
-4431
-4432    if api_key is not None:
-4433        real_api_key = api_key
-4434        del api_key
-4435    else:
-4436        real_api_key = get_cfbd_api_token(api_key_dir=api_key_dir)
-4437
-4438    if real_api_key == "tigersAreAwesome":
-4439        raise ValueError(
-4440            "You actually need to change `cfbd_key` to your CFBD API key."
-4441        )
-4442    elif "Bearer " in real_api_key:
-4443        pass
-4444    elif "Bearer" in real_api_key:
-4445        real_api_key = real_api_key.replace("Bearer", "Bearer ")
-4446    else:
-4447        real_api_key = "Bearer " + real_api_key
-4448
-4449    if (
-4450        ncaa_division.lower() == "fbs"
-4451        or ncaa_division.lower() == "fcs"
-4452        or ncaa_division.lower() == "ii"
-4453        or ncaa_division.lower() == "iii"
-4454    ):
-4455        pass
-4456    else:
-4457        raise ValueError(
-4458            "An invalid NCAA Division was inputted when calling this function."
-4459            + '\nValid inputs are:\n-"fbs"\n-"fcs"\n-"ii"\n-"iii"'
-4460            + f"\n\nYou entered:\n{ncaa_division}"
-4461        )
-4462
-4463    url += f"?classification={ncaa_division}"
-4464
-4465    if conference is not None and len(conference) > 0:
-4466        url += f"&conference={conference}"
-4467
-4468    headers = {
-4469        "Authorization": f"{real_api_key}",
-4470        "accept": "application/json"
-4471    }
-4472
-4473    response = requests.get(url, headers=headers)
-4474
-4475    if response.status_code == 200:
-4476        pass
-4477    elif response.status_code == 401:
-4478        raise ConnectionRefusedError(
-4479            "Could not connect. The connection was refused.\n" +
-4480            "HTTP Status Code 401."
-4481        )
-4482    else:
-4483        raise ConnectionError(
-4484            f"Could not connect.\nHTTP Status code {response.status_code}"
-4485        )
-4486
-4487    json_data = response.json()
-4488
-4489    if return_as_dict is True:
-4490        return json_data
-4491
-4492    scoreboard_df = pd.json_normalize(json_data)
-4493
-4494    if len(scoreboard_df) > 0:
-4495        scoreboard_df.rename(
-4496            columns={
-4497                "id": "game_id",
-4498                "startDate": "start_datetime",
-4499                "startTimeTBD": "is_start_time_tbd",
-4500                "tv": "tv_network",
-4501                "neutralSite": "is_neutral_site_game",
-4502                "conferenceGame": "is_conference_game",
-4503                "venue.name": "stadium_name",
-4504                "venue.city": "stadium_city",
-4505                "venue.state": "stadium_state",
-4506                "homeTeam.id": "home_team_id",
-4507                "homeTeam.name": "home_team_name",
-4508                "homeTeam.conference": "home_team_conference",
-4509                "awayTeam.id": "away_team_id",
-4510                "awayTeam.name": "away_team_name",
-4511                "awayTeam.conference": "away_team_conference",
-4512                "weather.temperature": "weather_temperature",
-4513                "weather.description": "weather_description",
-4514                "weather.windSpeed": "weather_wind_speed",
-4515                "weather.windDirection": "weather_wind_direction",
-4516                "betting.spread": "betting_spread",
-4517                "betting.overUnder": "betting_over_under",
-4518                "betting.homeMoneyline": "betting_home_moneyline",
-4519                "betting.awayMoneyline": "betting_away_moneyline",
-4520            },
-4521            inplace=True,
-4522        )
-4523
-4524    return scoreboard_df
+                
2725def get_cfbd_live_scoreboard(
+2726    ncaa_division: str = "fbs",
+2727    conference: str = None,
+2728    api_key: str = None,
+2729    api_key_dir: str = None,
+2730    return_as_dict: bool = False,
+2731):
+2732    """
+2733    YOU MUST BE SUBSCRIBED TO THE CFBD PATREON FOR THIS FUNCTION TO WORK!
+2734    To view the CFBD Patreon, visit https://www.patreon.com/collegefootballdata
+2735
+2736    Retrieves live scoreboard data from the CFBD API,
+2737    assuming the API key is an API key from a Patreon supporter.
+2738
+2739    Parameters
+2740    ----------
+2741    `ncaa_division` (str, semi-optional):
+2742        Semi-optional argument.
+2743        By default, `ncaa_division` will be set to "fbs",
+2744        short for the Football Bowl Subdivision (FBS),
+2745        formerly known as D1-A (read as "division one single A"),
+2746        the highest level in the NCAA football pyramid,
+2747        where teams can scholarship up to 85 players
+2748        on their football team solely for athletic ability,
+2749        and often have the largest athletics budgets
+2750        within the NCAA.
+2751
+2752        Other valid inputs are:
+2753        - "fcs": Football Championship Subdivision (FCS),
+2754            formerly known as D1-AA (read as "division one double A").
+2755            An FCS school is still in the 1st division of the NCAA,
+2756            making them eligible for the March Madness tournament,
+2757            but may not have the resources to compete at the FBS level
+2758            at this time. FCS schools are limited to 63 athletic scholarships
+2759            for football.
+2760        - "ii": NCAA Division II. Schools in this and D3 are not
+2761            eligible for the March Madness tournament,
+2762            and are limited to 36 athletic scholarships
+2763            for their football team.
+2764        - "iii": NCAA Division III. The largest single division within the
+2765            NCAA football pyramid.
+2766            D3 schools have the distinction of being part of
+2767            the only NCAA division that cannot give out scholarships solely
+2768            for athletic ability.
+2769
+2770    `conference` (str, optional):
+2771        Optional argument.
+2772        If you only want live scoreboard data from games
+2773        involving teams a specific conference,
+2774        set `conference` to the abbreviation
+2775        of the conference you want live scoreboard data from.
+2776
+2777    `api_key` (str, optional):
+2778        Semi-optional argument.
+2779        If `api_key` is null, this function will attempt to load a CFBD API key
+2780        from the python environment, or from a file on this computer.
+2781        If `api_key` is not null,
+2782        this function will automatically assume that the
+2783        inputted `api_key` is a valid CFBD API key.
+2784
+2785    `api_key_dir` (str, optional):
+2786        Optional argument.
+2787        If `api_key` is set to am empty string, this variable is ignored.
+2788        If `api_key_dir` is null, and `api_key` is null,
+2789        this function will try to find
+2790        a CFBD API key file in this user's home directory.
+2791        If `api_key_dir` is set to a string, and `api_key` is null,
+2792        this function will assume that `api_key_dir` is a directory,
+2793        and will try to find a CFBD API key file in that directory.
+2794
+2795    `return_as_dict` (bool, semi-optional):
+2796        Semi-optional argument.
+2797        If you want this function to return
+2798        the data as a dictionary (read: JSON object),
+2799        instead of a pandas `DataFrame` object,
+2800        set `return_as_dict` to `True`.
+2801    Usage
+2802    ----------
+2803    ```
+2804    import time
+2805
+2806    from cfbd_json_py.games import get_cfbd_live_scoreboard
+2807
+2808
+2809    cfbd_key = "tigersAreAwesome"  # placeholder for your CFBD API Key.
+2810
+2811    if cfbd_key != "tigersAreAwesome":
+2812        print(
+2813            "Using the user's API key declared " +
+2814            "in this script for this example."
+2815        )
+2816
+2817        # Get live scoreboard data from the CFBD API.
+2818        print(
+2819            "Get live scoreboard data from the CFBD API."
+2820        )
+2821        json_data = get_cfbd_live_scoreboard(
+2822            api_key=cfbd_key
+2823        )
+2824        print(json_data)
+2825        time.sleep(5)
+2826
+2827        # Get live scoreboard data from the CFBD API,
+2828        # but only from the FCS ranks.
+2829        print(
+2830            "Get live scoreboard data from the CFBD API, " +
+2831            "but only from the FCS ranks."
+2832        )
+2833        json_data = get_cfbd_live_scoreboard(
+2834            ncaa_division="fcs",
+2835            api_key=cfbd_key
+2836        )
+2837        print(json_data)
+2838        time.sleep(5)
+2839
+2840        # Get live scoreboard data from the CFBD API,
+2841        # but only from the Atlantic Coast Conference.
+2842        print(
+2843            "Get live scoreboard data from the CFBD API, " +
+2844            "but only from the Atlantic Coast Conference."
+2845        )
+2846        json_data = get_cfbd_live_scoreboard(
+2847            conference="ACC",
+2848            api_key=cfbd_key
+2849        )
+2850        print(json_data)
+2851        time.sleep(5)
+2852
+2853        # You can also tell this function to just return the API call as
+2854        # a Dictionary (read: JSON) object.
+2855        print(
+2856            "You can also tell this function to just return the API call " +
+2857            "as a Dictionary (read: JSON) object."
+2858        )
+2859        json_data = get_cfbd_live_scoreboard(
+2860            api_key=cfbd_key,
+2861            return_as_dict=True
+2862        )
+2863        print(json_data)
+2864
+2865    else:
+2866        # Alternatively, if the CFBD API key exists in this python environment,
+2867        # or it's been set by cfbd_json_py.utls.set_cfbd_api_token(),
+2868        # you could just call these functions directly,
+2869        # without setting the API key in the script.
+2870        print(
+2871            "Using the user's API key supposedly loaded " +
+2872            "into this python environment for this example."
+2873        )
+2874
+2875        # Get live scoreboard data from the CFBD API.
+2876        print(
+2877            "Get live scoreboard data from the CFBD API."
+2878        )
+2879        json_data = get_cfbd_live_scoreboard()
+2880        print(json_data)
+2881        time.sleep(5)
+2882
+2883        # Get live scoreboard data from the CFBD API,
+2884        # but only from the FCS ranks.
+2885        print(
+2886            "Get live scoreboard data from the CFBD API, " +
+2887            "but only from the FCS ranks."
+2888        )
+2889        json_data = get_cfbd_live_scoreboard(
+2890            ncaa_division="fcs",
+2891        )
+2892        print(json_data)
+2893        time.sleep(5)
+2894
+2895        # Get live scoreboard data from the CFBD API,
+2896        # but only from the Atlantic Coast Conference.
+2897        print(
+2898            "Get live scoreboard data from the CFBD API, " +
+2899            "but only from the Atlantic Coast Conference."
+2900        )
+2901        json_data = get_cfbd_live_scoreboard(
+2902            conference="ACC",
+2903        )
+2904        print(json_data)
+2905        time.sleep(5)
+2906
+2907        # You can also tell this function to just return the API call as
+2908        # a Dictionary (read: JSON) object.
+2909        print(
+2910            "You can also tell this function to just return the API call " +
+2911            "as a Dictionary (read: JSON) object."
+2912        )
+2913        json_data = get_cfbd_live_scoreboard(
+2914            return_as_dict=True
+2915        )
+2916        print(json_data)
+2917
+2918    ```
+2919
+2920    Returns
+2921    ----------
+2922    A pandas `DataFrame` object with live scoreboard data,
+2923    or (if `return_as_dict` is set to `True`)
+2924    a dictionary object with live scoreboard data.
+2925
+2926    """
+2927    # real_api_key = ""
+2928    scoreboard_df = pd.DataFrame()
+2929    url = "https://api.collegefootballdata.com/scoreboard"
+2930
+2931    if api_key is not None:
+2932        real_api_key = api_key
+2933        del api_key
+2934    else:
+2935        real_api_key = get_cfbd_api_token(api_key_dir=api_key_dir)
+2936
+2937    if real_api_key == "tigersAreAwesome":
+2938        raise ValueError(
+2939            "You actually need to change `cfbd_key` to your CFBD API key."
+2940        )
+2941    elif "Bearer " in real_api_key:
+2942        pass
+2943    elif "Bearer" in real_api_key:
+2944        real_api_key = real_api_key.replace("Bearer", "Bearer ")
+2945    else:
+2946        real_api_key = "Bearer " + real_api_key
+2947
+2948    if (
+2949        ncaa_division.lower() == "fbs"
+2950        or ncaa_division.lower() == "fcs"
+2951        or ncaa_division.lower() == "ii"
+2952        or ncaa_division.lower() == "iii"
+2953    ):
+2954        pass
+2955    else:
+2956        raise ValueError(
+2957            "An invalid NCAA Division was inputted when calling this function."
+2958            + '\nValid inputs are:\n-"fbs"\n-"fcs"\n-"ii"\n-"iii"'
+2959            + f"\n\nYou entered:\n{ncaa_division}"
+2960        )
+2961
+2962    url += f"?classification={ncaa_division}"
+2963
+2964    if conference is not None and len(conference) > 0:
+2965        url += f"&conference={conference}"
+2966
+2967    headers = {
+2968        "Authorization": f"{real_api_key}",
+2969        "accept": "application/json"
+2970    }
+2971
+2972    response = requests.get(url, headers=headers)
+2973
+2974    if response.status_code == 200:
+2975        pass
+2976    elif response.status_code == 401:
+2977        raise ConnectionRefusedError(
+2978            "Could not connect. The connection was refused.\n" +
+2979            "HTTP Status Code 401."
+2980        )
+2981    else:
+2982        raise ConnectionError(
+2983            f"Could not connect.\nHTTP Status code {response.status_code}"
+2984        )
+2985
+2986    json_data = response.json()
+2987
+2988    if return_as_dict is True:
+2989        return json_data
+2990
+2991    scoreboard_df = pd.json_normalize(json_data)
+2992
+2993    if len(scoreboard_df) > 0:
+2994        scoreboard_df.rename(
+2995            columns={
+2996                "id": "game_id",
+2997                "startDate": "start_datetime",
+2998                "startTimeTBD": "is_start_time_tbd",
+2999                "tv": "tv_network",
+3000                "neutralSite": "is_neutral_site_game",
+3001                "conferenceGame": "is_conference_game",
+3002                "venue.name": "stadium_name",
+3003                "venue.city": "stadium_city",
+3004                "venue.state": "stadium_state",
+3005                "homeTeam.id": "home_team_id",
+3006                "homeTeam.name": "home_team_name",
+3007                "homeTeam.conference": "home_team_conference",
+3008                "awayTeam.id": "away_team_id",
+3009                "awayTeam.name": "away_team_name",
+3010                "awayTeam.conference": "away_team_conference",
+3011                "weather.temperature": "weather_temperature",
+3012                "weather.description": "weather_description",
+3013                "weather.windSpeed": "weather_wind_speed",
+3014                "weather.windDirection": "weather_wind_direction",
+3015                "betting.spread": "betting_spread",
+3016                "betting.overUnder": "betting_over_under",
+3017                "betting.homeMoneyline": "betting_home_moneyline",
+3018                "betting.awayMoneyline": "betting_away_moneyline",
+3019            },
+3020            inplace=True,
+3021        )
+3022
+3023    return scoreboard_df
 
@@ -12882,8 +9886,6 @@

Returns

def get_cfbd_weather_info( game_id: int = None, season: int = None, week: int Returns

-
4527def get_cfbd_weather_info(
-4528    game_id: int = None,
-4529    season: int = None,
-4530    # `game_id` and/or `season` must be not null for this function to work.
-4531    week: int = None,
-4532    season_type: str = "both",  # "regular", "postseason", or "both"
-4533    conference: str = None,
-4534    team_name: str = None,
-4535    ncaa_division: str = "fbs",
-4536    api_key: str = None,
-4537    api_key_dir: str = None,
-4538    return_as_dict: bool = False,
-4539):
-4540    """
-4541    YOU MUST BE SUBSCRIBED TO THE CFBD PATREON FOR THIS FUNCTION TO WORK!
-4542    To view the CFBD Patreon, visit https://www.patreon.com/collegefootballdata
-4543
-4544    Parameters
-4545    ----------
-4546    Retrieves live scoreboard data from the CFBD API,
-4547    assuming the API key is an API key from a Patreon supporter.
-4548
-4549    Parameters
-4550    ----------
-4551
-4552    `game_id` (int, mandatory):
-4553        Mandatory requirement.
-4554        Specifies the game you want weather data from.
-4555        This or `season` must be set to a valid non-null value.
-4556
-4557    `season` (int, mandatory):
-4558        Mandatory requirement.
-4559        Specifies the season you want weather data from.
-4560        This or `season` must be set to a valid non-null value.
-4561
-4562    `week` (int, optional):
-4563        Optional argument.
-4564        If `week` is set to an integer, this function will attempt
-4565        to load weather data from games in that season, and in that week.
-4566
-4567    `season_type` (str, semi-optional):
-4568        Semi-optional argument.
-4569        By default, this will be set to "both", for the CFB regular season.
-4570        If you want postseason betting data, set `season_type` to "postseason".
-4571        If `season_type` is set to anything but "regular" or "postseason",
-4572        a `ValueError()` will be raised.
-4573
-4574    `conference` (str, optional):
-4575        Optional argument.
-4576        If you only want weather data from games
-4577        involving teams a specific conference,
-4578        set `conference` to the abbreviation
-4579        of the conference you want weather data from.
-4580
-4581    `team_name` (str, optional):
-4582        Optional argument.
-4583        If you only want weather data for a team,
-4584        regardless if they are the home/away team,
-4585        set `team` to the name of the team
-4586        you want weather data from.
-4587
-4588    `ncaa_division` (str, semi-optional):
-4589        Semi-optional argument.
-4590        By default, `ncaa_division` will be set to "fbs",
-4591        short for the Football Bowl Subdivision (FBS),
-4592        formerly known as D1-A (read as "division one single A"),
-4593        the highest level in the NCAA football pyramid,
-4594        where teams can scholarship up to 85 players
-4595        on their football team solely for athletic ability,
-4596        and often have the largest athletics budgets
-4597        within the NCAA.
-4598
-4599        Other valid inputs are:
-4600        - "fcs": Football Championship Subdivision (FCS),
-4601            formerly known as D1-AA (read as "division one double A").
-4602            An FCS school is still in the 1st division of the NCAA,
-4603            making them eligible for the March Madness tournament,
-4604            but may not have the resources to compete at the FBS level
-4605            at this time. FCS schools are limited to 63 athletic scholarships
-4606            for football.
-4607        - "ii": NCAA Division II. Schools in this and D3 are not
-4608            eligible for the March Madness tournament,
-4609            and are limited to 36 athletic scholarships
-4610            for their football team.
-4611        - "iii": NCAA Division III. The largest single division within the
-4612            NCAA football pyramid.
-4613            D3 schools have the distinction of being part of
-4614            the only NCAA division that cannot give out scholarships solely
-4615            for athletic ability.
-4616
-4617    `api_key` (str, optional):
-4618        Semi-optional argument.
-4619        If `api_key` is null, this function will attempt to load a CFBD API key
-4620        from the python environment, or from a file on this computer.
-4621        If `api_key` is not null,
-4622        this function will automatically assume that the
-4623        inputted `api_key` is a valid CFBD API key.
-4624
-4625    `api_key_dir` (str, optional):
-4626        Optional argument.
-4627        If `api_key` is set to am empty string, this variable is ignored.
-4628        If `api_key_dir` is null, and `api_key` is null,
-4629        this function will try to find
-4630        a CFBD API key file in this user's home directory.
-4631        If `api_key_dir` is set to a string, and `api_key` is null,
-4632        this function will assume that `api_key_dir` is a directory,
-4633        and will try to find a CFBD API key file in that directory.
-4634
-4635    `return_as_dict` (bool, semi-optional):
-4636        Semi-optional argument.
-4637        If you want this function to return
-4638        the data as a dictionary (read: JSON object),
-4639        instead of a pandas `DataFrame` object,
-4640        set `return_as_dict` to `True`.
-4641    Usage
-4642    ----------
-4643    ```
-4644    import time
-4645
-4646    from cfbd_json_py.games import get_cfbd_weather_info
-4647
-4648
-4649    cfbd_key = "tigersAreAwesome"  # placeholder for your CFBD API Key.
-4650
-4651    if cfbd_key != "tigersAreAwesome":
-4652        print(
-4653            "Using the user's API key declared " +
-4654            "in this script for this example."
-4655        )
-4656
-4657        # Get weather data for the 2024 CFB season
-4658        print(
-4659            "Get weather data for the 2024 CFB season."
-4660        )
-4661        json_data = get_cfbd_weather_info(
-4662            season=2024,
-4663            api_key=cfbd_key
-4664        )
-4665        print(json_data)
-4666        time.sleep(5)
-4667
-4668        # Get weather data for the 2024 Rose Bowl (game ID #401551786).
-4669        print(
-4670            "Get weather data for the 2024 Rose Bowl (game ID #401551786)."
-4671        )
-4672        json_data = get_cfbd_weather_info(
-4673            game_id=401551786,
-4674            api_key=cfbd_key
-4675        )
-4676        print(json_data)
-4677        time.sleep(5)
-4678
-4679        # Get weather data for week 1 of the 2024 CFB season
-4680        print(
-4681            "Get weather data for week 1 of the 2024 CFB season."
-4682        )
-4683        json_data = get_cfbd_weather_info(
-4684            season=2024,
-4685            week=1,
-4686            api_key=cfbd_key
-4687        )
-4688        print(json_data)
-4689        time.sleep(5)
-4690
-4691        # Get weather data for postseason games of the 2023 CFB season.
-4692        print(
-4693            "Get weather data for postseason games of the 2023 CFB season."
-4694        )
-4695        json_data = get_cfbd_weather_info(
-4696            season=2023,
-4697            season_type="postseason",
-4698            api_key=cfbd_key
-4699        )
-4700        print(json_data)
-4701        time.sleep(5)
-4702
-4703        # Get weather data for postseason games of the 2023 CFB season.
-4704        print(
-4705            "Get weather data for postseason games of the 2023 CFB season."
-4706        )
-4707        json_data = get_cfbd_weather_info(
-4708            season=2023,
-4709            season_type="postseason",
-4710            api_key=cfbd_key
-4711        )
-4712        print(json_data)
-4713        time.sleep(5)
-4714
-4715        # Get weather data for Big 10 (B1G) games of the 2024 CFB season.
-4716        print(
-4717            "Get weather data for Big 10 (B1G) games of the 2024 CFB season."
-4718        )
-4719        json_data = get_cfbd_weather_info(
-4720            season=2024,
-4721            conference="B1G",
-4722            api_key=cfbd_key
-4723        )
-4724        print(json_data)
-4725        time.sleep(5)
-4726
-4727        # Get weather data for FCS games of the 2024 CFB season.
-4728        print(
-4729            "Get weather data for FCS games of the 2024 CFB season."
-4730        )
-4731        json_data = get_cfbd_weather_info(
-4732            season=2024,
-4733            ncaa_division="fcs",
-4734            api_key=cfbd_key
-4735        )
-4736        print(json_data)
-4737        time.sleep(5)
-4738
-4739        # Get weather data for University of Cincinnati games
-4740        # of the 2024 CFB season.
-4741        print(
-4742            "Get weather data for Big 10 (B1G) games of the 2024 CFB season."
-4743        )
-4744        json_data = get_cfbd_weather_info(
-4745            season=2024,
-4746            team_name="Cincinnati",
-4747            api_key=cfbd_key
-4748        )
-4749        print(json_data)
-4750        time.sleep(5)
-4751
-4752        # You can also tell this function to just return the API call
-4753        # as a Dictionary (read: JSON) object.
-4754        print(
-4755            "You can also tell this function to just return the API call " +
-4756            "as a Dictionary (read: JSON) object."
-4757        )
-4758        json_data = get_cfbd_weather_info(
-4759            api_key=cfbd_key,
-4760            season=2023,
-4761            return_as_dict=True
-4762        )
-4763        print(json_data)
-4764
-4765    else:
-4766        # Alternatively, if the CFBD API key exists in this python environment,
-4767        # or it's been set by cfbd_json_py.utls.set_cfbd_api_token(),
-4768        # you could just call these functions directly,
-4769        # without setting the API key in the script.
-4770        print(
-4771            "Using the user's API key supposedly loaded " +
-4772            "into this python environment for this example."
-4773        )
-4774
-4775        # Get weather data for the 2024 CFB season
-4776        print(
-4777            "Get weather data for the 2024 CFB season."
-4778        )
-4779        json_data = get_cfbd_weather_info(
-4780            season=2024
-4781        )
-4782        print(json_data)
-4783        time.sleep(5)
-4784
-4785        # Get weather data for the 2024 Rose Bowl (game ID #401551786).
-4786        print(
-4787            "Get weather data for the 2024 Rose Bowl (game ID #401551786)."
-4788        )
-4789        json_data = get_cfbd_weather_info(
-4790            game_id=401551786
-4791        )
-4792        print(json_data)
-4793        time.sleep(5)
-4794
-4795        # Get weather data for week 1 of the 2024 CFB season
-4796        print(
-4797            "Get weather data for week 1 of the 2024 CFB season."
-4798        )
-4799        json_data = get_cfbd_weather_info(
-4800            season=2024,
-4801            week=1
-4802        )
-4803        print(json_data)
-4804        time.sleep(5)
-4805
-4806        # Get weather data for postseason games of the 2023 CFB season.
-4807        print(
-4808            "Get weather data for postseason games of the 2023 CFB season."
-4809        )
-4810        json_data = get_cfbd_weather_info(
-4811            season=2023,
-4812            season_type="postseason"
-4813        )
-4814        print(json_data)
-4815        time.sleep(5)
-4816
-4817        # Get weather data for postseason games of the 2023 CFB season.
-4818        print(
-4819            "Get weather data for postseason games of the 2023 CFB season."
-4820        )
-4821        json_data = get_cfbd_weather_info(
-4822            season=2023,
-4823            season_type="postseason"
-4824        )
-4825        print(json_data)
-4826        time.sleep(5)
-4827
-4828        # Get weather data for Big 10 (B1G) games of the 2024 CFB season.
-4829        print(
-4830            "Get weather data for Big 10 (B1G) games of the 2024 CFB season."
-4831        )
-4832        json_data = get_cfbd_weather_info(
-4833            season=2024,
-4834            conference="B1G"
-4835        )
-4836        print(json_data)
-4837        time.sleep(5)
-4838
-4839        # Get weather data for FCS games of the 2024 CFB season.
-4840        print(
-4841            "Get weather data for FCS games of the 2024 CFB season."
-4842        )
-4843        json_data = get_cfbd_weather_info(
-4844            season=2024,
-4845            ncaa_division="fcs"
-4846        )
-4847        print(json_data)
-4848        time.sleep(5)
-4849
-4850        # Get weather data for University of Cincinnati games
-4851        # of the 2024 CFB season.
-4852        print(
-4853            "Get weather data for Big 10 (B1G) games of the 2024 CFB season."
-4854        )
-4855        json_data = get_cfbd_weather_info(
-4856            season=2024,
-4857            team_name="Cincinnati"
-4858        )
-4859        print(json_data)
-4860        time.sleep(5)
-4861
-4862        # You can also tell this function to just return the API call
-4863        # as a Dictionary (read: JSON) object.
-4864        print(
-4865            "You can also tell this function to just return the API call " +
-4866            "as a Dictionary (read: JSON) object."
-4867        )
-4868        json_data = get_cfbd_weather_info(
-4869            season=2023,
-4870            return_as_dict=True
-4871        )
-4872        print(json_data)
-4873
-4874    ```
-4875    Returns
-4876    ----------
-4877    A pandas `DataFrame` object with live weather data,
-4878    or (if `return_as_dict` is set to `True`)
-4879    a dictionary object with live weather data.
-4880
-4881    """
-4882
-4883    weather_df = pd.DataFrame()
-4884    url = "https://api.collegefootballdata.com/games/weather"
-4885
-4886    if api_key is not None:
-4887        real_api_key = api_key
-4888        del api_key
-4889    else:
-4890        real_api_key = get_cfbd_api_token(api_key_dir=api_key_dir)
-4891
-4892    if real_api_key == "tigersAreAwesome":
-4893        raise ValueError(
-4894            "You actually need to change `cfbd_key` to your CFBD API key."
-4895        )
-4896    elif "Bearer " in real_api_key:
-4897        pass
-4898    elif "Bearer" in real_api_key:
-4899        real_api_key = real_api_key.replace("Bearer", "Bearer ")
-4900    else:
-4901        real_api_key = "Bearer " + real_api_key
-4902
-4903    if (game_id is None) and (season is None):
-4904        raise ValueError(
-4905            "`game_id` and/or `season` must be set to valid, non-null values."
-4906        )
-4907    elif (game_id is not None) and (season is not None):
-4908        url += f"?gameId={game_id}&year={season}"
-4909    elif game_id is not None:
-4910        url += f"?gameId={game_id}"
-4911    elif season is not None:
-4912        url += f"?year={season}"
-4913
-4914    if (ncaa_division is not None) and (
-4915        ncaa_division.lower() == "fbs"
-4916        or ncaa_division.lower() == "fcs"
-4917        or ncaa_division.lower() == "ii"
-4918        or ncaa_division.lower() == "iii"
-4919    ):
-4920        ncaa_division = ncaa_division.lower()
-4921        url += f"&classification={ncaa_division}"
-4922    else:
-4923        raise ValueError(
-4924            "An invalid NCAA Division was inputted when calling this function."
-4925            + '\nValid inputs are:\n-"fbs"\n-"fcs"\n-"ii"\n-"iii"'
-4926            + f"\n\nYou entered:\n{ncaa_division}"
-4927        )
-4928
-4929    if week is not None:
-4930        url += f"&week={week}"
-4931
-4932    if (
-4933        season_type == "regular" or
-4934        season_type == "postseason" or
-4935        season_type == "both"
-4936    ):
-4937        url += f"&seasonType={season_type}"
-4938    elif season_type is not None:
-4939        raise ValueError(
-4940            '`season_type` must be set to either "regular", '
-4941            + '"postseason", or "both" if you want to specify '
-4942            + "a part of the season."
-4943        )
-4944
-4945    if team_name is not None:
-4946        url += f"&team={team_name}"
-4947
-4948    if conference is not None:
-4949        url += f"&conference={conference}"
-4950
-4951    headers = {
-4952        "Authorization": f"{real_api_key}",
-4953        "accept": "application/json"
-4954    }
-4955
-4956    response = requests.get(url, headers=headers)
-4957
-4958    if response.status_code == 200:
-4959        pass
-4960    elif response.status_code == 401:
-4961        raise ConnectionRefusedError(
-4962            "Could not connect. The connection was refused.\n" +
-4963            "HTTP Status Code 401."
-4964        )
-4965    else:
-4966        raise ConnectionError(
-4967            f"Could not connect.\nHTTP Status code {response.status_code}"
-4968        )
-4969
-4970    json_data = response.json()
-4971
-4972    if return_as_dict is True:
-4973        return json_data
-4974
-4975    weather_df = pd.json_normalize(json_data)
-4976    # print(weather_df.columns)
-4977
-4978    [
-4979        "weatherConditionCode",
-4980        "weatherCondition",
-4981    ]
-4982    if len(weather_df) > 0:
-4983        weather_df.rename(
-4984            columns={
-4985                "id": "game_id",
-4986                "startTime": "start_datetime",
-4987                "seasonType": "season_type",
-4988                "gameIndoors": "is_game_indoors",
-4989                "homeTeam": "home_team_name",
-4990                "homeConference": "home_team_conference",
-4991                "awayTeam": "away_team_name",
-4992                "awayConference": "away_team_conference",
-4993                "venueId": "venue_id",
-4994                "venue": "venue_name",
-4995                "windDirection": "wind_direction",
-4996                "windSpeed": "wind_speed",
-4997                "weatherConditionCode": "weather_condition_code",
-4998                "weatherCondition": "weather_condition",
-4999            },
-5000            inplace=True,
-5001        )
-5002
-5003    return weather_df
+                
3026def get_cfbd_weather_info(
+3027    # game_id: int = None,
+3028    season: int = None,
+3029    # `game_id` and/or `season` must be not null for this function to work.
+3030    week: int = None,
+3031    season_type: str = "both",  # "regular", "postseason", or "both"
+3032    conference: str = None,
+3033    team_name: str = None,
+3034    ncaa_division: str = "fbs",
+3035    api_key: str = None,
+3036    api_key_dir: str = None,
+3037    return_as_dict: bool = False,
+3038):
+3039    """
+3040    YOU MUST BE SUBSCRIBED TO THE CFBD PATREON FOR THIS FUNCTION TO WORK!
+3041    To view the CFBD Patreon, visit https://www.patreon.com/collegefootballdata
+3042
+3043    Parameters
+3044    ----------
+3045    Retrieves live scoreboard data from the CFBD API,
+3046    assuming the API key is an API key from a Patreon supporter.
+3047
+3048    Parameters
+3049    ----------
+3050
+3051    `game_id` (int, mandatory):
+3052        DEPRECATED FROM V1.
+3053        Specifies the game you want weather data from.
+3054        This or `season` must be set to a valid non-null value.
+3055
+3056    `season` (int, mandatory):
+3057        Mandatory requirement.
+3058        Specifies the season you want weather data from.
+3059        This or `season` must be set to a valid non-null value.
+3060
+3061    `week` (int, optional):
+3062        Optional argument.
+3063        If `week` is set to an integer, this function will attempt
+3064        to load weather data from games in that season, and in that week.
+3065
+3066    `season_type` (str, semi-optional):
+3067        Semi-optional argument.
+3068        By default, this will be set to "both", for the CFB regular season.
+3069        If you want postseason betting data, set `season_type` to "postseason".
+3070        If `season_type` is set to anything but "regular" or "postseason",
+3071        a `ValueError()` will be raised.
+3072
+3073    `conference` (str, optional):
+3074        Optional argument.
+3075        If you only want weather data from games
+3076        involving teams a specific conference,
+3077        set `conference` to the abbreviation
+3078        of the conference you want weather data from.
+3079
+3080    `team_name` (str, optional):
+3081        Optional argument.
+3082        If you only want weather data for a team,
+3083        regardless if they are the home/away team,
+3084        set `team` to the name of the team
+3085        you want weather data from.
+3086
+3087    `ncaa_division` (str, semi-optional):
+3088        Semi-optional argument.
+3089        By default, `ncaa_division` will be set to "fbs",
+3090        short for the Football Bowl Subdivision (FBS),
+3091        formerly known as D1-A (read as "division one single A"),
+3092        the highest level in the NCAA football pyramid,
+3093        where teams can scholarship up to 85 players
+3094        on their football team solely for athletic ability,
+3095        and often have the largest athletics budgets
+3096        within the NCAA.
+3097
+3098        Other valid inputs are:
+3099        - "fcs": Football Championship Subdivision (FCS),
+3100            formerly known as D1-AA (read as "division one double A").
+3101            An FCS school is still in the 1st division of the NCAA,
+3102            making them eligible for the March Madness tournament,
+3103            but may not have the resources to compete at the FBS level
+3104            at this time. FCS schools are limited to 63 athletic scholarships
+3105            for football.
+3106        - "ii": NCAA Division II. Schools in this and D3 are not
+3107            eligible for the March Madness tournament,
+3108            and are limited to 36 athletic scholarships
+3109            for their football team.
+3110        - "iii": NCAA Division III. The largest single division within the
+3111            NCAA football pyramid.
+3112            D3 schools have the distinction of being part of
+3113            the only NCAA division that cannot give out scholarships solely
+3114            for athletic ability.
+3115
+3116    `api_key` (str, optional):
+3117        Semi-optional argument.
+3118        If `api_key` is null, this function will attempt to load a CFBD API key
+3119        from the python environment, or from a file on this computer.
+3120        If `api_key` is not null,
+3121        this function will automatically assume that the
+3122        inputted `api_key` is a valid CFBD API key.
+3123
+3124    `api_key_dir` (str, optional):
+3125        Optional argument.
+3126        If `api_key` is set to am empty string, this variable is ignored.
+3127        If `api_key_dir` is null, and `api_key` is null,
+3128        this function will try to find
+3129        a CFBD API key file in this user's home directory.
+3130        If `api_key_dir` is set to a string, and `api_key` is null,
+3131        this function will assume that `api_key_dir` is a directory,
+3132        and will try to find a CFBD API key file in that directory.
+3133
+3134    `return_as_dict` (bool, semi-optional):
+3135        Semi-optional argument.
+3136        If you want this function to return
+3137        the data as a dictionary (read: JSON object),
+3138        instead of a pandas `DataFrame` object,
+3139        set `return_as_dict` to `True`.
+3140    Usage
+3141    ----------
+3142    ```
+3143    import time
+3144
+3145    from cfbd_json_py.games import get_cfbd_weather_info
+3146
+3147
+3148    cfbd_key = "tigersAreAwesome"  # placeholder for your CFBD API Key.
+3149
+3150    if cfbd_key != "tigersAreAwesome":
+3151        print(
+3152            "Using the user's API key declared " +
+3153            "in this script for this example."
+3154        )
+3155
+3156        # Get weather data for the 2024 CFB season
+3157        print(
+3158            "Get weather data for the 2024 CFB season."
+3159        )
+3160        json_data = get_cfbd_weather_info(
+3161            season=2024,
+3162            api_key=cfbd_key
+3163        )
+3164        print(json_data)
+3165        time.sleep(5)
+3166
+3167        # Get weather data for the 2024 Rose Bowl (game ID #401551786).
+3168        print(
+3169            "Get weather data for the 2024 Rose Bowl (game ID #401551786)."
+3170        )
+3171        json_data = get_cfbd_weather_info(
+3172            game_id=401551786,
+3173            api_key=cfbd_key
+3174        )
+3175        print(json_data)
+3176        time.sleep(5)
+3177
+3178        # Get weather data for week 1 of the 2024 CFB season
+3179        print(
+3180            "Get weather data for week 1 of the 2024 CFB season."
+3181        )
+3182        json_data = get_cfbd_weather_info(
+3183            season=2024,
+3184            week=1,
+3185            api_key=cfbd_key
+3186        )
+3187        print(json_data)
+3188        time.sleep(5)
+3189
+3190        # Get weather data for postseason games of the 2023 CFB season.
+3191        print(
+3192            "Get weather data for postseason games of the 2023 CFB season."
+3193        )
+3194        json_data = get_cfbd_weather_info(
+3195            season=2023,
+3196            season_type="postseason",
+3197            api_key=cfbd_key
+3198        )
+3199        print(json_data)
+3200        time.sleep(5)
+3201
+3202        # Get weather data for postseason games of the 2023 CFB season.
+3203        print(
+3204            "Get weather data for postseason games of the 2023 CFB season."
+3205        )
+3206        json_data = get_cfbd_weather_info(
+3207            season=2023,
+3208            season_type="postseason",
+3209            api_key=cfbd_key
+3210        )
+3211        print(json_data)
+3212        time.sleep(5)
+3213
+3214        # Get weather data for Big 10 (B1G) games of the 2024 CFB season.
+3215        print(
+3216            "Get weather data for Big 10 (B1G) games of the 2024 CFB season."
+3217        )
+3218        json_data = get_cfbd_weather_info(
+3219            season=2024,
+3220            conference="B1G",
+3221            api_key=cfbd_key
+3222        )
+3223        print(json_data)
+3224        time.sleep(5)
+3225
+3226        # Get weather data for FCS games of the 2024 CFB season.
+3227        print(
+3228            "Get weather data for FCS games of the 2024 CFB season."
+3229        )
+3230        json_data = get_cfbd_weather_info(
+3231            season=2024,
+3232            ncaa_division="fcs",
+3233            api_key=cfbd_key
+3234        )
+3235        print(json_data)
+3236        time.sleep(5)
+3237
+3238        # Get weather data for University of Cincinnati games
+3239        # of the 2024 CFB season.
+3240        print(
+3241            "Get weather data for Big 10 (B1G) games of the 2024 CFB season."
+3242        )
+3243        json_data = get_cfbd_weather_info(
+3244            season=2024,
+3245            team_name="Cincinnati",
+3246            api_key=cfbd_key
+3247        )
+3248        print(json_data)
+3249        time.sleep(5)
+3250
+3251        # You can also tell this function to just return the API call
+3252        # as a Dictionary (read: JSON) object.
+3253        print(
+3254            "You can also tell this function to just return the API call " +
+3255            "as a Dictionary (read: JSON) object."
+3256        )
+3257        json_data = get_cfbd_weather_info(
+3258            api_key=cfbd_key,
+3259            season=2023,
+3260            return_as_dict=True
+3261        )
+3262        print(json_data)
+3263
+3264    else:
+3265        # Alternatively, if the CFBD API key exists in this python environment,
+3266        # or it's been set by cfbd_json_py.utls.set_cfbd_api_token(),
+3267        # you could just call these functions directly,
+3268        # without setting the API key in the script.
+3269        print(
+3270            "Using the user's API key supposedly loaded " +
+3271            "into this python environment for this example."
+3272        )
+3273
+3274        # Get weather data for the 2024 CFB season
+3275        print(
+3276            "Get weather data for the 2024 CFB season."
+3277        )
+3278        json_data = get_cfbd_weather_info(
+3279            season=2024
+3280        )
+3281        print(json_data)
+3282        time.sleep(5)
+3283
+3284        # Get weather data for the 2024 Rose Bowl (game ID #401551786).
+3285        print(
+3286            "Get weather data for the 2024 Rose Bowl (game ID #401551786)."
+3287        )
+3288        json_data = get_cfbd_weather_info(
+3289            game_id=401551786
+3290        )
+3291        print(json_data)
+3292        time.sleep(5)
+3293
+3294        # Get weather data for week 1 of the 2024 CFB season
+3295        print(
+3296            "Get weather data for week 1 of the 2024 CFB season."
+3297        )
+3298        json_data = get_cfbd_weather_info(
+3299            season=2024,
+3300            week=1
+3301        )
+3302        print(json_data)
+3303        time.sleep(5)
+3304
+3305        # Get weather data for postseason games of the 2023 CFB season.
+3306        print(
+3307            "Get weather data for postseason games of the 2023 CFB season."
+3308        )
+3309        json_data = get_cfbd_weather_info(
+3310            season=2023,
+3311            season_type="postseason"
+3312        )
+3313        print(json_data)
+3314        time.sleep(5)
+3315
+3316        # Get weather data for postseason games of the 2023 CFB season.
+3317        print(
+3318            "Get weather data for postseason games of the 2023 CFB season."
+3319        )
+3320        json_data = get_cfbd_weather_info(
+3321            season=2023,
+3322            season_type="postseason"
+3323        )
+3324        print(json_data)
+3325        time.sleep(5)
+3326
+3327        # Get weather data for Big 10 (B1G) games of the 2024 CFB season.
+3328        print(
+3329            "Get weather data for Big 10 (B1G) games of the 2024 CFB season."
+3330        )
+3331        json_data = get_cfbd_weather_info(
+3332            season=2024,
+3333            conference="B1G"
+3334        )
+3335        print(json_data)
+3336        time.sleep(5)
+3337
+3338        # Get weather data for FCS games of the 2024 CFB season.
+3339        print(
+3340            "Get weather data for FCS games of the 2024 CFB season."
+3341        )
+3342        json_data = get_cfbd_weather_info(
+3343            season=2024,
+3344            ncaa_division="fcs"
+3345        )
+3346        print(json_data)
+3347        time.sleep(5)
+3348
+3349        # Get weather data for University of Cincinnati games
+3350        # of the 2024 CFB season.
+3351        print(
+3352            "Get weather data for Big 10 (B1G) games of the 2024 CFB season."
+3353        )
+3354        json_data = get_cfbd_weather_info(
+3355            season=2024,
+3356            team_name="Cincinnati"
+3357        )
+3358        print(json_data)
+3359        time.sleep(5)
+3360
+3361        # You can also tell this function to just return the API call
+3362        # as a Dictionary (read: JSON) object.
+3363        print(
+3364            "You can also tell this function to just return the API call " +
+3365            "as a Dictionary (read: JSON) object."
+3366        )
+3367        json_data = get_cfbd_weather_info(
+3368            season=2023,
+3369            return_as_dict=True
+3370        )
+3371        print(json_data)
+3372
+3373    ```
+3374    Returns
+3375    ----------
+3376    A pandas `DataFrame` object with live weather data,
+3377    or (if `return_as_dict` is set to `True`)
+3378    a dictionary object with live weather data.
+3379
+3380    """
+3381
+3382    weather_df = pd.DataFrame()
+3383    url = "https://api.collegefootballdata.com/games/weather"
+3384
+3385    if api_key is not None:
+3386        real_api_key = api_key
+3387        del api_key
+3388    else:
+3389        real_api_key = get_cfbd_api_token(api_key_dir=api_key_dir)
+3390
+3391    if real_api_key == "tigersAreAwesome":
+3392        raise ValueError(
+3393            "You actually need to change `cfbd_key` to your CFBD API key."
+3394        )
+3395    elif "Bearer " in real_api_key:
+3396        pass
+3397    elif "Bearer" in real_api_key:
+3398        real_api_key = real_api_key.replace("Bearer", "Bearer ")
+3399    else:
+3400        real_api_key = "Bearer " + real_api_key
+3401
+3402    # if (game_id is None) and (season is None):
+3403    #     raise ValueError(
+3404    #         "`game_id` and/or `season` must be set to " +
+3405    #         "valid, non-null values."
+3406    #     )
+3407    # elif (game_id is not None) and (season is not None):
+3408    #     url += f"?gameId={game_id}&year={season}"
+3409    # elif game_id is not None:
+3410    #     url += f"?gameId={game_id}"
+3411    # elif season is not None:
+3412    #     url += f"?year={season}"
+3413    if season is None:
+3414        raise ValueError(
+3415            "`season` must be set to a valid, non-null value."
+3416        )
+3417    elif season is not None:
+3418        url += f"?year={season}"
+3419
+3420    if (ncaa_division is not None) and (
+3421        ncaa_division.lower() == "fbs"
+3422        or ncaa_division.lower() == "fcs"
+3423        or ncaa_division.lower() == "ii"
+3424        or ncaa_division.lower() == "iii"
+3425    ):
+3426        ncaa_division = ncaa_division.lower()
+3427        url += f"&classification={ncaa_division}"
+3428    else:
+3429        raise ValueError(
+3430            "An invalid NCAA Division was inputted when calling this function."
+3431            + '\nValid inputs are:\n-"fbs"\n-"fcs"\n-"ii"\n-"iii"'
+3432            + f"\n\nYou entered:\n{ncaa_division}"
+3433        )
+3434
+3435    if week is not None:
+3436        url += f"&week={week}"
+3437
+3438    if (
+3439        season_type == "regular" or
+3440        season_type == "postseason" or
+3441        season_type == "both"
+3442    ):
+3443        url += f"&seasonType={season_type}"
+3444    elif season_type is not None:
+3445        raise ValueError(
+3446            '`season_type` must be set to either "regular", '
+3447            + '"postseason", or "both" if you want to specify '
+3448            + "a part of the season."
+3449        )
+3450
+3451    if team_name is not None:
+3452        url += f"&team={team_name}"
+3453
+3454    if conference is not None:
+3455        url += f"&conference={conference}"
+3456
+3457    headers = {
+3458        "Authorization": f"{real_api_key}",
+3459        "accept": "application/json"
+3460    }
+3461
+3462    response = requests.get(url, headers=headers)
+3463
+3464    if response.status_code == 200:
+3465        pass
+3466    elif response.status_code == 401:
+3467        raise ConnectionRefusedError(
+3468            "Could not connect. The connection was refused.\n" +
+3469            "HTTP Status Code 401."
+3470        )
+3471    else:
+3472        raise ConnectionError(
+3473            f"Could not connect.\nHTTP Status code {response.status_code}"
+3474        )
+3475
+3476    json_data = response.json()
+3477
+3478    if return_as_dict is True:
+3479        return json_data
+3480
+3481    weather_df = pd.json_normalize(json_data)
+3482    # print(weather_df.columns)
+3483
+3484    [
+3485        "weatherConditionCode",
+3486        "weatherCondition",
+3487    ]
+3488    if len(weather_df) > 0:
+3489        weather_df.rename(
+3490            columns={
+3491                "id": "game_id",
+3492                "startTime": "start_datetime",
+3493                "seasonType": "season_type",
+3494                "gameIndoors": "is_game_indoors",
+3495                "homeTeam": "home_team_name",
+3496                "homeConference": "home_team_conference",
+3497                "awayTeam": "away_team_name",
+3498                "awayConference": "away_team_conference",
+3499                "venueId": "venue_id",
+3500                "venue": "venue_name",
+3501                "windDirection": "wind_direction",
+3502                "windSpeed": "wind_speed",
+3503                "weatherConditionCode": "weather_condition_code",
+3504                "weatherCondition": "weather_condition",
+3505            },
+3506            inplace=True,
+3507        )
+3508
+3509    return weather_df
 
@@ -13405,7 +10414,7 @@

Parameters

Parameters

game_id (int, mandatory): - Mandatory requirement. + DEPRECATED FROM V1. Specifies the game you want weather data from. This or season must be set to a valid non-null value.

@@ -13923,4 +10932,4 @@

Returns

- \ No newline at end of file + diff --git a/docs/cfbd_json_py/metrics.html b/docs/cfbd_json_py/metrics.html index 586bd3b..3877cb6 100644 --- a/docs/cfbd_json_py/metrics.html +++ b/docs/cfbd_json_py/metrics.html @@ -1697,7 +1697,7 @@

197 # but we have to convey to the person calling this 198 # function that setting `down = 5` 199 # is not something they should be doing. - 200 logging.warn( + 200 logging.warning( 201 'There is a very limited number of "5th down" situations ' 202 + "in American Football history. " 203 + "Do not expect anything back when calling this function, " @@ -4533,7 +4533,7 @@

198 # but we have to convey to the person calling this 199 # function that setting `down = 5` 200 # is not something they should be doing. -201 logging.warn( +201 logging.warning( 202 'There is a very limited number of "5th down" situations ' 203 + "in American Football history. " 204 + "Do not expect anything back when calling this function, " @@ -9365,4 +9365,4 @@

Returns

- \ No newline at end of file + diff --git a/docs/cfbd_json_py/players.html b/docs/cfbd_json_py/players.html index b2d83aa..bcc936e 100644 --- a/docs/cfbd_json_py/players.html +++ b/docs/cfbd_json_py/players.html @@ -1498,7 +1498,7 @@

10 11import pandas as pd 12import requests - 13from tqdm import tqdm + 13# from tqdm import tqdm 14 15# from cfbd_json_py.games import get_cfbd_player_game_stats 16from cfbd_json_py.utls import get_cfbd_api_token @@ -2270,987 +2270,987 @@

782 783 if player_id is not None: 784 url += f"&playerId={player_id}" - 785 # print() - 786 if exclude_garbage_time is not None: - 787 url += f"&excludeGarbageTime={gt_str}" - 788 - 789 headers = { - 790 "Authorization": f"{real_api_key}", - 791 "accept": "application/json" - 792 } - 793 - 794 response = requests.get(url, headers=headers) - 795 - 796 if response.status_code == 200: - 797 pass - 798 elif response.status_code == 401: - 799 raise ConnectionRefusedError( - 800 "Could not connect. The connection was refused." + - 801 "\nHTTP Status Code 401." - 802 ) - 803 else: - 804 raise ConnectionError( - 805 f"Could not connect.\nHTTP Status code {response.status_code}" - 806 ) - 807 - 808 json_data = response.json() - 809 - 810 if return_as_dict is True: - 811 return json_data - 812 - 813 players_df = pd.json_normalize(json_data) - 814 players_df.rename( - 815 columns={ - 816 "id": "player_id", - 817 "name": "player_name", - 818 "position": "position_abv", - 819 "team": "team_name", - 820 "conference": "conference_name", - 821 "usage.overall": "usage_overall", - 822 "usage.pass": "usage_pass", - 823 "usage.rush": "usage_rush", - 824 "usage.firstDown": "usage_first_down", - 825 "usage.secondDown": "usage_second_down", - 826 "usage.thirdDown": "usage_third_down", - 827 "usage.standardDowns": "usage_standard_downs", - 828 "usage.passingDowns": "usage_passing_downs", - 829 }, - 830 inplace=True, - 831 ) - 832 return players_df + 785 if exclude_garbage_time is not None: + 786 url += f"&excludeGarbageTime={gt_str}" + 787 + 788 headers = { + 789 "Authorization": f"{real_api_key}", + 790 "accept": "application/json" + 791 } + 792 + 793 response = requests.get(url, headers=headers) + 794 + 795 if response.status_code == 200: + 796 pass + 797 elif response.status_code == 401: + 798 raise ConnectionRefusedError( + 799 "Could not connect. The connection was refused." + + 800 "\nHTTP Status Code 401." + 801 ) + 802 else: + 803 raise ConnectionError( + 804 f"Could not connect.\nHTTP Status code {response.status_code}" + 805 ) + 806 + 807 json_data = response.json() + 808 + 809 if return_as_dict is True: + 810 return json_data + 811 + 812 players_df = pd.json_normalize(json_data) + 813 players_df.rename( + 814 columns={ + 815 "id": "player_id", + 816 "name": "player_name", + 817 "position": "position_abv", + 818 "team": "team_name", + 819 "conference": "conference_name", + 820 "usage.overall": "usage_overall", + 821 "usage.pass": "usage_pass", + 822 "usage.rush": "usage_rush", + 823 "usage.firstDown": "usage_first_down", + 824 "usage.secondDown": "usage_second_down", + 825 "usage.thirdDown": "usage_third_down", + 826 "usage.standardDowns": "usage_standard_downs", + 827 "usage.passingDowns": "usage_passing_downs", + 828 }, + 829 inplace=True, + 830 ) + 831 return players_df + 832 833 - 834 - 835def get_cfbd_returning_production( - 836 api_key: str = None, - 837 api_key_dir: str = None, - 838 season: int = None, - 839 team: str = None, - 840 # `season` or `team` must be specified. - 841 conference: str = None, - 842 return_as_dict: bool = False, - 843): - 844 """ - 845 Get data from the CFBD API - 846 on how much returning production a team has going into a CFB season. - 847 - 848 Parameters - 849 ---------- - 850 - 851 `api_key` (str, optional): - 852 Semi-optional argument. - 853 If `api_key` is null, this function will attempt to load a CFBD API key - 854 from the python environment, or from a file on this computer. - 855 If `api_key` is not null, - 856 this function will automatically assume that the - 857 inputted `api_key` is a valid CFBD API key. - 858 - 859 `api_key_dir` (str, optional): - 860 Optional argument. - 861 If `api_key` is set to am empty string, this variable is ignored. - 862 If `api_key_dir` is null, and `api_key` is null, - 863 this function will try to find - 864 a CFBD API key file in this user's home directory. - 865 If `api_key_dir` is set to a string, and `api_key` is null, - 866 this function will assume that `api_key_dir` is a directory, - 867 and will try to find a CFBD API key file in that directory. - 868 - 869 `season` (int, optional): - 870 Semi-optional argument. - 871 Specifies the season you want team PPA data from. - 872 You MUST set `season` or `team` to a non-null value for - 873 this function to work. If you don't, a `ValueError()` - 874 will be raised. - 875 - 876 `team` (str, optional): - 877 Semi-optional argument. - 878 If you only want team PPA data for a specific team, - 879 set `team` to the name of the team you want team PPA data from. - 880 You MUST set `season` or `team` to a non-null value for - 881 this function to work. If you don't, a `ValueError()` - 882 will be raised. - 883 - 884 `conference` (str, optional): - 885 Optional argument. - 886 If you only want team PPA data from games - 887 involving teams from a specific conference, - 888 set `conference` to the abbreviation - 889 of the conference you want team PPA data from. - 890 For a list of conferences, - 891 use the `cfbd_json_py.conferences.get_cfbd_conference_info()` - 892 function. - 893 - 894 `return_as_dict` (bool, semi-optional): - 895 Semi-optional argument. - 896 If you want this function to return - 897 the data as a dictionary (read: JSON object), - 898 instead of a pandas `DataFrame` object, - 899 set `return_as_dict` to `True`. - 900 - 901 Usage - 902 ---------- - 903 ``` - 904 import time - 905 - 906 from cfbd_json_py.players import get_cfbd_returning_production + 834def get_cfbd_returning_production( + 835 api_key: str = None, + 836 api_key_dir: str = None, + 837 season: int = None, + 838 team: str = None, + 839 # `season` or `team` must be specified. + 840 conference: str = None, + 841 return_as_dict: bool = False, + 842): + 843 """ + 844 Get data from the CFBD API + 845 on how much returning production a team has going into a CFB season. + 846 + 847 Parameters + 848 ---------- + 849 + 850 `api_key` (str, optional): + 851 Semi-optional argument. + 852 If `api_key` is null, this function will attempt to load a CFBD API key + 853 from the python environment, or from a file on this computer. + 854 If `api_key` is not null, + 855 this function will automatically assume that the + 856 inputted `api_key` is a valid CFBD API key. + 857 + 858 `api_key_dir` (str, optional): + 859 Optional argument. + 860 If `api_key` is set to am empty string, this variable is ignored. + 861 If `api_key_dir` is null, and `api_key` is null, + 862 this function will try to find + 863 a CFBD API key file in this user's home directory. + 864 If `api_key_dir` is set to a string, and `api_key` is null, + 865 this function will assume that `api_key_dir` is a directory, + 866 and will try to find a CFBD API key file in that directory. + 867 + 868 `season` (int, optional): + 869 Semi-optional argument. + 870 Specifies the season you want team PPA data from. + 871 You MUST set `season` or `team` to a non-null value for + 872 this function to work. If you don't, a `ValueError()` + 873 will be raised. + 874 + 875 `team` (str, optional): + 876 Semi-optional argument. + 877 If you only want team PPA data for a specific team, + 878 set `team` to the name of the team you want team PPA data from. + 879 You MUST set `season` or `team` to a non-null value for + 880 this function to work. If you don't, a `ValueError()` + 881 will be raised. + 882 + 883 `conference` (str, optional): + 884 Optional argument. + 885 If you only want team PPA data from games + 886 involving teams from a specific conference, + 887 set `conference` to the abbreviation + 888 of the conference you want team PPA data from. + 889 For a list of conferences, + 890 use the `cfbd_json_py.conferences.get_cfbd_conference_info()` + 891 function. + 892 + 893 `return_as_dict` (bool, semi-optional): + 894 Semi-optional argument. + 895 If you want this function to return + 896 the data as a dictionary (read: JSON object), + 897 instead of a pandas `DataFrame` object, + 898 set `return_as_dict` to `True`. + 899 + 900 Usage + 901 ---------- + 902 ``` + 903 import time + 904 + 905 from cfbd_json_py.players import get_cfbd_returning_production + 906 907 - 908 - 909 cfbd_key = "tigersAreAwesome" # placeholder for your CFBD API Key. - 910 - 911 if cfbd_key != "tigersAreAwesome": - 912 print( - 913 "Using the user's API key declared in this script " + - 914 "for this example." - 915 ) - 916 - 917 # Get returning production - 918 # for teams who competed in the 2020 CFB season. - 919 print( - 920 "Get returning production for teams " + - 921 "who competed in the 2020 CFB season." - 922 ) - 923 json_data = get_cfbd_returning_production( - 924 api_key=cfbd_key, - 925 season=2020 - 926 ) - 927 print(json_data) - 928 time.sleep(5) - 929 - 930 # Get historical returning production - 931 # for the Ohio Bobcats Football Team. - 932 print( - 933 "Get historical returning production " + - 934 "for the Ohio Bobcats Football Team." - 935 ) - 936 json_data = get_cfbd_returning_production( - 937 api_key=cfbd_key, - 938 team="Ohio" - 939 ) - 940 print(json_data) - 941 time.sleep(5) - 942 - 943 # Get returning production for the 2019 LSU Tigers. - 944 print("Get returning production for the 2019 LSU Tigers.") - 945 json_data = get_cfbd_returning_production( - 946 api_key=cfbd_key, - 947 season=2019, - 948 team="LSU" - 949 ) - 950 print(json_data) - 951 time.sleep(5) - 952 - 953 # Get returning production for Maryland, - 954 # for seasons where Maryland is a member - 955 # of the Big 10 (B1G) Conference. - 956 print( - 957 "Get returning production for Maryland, " + - 958 "for seasons where Maryland is a member " + - 959 "of the Big 10 (B1G) Conference." - 960 ) - 961 json_data = get_cfbd_returning_production( - 962 api_key=cfbd_key, - 963 team="Maryland", - 964 conference="B1G" - 965 ) - 966 print(json_data) - 967 time.sleep(5) - 968 - 969 # You can also tell this function to just return the API call as - 970 # a Dictionary (read: JSON) object. - 971 print( - 972 "You can also tell this function to just return the API call " + - 973 "as a Dictionary (read: JSON) object." - 974 ) - 975 json_data = get_cfbd_returning_production( - 976 api_key=cfbd_key, - 977 season=2020, - 978 team="LSU", - 979 return_as_dict=True - 980 ) - 981 print(json_data) - 982 - 983 else: - 984 # Alternatively, if the CFBD API key exists in this python environment, - 985 # or it's been set by cfbd_json_py.utls.set_cfbd_api_token(), - 986 # you could just call these functions directly, - 987 # without setting the API key in the script. - 988 print( - 989 "Using the user's API key supposedly loaded " + - 990 "into this python environment for this example." - 991 ) - 992 - 993 # Get returning production - 994 # for teams who competed in the 2020 CFB season. - 995 print( - 996 "Get returning production for teams " + - 997 "who competed in the 2020 CFB season." - 998 ) - 999 json_data = get_cfbd_returning_production( -1000 season=2020 -1001 ) -1002 print(json_data) -1003 time.sleep(5) -1004 -1005 # Get historical returning production -1006 # for the Ohio Bobcats Football Team. -1007 print( -1008 "Get historical returning production " + -1009 "for the Ohio Bobcats Football Team." -1010 ) -1011 json_data = get_cfbd_returning_production( -1012 team="Ohio" -1013 ) -1014 print(json_data) -1015 time.sleep(5) -1016 -1017 # Get returning production for the 2019 LSU Tigers. -1018 print("Get returning production for the 2019 LSU Tigers.") -1019 json_data = get_cfbd_returning_production( -1020 season=2019, -1021 team="LSU" -1022 ) -1023 print(json_data) -1024 time.sleep(5) -1025 -1026 # Get returning production for Maryland, -1027 # for seasons where Maryland is a member -1028 # of the Big 10 (B1G) Conference. -1029 print( -1030 "Get returning production for Maryland, " + -1031 "for seasons where Maryland is a member " + -1032 "of the Big 10 (B1G) Conference." -1033 ) -1034 json_data = get_cfbd_returning_production( -1035 team="Maryland", -1036 conference="B1G" -1037 ) -1038 print(json_data) -1039 time.sleep(5) -1040 -1041 # You can also tell this function to just return the API call as -1042 # a Dictionary (read: JSON) object. -1043 print( -1044 "You can also tell this function to just return the API call " + -1045 "as a Dictionary (read: JSON) object." -1046 ) -1047 json_data = get_cfbd_returning_production( -1048 season=2020, -1049 team="LSU", -1050 return_as_dict=True -1051 ) -1052 print(json_data) + 908 cfbd_key = "tigersAreAwesome" # placeholder for your CFBD API Key. + 909 + 910 if cfbd_key != "tigersAreAwesome": + 911 print( + 912 "Using the user's API key declared in this script " + + 913 "for this example." + 914 ) + 915 + 916 # Get returning production + 917 # for teams who competed in the 2020 CFB season. + 918 print( + 919 "Get returning production for teams " + + 920 "who competed in the 2020 CFB season." + 921 ) + 922 json_data = get_cfbd_returning_production( + 923 api_key=cfbd_key, + 924 season=2020 + 925 ) + 926 print(json_data) + 927 time.sleep(5) + 928 + 929 # Get historical returning production + 930 # for the Ohio Bobcats Football Team. + 931 print( + 932 "Get historical returning production " + + 933 "for the Ohio Bobcats Football Team." + 934 ) + 935 json_data = get_cfbd_returning_production( + 936 api_key=cfbd_key, + 937 team="Ohio" + 938 ) + 939 print(json_data) + 940 time.sleep(5) + 941 + 942 # Get returning production for the 2019 LSU Tigers. + 943 print("Get returning production for the 2019 LSU Tigers.") + 944 json_data = get_cfbd_returning_production( + 945 api_key=cfbd_key, + 946 season=2019, + 947 team="LSU" + 948 ) + 949 print(json_data) + 950 time.sleep(5) + 951 + 952 # Get returning production for Maryland, + 953 # for seasons where Maryland is a member + 954 # of the Big 10 (B1G) Conference. + 955 print( + 956 "Get returning production for Maryland, " + + 957 "for seasons where Maryland is a member " + + 958 "of the Big 10 (B1G) Conference." + 959 ) + 960 json_data = get_cfbd_returning_production( + 961 api_key=cfbd_key, + 962 team="Maryland", + 963 conference="B1G" + 964 ) + 965 print(json_data) + 966 time.sleep(5) + 967 + 968 # You can also tell this function to just return the API call as + 969 # a Dictionary (read: JSON) object. + 970 print( + 971 "You can also tell this function to just return the API call " + + 972 "as a Dictionary (read: JSON) object." + 973 ) + 974 json_data = get_cfbd_returning_production( + 975 api_key=cfbd_key, + 976 season=2020, + 977 team="LSU", + 978 return_as_dict=True + 979 ) + 980 print(json_data) + 981 + 982 else: + 983 # Alternatively, if the CFBD API key exists in this python environment, + 984 # or it's been set by cfbd_json_py.utls.set_cfbd_api_token(), + 985 # you could just call these functions directly, + 986 # without setting the API key in the script. + 987 print( + 988 "Using the user's API key supposedly loaded " + + 989 "into this python environment for this example." + 990 ) + 991 + 992 # Get returning production + 993 # for teams who competed in the 2020 CFB season. + 994 print( + 995 "Get returning production for teams " + + 996 "who competed in the 2020 CFB season." + 997 ) + 998 json_data = get_cfbd_returning_production( + 999 season=2020 +1000 ) +1001 print(json_data) +1002 time.sleep(5) +1003 +1004 # Get historical returning production +1005 # for the Ohio Bobcats Football Team. +1006 print( +1007 "Get historical returning production " + +1008 "for the Ohio Bobcats Football Team." +1009 ) +1010 json_data = get_cfbd_returning_production( +1011 team="Ohio" +1012 ) +1013 print(json_data) +1014 time.sleep(5) +1015 +1016 # Get returning production for the 2019 LSU Tigers. +1017 print("Get returning production for the 2019 LSU Tigers.") +1018 json_data = get_cfbd_returning_production( +1019 season=2019, +1020 team="LSU" +1021 ) +1022 print(json_data) +1023 time.sleep(5) +1024 +1025 # Get returning production for Maryland, +1026 # for seasons where Maryland is a member +1027 # of the Big 10 (B1G) Conference. +1028 print( +1029 "Get returning production for Maryland, " + +1030 "for seasons where Maryland is a member " + +1031 "of the Big 10 (B1G) Conference." +1032 ) +1033 json_data = get_cfbd_returning_production( +1034 team="Maryland", +1035 conference="B1G" +1036 ) +1037 print(json_data) +1038 time.sleep(5) +1039 +1040 # You can also tell this function to just return the API call as +1041 # a Dictionary (read: JSON) object. +1042 print( +1043 "You can also tell this function to just return the API call " + +1044 "as a Dictionary (read: JSON) object." +1045 ) +1046 json_data = get_cfbd_returning_production( +1047 season=2020, +1048 team="LSU", +1049 return_as_dict=True +1050 ) +1051 print(json_data) +1052 1053 -1054 -1055 ``` -1056 Returns -1057 ---------- -1058 A pandas `DataFrame` object with returning production data, -1059 or (if `return_as_dict` is set to `True`) -1060 a dictionary object with returning production data. -1061 -1062 """ -1063 now = datetime.now() -1064 team_df = pd.DataFrame() -1065 # row_df = pd.DataFrame() -1066 url = "https://api.collegefootballdata.com/player/returning" -1067 -1068 ########################################################################## -1069 -1070 if api_key is not None: -1071 real_api_key = api_key -1072 del api_key -1073 else: -1074 real_api_key = get_cfbd_api_token(api_key_dir=api_key_dir) -1075 -1076 if real_api_key == "tigersAreAwesome": -1077 raise ValueError( -1078 "You actually need to change `cfbd_key` to your CFBD API key." -1079 ) -1080 elif "Bearer " in real_api_key: -1081 pass -1082 elif "Bearer" in real_api_key: -1083 real_api_key = real_api_key.replace("Bearer", "Bearer ") -1084 else: -1085 real_api_key = "Bearer " + real_api_key -1086 -1087 if season is None and team is None: -1088 raise ValueError( -1089 "To use this function, `season` and/or `team` must be set to a " -1090 + "non-null variable." -1091 ) -1092 -1093 if season is None: -1094 # Rare, but in this endpoint, -1095 # you don't need to input the season. -1096 pass -1097 elif season > (now.year + 1): -1098 raise ValueError(f"`season` cannot be greater than {season}.") -1099 elif season < 1869: -1100 raise ValueError("`season` cannot be less than 1869.") -1101 -1102 # URL Builder -1103 ########################################################################## -1104 -1105 url_elements = 0 -1106 -1107 if season is not None and url_elements == 0: -1108 url += f"?year={season}" -1109 url_elements += 1 -1110 elif season is not None: -1111 url += f"&year={season}" -1112 url_elements += 1 -1113 -1114 if team is not None and url_elements == 0: -1115 url += f"?team={team}" -1116 url_elements += 1 -1117 elif team is not None: -1118 url += f"&team={team}" -1119 url_elements += 1 -1120 -1121 if conference is not None and url_elements == 0: -1122 url += f"?conference={conference}" -1123 url_elements += 1 -1124 elif conference is not None: -1125 url += f"&conference={conference}" -1126 url_elements += 1 -1127 -1128 headers = { -1129 "Authorization": f"{real_api_key}", -1130 "accept": "application/json" -1131 } -1132 -1133 response = requests.get(url, headers=headers) -1134 -1135 if response.status_code == 200: -1136 pass -1137 elif response.status_code == 401: -1138 raise ConnectionRefusedError( -1139 "Could not connect. The connection was refused." + -1140 "\nHTTP Status Code 401." -1141 ) -1142 else: -1143 raise ConnectionError( -1144 f"Could not connect.\nHTTP Status code {response.status_code}" -1145 ) -1146 -1147 json_data = response.json() -1148 -1149 if return_as_dict is True: -1150 return json_data -1151 -1152 team_df = pd.json_normalize(json_data) -1153 team_df.rename( -1154 columns={ -1155 "team": "team_name", -1156 "conference": "conference_name", -1157 "totalPPA": "returning_total_ppa", -1158 "totalPassingPPA": "returning_total_passing_ppa", -1159 "totalReceivingPPA": "returning_total_receiving_ppa", -1160 "totalRushingPPA": "returning_total_rush_ppa", -1161 "percentPPA": "returning_ppa_percent", -1162 "percentPassingPPA": "returning_percent_passing_ppa", -1163 "percentReceivingPPA": "returning_percent_receiving_ppa", -1164 "percentRushingPPA": "returning_percent_rushing_ppa", -1165 "usage": "returning_usage", -1166 "passingUsage": "returning_passing_usage", -1167 "receivingUsage": "returning_receiving_usage", -1168 "rushingUsage": "returning_rushing_usage", -1169 }, -1170 inplace=True, -1171 ) -1172 return team_df +1054 ``` +1055 Returns +1056 ---------- +1057 A pandas `DataFrame` object with returning production data, +1058 or (if `return_as_dict` is set to `True`) +1059 a dictionary object with returning production data. +1060 +1061 """ +1062 now = datetime.now() +1063 team_df = pd.DataFrame() +1064 # row_df = pd.DataFrame() +1065 url = "https://api.collegefootballdata.com/player/returning" +1066 +1067 ########################################################################## +1068 +1069 if api_key is not None: +1070 real_api_key = api_key +1071 del api_key +1072 else: +1073 real_api_key = get_cfbd_api_token(api_key_dir=api_key_dir) +1074 +1075 if real_api_key == "tigersAreAwesome": +1076 raise ValueError( +1077 "You actually need to change `cfbd_key` to your CFBD API key." +1078 ) +1079 elif "Bearer " in real_api_key: +1080 pass +1081 elif "Bearer" in real_api_key: +1082 real_api_key = real_api_key.replace("Bearer", "Bearer ") +1083 else: +1084 real_api_key = "Bearer " + real_api_key +1085 +1086 if season is None and team is None: +1087 raise ValueError( +1088 "To use this function, `season` and/or `team` must be set to a " +1089 + "non-null variable." +1090 ) +1091 +1092 if season is None: +1093 # Rare, but in this endpoint, +1094 # you don't need to input the season. +1095 pass +1096 elif season > (now.year + 1): +1097 raise ValueError(f"`season` cannot be greater than {season}.") +1098 elif season < 1869: +1099 raise ValueError("`season` cannot be less than 1869.") +1100 +1101 # URL Builder +1102 ########################################################################## +1103 +1104 url_elements = 0 +1105 +1106 if season is not None and url_elements == 0: +1107 url += f"?year={season}" +1108 url_elements += 1 +1109 elif season is not None: +1110 url += f"&year={season}" +1111 url_elements += 1 +1112 +1113 if team is not None and url_elements == 0: +1114 url += f"?team={team}" +1115 url_elements += 1 +1116 elif team is not None: +1117 url += f"&team={team}" +1118 url_elements += 1 +1119 +1120 if conference is not None and url_elements == 0: +1121 url += f"?conference={conference}" +1122 url_elements += 1 +1123 elif conference is not None: +1124 url += f"&conference={conference}" +1125 url_elements += 1 +1126 +1127 headers = { +1128 "Authorization": f"{real_api_key}", +1129 "accept": "application/json" +1130 } +1131 +1132 response = requests.get(url, headers=headers) +1133 +1134 if response.status_code == 200: +1135 pass +1136 elif response.status_code == 401: +1137 raise ConnectionRefusedError( +1138 "Could not connect. The connection was refused." + +1139 "\nHTTP Status Code 401." +1140 ) +1141 else: +1142 raise ConnectionError( +1143 f"Could not connect.\nHTTP Status code {response.status_code}" +1144 ) +1145 +1146 json_data = response.json() +1147 +1148 if return_as_dict is True: +1149 return json_data +1150 +1151 team_df = pd.json_normalize(json_data) +1152 team_df.rename( +1153 columns={ +1154 "team": "team_name", +1155 "conference": "conference_name", +1156 "totalPPA": "returning_total_ppa", +1157 "totalPassingPPA": "returning_total_passing_ppa", +1158 "totalReceivingPPA": "returning_total_receiving_ppa", +1159 "totalRushingPPA": "returning_total_rush_ppa", +1160 "percentPPA": "returning_ppa_percent", +1161 "percentPassingPPA": "returning_percent_passing_ppa", +1162 "percentReceivingPPA": "returning_percent_receiving_ppa", +1163 "percentRushingPPA": "returning_percent_rushing_ppa", +1164 "usage": "returning_usage", +1165 "passingUsage": "returning_passing_usage", +1166 "receivingUsage": "returning_receiving_usage", +1167 "rushingUsage": "returning_rushing_usage", +1168 }, +1169 inplace=True, +1170 ) +1171 return team_df +1172 1173 -1174 -1175def get_cfbd_player_season_stats( -1176 season: int, -1177 api_key: str = None, -1178 api_key_dir: str = None, -1179 team: str = None, -1180 conference: str = None, -1181 start_week: int = None, -1182 end_week: int = None, -1183 season_type: str = "both", # "regular", "postseason", or "both" -1184 stat_category: str = None, -1185 return_as_dict: bool = False, -1186): -1187 """ -1188 Get player season stats, -1189 or the stats of players in a specific time frame, from the CFBD API. -1190 -1191 Parameters -1192 ---------- -1193 `season` (int, mandatory): -1194 Required argument. -1195 Specifies the season you want CFB player season stats from. -1196 This must be specified, otherwise this package, and by extension -1197 the CFBD API, will not accept -1198 the request to get CFB player season stats. -1199 -1200 `api_key` (str, optional): -1201 Semi-optional argument. -1202 If `api_key` is null, this function will attempt to load a CFBD API key -1203 from the python environment, or from a file on this computer. -1204 If `api_key` is not null, -1205 this function will automatically assume that the -1206 inputted `api_key` is a valid CFBD API key. -1207 -1208 `api_key_dir` (str, optional): -1209 Optional argument. -1210 If `api_key` is set to am empty string, this variable is ignored. -1211 If `api_key_dir` is null, and `api_key` is null, -1212 this function will try to find -1213 a CFBD API key file in this user's home directory. -1214 If `api_key_dir` is set to a string, and `api_key` is null, -1215 this function will assume that `api_key_dir` is a directory, -1216 and will try to find a CFBD API key file in that directory. -1217 -1218 `team` (str, optional): -1219 Optional argument. -1220 If you only want CFB player season stats for a team, -1221 regardless if they are the home/away team, -1222 set `team` to the name of the team -1223 you want CFB player season stats from. -1224 -1225 `conference` (str, optional): -1226 Optional argument. -1227 If you only want player season stats from games -1228 involving teams a specific conference, -1229 set `conference` to the abbreviation -1230 of the conference you want stats from. -1231 -1232 `start_week` (int, semi-optional): -1233 Optional argument. -1234 If you only want player stats for a range of weeks, -1235 set `start_week` and `end_week` to -1236 the range of weeks you want season-level data for. -1237 -1238 `end_week` (int, semi-optional): -1239 Optional argument. -1240 If you only want player stats for a range of weeks, -1241 set `start_week` and `end_week` to -1242 the range of weeks you want season-level data for. -1243 -1244 **NOTE**: If the following conditions are `True`, a `ValueError()` -1245 will be raised when calling this function: -1246 - `start_week < 0` -1247 - `end_week < 0` -1248 - `start_week is not None and end_week is None` -1249 (will be changed in a future version) -1250 - `start_week is None and end_week is not None` -1251 (will be changed in a future version) -1252 - `end_week < start_week` -1253 - `end_week = start_week` -1254 -1255 `season_type` (str, semi-optional): -1256 Semi-optional argument. -1257 By default, this will be set to "regular", for the CFB regular season. -1258 If you want CFB media information for non-regular season games, -1259 set `season_type` to "postseason". -1260 If you want ***both*** regular -1261 and postseason stats, set `season_type = "both"`. -1262 If `season_type` is set to anything but "regular", -1263 "postseason", or "both", a `ValueError()` will be raised. -1264 -1265 `stat_category` (str, optional): -1266 Optional argument. -1267 If only want stats for a specific stat category, -1268 set this variable to that category. -1269 -1270 Valid inputs are: -1271 - `passing` -1272 - `rushing` -1273 - `receiving` -1274 - `fumbles` -1275 - `defensive` -1276 - `interceptions` -1277 - `punting` -1278 - `kicking` -1279 - `kickReturns` -1280 - `puntReturns` -1281 -1282 `return_as_dict` (bool, semi-optional): -1283 Semi-optional argument. -1284 If you want this function to return -1285 the data as a dictionary (read: JSON object), -1286 instead of a pandas `DataFrame` object, -1287 set `return_as_dict` to `True`. -1288 -1289 Usage -1290 ---------- -1291 ``` -1292 import time -1293 -1294 from cfbd_json_py.players import get_cfbd_player_season_stats +1174def get_cfbd_player_season_stats( +1175 season: int, +1176 api_key: str = None, +1177 api_key_dir: str = None, +1178 team: str = None, +1179 conference: str = None, +1180 start_week: int = None, +1181 end_week: int = None, +1182 season_type: str = "both", # "regular", "postseason", or "both" +1183 stat_category: str = None, +1184 return_as_dict: bool = False, +1185): +1186 """ +1187 Get player season stats, +1188 or the stats of players in a specific time frame, from the CFBD API. +1189 +1190 Parameters +1191 ---------- +1192 `season` (int, mandatory): +1193 Required argument. +1194 Specifies the season you want CFB player season stats from. +1195 This must be specified, otherwise this package, and by extension +1196 the CFBD API, will not accept +1197 the request to get CFB player season stats. +1198 +1199 `api_key` (str, optional): +1200 Semi-optional argument. +1201 If `api_key` is null, this function will attempt to load a CFBD API key +1202 from the python environment, or from a file on this computer. +1203 If `api_key` is not null, +1204 this function will automatically assume that the +1205 inputted `api_key` is a valid CFBD API key. +1206 +1207 `api_key_dir` (str, optional): +1208 Optional argument. +1209 If `api_key` is set to am empty string, this variable is ignored. +1210 If `api_key_dir` is null, and `api_key` is null, +1211 this function will try to find +1212 a CFBD API key file in this user's home directory. +1213 If `api_key_dir` is set to a string, and `api_key` is null, +1214 this function will assume that `api_key_dir` is a directory, +1215 and will try to find a CFBD API key file in that directory. +1216 +1217 `team` (str, optional): +1218 Optional argument. +1219 If you only want CFB player season stats for a team, +1220 regardless if they are the home/away team, +1221 set `team` to the name of the team +1222 you want CFB player season stats from. +1223 +1224 `conference` (str, optional): +1225 Optional argument. +1226 If you only want player season stats from games +1227 involving teams a specific conference, +1228 set `conference` to the abbreviation +1229 of the conference you want stats from. +1230 +1231 `start_week` (int, semi-optional): +1232 Optional argument. +1233 If you only want player stats for a range of weeks, +1234 set `start_week` and `end_week` to +1235 the range of weeks you want season-level data for. +1236 +1237 `end_week` (int, semi-optional): +1238 Optional argument. +1239 If you only want player stats for a range of weeks, +1240 set `start_week` and `end_week` to +1241 the range of weeks you want season-level data for. +1242 +1243 **NOTE**: If the following conditions are `True`, a `ValueError()` +1244 will be raised when calling this function: +1245 - `start_week < 0` +1246 - `end_week < 0` +1247 - `start_week is not None and end_week is None` +1248 (will be changed in a future version) +1249 - `start_week is None and end_week is not None` +1250 (will be changed in a future version) +1251 - `end_week < start_week` +1252 - `end_week = start_week` +1253 +1254 `season_type` (str, semi-optional): +1255 Semi-optional argument. +1256 By default, this will be set to "regular", for the CFB regular season. +1257 If you want CFB media information for non-regular season games, +1258 set `season_type` to "postseason". +1259 If you want ***both*** regular +1260 and postseason stats, set `season_type = "both"`. +1261 If `season_type` is set to anything but "regular", +1262 "postseason", or "both", a `ValueError()` will be raised. +1263 +1264 `stat_category` (str, optional): +1265 Optional argument. +1266 If only want stats for a specific stat category, +1267 set this variable to that category. +1268 +1269 Valid inputs are: +1270 - `passing` +1271 - `rushing` +1272 - `receiving` +1273 - `fumbles` +1274 - `defensive` +1275 - `interceptions` +1276 - `punting` +1277 - `kicking` +1278 - `kickReturns` +1279 - `puntReturns` +1280 +1281 `return_as_dict` (bool, semi-optional): +1282 Semi-optional argument. +1283 If you want this function to return +1284 the data as a dictionary (read: JSON object), +1285 instead of a pandas `DataFrame` object, +1286 set `return_as_dict` to `True`. +1287 +1288 Usage +1289 ---------- +1290 ``` +1291 import time +1292 +1293 from cfbd_json_py.players import get_cfbd_player_season_stats +1294 1295 -1296 -1297 cfbd_key = "tigersAreAwesome" # placeholder for your CFBD API Key. -1298 -1299 if cfbd_key != "tigersAreAwesome": -1300 print( -1301 "Using the user's API key declared in this script " + -1302 "for this example." -1303 ) -1304 -1305 # Get player season stats for -1306 # the Ohio Bobcats Football team in the 2020 CFB season. -1307 print( -1308 "Get player season stats for " + -1309 "the Ohio Bobcats Football team in the 2020 CFB season." -1310 ) -1311 json_data = get_cfbd_player_season_stats( -1312 api_key=cfbd_key, -1313 season=2020, -1314 team="Ohio" -1315 ) -1316 print(json_data) -1317 time.sleep(5) -1318 -1319 # Get player season stats for teams who competed in -1320 # the Southeastern conference (SEC) in the 2023 CFB season. -1321 print( -1322 "Get player season stats for teams who competed " + -1323 "in the Southeastern conference (SEC) in the 2023 CFB season." -1324 ) -1325 json_data = get_cfbd_player_season_stats( -1326 api_key=cfbd_key, -1327 season=2020, -1328 conference="SEC" -1329 ) -1330 print(json_data) -1331 time.sleep(5) -1332 -1333 # Get player season stats for teams who competed in -1334 # the Southeastern conference (SEC) in the 2023 CFB season, -1335 # but only between weeks 1 and 5. -1336 print( -1337 "Get player season stats for teams who competed " + -1338 "in the Southeastern conference (SEC) in the 2023 CFB season." -1339 ) -1340 json_data = get_cfbd_player_season_stats( -1341 api_key=cfbd_key, -1342 season=2020, -1343 conference="SEC", -1344 start_week=1, -1345 end_week=5 -1346 ) -1347 print(json_data) -1348 time.sleep(5) -1349 -1350 # Get player season stats for the 2020 CFB season. -1351 print("Get player season stats for the 2020 CFB season.") -1352 json_data = get_cfbd_player_season_stats( -1353 api_key=cfbd_key, -1354 season=2020 -1355 ) -1356 print(json_data) -1357 time.sleep(5) -1358 -1359 # Get player season stats for -1360 # the Ohio Bobcats Football team in the 2022 CFB season, -1361 # but only use regular season games when calculating season stats. -1362 print( -1363 "Get player season stats for the Ohio Bobcats Football team " + -1364 "in the 2020 CFB season, but only use regular season games " + -1365 "when calculating season stats." -1366 ) -1367 json_data = get_cfbd_player_season_stats( -1368 api_key=cfbd_key, -1369 season=2022, -1370 team="Ohio", -1371 season_type="regular" -1372 ) -1373 print(json_data) -1374 time.sleep(5) -1375 -1376 # Get passing stats for teams who competed in -1377 # the Southeastern conference (SEC) in the 2023 CFB season. -1378 print( -1379 "Get passing stats for teams who competed " + -1380 "in the Southeastern conference (SEC) in the 2023 CFB season." -1381 ) -1382 json_data = get_cfbd_player_season_stats( -1383 api_key=cfbd_key, -1384 season=2020, -1385 conference="SEC", -1386 stat_category="passing" -1387 ) -1388 print(json_data) -1389 time.sleep(5) -1390 -1391 # You can also tell this function to just return the API call as -1392 # a Dictionary (read: JSON) object. -1393 print( -1394 "You can also tell this function to just return the API call " + -1395 "as a Dictionary (read: JSON) object." -1396 ) -1397 json_data = get_cfbd_player_season_stats( -1398 api_key=cfbd_key, -1399 season=2020, -1400 team="LSU", -1401 stat_category="kicking", -1402 return_as_dict=True -1403 ) -1404 print(json_data) -1405 -1406 else: -1407 # Alternatively, if the CFBD API key exists in this python environment, -1408 # or it's been set by cfbd_json_py.utls.set_cfbd_api_token(), -1409 # you could just call these functions directly, -1410 # without setting the API key in the script. -1411 print( -1412 "Using the user's API key supposedly loaded " + -1413 "into this python environment for this example." -1414 ) -1415 -1416 # Get player season stats for -1417 # the Ohio Bobcats Football team in the 2020 CFB season. -1418 print( -1419 "Get player season stats for " + -1420 "the Ohio Bobcats Football team in the 2020 CFB season." -1421 ) -1422 json_data = get_cfbd_player_season_stats( -1423 season=2020, -1424 team="Ohio" -1425 ) -1426 print(json_data) -1427 time.sleep(5) -1428 -1429 # Get player season stats for teams who competed in -1430 # the Southeastern conference (SEC) in the 2023 CFB season. -1431 print( -1432 "Get player season stats for teams who competed " + -1433 "in the Southeastern conference (SEC) in the 2023 CFB season." -1434 ) -1435 json_data = get_cfbd_player_season_stats( -1436 season=2020, -1437 conference="SEC" -1438 ) -1439 print(json_data) -1440 time.sleep(5) -1441 -1442 # Get player season stats for teams who competed in -1443 # the Southeastern conference (SEC) in the 2023 CFB season, -1444 # but only between weeks 1 and 5. -1445 print( -1446 "Get player season stats for teams who competed " + -1447 "in the Southeastern conference (SEC) in the 2023 CFB season." -1448 ) -1449 json_data = get_cfbd_player_season_stats( -1450 season=2020, -1451 conference="SEC", -1452 start_week=1, -1453 end_week=5 -1454 ) -1455 print(json_data) -1456 time.sleep(5) -1457 -1458 # Get player season stats for the 2020 CFB season. -1459 print("Get player season stats for the 2020 CFB season.") -1460 json_data = get_cfbd_player_season_stats( -1461 season=2020 -1462 ) -1463 print(json_data) -1464 time.sleep(5) -1465 -1466 # Get player season stats for -1467 # the Ohio Bobcats Football team in the 2022 CFB season, -1468 # but only use regular season games when calculating season stats. -1469 print( -1470 "Get player season stats for the Ohio Bobcats Football team " + -1471 "in the 2020 CFB season, but only use regular season games " + -1472 "when calculating season stats." -1473 ) -1474 json_data = get_cfbd_player_season_stats( -1475 season=2022, -1476 team="Ohio", -1477 season_type="regular" -1478 ) -1479 print(json_data) -1480 time.sleep(5) -1481 -1482 # Get passing stats for teams who competed in -1483 # the Southeastern conference (SEC) in the 2023 CFB season. -1484 print( -1485 "Get passing stats for teams who competed " + -1486 "in the Southeastern conference (SEC) in the 2023 CFB season." -1487 ) -1488 json_data = get_cfbd_player_season_stats( -1489 season=2020, -1490 conference="SEC", -1491 stat_category="passing" -1492 ) -1493 print(json_data) -1494 time.sleep(5) -1495 -1496 # You can also tell this function to just return the API call as -1497 # a Dictionary (read: JSON) object. -1498 print( -1499 "You can also tell this function to just return the API call " + -1500 "as a Dictionary (read: JSON) object." -1501 ) -1502 json_data = get_cfbd_player_season_stats( -1503 season=2020, -1504 team="LSU", -1505 stat_category="kicking", -1506 return_as_dict=True -1507 ) -1508 print(json_data) -1509 -1510 ``` -1511 Returns -1512 ---------- -1513 A pandas `DataFrame` object with -1514 a list of players who matched the search string, -1515 or (if `return_as_dict` is set to `True`) -1516 a dictionary object with a list of players who matched the search string. -1517 -1518 """ -1519 -1520 rebuilt_json = {} -1521 stat_columns = [ -1522 "season", -1523 "team_name", -1524 "team_conference", -1525 "player_id", -1526 "player_name", -1527 # PASS -1528 "passing_COMP", -1529 "passing_ATT", -1530 "passing_COMP%", -1531 "passing_YDS", -1532 "passing_AVG", -1533 "passing_TD", -1534 "passing_INT", -1535 # RUSH -1536 "rushing_CAR", -1537 "rushing_YDS", -1538 "rushing_AVG", -1539 "rushing_TD", -1540 "rushing_LONG", -1541 # REC -1542 "receiving_REC", -1543 "receiving_YDS", -1544 "receiving_AVG", -1545 "receiving_TD", -1546 "receiving_LONG", -1547 # FUM -1548 "fumbles_FUM", -1549 "fumbles_LOST", -1550 "fumbles_REC", -1551 # DEFENSE -1552 "defensive_TOT", -1553 "defensive_SOLO", -1554 "defensive_TFL", -1555 "defensive_QB HUR", -1556 "defensive_SACKS", -1557 "defensive_PD", -1558 "defensive_TD", -1559 # INT -1560 "interceptions_INT", -1561 "interceptions_YDS", -1562 "interceptions_TD", -1563 # PUNT -1564 "punting_NO", -1565 "punting_YDS", -1566 "punting_AVG", -1567 "punting_TB", -1568 "punting_In 20", -1569 "punting_LONG", -1570 # KICK -1571 "kicking_FGM", -1572 "kicking_FGA", -1573 "kicking_FG%", -1574 "kicking_LONG", -1575 "kicking_XPM", -1576 "kicking_XPA", -1577 "kicking_XP%", -1578 # KR -1579 "kickReturns_NO", -1580 "kickReturns_YDS", -1581 "kickReturns_AVG", -1582 "kickReturns_TD", -1583 "kickReturns_LONG", -1584 # PR -1585 "puntReturns_NO", -1586 "puntReturns_YDS", -1587 "puntReturns_AVG", -1588 "puntReturns_TD", -1589 "puntReturns_LONG", -1590 ] -1591 -1592 now = datetime.now() -1593 url = "https://api.collegefootballdata.com/stats/player/season" -1594 -1595 final_df = pd.DataFrame() -1596 -1597 if api_key is not None: -1598 real_api_key = api_key -1599 del api_key -1600 else: -1601 real_api_key = get_cfbd_api_token(api_key_dir=api_key_dir) -1602 -1603 if real_api_key == "tigersAreAwesome": -1604 raise ValueError( -1605 "You actually need to change `cfbd_key` to your CFBD API key." -1606 ) -1607 elif "Bearer " in real_api_key: -1608 pass -1609 elif "Bearer" in real_api_key: -1610 real_api_key = real_api_key.replace("Bearer", "Bearer ") -1611 else: -1612 real_api_key = "Bearer " + real_api_key -1613 -1614 if season is None: -1615 # This should never happen without user tampering, but if it does, -1616 # we need to raise an error, -1617 # because the CFBD API will refuse this call without a valid season. -1618 raise SystemError( -1619 "I don't know how, I don't know why, " -1620 + "but you managed to call this function " -1621 + "while `season` was `None` (NULL)," -1622 + " and the function got to this point in the code." -1623 + "\nIf you have a GitHub account, " -1624 + "please raise an issue on this python package's GitHub page:\n" -1625 + "https://github.com/armstjc/cfbd-json-py/issues" -1626 ) -1627 elif season > (now.year + 1): -1628 raise ValueError(f"`season` cannot be greater than {season}.") -1629 elif season < 1869: -1630 raise ValueError("`season` cannot be less than 1869.") -1631 -1632 if ( -1633 season_type != "regular" -1634 and season_type != "postseason" -1635 and season_type != "both" -1636 ): -1637 raise ValueError( -1638 '`season_type` must be set to either "regular" or ' -1639 + '"postseason" for this function to work.' -1640 ) -1641 -1642 filter_by_stat_category = False -1643 -1644 if stat_category is None: -1645 pass -1646 elif stat_category == "passing": -1647 filter_by_stat_category = True -1648 elif stat_category == "rushing": -1649 filter_by_stat_category = True -1650 elif stat_category == "receiving": -1651 filter_by_stat_category = True -1652 elif stat_category == "fumbles": -1653 filter_by_stat_category = True -1654 elif stat_category == "passing": -1655 filter_by_stat_category = True -1656 elif stat_category == "defensive": -1657 filter_by_stat_category = True -1658 elif stat_category == "interceptions": -1659 filter_by_stat_category = True -1660 elif stat_category == "punting": -1661 filter_by_stat_category = True -1662 elif stat_category == "kicking": -1663 filter_by_stat_category = True -1664 elif stat_category == "kickReturns": -1665 filter_by_stat_category = True -1666 elif stat_category == "puntReturns": -1667 filter_by_stat_category = True -1668 else: -1669 raise ValueError( -1670 "Invalid input for `stat_category`." -1671 + "\nValid inputs are:" -1672 + """ -1673 - `passing` -1674 - `rushing` -1675 - `receiving` -1676 - `fumbles` -1677 - `defensive` -1678 - `interceptions` -1679 - `punting` -1680 - `kicking` -1681 - `kickReturns` -1682 - `puntReturns` -1683 """ -1684 ) -1685 -1686 if start_week is not None and end_week is not None: -1687 if start_week > end_week: -1688 raise ValueError("`start_week` cannot be greater than `end_week`.") -1689 elif start_week == end_week: -1690 raise ValueError( -1691 "`start_week` cannot be equal to `end_week`." -1692 + "\n Use " -1693 + "`cfbd_json_py.games.get_cfbd_player_game_stats()` instead " -1694 + "if you want player stats for a specific week in ." -1695 ) -1696 elif start_week < 0: -1697 raise ValueError("`start_week` cannot be less than 0.") -1698 elif end_week < 0: -1699 raise ValueError("`end_week` cannot be less than 0.") -1700 -1701 if filter_by_stat_category is True: -1702 pass -1703 -1704 # URL builder -1705 ########################################################################## -1706 -1707 # Required by the API -1708 url += f"?year={season}" -1709 -1710 if team is not None: -1711 url += f"&team={team}" -1712 -1713 if conference is not None: -1714 url += f"&conference={conference}" -1715 -1716 if season_type is not None: -1717 url += f"&seasonType={season_type}" -1718 -1719 if stat_category is not None: -1720 url += f"&category={stat_category}" -1721 -1722 if start_week is not None: -1723 url += f"&startWeek={start_week}" -1724 -1725 if end_week is not None: -1726 url += f"&endWeek={end_week}" -1727 -1728 headers = { -1729 "Authorization": f"{real_api_key}", -1730 "accept": "application/json" -1731 } -1732 -1733 response = requests.get(url, headers=headers) -1734 -1735 if response.status_code == 200: -1736 pass -1737 elif response.status_code == 401: -1738 raise ConnectionRefusedError( -1739 "Could not connect. The connection was refused." + -1740 "\nHTTP Status Code 401." -1741 ) -1742 else: -1743 raise ConnectionError( -1744 f"Could not connect.\nHTTP Status code {response.status_code}" -1745 ) -1746 -1747 json_data = response.json() -1748 -1749 if return_as_dict is True: -1750 return json_data -1751 -1752 for player in tqdm(json_data): -1753 player_id = int(player["playerId"]) -1754 player_name = player["player"] -1755 team_name = player["team"] -1756 team_conference = player["conference"] -1757 s_category = player["category"] -1758 s_type = player["statType"] -1759 s_num = player["stat"] -1760 -1761 if rebuilt_json.get(player_id) is None: -1762 rebuilt_json[player_id] = {} -1763 -1764 if s_category == "passing": -1765 if s_type == "COMPLETIONS": +1296 cfbd_key = "tigersAreAwesome" # placeholder for your CFBD API Key. +1297 +1298 if cfbd_key != "tigersAreAwesome": +1299 print( +1300 "Using the user's API key declared in this script " + +1301 "for this example." +1302 ) +1303 +1304 # Get player season stats for +1305 # the Ohio Bobcats Football team in the 2020 CFB season. +1306 print( +1307 "Get player season stats for " + +1308 "the Ohio Bobcats Football team in the 2020 CFB season." +1309 ) +1310 json_data = get_cfbd_player_season_stats( +1311 api_key=cfbd_key, +1312 season=2020, +1313 team="Ohio" +1314 ) +1315 print(json_data) +1316 time.sleep(5) +1317 +1318 # Get player season stats for teams who competed in +1319 # the Southeastern conference (SEC) in the 2023 CFB season. +1320 print( +1321 "Get player season stats for teams who competed " + +1322 "in the Southeastern conference (SEC) in the 2023 CFB season." +1323 ) +1324 json_data = get_cfbd_player_season_stats( +1325 api_key=cfbd_key, +1326 season=2020, +1327 conference="SEC" +1328 ) +1329 print(json_data) +1330 time.sleep(5) +1331 +1332 # Get player season stats for teams who competed in +1333 # the Southeastern conference (SEC) in the 2023 CFB season, +1334 # but only between weeks 1 and 5. +1335 print( +1336 "Get player season stats for teams who competed " + +1337 "in the Southeastern conference (SEC) in the 2023 CFB season." +1338 ) +1339 json_data = get_cfbd_player_season_stats( +1340 api_key=cfbd_key, +1341 season=2020, +1342 conference="SEC", +1343 start_week=1, +1344 end_week=5 +1345 ) +1346 print(json_data) +1347 time.sleep(5) +1348 +1349 # Get player season stats for the 2020 CFB season. +1350 print("Get player season stats for the 2020 CFB season.") +1351 json_data = get_cfbd_player_season_stats( +1352 api_key=cfbd_key, +1353 season=2020 +1354 ) +1355 print(json_data) +1356 time.sleep(5) +1357 +1358 # Get player season stats for +1359 # the Ohio Bobcats Football team in the 2022 CFB season, +1360 # but only use regular season games when calculating season stats. +1361 print( +1362 "Get player season stats for the Ohio Bobcats Football team " + +1363 "in the 2020 CFB season, but only use regular season games " + +1364 "when calculating season stats." +1365 ) +1366 json_data = get_cfbd_player_season_stats( +1367 api_key=cfbd_key, +1368 season=2022, +1369 team="Ohio", +1370 season_type="regular" +1371 ) +1372 print(json_data) +1373 time.sleep(5) +1374 +1375 # Get passing stats for teams who competed in +1376 # the Southeastern conference (SEC) in the 2023 CFB season. +1377 print( +1378 "Get passing stats for teams who competed " + +1379 "in the Southeastern conference (SEC) in the 2023 CFB season." +1380 ) +1381 json_data = get_cfbd_player_season_stats( +1382 api_key=cfbd_key, +1383 season=2020, +1384 conference="SEC", +1385 stat_category="passing" +1386 ) +1387 print(json_data) +1388 time.sleep(5) +1389 +1390 # You can also tell this function to just return the API call as +1391 # a Dictionary (read: JSON) object. +1392 print( +1393 "You can also tell this function to just return the API call " + +1394 "as a Dictionary (read: JSON) object." +1395 ) +1396 json_data = get_cfbd_player_season_stats( +1397 api_key=cfbd_key, +1398 season=2020, +1399 team="LSU", +1400 stat_category="kicking", +1401 return_as_dict=True +1402 ) +1403 print(json_data) +1404 +1405 else: +1406 # Alternatively, if the CFBD API key exists in this python environment, +1407 # or it's been set by cfbd_json_py.utls.set_cfbd_api_token(), +1408 # you could just call these functions directly, +1409 # without setting the API key in the script. +1410 print( +1411 "Using the user's API key supposedly loaded " + +1412 "into this python environment for this example." +1413 ) +1414 +1415 # Get player season stats for +1416 # the Ohio Bobcats Football team in the 2020 CFB season. +1417 print( +1418 "Get player season stats for " + +1419 "the Ohio Bobcats Football team in the 2020 CFB season." +1420 ) +1421 json_data = get_cfbd_player_season_stats( +1422 season=2020, +1423 team="Ohio" +1424 ) +1425 print(json_data) +1426 time.sleep(5) +1427 +1428 # Get player season stats for teams who competed in +1429 # the Southeastern conference (SEC) in the 2023 CFB season. +1430 print( +1431 "Get player season stats for teams who competed " + +1432 "in the Southeastern conference (SEC) in the 2023 CFB season." +1433 ) +1434 json_data = get_cfbd_player_season_stats( +1435 season=2020, +1436 conference="SEC" +1437 ) +1438 print(json_data) +1439 time.sleep(5) +1440 +1441 # Get player season stats for teams who competed in +1442 # the Southeastern conference (SEC) in the 2023 CFB season, +1443 # but only between weeks 1 and 5. +1444 print( +1445 "Get player season stats for teams who competed " + +1446 "in the Southeastern conference (SEC) in the 2023 CFB season." +1447 ) +1448 json_data = get_cfbd_player_season_stats( +1449 season=2020, +1450 conference="SEC", +1451 start_week=1, +1452 end_week=5 +1453 ) +1454 print(json_data) +1455 time.sleep(5) +1456 +1457 # Get player season stats for the 2020 CFB season. +1458 print("Get player season stats for the 2020 CFB season.") +1459 json_data = get_cfbd_player_season_stats( +1460 season=2020 +1461 ) +1462 print(json_data) +1463 time.sleep(5) +1464 +1465 # Get player season stats for +1466 # the Ohio Bobcats Football team in the 2022 CFB season, +1467 # but only use regular season games when calculating season stats. +1468 print( +1469 "Get player season stats for the Ohio Bobcats Football team " + +1470 "in the 2020 CFB season, but only use regular season games " + +1471 "when calculating season stats." +1472 ) +1473 json_data = get_cfbd_player_season_stats( +1474 season=2022, +1475 team="Ohio", +1476 season_type="regular" +1477 ) +1478 print(json_data) +1479 time.sleep(5) +1480 +1481 # Get passing stats for teams who competed in +1482 # the Southeastern conference (SEC) in the 2023 CFB season. +1483 print( +1484 "Get passing stats for teams who competed " + +1485 "in the Southeastern conference (SEC) in the 2023 CFB season." +1486 ) +1487 json_data = get_cfbd_player_season_stats( +1488 season=2020, +1489 conference="SEC", +1490 stat_category="passing" +1491 ) +1492 print(json_data) +1493 time.sleep(5) +1494 +1495 # You can also tell this function to just return the API call as +1496 # a Dictionary (read: JSON) object. +1497 print( +1498 "You can also tell this function to just return the API call " + +1499 "as a Dictionary (read: JSON) object." +1500 ) +1501 json_data = get_cfbd_player_season_stats( +1502 season=2020, +1503 team="LSU", +1504 stat_category="kicking", +1505 return_as_dict=True +1506 ) +1507 print(json_data) +1508 +1509 ``` +1510 Returns +1511 ---------- +1512 A pandas `DataFrame` object with +1513 a list of players who matched the search string, +1514 or (if `return_as_dict` is set to `True`) +1515 a dictionary object with a list of players who matched the search string. +1516 +1517 """ +1518 +1519 rebuilt_json = {} +1520 stat_columns = [ +1521 "season", +1522 "team_name", +1523 "team_conference", +1524 "player_id", +1525 "player_name", +1526 # PASS +1527 "passing_COMP", +1528 "passing_ATT", +1529 "passing_COMP%", +1530 "passing_YDS", +1531 "passing_AVG", +1532 "passing_TD", +1533 "passing_INT", +1534 # RUSH +1535 "rushing_CAR", +1536 "rushing_YDS", +1537 "rushing_AVG", +1538 "rushing_TD", +1539 "rushing_LONG", +1540 # REC +1541 "receiving_REC", +1542 "receiving_YDS", +1543 "receiving_AVG", +1544 "receiving_TD", +1545 "receiving_LONG", +1546 # FUM +1547 "fumbles_FUM", +1548 "fumbles_LOST", +1549 "fumbles_REC", +1550 # DEFENSE +1551 "defensive_TOT", +1552 "defensive_SOLO", +1553 "defensive_TFL", +1554 "defensive_QB HUR", +1555 "defensive_SACKS", +1556 "defensive_PD", +1557 "defensive_TD", +1558 # INT +1559 "interceptions_INT", +1560 "interceptions_YDS", +1561 "interceptions_TD", +1562 # PUNT +1563 "punting_NO", +1564 "punting_YDS", +1565 "punting_AVG", +1566 "punting_TB", +1567 "punting_In 20", +1568 "punting_LONG", +1569 # KICK +1570 "kicking_FGM", +1571 "kicking_FGA", +1572 "kicking_FG%", +1573 "kicking_LONG", +1574 "kicking_XPM", +1575 "kicking_XPA", +1576 "kicking_XP%", +1577 # KR +1578 "kickReturns_NO", +1579 "kickReturns_YDS", +1580 "kickReturns_AVG", +1581 "kickReturns_TD", +1582 "kickReturns_LONG", +1583 # PR +1584 "puntReturns_NO", +1585 "puntReturns_YDS", +1586 "puntReturns_AVG", +1587 "puntReturns_TD", +1588 "puntReturns_LONG", +1589 ] +1590 +1591 now = datetime.now() +1592 url = "https://api.collegefootballdata.com/stats/player/season" +1593 +1594 final_df = pd.DataFrame() +1595 +1596 if api_key is not None: +1597 real_api_key = api_key +1598 del api_key +1599 else: +1600 real_api_key = get_cfbd_api_token(api_key_dir=api_key_dir) +1601 +1602 if real_api_key == "tigersAreAwesome": +1603 raise ValueError( +1604 "You actually need to change `cfbd_key` to your CFBD API key." +1605 ) +1606 elif "Bearer " in real_api_key: +1607 pass +1608 elif "Bearer" in real_api_key: +1609 real_api_key = real_api_key.replace("Bearer", "Bearer ") +1610 else: +1611 real_api_key = "Bearer " + real_api_key +1612 +1613 if season is None: +1614 # This should never happen without user tampering, but if it does, +1615 # we need to raise an error, +1616 # because the CFBD API will refuse this call without a valid season. +1617 raise SystemError( +1618 "I don't know how, I don't know why, " +1619 + "but you managed to call this function " +1620 + "while `season` was `None` (NULL)," +1621 + " and the function got to this point in the code." +1622 + "\nIf you have a GitHub account, " +1623 + "please raise an issue on this python package's GitHub page:\n" +1624 + "https://github.com/armstjc/cfbd-json-py/issues" +1625 ) +1626 elif season > (now.year + 1): +1627 raise ValueError(f"`season` cannot be greater than {season}.") +1628 elif season < 1869: +1629 raise ValueError("`season` cannot be less than 1869.") +1630 +1631 if ( +1632 season_type != "regular" +1633 and season_type != "postseason" +1634 and season_type != "both" +1635 ): +1636 raise ValueError( +1637 '`season_type` must be set to either "regular" or ' +1638 + '"postseason" for this function to work.' +1639 ) +1640 +1641 filter_by_stat_category = False +1642 +1643 if stat_category is None: +1644 pass +1645 elif stat_category == "passing": +1646 filter_by_stat_category = True +1647 elif stat_category == "rushing": +1648 filter_by_stat_category = True +1649 elif stat_category == "receiving": +1650 filter_by_stat_category = True +1651 elif stat_category == "fumbles": +1652 filter_by_stat_category = True +1653 elif stat_category == "passing": +1654 filter_by_stat_category = True +1655 elif stat_category == "defensive": +1656 filter_by_stat_category = True +1657 elif stat_category == "interceptions": +1658 filter_by_stat_category = True +1659 elif stat_category == "punting": +1660 filter_by_stat_category = True +1661 elif stat_category == "kicking": +1662 filter_by_stat_category = True +1663 elif stat_category == "kickReturns": +1664 filter_by_stat_category = True +1665 elif stat_category == "puntReturns": +1666 filter_by_stat_category = True +1667 else: +1668 raise ValueError( +1669 "Invalid input for `stat_category`." +1670 + "\nValid inputs are:" +1671 + """ +1672 - `passing` +1673 - `rushing` +1674 - `receiving` +1675 - `fumbles` +1676 - `defensive` +1677 - `interceptions` +1678 - `punting` +1679 - `kicking` +1680 - `kickReturns` +1681 - `puntReturns` +1682 """ +1683 ) +1684 +1685 if start_week is not None and end_week is not None: +1686 if start_week > end_week: +1687 raise ValueError("`start_week` cannot be greater than `end_week`.") +1688 elif start_week == end_week: +1689 raise ValueError( +1690 "`start_week` cannot be equal to `end_week`." +1691 + "\n Use " +1692 + "`cfbd_json_py.games.get_cfbd_player_game_stats()` instead " +1693 + "if you want player stats for a specific week in ." +1694 ) +1695 elif start_week < 0: +1696 raise ValueError("`start_week` cannot be less than 0.") +1697 elif end_week < 0: +1698 raise ValueError("`end_week` cannot be less than 0.") +1699 +1700 if filter_by_stat_category is True: +1701 pass +1702 +1703 # URL builder +1704 ########################################################################## +1705 +1706 # Required by the API +1707 url += f"?year={season}" +1708 +1709 if team is not None: +1710 url += f"&team={team}" +1711 +1712 if conference is not None: +1713 url += f"&conference={conference}" +1714 +1715 if season_type is not None: +1716 url += f"&seasonType={season_type}" +1717 +1718 if stat_category is not None: +1719 url += f"&category={stat_category}" +1720 +1721 if start_week is not None: +1722 url += f"&startWeek={start_week}" +1723 +1724 if end_week is not None: +1725 url += f"&endWeek={end_week}" +1726 +1727 headers = { +1728 "Authorization": f"{real_api_key}", +1729 "accept": "application/json" +1730 } +1731 +1732 response = requests.get(url, headers=headers) +1733 +1734 if response.status_code == 200: +1735 pass +1736 elif response.status_code == 401: +1737 raise ConnectionRefusedError( +1738 "Could not connect. The connection was refused." + +1739 "\nHTTP Status Code 401." +1740 ) +1741 else: +1742 raise ConnectionError( +1743 f"Could not connect.\nHTTP Status code {response.status_code}" +1744 ) +1745 +1746 json_data = response.json() +1747 +1748 if return_as_dict is True: +1749 return json_data +1750 +1751 for player in json_data: +1752 player_id = int(player["playerId"]) +1753 player_name = player["player"] +1754 team_name = player["team"] +1755 team_conference = player["conference"] +1756 s_category = player["category"] +1757 s_type = player["statType"] +1758 s_num = player["stat"] +1759 +1760 if rebuilt_json.get(player_id) is None: +1761 rebuilt_json[player_id] = {} +1762 +1763 if s_category == "passing": +1764 if s_type == "COMPLETIONS": +1765 rebuilt_json[player_id]["player_id"] = player_name 1766 rebuilt_json[player_id]["player_name"] = player_name 1767 rebuilt_json[player_id]["team_name"] = team_name 1768 rebuilt_json[player_id]["team_conference"] = team_conference @@ -3589,586 +3589,605 @@

2101 del player_id, player_name, team_name, \ 2102 team_conference, s_category, s_type, s_num 2103 -2104 for key, value in tqdm(rebuilt_json.items()): +2104 for key, value in rebuilt_json.items(): 2105 row_df = pd.json_normalize(value) -2106 final_df = pd.concat([final_df, row_df], ignore_index=True) -2107 del row_df -2108 -2109 final_df = final_df.fillna(0) -2110 -2111 final_df["season"] = season -2112 -2113 if filter_by_stat_category is False: -2114 final_df = final_df.reindex(columns=stat_columns) -2115 final_df = final_df.astype( -2116 { -2117 "passing_COMP": "int", -2118 "passing_ATT": "int", -2119 "rushing_CAR": "int", -2120 "rushing_YDS": "int", -2121 "receiving_REC": "int", -2122 "receiving_YDS": "int", -2123 "punting_NO": "int", -2124 "punting_YDS": "int", -2125 "kicking_FGM": "int", -2126 "kicking_FGA": "int", -2127 "kicking_XPM": "int", -2128 "kicking_XPA": "int", -2129 "kickReturns_NO": "int", -2130 "kickReturns_YDS": "int", -2131 "puntReturns_NO": "int", -2132 "puntReturns_YDS": "int", -2133 } -2134 ) -2135 -2136 final_df.loc[final_df["passing_ATT"] > 0, "passing_COMP%"] = ( -2137 final_df["passing_COMP"] / final_df["passing_ATT"] -2138 ) -2139 -2140 final_df.loc[final_df["rushing_CAR"] > 0, "rushing_AVG"] = ( -2141 final_df["rushing_YDS"] / final_df["rushing_CAR"] -2142 ) -2143 -2144 final_df.loc[final_df["receiving_REC"] > 0, "receiving_AVG"] = ( -2145 final_df["receiving_YDS"] / final_df["receiving_REC"] -2146 ) +2106 row_df["player_id"] = key +2107 final_df = pd.concat([final_df, row_df], ignore_index=True) +2108 del row_df +2109 +2110 final_df = final_df.fillna(0) +2111 +2112 final_df["season"] = season +2113 +2114 if filter_by_stat_category is False: +2115 final_df = final_df.reindex(columns=stat_columns) +2116 final_df = final_df.astype( +2117 { +2118 "passing_COMP": "int", +2119 "passing_ATT": "int", +2120 "rushing_CAR": "int", +2121 "rushing_YDS": "int", +2122 "receiving_REC": "int", +2123 "receiving_YDS": "int", +2124 "punting_NO": "int", +2125 "punting_YDS": "int", +2126 "kicking_FGM": "int", +2127 "kicking_FGA": "int", +2128 "kicking_XPM": "int", +2129 "kicking_XPA": "int", +2130 "kickReturns_NO": "int", +2131 "kickReturns_YDS": "int", +2132 "puntReturns_NO": "int", +2133 "puntReturns_YDS": "int", +2134 }, +2135 errors="ignore" +2136 ) +2137 +2138 final_df.loc[final_df["passing_ATT"] > 0, "passing_COMP%"] = ( +2139 final_df["passing_COMP"] / final_df["passing_ATT"] +2140 ) +2141 final_df["passing_COMP%"] = final_df["passing_COMP%"].round(3) +2142 +2143 final_df.loc[final_df["rushing_CAR"] > 0, "rushing_AVG"] = ( +2144 final_df["rushing_YDS"] / final_df["rushing_CAR"] +2145 ) +2146 final_df["rushing_AVG"] = final_df["rushing_AVG"].round(3) 2147 -2148 final_df.loc[final_df["punting_NO"] > 0, "punting_AVG"] = ( -2149 final_df["punting_YDS"] / final_df["punting_NO"] +2148 final_df.loc[final_df["receiving_REC"] > 0, "receiving_AVG"] = ( +2149 final_df["receiving_YDS"] / final_df["receiving_REC"] 2150 ) -2151 -2152 final_df.loc[final_df["kicking_FGA"] > 0, "kicking_FG%"] = ( -2153 final_df["kicking_FGM"] / final_df["kicking_FGA"] -2154 ) -2155 -2156 final_df.loc[final_df["kicking_XPA"] > 0, "kicking_XP%"] = ( -2157 final_df["kicking_XPM"] / final_df["kicking_XPA"] -2158 ) -2159 -2160 final_df.loc[final_df["kickReturns_NO"] > 0, "kickReturns_AVG"] = ( -2161 final_df["kickReturns_YDS"] / final_df["kickReturns_NO"] -2162 ) -2163 -2164 final_df.loc[final_df["puntReturns_NO"] > 0, "puntReturns_AVG"] = ( -2165 final_df["puntReturns_YDS"] / final_df["puntReturns_NO"] -2166 ) +2151 final_df["receiving_AVG"] = final_df["receiving_AVG"].round(3) +2152 +2153 final_df.loc[final_df["punting_NO"] > 0, "punting_AVG"] = ( +2154 final_df["punting_YDS"] / final_df["punting_NO"] +2155 ) +2156 final_df["punting_AVG"] = final_df["punting_AVG"].round(3) +2157 +2158 final_df.loc[final_df["kicking_FGA"] > 0, "kicking_FG%"] = ( +2159 final_df["kicking_FGM"] / final_df["kicking_FGA"] +2160 ) +2161 final_df["kicking_FG%"] = final_df["kicking_FG%"].round(5) +2162 +2163 final_df.loc[final_df["kicking_XPA"] > 0, "kicking_XP%"] = ( +2164 final_df["kicking_XPM"] / final_df["kicking_XPA"] +2165 ) +2166 final_df["kicking_XP%"] = final_df["kicking_XP%"].round(5) 2167 -2168 elif filter_by_stat_category is True and stat_category == "passing": -2169 try: -2170 final_df = final_df.astype( -2171 { -2172 "passing_COMP": "int", -2173 "passing_ATT": "int", -2174 } -2175 ) -2176 except Exception as e: -2177 logging.warning( -2178 "Could not reformat [passing_COMP]" -2179 + " and [passing_ATT] into integers. " -2180 + f"Full Exception: {e}" -2181 ) -2182 -2183 final_df.loc[final_df["passing_ATT"] >= 1, "passing_COMP%"] = ( -2184 final_df["passing_COMP"] / final_df["passing_ATT"] -2185 ) -2186 -2187 final_df = final_df[ -2188 [ -2189 "season", -2190 "team_name", -2191 "team_conference", -2192 # "player_id", -2193 "player_name", -2194 # PASS -2195 "passing_COMP", -2196 "passing_ATT", -2197 "passing_YDS", -2198 "passing_TD", -2199 "passing_INT", -2200 ] -2201 ] -2202 -2203 elif filter_by_stat_category is True and stat_category == "rushing": -2204 try: -2205 final_df = final_df.astype( -2206 { -2207 "rushing_CAR": "int", -2208 "rushing_YDS": "int", -2209 } -2210 ) -2211 except Exception as e: -2212 logging.warning( -2213 "Could not reformat [rushing_CAR] " -2214 + "and [rushing_YDS] into integers. " -2215 + f"Full Exception: {e}" -2216 ) -2217 -2218 final_df.loc[final_df["rushing_CAR"] >= 1, "rushing_AVG"] = ( -2219 final_df["rushing_YDS"] / final_df["rushing_CAR"] -2220 ) -2221 -2222 final_df = final_df[ -2223 [ -2224 "season", -2225 "team_name", -2226 "team_conference", -2227 "player_id", -2228 "player_name", -2229 # RUSH -2230 "rushing_CAR", -2231 "rushing_YDS", -2232 "rushing_AVG", -2233 "rushing_TD", -2234 "rushing_LONG", -2235 ] -2236 ] -2237 -2238 elif filter_by_stat_category is True and stat_category == "receiving": -2239 try: -2240 final_df = final_df.astype( -2241 { -2242 "receiving_REC": "int", -2243 "receiving_YDS": "int", -2244 } -2245 ) -2246 except Exception as e: -2247 logging.warning( -2248 "Could not reformat [receiving_REC] " -2249 + "and [receiving_YDS] into integers. " -2250 + f"Full Exception: {e}" -2251 ) -2252 -2253 final_df.loc[final_df["receiving_REC"] > 0, "receiving_AVG"] = ( -2254 final_df["receiving_YDS"] / final_df["receiving_REC"] -2255 ) -2256 -2257 final_df = final_df[ -2258 [ -2259 "season", -2260 "team_name", -2261 "team_conference", -2262 "player_id", -2263 "player_name", -2264 # REC -2265 "receiving_REC", -2266 "receiving_YDS", -2267 "receiving_AVG", -2268 "receiving_TD", -2269 "receiving_LONG", -2270 ] -2271 ] -2272 -2273 elif filter_by_stat_category is True and stat_category == "fumbles": -2274 final_df = final_df[ -2275 [ -2276 "season", -2277 "team_name", -2278 "team_conference", -2279 "player_id", -2280 "player_name", -2281 # FUM -2282 "fumbles_FUM", -2283 "fumbles_LOST", -2284 "fumbles_REC", -2285 ] -2286 ] -2287 -2288 elif filter_by_stat_category is True and stat_category == "defensive": -2289 final_df = final_df[ -2290 [ -2291 "season", -2292 "team_name", -2293 "team_conference", -2294 "player_id", -2295 "player_name", -2296 # DEFENSE -2297 "defensive_TOT", -2298 "defensive_SOLO", -2299 "defensive_TFL", -2300 "defensive_QB HUR", -2301 "defensive_SACKS", -2302 "defensive_PD", -2303 "defensive_TD", -2304 ] -2305 ] -2306 -2307 elif filter_by_stat_category is True and stat_category == "interceptions": -2308 final_df = final_df[ -2309 [ -2310 "season", -2311 "team_name", -2312 "team_conference", -2313 "player_id", -2314 "player_name", -2315 # INT -2316 "interceptions_INT", -2317 "interceptions_YDS", -2318 "interceptions_TD", -2319 ] -2320 ] -2321 -2322 elif filter_by_stat_category is True and stat_category == "punting": -2323 try: -2324 final_df = final_df.astype( -2325 { -2326 "punting_NO": "int", -2327 "punting_YDS": "int", -2328 } -2329 ) -2330 except Exception as e: -2331 logging.warning( -2332 "Could not reformat [punting_YDS] " -2333 + "and [punting_NO] into integers. " -2334 + f"Full Exception: {e}" -2335 ) -2336 -2337 final_df.loc[final_df["punting_NO"] > 0, "punting_AVG"] = ( -2338 final_df["punting_YDS"] / final_df["punting_NO"] -2339 ) -2340 -2341 final_df = final_df[ -2342 [ -2343 "season", -2344 "team_name", -2345 "team_conference", -2346 "player_id", -2347 "player_name", -2348 # PUNT -2349 "punting_NO", -2350 "punting_YDS", -2351 "punting_AVG", -2352 "punting_TB", -2353 "punting_In 20", -2354 "punting_LONG", -2355 ] -2356 ] -2357 -2358 elif filter_by_stat_category is True and stat_category == "kicking": -2359 try: -2360 final_df = final_df.astype( -2361 { -2362 "kicking_FGM": "int", -2363 "kicking_FGA": "int", -2364 "kicking_XPM": "int", -2365 "kicking_XPA": "int", -2366 } -2367 ) -2368 except Exception as e: -2369 logging.warning( -2370 "Could not reformat the following columns into integers.:" -2371 + "\n-[kicking_FGM]" -2372 + "\n-[kicking_FGA]" -2373 + "\n-[kicking_XPM]" -2374 + "\n-[kicking_XPA]" -2375 + f"\nFull Exception: {e}" -2376 ) -2377 -2378 final_df.loc[final_df["kicking_FGA"] > 0, "kicking_FG%"] = ( -2379 final_df["kicking_FGM"] / final_df["kicking_FGA"] -2380 ) -2381 -2382 final_df.loc[final_df["kicking_XPA"] > 0, "kicking_XP%"] = ( -2383 final_df["kicking_XPM"] / final_df["kicking_XPA"] -2384 ) -2385 -2386 final_df = final_df[ -2387 [ -2388 "season", -2389 "team_name", -2390 "team_conference", -2391 "player_id", -2392 "player_name", -2393 # KICK -2394 "kicking_FGM", -2395 "kicking_FGA", -2396 "kicking_FG%", -2397 "kicking_LONG", -2398 "kicking_XPM", -2399 "kicking_XPA" "kicking_XP%", -2400 ] -2401 ] +2168 final_df.loc[final_df["kickReturns_NO"] > 0, "kickReturns_AVG"] = ( +2169 final_df["kickReturns_YDS"] / final_df["kickReturns_NO"] +2170 ) +2171 final_df["kickReturns_AVG"] = final_df["kickReturns_AVG"].round(3) +2172 +2173 final_df.loc[final_df["puntReturns_NO"] > 0, "puntReturns_AVG"] = ( +2174 final_df["puntReturns_YDS"] / final_df["puntReturns_NO"] +2175 ) +2176 final_df["puntReturns_AVG"] = final_df["puntReturns_AVG"].round(3) +2177 +2178 elif filter_by_stat_category is True and stat_category == "passing": +2179 try: +2180 final_df = final_df.astype( +2181 { +2182 "passing_COMP": "int", +2183 "passing_ATT": "int", +2184 } +2185 ) +2186 except Exception as e: +2187 logging.warning( +2188 "Could not reformat [passing_COMP]" +2189 + " and [passing_ATT] into integers. " +2190 + f"Full Exception: {e}" +2191 ) +2192 +2193 final_df.loc[final_df["passing_ATT"] >= 1, "passing_COMP%"] = ( +2194 final_df["passing_COMP"] / final_df["passing_ATT"] +2195 ) +2196 +2197 final_df["passing_COMP%"] = final_df["passing_COMP%"].round(3) +2198 +2199 final_df = final_df[ +2200 [ +2201 "season", +2202 "team_name", +2203 "team_conference", +2204 "player_id", +2205 "player_name", +2206 # PASS +2207 "passing_COMP", +2208 "passing_ATT", +2209 "passing_YDS", +2210 "passing_TD", +2211 "passing_INT", +2212 ] +2213 ] +2214 +2215 elif filter_by_stat_category is True and stat_category == "rushing": +2216 try: +2217 final_df = final_df.astype( +2218 { +2219 "rushing_CAR": "int", +2220 "rushing_YDS": "int", +2221 } +2222 ) +2223 except Exception as e: +2224 logging.warning( +2225 "Could not reformat [rushing_CAR] " +2226 + "and [rushing_YDS] into integers. " +2227 + f"Full Exception: {e}" +2228 ) +2229 +2230 final_df.loc[final_df["rushing_CAR"] >= 1, "rushing_AVG"] = ( +2231 final_df["rushing_YDS"] / final_df["rushing_CAR"] +2232 ) +2233 final_df["rushing_AVG"] = final_df["rushing_AVG"].round(3) +2234 +2235 final_df = final_df[ +2236 [ +2237 "season", +2238 "team_name", +2239 "team_conference", +2240 "player_id", +2241 "player_name", +2242 # RUSH +2243 "rushing_CAR", +2244 "rushing_YDS", +2245 "rushing_AVG", +2246 "rushing_TD", +2247 "rushing_LONG", +2248 ] +2249 ] +2250 +2251 elif filter_by_stat_category is True and stat_category == "receiving": +2252 try: +2253 final_df = final_df.astype( +2254 { +2255 "receiving_REC": "int", +2256 "receiving_YDS": "int", +2257 } +2258 ) +2259 except Exception as e: +2260 logging.warning( +2261 "Could not reformat [receiving_REC] " +2262 + "and [receiving_YDS] into integers. " +2263 + f"Full Exception: {e}" +2264 ) +2265 +2266 final_df.loc[final_df["receiving_REC"] > 0, "receiving_AVG"] = ( +2267 final_df["receiving_YDS"] / final_df["receiving_REC"] +2268 ) +2269 final_df["receiving_AVG"] = final_df["receiving_AVG"].round(3) +2270 +2271 final_df = final_df[ +2272 [ +2273 "season", +2274 "team_name", +2275 "team_conference", +2276 "player_id", +2277 "player_name", +2278 # REC +2279 "receiving_REC", +2280 "receiving_YDS", +2281 "receiving_AVG", +2282 "receiving_TD", +2283 "receiving_LONG", +2284 ] +2285 ] +2286 +2287 elif filter_by_stat_category is True and stat_category == "fumbles": +2288 final_df = final_df[ +2289 [ +2290 "season", +2291 "team_name", +2292 "team_conference", +2293 "player_id", +2294 "player_name", +2295 # FUM +2296 "fumbles_FUM", +2297 "fumbles_LOST", +2298 "fumbles_REC", +2299 ] +2300 ] +2301 +2302 elif filter_by_stat_category is True and stat_category == "defensive": +2303 final_df = final_df[ +2304 [ +2305 "season", +2306 "team_name", +2307 "team_conference", +2308 "player_id", +2309 "player_name", +2310 # DEFENSE +2311 "defensive_TOT", +2312 "defensive_SOLO", +2313 "defensive_TFL", +2314 "defensive_QB HUR", +2315 "defensive_SACKS", +2316 "defensive_PD", +2317 "defensive_TD", +2318 ] +2319 ] +2320 +2321 elif filter_by_stat_category is True and stat_category == "interceptions": +2322 final_df = final_df[ +2323 [ +2324 "season", +2325 "team_name", +2326 "team_conference", +2327 "player_id", +2328 "player_name", +2329 # INT +2330 "interceptions_INT", +2331 "interceptions_YDS", +2332 "interceptions_TD", +2333 ] +2334 ] +2335 +2336 elif filter_by_stat_category is True and stat_category == "punting": +2337 try: +2338 final_df = final_df.astype( +2339 { +2340 "punting_NO": "int", +2341 "punting_YDS": "int", +2342 } +2343 ) +2344 except Exception as e: +2345 logging.warning( +2346 "Could not reformat [punting_YDS] " +2347 + "and [punting_NO] into integers. " +2348 + f"Full Exception: {e}" +2349 ) +2350 +2351 final_df.loc[final_df["punting_NO"] > 0, "punting_AVG"] = ( +2352 final_df["punting_YDS"] / final_df["punting_NO"] +2353 ) +2354 final_df["punting_AVG"] = final_df["punting_AVG"].round(3) +2355 +2356 final_df = final_df[ +2357 [ +2358 "season", +2359 "team_name", +2360 "team_conference", +2361 "player_id", +2362 "player_name", +2363 # PUNT +2364 "punting_NO", +2365 "punting_YDS", +2366 "punting_AVG", +2367 "punting_TB", +2368 "punting_In 20", +2369 "punting_LONG", +2370 ] +2371 ] +2372 +2373 elif filter_by_stat_category is True and stat_category == "kicking": +2374 try: +2375 final_df = final_df.astype( +2376 { +2377 "kicking_FGM": "int", +2378 "kicking_FGA": "int", +2379 "kicking_XPM": "int", +2380 "kicking_XPA": "int", +2381 } +2382 ) +2383 except Exception as e: +2384 logging.warning( +2385 "Could not reformat the following columns into integers.:" +2386 + "\n-[kicking_FGM]" +2387 + "\n-[kicking_FGA]" +2388 + "\n-[kicking_XPM]" +2389 + "\n-[kicking_XPA]" +2390 + f"\nFull Exception: {e}" +2391 ) +2392 +2393 final_df.loc[final_df["kicking_FGA"] > 0, "kicking_FG%"] = ( +2394 final_df["kicking_FGM"] / final_df["kicking_FGA"] +2395 ) +2396 final_df["kicking_FG%"] = final_df["kicking_FG%"].round(5) +2397 +2398 final_df.loc[final_df["kicking_XPA"] > 0, "kicking_XP%"] = ( +2399 final_df["kicking_XPM"] / final_df["kicking_XPA"] +2400 ) +2401 final_df["kicking_XP%"] = final_df["kicking_XP%"].round(5) 2402 -2403 elif filter_by_stat_category is True and stat_category == "kickReturns": -2404 try: -2405 final_df = final_df.astype( -2406 { -2407 "kickReturns_NO": "int", -2408 "kickReturns_YDS": "int", -2409 } -2410 ) -2411 except Exception as e: -2412 logging.warning( -2413 "Could not reformat [passing_COMP] " -2414 + "and [kickReturns_YDS] into integers. " -2415 + f"Full Exception: {e}" -2416 ) -2417 -2418 final_df.loc[final_df["kickReturns_NO"] > 0, "kickReturns_AVG"] = ( -2419 final_df["kickReturns_YDS"] / final_df["kickReturns_NO"] -2420 ) -2421 -2422 final_df = final_df[ -2423 [ -2424 "season", -2425 "team_name", -2426 "team_conference", -2427 "player_id", -2428 "player_name", -2429 # KR -2430 "kickReturns_NO", -2431 "kickReturns_YDS", -2432 "kickReturns_AVG", -2433 "kickReturns_TD", -2434 "kickReturns_LONG", -2435 ] -2436 ] -2437 -2438 elif filter_by_stat_category is True and stat_category == "puntReturns": -2439 try: -2440 final_df = final_df.astype( -2441 { -2442 "puntReturns_NO": "int", -2443 "puntReturns_YDS": "int", -2444 } -2445 ) -2446 except Exception as e: -2447 logging.warning( -2448 "Could not reformat [passing_COMP] " -2449 + "and [puntReturns_YDS] into integers." -2450 + f"Full Exception: {e}" -2451 ) -2452 -2453 final_df.loc[final_df["puntReturns_NO"] > 0, "puntReturns_AVG"] = ( -2454 final_df["puntReturns_YDS"] / final_df["puntReturns_NO"] -2455 ) -2456 -2457 final_df = final_df[ -2458 [ -2459 "season", -2460 "team_name", -2461 "team_conference", -2462 "player_id", -2463 "player_name", -2464 # KR -2465 "puntReturns_NO", -2466 "puntReturns_YDS", -2467 "puntReturns_AVG", -2468 "puntReturns_TD", -2469 "puntReturns_LONG", -2470 ] -2471 ] -2472 -2473 return final_df -2474 +2403 final_df = final_df[ +2404 [ +2405 "season", +2406 "team_name", +2407 "team_conference", +2408 "player_id", +2409 "player_name", +2410 # KICK +2411 "kicking_FGM", +2412 "kicking_FGA", +2413 "kicking_FG%", +2414 "kicking_LONG", +2415 "kicking_XPM", +2416 "kicking_XPA" "kicking_XP%", +2417 ] +2418 ] +2419 +2420 elif filter_by_stat_category is True and stat_category == "kickReturns": +2421 try: +2422 final_df = final_df.astype( +2423 { +2424 "kickReturns_NO": "int", +2425 "kickReturns_YDS": "int", +2426 } +2427 ) +2428 except Exception as e: +2429 logging.warning( +2430 "Could not reformat [passing_COMP] " +2431 + "and [kickReturns_YDS] into integers. " +2432 + f"Full Exception: {e}" +2433 ) +2434 +2435 final_df.loc[final_df["kickReturns_NO"] > 0, "kickReturns_AVG"] = ( +2436 final_df["kickReturns_YDS"] / final_df["kickReturns_NO"] +2437 ) +2438 final_df["kickReturns_AVG"] = final_df["kickReturns_AVG"].round(3) +2439 +2440 final_df = final_df[ +2441 [ +2442 "season", +2443 "team_name", +2444 "team_conference", +2445 "player_id", +2446 "player_name", +2447 # KR +2448 "kickReturns_NO", +2449 "kickReturns_YDS", +2450 "kickReturns_AVG", +2451 "kickReturns_TD", +2452 "kickReturns_LONG", +2453 ] +2454 ] +2455 +2456 elif filter_by_stat_category is True and stat_category == "puntReturns": +2457 try: +2458 final_df = final_df.astype( +2459 { +2460 "puntReturns_NO": "int", +2461 "puntReturns_YDS": "int", +2462 } +2463 ) +2464 except Exception as e: +2465 logging.warning( +2466 "Could not reformat [passing_COMP] " +2467 + "and [puntReturns_YDS] into integers." +2468 + f"Full Exception: {e}" +2469 ) +2470 +2471 final_df.loc[final_df["puntReturns_NO"] > 0, "puntReturns_AVG"] = ( +2472 final_df["puntReturns_YDS"] / final_df["puntReturns_NO"] +2473 ) +2474 final_df["puntReturns_AVG"] = final_df["puntReturns_AVG"].round(3) 2475 -2476def get_cfbd_transfer_portal_data( -2477 season: int, -2478 api_key: str = None, -2479 api_key_dir: str = None, -2480 return_as_dict: bool = False, -2481): -2482 """ -2483 Get player usage data -2484 (A.K.A., the percentages for how often a player touched the ball), -2485 for a given season, from the CFBD API. -2486 -2487 Parameters -2488 ---------- -2489 `season` (int, mandatory): -2490 Required argument. -2491 Specifies the season you want CFB transfer portal data from. -2492 This must be specified, otherwise this package, and by extension -2493 the CFBD API, will not accept -2494 the request to get CFB transfer portal data stats. -2495 -2496 `api_key` (str, optional): -2497 Semi-optional argument. -2498 If `api_key` is null, this function will attempt to load a CFBD API key -2499 from the python environment, or from a file on this computer. -2500 If `api_key` is not null, -2501 this function will automatically assume that the -2502 inputted `api_key` is a valid CFBD API key. -2503 -2504 `api_key_dir` (str, optional): -2505 Optional argument. -2506 If `api_key` is set to am empty string, this variable is ignored. -2507 If `api_key_dir` is null, and `api_key` is null, -2508 this function will try to find -2509 a CFBD API key file in this user's home directory. -2510 If `api_key_dir` is set to a string, and `api_key` is null, -2511 this function will assume that `api_key_dir` is a directory, -2512 and will try to find a CFBD API key file in that directory. -2513 -2514 `return_as_dict` (bool, semi-optional): -2515 Semi-optional argument. -2516 If you want this function to return -2517 the data as a dictionary (read: JSON object), -2518 instead of a pandas `DataFrame` object, -2519 set `return_as_dict` to `True`. -2520 -2521 Usage -2522 ---------- -2523 ``` -2524 import time -2525 -2526 from cfbd_json_py.players import get_cfbd_transfer_portal_data -2527 -2528 -2529 cfbd_key = "tigersAreAwesome" # placeholder for your CFBD API Key. -2530 -2531 if cfbd_key != "tigersAreAwesome": -2532 print( -2533 "Using the user's API key declared in this script " + -2534 "for this example." -2535 ) -2536 -2537 # Get Transfer Portal data for the 2021 CFB season. -2538 print("Get Transfer Portal data for the 2021 CFB season.") -2539 json_data = get_cfbd_transfer_portal_data( -2540 api_key=cfbd_key, -2541 season=2021 -2542 ) -2543 print(json_data) -2544 time.sleep(5) -2545 -2546 # You can also tell this function to just return the API call as -2547 # a Dictionary (read: JSON) object. -2548 print( -2549 "You can also tell this function to just return the API call " + -2550 "as a Dictionary (read: JSON) object." -2551 ) -2552 json_data = get_cfbd_transfer_portal_data( -2553 api_key=cfbd_key, -2554 season=2021, -2555 return_as_dict=True -2556 ) -2557 print(json_data) -2558 -2559 else: -2560 # Alternatively, if the CFBD API key exists in this python environment, -2561 # or it's been set by cfbd_json_py.utls.set_cfbd_api_token(), -2562 # you could just call these functions directly, -2563 # without setting the API key in the script. -2564 print( -2565 "Using the user's API key supposedly loaded " + -2566 "into this python environment for this example." -2567 ) -2568 -2569 # Get Transfer Portal data for the 2021 CFB season. -2570 print("Get Transfer Portal data for the 2021 CFB season.") +2476 final_df = final_df[ +2477 [ +2478 "season", +2479 "team_name", +2480 "team_conference", +2481 "player_id", +2482 "player_name", +2483 # KR +2484 "puntReturns_NO", +2485 "puntReturns_YDS", +2486 "puntReturns_AVG", +2487 "puntReturns_TD", +2488 "puntReturns_LONG", +2489 ] +2490 ] +2491 +2492 return final_df +2493 +2494 +2495def get_cfbd_transfer_portal_data( +2496 season: int, +2497 api_key: str = None, +2498 api_key_dir: str = None, +2499 return_as_dict: bool = False, +2500): +2501 """ +2502 Get player usage data +2503 (A.K.A., the percentages for how often a player touched the ball), +2504 for a given season, from the CFBD API. +2505 +2506 Parameters +2507 ---------- +2508 `season` (int, mandatory): +2509 Required argument. +2510 Specifies the season you want CFB transfer portal data from. +2511 This must be specified, otherwise this package, and by extension +2512 the CFBD API, will not accept +2513 the request to get CFB transfer portal data stats. +2514 +2515 `api_key` (str, optional): +2516 Semi-optional argument. +2517 If `api_key` is null, this function will attempt to load a CFBD API key +2518 from the python environment, or from a file on this computer. +2519 If `api_key` is not null, +2520 this function will automatically assume that the +2521 inputted `api_key` is a valid CFBD API key. +2522 +2523 `api_key_dir` (str, optional): +2524 Optional argument. +2525 If `api_key` is set to am empty string, this variable is ignored. +2526 If `api_key_dir` is null, and `api_key` is null, +2527 this function will try to find +2528 a CFBD API key file in this user's home directory. +2529 If `api_key_dir` is set to a string, and `api_key` is null, +2530 this function will assume that `api_key_dir` is a directory, +2531 and will try to find a CFBD API key file in that directory. +2532 +2533 `return_as_dict` (bool, semi-optional): +2534 Semi-optional argument. +2535 If you want this function to return +2536 the data as a dictionary (read: JSON object), +2537 instead of a pandas `DataFrame` object, +2538 set `return_as_dict` to `True`. +2539 +2540 Usage +2541 ---------- +2542 ``` +2543 import time +2544 +2545 from cfbd_json_py.players import get_cfbd_transfer_portal_data +2546 +2547 +2548 cfbd_key = "tigersAreAwesome" # placeholder for your CFBD API Key. +2549 +2550 if cfbd_key != "tigersAreAwesome": +2551 print( +2552 "Using the user's API key declared in this script " + +2553 "for this example." +2554 ) +2555 +2556 # Get Transfer Portal data for the 2021 CFB season. +2557 print("Get Transfer Portal data for the 2021 CFB season.") +2558 json_data = get_cfbd_transfer_portal_data( +2559 api_key=cfbd_key, +2560 season=2021 +2561 ) +2562 print(json_data) +2563 time.sleep(5) +2564 +2565 # You can also tell this function to just return the API call as +2566 # a Dictionary (read: JSON) object. +2567 print( +2568 "You can also tell this function to just return the API call " + +2569 "as a Dictionary (read: JSON) object." +2570 ) 2571 json_data = get_cfbd_transfer_portal_data( -2572 season=2021 -2573 ) -2574 print(json_data) -2575 time.sleep(5) -2576 -2577 # You can also tell this function to just return the API call as -2578 # a Dictionary (read: JSON) object. -2579 print( -2580 "You can also tell this function to just return the API call " + -2581 "as a Dictionary (read: JSON) object." -2582 ) -2583 json_data = get_cfbd_transfer_portal_data( -2584 season=2021, -2585 return_as_dict=True +2572 api_key=cfbd_key, +2573 season=2021, +2574 return_as_dict=True +2575 ) +2576 print(json_data) +2577 +2578 else: +2579 # Alternatively, if the CFBD API key exists in this python environment, +2580 # or it's been set by cfbd_json_py.utls.set_cfbd_api_token(), +2581 # you could just call these functions directly, +2582 # without setting the API key in the script. +2583 print( +2584 "Using the user's API key supposedly loaded " + +2585 "into this python environment for this example." 2586 ) -2587 print(json_data) -2588 -2589 ``` -2590 Returns -2591 ---------- -2592 A pandas `DataFrame` object with transfer portal data, -2593 or (if `return_as_dict` is set to `True`) -2594 a dictionary object with transfer portal data. +2587 +2588 # Get Transfer Portal data for the 2021 CFB season. +2589 print("Get Transfer Portal data for the 2021 CFB season.") +2590 json_data = get_cfbd_transfer_portal_data( +2591 season=2021 +2592 ) +2593 print(json_data) +2594 time.sleep(5) 2595 -2596 """ -2597 now = datetime.now() -2598 url = "https://api.collegefootballdata.com/player/portal" -2599 -2600 portal_df = pd.DataFrame() -2601 # row_df = pd.DataFrame() -2602 -2603 if api_key is not None: -2604 real_api_key = api_key -2605 del api_key -2606 else: -2607 real_api_key = get_cfbd_api_token(api_key_dir=api_key_dir) -2608 -2609 if real_api_key == "tigersAreAwesome": -2610 raise ValueError( -2611 "You actually need to change `cfbd_key` to your CFBD API key." -2612 ) -2613 elif "Bearer " in real_api_key: -2614 pass -2615 elif "Bearer" in real_api_key: -2616 real_api_key = real_api_key.replace("Bearer", "Bearer ") -2617 else: -2618 real_api_key = "Bearer " + real_api_key -2619 -2620 if season is None: -2621 # This should never happen without user tampering, but if it does, -2622 # we need to raise an error, -2623 # because the CFBD API will refuse this call without a valid season. -2624 raise SystemError( -2625 "I don't know how, I don't know why, " -2626 + "but you managed to call this function " -2627 + "while `season` was `None` (NULL)," -2628 + " and the function got to this point in the code." -2629 + "\nIf you have a GitHub account, " -2630 + "please raise an issue on this python package's GitHub page:\n" -2631 + "https://github.com/armstjc/cfbd-json-py/issues" -2632 ) -2633 elif season > (now.year + 1): -2634 raise ValueError(f"`season` cannot be greater than {season}.") -2635 elif season < 2017: -2636 raise ValueError(f"Transfer portal wasn't really a thing in {season}.") -2637 -2638 # URL builder -2639 ########################################################################## -2640 -2641 # required by API -2642 url += f"?year={season}" -2643 -2644 headers = { -2645 "Authorization": f"{real_api_key}", -2646 "accept": "application/json" -2647 } -2648 -2649 response = requests.get(url, headers=headers) -2650 -2651 if response.status_code == 200: -2652 pass -2653 elif response.status_code == 401: -2654 raise ConnectionRefusedError( -2655 "Could not connect. The connection was refused." + -2656 "\nHTTP Status Code 401." -2657 ) -2658 else: -2659 raise ConnectionError( -2660 f"Could not connect.\nHTTP Status code {response.status_code}" -2661 ) +2596 # You can also tell this function to just return the API call as +2597 # a Dictionary (read: JSON) object. +2598 print( +2599 "You can also tell this function to just return the API call " + +2600 "as a Dictionary (read: JSON) object." +2601 ) +2602 json_data = get_cfbd_transfer_portal_data( +2603 season=2021, +2604 return_as_dict=True +2605 ) +2606 print(json_data) +2607 +2608 ``` +2609 Returns +2610 ---------- +2611 A pandas `DataFrame` object with transfer portal data, +2612 or (if `return_as_dict` is set to `True`) +2613 a dictionary object with transfer portal data. +2614 +2615 """ +2616 now = datetime.now() +2617 url = "https://api.collegefootballdata.com/player/portal" +2618 +2619 portal_df = pd.DataFrame() +2620 # row_df = pd.DataFrame() +2621 +2622 if api_key is not None: +2623 real_api_key = api_key +2624 del api_key +2625 else: +2626 real_api_key = get_cfbd_api_token(api_key_dir=api_key_dir) +2627 +2628 if real_api_key == "tigersAreAwesome": +2629 raise ValueError( +2630 "You actually need to change `cfbd_key` to your CFBD API key." +2631 ) +2632 elif "Bearer " in real_api_key: +2633 pass +2634 elif "Bearer" in real_api_key: +2635 real_api_key = real_api_key.replace("Bearer", "Bearer ") +2636 else: +2637 real_api_key = "Bearer " + real_api_key +2638 +2639 if season is None: +2640 # This should never happen without user tampering, but if it does, +2641 # we need to raise an error, +2642 # because the CFBD API will refuse this call without a valid season. +2643 raise SystemError( +2644 "I don't know how, I don't know why, " +2645 + "but you managed to call this function " +2646 + "while `season` was `None` (NULL)," +2647 + " and the function got to this point in the code." +2648 + "\nIf you have a GitHub account, " +2649 + "please raise an issue on this python package's GitHub page:\n" +2650 + "https://github.com/armstjc/cfbd-json-py/issues" +2651 ) +2652 elif season > (now.year + 1): +2653 raise ValueError(f"`season` cannot be greater than {season}.") +2654 elif season < 2017: +2655 raise ValueError(f"Transfer portal wasn't really a thing in {season}.") +2656 +2657 # URL builder +2658 ########################################################################## +2659 +2660 # required by API +2661 url += f"?year={season}" 2662 -2663 json_data = response.json() -2664 -2665 if return_as_dict is True: -2666 return json_data +2663 headers = { +2664 "Authorization": f"{real_api_key}", +2665 "accept": "application/json" +2666 } 2667 -2668 portal_df = pd.json_normalize(json_data) -2669 portal_df.rename( -2670 columns={ -2671 "firstName": "first_name", -2672 "lastName": "last_name", -2673 "position": "position_abv", -2674 "origin": "origin_team", -2675 "destination": "destination_team", -2676 "transferDate": "transfer_date", -2677 "rating": "rating", -2678 "stars": "stars", -2679 "eligibility": "eligibility", -2680 }, -2681 inplace=True, -2682 ) -2683 return portal_df +2668 response = requests.get(url, headers=headers) +2669 +2670 if response.status_code == 200: +2671 pass +2672 elif response.status_code == 401: +2673 raise ConnectionRefusedError( +2674 "Could not connect. The connection was refused." + +2675 "\nHTTP Status Code 401." +2676 ) +2677 else: +2678 raise ConnectionError( +2679 f"Could not connect.\nHTTP Status code {response.status_code}" +2680 ) +2681 +2682 json_data = response.json() +2683 +2684 if return_as_dict is True: +2685 return json_data +2686 +2687 portal_df = pd.json_normalize(json_data) +2688 portal_df.rename( +2689 columns={ +2690 "firstName": "first_name", +2691 "lastName": "last_name", +2692 "position": "position_abv", +2693 "origin": "origin_team", +2694 "destination": "destination_team", +2695 "transferDate": "transfer_date", +2696 "rating": "rating", +2697 "stars": "stars", +2698 "eligibility": "eligibility", +2699 }, +2700 inplace=True, +2701 ) +2702 return portal_df @@ -5281,54 +5300,53 @@

Returns

783 784 if player_id is not None: 785 url += f"&playerId={player_id}" -786 # print() -787 if exclude_garbage_time is not None: -788 url += f"&excludeGarbageTime={gt_str}" -789 -790 headers = { -791 "Authorization": f"{real_api_key}", -792 "accept": "application/json" -793 } -794 -795 response = requests.get(url, headers=headers) -796 -797 if response.status_code == 200: -798 pass -799 elif response.status_code == 401: -800 raise ConnectionRefusedError( -801 "Could not connect. The connection was refused." + -802 "\nHTTP Status Code 401." -803 ) -804 else: -805 raise ConnectionError( -806 f"Could not connect.\nHTTP Status code {response.status_code}" -807 ) -808 -809 json_data = response.json() -810 -811 if return_as_dict is True: -812 return json_data -813 -814 players_df = pd.json_normalize(json_data) -815 players_df.rename( -816 columns={ -817 "id": "player_id", -818 "name": "player_name", -819 "position": "position_abv", -820 "team": "team_name", -821 "conference": "conference_name", -822 "usage.overall": "usage_overall", -823 "usage.pass": "usage_pass", -824 "usage.rush": "usage_rush", -825 "usage.firstDown": "usage_first_down", -826 "usage.secondDown": "usage_second_down", -827 "usage.thirdDown": "usage_third_down", -828 "usage.standardDowns": "usage_standard_downs", -829 "usage.passingDowns": "usage_passing_downs", -830 }, -831 inplace=True, -832 ) -833 return players_df +786 if exclude_garbage_time is not None: +787 url += f"&excludeGarbageTime={gt_str}" +788 +789 headers = { +790 "Authorization": f"{real_api_key}", +791 "accept": "application/json" +792 } +793 +794 response = requests.get(url, headers=headers) +795 +796 if response.status_code == 200: +797 pass +798 elif response.status_code == 401: +799 raise ConnectionRefusedError( +800 "Could not connect. The connection was refused." + +801 "\nHTTP Status Code 401." +802 ) +803 else: +804 raise ConnectionError( +805 f"Could not connect.\nHTTP Status code {response.status_code}" +806 ) +807 +808 json_data = response.json() +809 +810 if return_as_dict is True: +811 return json_data +812 +813 players_df = pd.json_normalize(json_data) +814 players_df.rename( +815 columns={ +816 "id": "player_id", +817 "name": "player_name", +818 "position": "position_abv", +819 "team": "team_name", +820 "conference": "conference_name", +821 "usage.overall": "usage_overall", +822 "usage.pass": "usage_pass", +823 "usage.rush": "usage_rush", +824 "usage.firstDown": "usage_first_down", +825 "usage.secondDown": "usage_second_down", +826 "usage.thirdDown": "usage_third_down", +827 "usage.standardDowns": "usage_standard_downs", +828 "usage.passingDowns": "usage_passing_downs", +829 }, +830 inplace=True, +831 ) +832 return players_df @@ -5678,344 +5696,344 @@

Returns

-
 836def get_cfbd_returning_production(
- 837    api_key: str = None,
- 838    api_key_dir: str = None,
- 839    season: int = None,
- 840    team: str = None,
- 841    # `season` or `team` must be specified.
- 842    conference: str = None,
- 843    return_as_dict: bool = False,
- 844):
- 845    """
- 846    Get data from the CFBD API
- 847    on how much returning production a team has going into a CFB season.
- 848
- 849    Parameters
- 850    ----------
- 851
- 852    `api_key` (str, optional):
- 853        Semi-optional argument.
- 854        If `api_key` is null, this function will attempt to load a CFBD API key
- 855        from the python environment, or from a file on this computer.
- 856        If `api_key` is not null,
- 857        this function will automatically assume that the
- 858        inputted `api_key` is a valid CFBD API key.
- 859
- 860    `api_key_dir` (str, optional):
- 861        Optional argument.
- 862        If `api_key` is set to am empty string, this variable is ignored.
- 863        If `api_key_dir` is null, and `api_key` is null,
- 864        this function will try to find
- 865        a CFBD API key file in this user's home directory.
- 866        If `api_key_dir` is set to a string, and `api_key` is null,
- 867        this function will assume that `api_key_dir` is a directory,
- 868        and will try to find a CFBD API key file in that directory.
- 869
- 870    `season` (int, optional):
- 871        Semi-optional argument.
- 872        Specifies the season you want team PPA data from.
- 873        You MUST set `season` or `team` to a non-null value for
- 874        this function to work. If you don't, a `ValueError()`
- 875        will be raised.
- 876
- 877    `team` (str, optional):
- 878        Semi-optional argument.
- 879        If you only want team PPA data for a specific team,
- 880        set `team` to the name of the team you want team PPA data from.
- 881        You MUST set `season` or `team` to a non-null value for
- 882        this function to work. If you don't, a `ValueError()`
- 883        will be raised.
- 884
- 885    `conference` (str, optional):
- 886        Optional argument.
- 887        If you only want team PPA data from games
- 888        involving teams from a specific conference,
- 889        set `conference` to the abbreviation
- 890        of the conference you want team PPA data from.
- 891        For a list of conferences,
- 892        use the `cfbd_json_py.conferences.get_cfbd_conference_info()`
- 893        function.
- 894
- 895    `return_as_dict` (bool, semi-optional):
- 896        Semi-optional argument.
- 897        If you want this function to return
- 898        the data as a dictionary (read: JSON object),
- 899        instead of a pandas `DataFrame` object,
- 900        set `return_as_dict` to `True`.
- 901
- 902    Usage
- 903    ----------
- 904    ```
- 905    import time
- 906
- 907    from cfbd_json_py.players import get_cfbd_returning_production
+                
 835def get_cfbd_returning_production(
+ 836    api_key: str = None,
+ 837    api_key_dir: str = None,
+ 838    season: int = None,
+ 839    team: str = None,
+ 840    # `season` or `team` must be specified.
+ 841    conference: str = None,
+ 842    return_as_dict: bool = False,
+ 843):
+ 844    """
+ 845    Get data from the CFBD API
+ 846    on how much returning production a team has going into a CFB season.
+ 847
+ 848    Parameters
+ 849    ----------
+ 850
+ 851    `api_key` (str, optional):
+ 852        Semi-optional argument.
+ 853        If `api_key` is null, this function will attempt to load a CFBD API key
+ 854        from the python environment, or from a file on this computer.
+ 855        If `api_key` is not null,
+ 856        this function will automatically assume that the
+ 857        inputted `api_key` is a valid CFBD API key.
+ 858
+ 859    `api_key_dir` (str, optional):
+ 860        Optional argument.
+ 861        If `api_key` is set to am empty string, this variable is ignored.
+ 862        If `api_key_dir` is null, and `api_key` is null,
+ 863        this function will try to find
+ 864        a CFBD API key file in this user's home directory.
+ 865        If `api_key_dir` is set to a string, and `api_key` is null,
+ 866        this function will assume that `api_key_dir` is a directory,
+ 867        and will try to find a CFBD API key file in that directory.
+ 868
+ 869    `season` (int, optional):
+ 870        Semi-optional argument.
+ 871        Specifies the season you want team PPA data from.
+ 872        You MUST set `season` or `team` to a non-null value for
+ 873        this function to work. If you don't, a `ValueError()`
+ 874        will be raised.
+ 875
+ 876    `team` (str, optional):
+ 877        Semi-optional argument.
+ 878        If you only want team PPA data for a specific team,
+ 879        set `team` to the name of the team you want team PPA data from.
+ 880        You MUST set `season` or `team` to a non-null value for
+ 881        this function to work. If you don't, a `ValueError()`
+ 882        will be raised.
+ 883
+ 884    `conference` (str, optional):
+ 885        Optional argument.
+ 886        If you only want team PPA data from games
+ 887        involving teams from a specific conference,
+ 888        set `conference` to the abbreviation
+ 889        of the conference you want team PPA data from.
+ 890        For a list of conferences,
+ 891        use the `cfbd_json_py.conferences.get_cfbd_conference_info()`
+ 892        function.
+ 893
+ 894    `return_as_dict` (bool, semi-optional):
+ 895        Semi-optional argument.
+ 896        If you want this function to return
+ 897        the data as a dictionary (read: JSON object),
+ 898        instead of a pandas `DataFrame` object,
+ 899        set `return_as_dict` to `True`.
+ 900
+ 901    Usage
+ 902    ----------
+ 903    ```
+ 904    import time
+ 905
+ 906    from cfbd_json_py.players import get_cfbd_returning_production
+ 907
  908
- 909
- 910    cfbd_key = "tigersAreAwesome"  # placeholder for your CFBD API Key.
- 911
- 912    if cfbd_key != "tigersAreAwesome":
- 913        print(
- 914            "Using the user's API key declared in this script " +
- 915            "for this example."
- 916        )
- 917
- 918        # Get returning production
- 919        # for teams who competed in the 2020 CFB season.
- 920        print(
- 921            "Get returning production for teams " +
- 922            "who competed in the 2020 CFB season."
- 923        )
- 924        json_data = get_cfbd_returning_production(
- 925            api_key=cfbd_key,
- 926            season=2020
- 927        )
- 928        print(json_data)
- 929        time.sleep(5)
- 930
- 931        # Get historical returning production
- 932        # for the Ohio Bobcats Football Team.
- 933        print(
- 934            "Get historical returning production " +
- 935            "for the Ohio Bobcats Football Team."
- 936        )
- 937        json_data = get_cfbd_returning_production(
- 938            api_key=cfbd_key,
- 939            team="Ohio"
- 940        )
- 941        print(json_data)
- 942        time.sleep(5)
- 943
- 944        # Get returning production for the 2019 LSU Tigers.
- 945        print("Get returning production for the 2019 LSU Tigers.")
- 946        json_data = get_cfbd_returning_production(
- 947            api_key=cfbd_key,
- 948            season=2019,
- 949            team="LSU"
- 950        )
- 951        print(json_data)
- 952        time.sleep(5)
- 953
- 954        # Get returning production for Maryland,
- 955        # for seasons where Maryland is a member
- 956        # of the Big 10 (B1G) Conference.
- 957        print(
- 958            "Get returning production for Maryland, " +
- 959            "for seasons where Maryland is a member " +
- 960            "of the Big 10 (B1G) Conference."
- 961        )
- 962        json_data = get_cfbd_returning_production(
- 963            api_key=cfbd_key,
- 964            team="Maryland",
- 965            conference="B1G"
- 966        )
- 967        print(json_data)
- 968        time.sleep(5)
- 969
- 970        # You can also tell this function to just return the API call as
- 971        # a Dictionary (read: JSON) object.
- 972        print(
- 973            "You can also tell this function to just return the API call " +
- 974            "as a Dictionary (read: JSON) object."
- 975        )
- 976        json_data = get_cfbd_returning_production(
- 977            api_key=cfbd_key,
- 978            season=2020,
- 979            team="LSU",
- 980            return_as_dict=True
- 981        )
- 982        print(json_data)
- 983
- 984    else:
- 985        # Alternatively, if the CFBD API key exists in this python environment,
- 986        # or it's been set by cfbd_json_py.utls.set_cfbd_api_token(),
- 987        # you could just call these functions directly,
- 988        # without setting the API key in the script.
- 989        print(
- 990            "Using the user's API key supposedly loaded " +
- 991            "into this python environment for this example."
- 992        )
- 993
- 994        # Get returning production
- 995        # for teams who competed in the 2020 CFB season.
- 996        print(
- 997            "Get returning production for teams " +
- 998            "who competed in the 2020 CFB season."
- 999        )
-1000        json_data = get_cfbd_returning_production(
-1001            season=2020
-1002        )
-1003        print(json_data)
-1004        time.sleep(5)
-1005
-1006        # Get historical returning production
-1007        # for the Ohio Bobcats Football Team.
-1008        print(
-1009            "Get historical returning production " +
-1010            "for the Ohio Bobcats Football Team."
-1011        )
-1012        json_data = get_cfbd_returning_production(
-1013            team="Ohio"
-1014        )
-1015        print(json_data)
-1016        time.sleep(5)
-1017
-1018        # Get returning production for the 2019 LSU Tigers.
-1019        print("Get returning production for the 2019 LSU Tigers.")
-1020        json_data = get_cfbd_returning_production(
-1021            season=2019,
-1022            team="LSU"
-1023        )
-1024        print(json_data)
-1025        time.sleep(5)
-1026
-1027        # Get returning production for Maryland,
-1028        # for seasons where Maryland is a member
-1029        # of the Big 10 (B1G) Conference.
-1030        print(
-1031            "Get returning production for Maryland, " +
-1032            "for seasons where Maryland is a member " +
-1033            "of the Big 10 (B1G) Conference."
-1034        )
-1035        json_data = get_cfbd_returning_production(
-1036            team="Maryland",
-1037            conference="B1G"
-1038        )
-1039        print(json_data)
-1040        time.sleep(5)
-1041
-1042        # You can also tell this function to just return the API call as
-1043        # a Dictionary (read: JSON) object.
-1044        print(
-1045            "You can also tell this function to just return the API call " +
-1046            "as a Dictionary (read: JSON) object."
-1047        )
-1048        json_data = get_cfbd_returning_production(
-1049            season=2020,
-1050            team="LSU",
-1051            return_as_dict=True
-1052        )
-1053        print(json_data)
+ 909    cfbd_key = "tigersAreAwesome"  # placeholder for your CFBD API Key.
+ 910
+ 911    if cfbd_key != "tigersAreAwesome":
+ 912        print(
+ 913            "Using the user's API key declared in this script " +
+ 914            "for this example."
+ 915        )
+ 916
+ 917        # Get returning production
+ 918        # for teams who competed in the 2020 CFB season.
+ 919        print(
+ 920            "Get returning production for teams " +
+ 921            "who competed in the 2020 CFB season."
+ 922        )
+ 923        json_data = get_cfbd_returning_production(
+ 924            api_key=cfbd_key,
+ 925            season=2020
+ 926        )
+ 927        print(json_data)
+ 928        time.sleep(5)
+ 929
+ 930        # Get historical returning production
+ 931        # for the Ohio Bobcats Football Team.
+ 932        print(
+ 933            "Get historical returning production " +
+ 934            "for the Ohio Bobcats Football Team."
+ 935        )
+ 936        json_data = get_cfbd_returning_production(
+ 937            api_key=cfbd_key,
+ 938            team="Ohio"
+ 939        )
+ 940        print(json_data)
+ 941        time.sleep(5)
+ 942
+ 943        # Get returning production for the 2019 LSU Tigers.
+ 944        print("Get returning production for the 2019 LSU Tigers.")
+ 945        json_data = get_cfbd_returning_production(
+ 946            api_key=cfbd_key,
+ 947            season=2019,
+ 948            team="LSU"
+ 949        )
+ 950        print(json_data)
+ 951        time.sleep(5)
+ 952
+ 953        # Get returning production for Maryland,
+ 954        # for seasons where Maryland is a member
+ 955        # of the Big 10 (B1G) Conference.
+ 956        print(
+ 957            "Get returning production for Maryland, " +
+ 958            "for seasons where Maryland is a member " +
+ 959            "of the Big 10 (B1G) Conference."
+ 960        )
+ 961        json_data = get_cfbd_returning_production(
+ 962            api_key=cfbd_key,
+ 963            team="Maryland",
+ 964            conference="B1G"
+ 965        )
+ 966        print(json_data)
+ 967        time.sleep(5)
+ 968
+ 969        # You can also tell this function to just return the API call as
+ 970        # a Dictionary (read: JSON) object.
+ 971        print(
+ 972            "You can also tell this function to just return the API call " +
+ 973            "as a Dictionary (read: JSON) object."
+ 974        )
+ 975        json_data = get_cfbd_returning_production(
+ 976            api_key=cfbd_key,
+ 977            season=2020,
+ 978            team="LSU",
+ 979            return_as_dict=True
+ 980        )
+ 981        print(json_data)
+ 982
+ 983    else:
+ 984        # Alternatively, if the CFBD API key exists in this python environment,
+ 985        # or it's been set by cfbd_json_py.utls.set_cfbd_api_token(),
+ 986        # you could just call these functions directly,
+ 987        # without setting the API key in the script.
+ 988        print(
+ 989            "Using the user's API key supposedly loaded " +
+ 990            "into this python environment for this example."
+ 991        )
+ 992
+ 993        # Get returning production
+ 994        # for teams who competed in the 2020 CFB season.
+ 995        print(
+ 996            "Get returning production for teams " +
+ 997            "who competed in the 2020 CFB season."
+ 998        )
+ 999        json_data = get_cfbd_returning_production(
+1000            season=2020
+1001        )
+1002        print(json_data)
+1003        time.sleep(5)
+1004
+1005        # Get historical returning production
+1006        # for the Ohio Bobcats Football Team.
+1007        print(
+1008            "Get historical returning production " +
+1009            "for the Ohio Bobcats Football Team."
+1010        )
+1011        json_data = get_cfbd_returning_production(
+1012            team="Ohio"
+1013        )
+1014        print(json_data)
+1015        time.sleep(5)
+1016
+1017        # Get returning production for the 2019 LSU Tigers.
+1018        print("Get returning production for the 2019 LSU Tigers.")
+1019        json_data = get_cfbd_returning_production(
+1020            season=2019,
+1021            team="LSU"
+1022        )
+1023        print(json_data)
+1024        time.sleep(5)
+1025
+1026        # Get returning production for Maryland,
+1027        # for seasons where Maryland is a member
+1028        # of the Big 10 (B1G) Conference.
+1029        print(
+1030            "Get returning production for Maryland, " +
+1031            "for seasons where Maryland is a member " +
+1032            "of the Big 10 (B1G) Conference."
+1033        )
+1034        json_data = get_cfbd_returning_production(
+1035            team="Maryland",
+1036            conference="B1G"
+1037        )
+1038        print(json_data)
+1039        time.sleep(5)
+1040
+1041        # You can also tell this function to just return the API call as
+1042        # a Dictionary (read: JSON) object.
+1043        print(
+1044            "You can also tell this function to just return the API call " +
+1045            "as a Dictionary (read: JSON) object."
+1046        )
+1047        json_data = get_cfbd_returning_production(
+1048            season=2020,
+1049            team="LSU",
+1050            return_as_dict=True
+1051        )
+1052        print(json_data)
+1053
 1054
-1055
-1056    ```
-1057    Returns
-1058    ----------
-1059    A pandas `DataFrame` object with returning production data,
-1060    or (if `return_as_dict` is set to `True`)
-1061    a dictionary object with returning production data.
-1062
-1063    """
-1064    now = datetime.now()
-1065    team_df = pd.DataFrame()
-1066    # row_df = pd.DataFrame()
-1067    url = "https://api.collegefootballdata.com/player/returning"
-1068
-1069    ##########################################################################
-1070
-1071    if api_key is not None:
-1072        real_api_key = api_key
-1073        del api_key
-1074    else:
-1075        real_api_key = get_cfbd_api_token(api_key_dir=api_key_dir)
-1076
-1077    if real_api_key == "tigersAreAwesome":
-1078        raise ValueError(
-1079            "You actually need to change `cfbd_key` to your CFBD API key."
-1080        )
-1081    elif "Bearer " in real_api_key:
-1082        pass
-1083    elif "Bearer" in real_api_key:
-1084        real_api_key = real_api_key.replace("Bearer", "Bearer ")
-1085    else:
-1086        real_api_key = "Bearer " + real_api_key
-1087
-1088    if season is None and team is None:
-1089        raise ValueError(
-1090            "To use this function, `season` and/or `team` must be set to a "
-1091            + "non-null variable."
-1092        )
-1093
-1094    if season is None:
-1095        # Rare, but in this endpoint,
-1096        # you don't need to input the season.
-1097        pass
-1098    elif season > (now.year + 1):
-1099        raise ValueError(f"`season` cannot be greater than {season}.")
-1100    elif season < 1869:
-1101        raise ValueError("`season` cannot be less than 1869.")
-1102
-1103    # URL Builder
-1104    ##########################################################################
-1105
-1106    url_elements = 0
-1107
-1108    if season is not None and url_elements == 0:
-1109        url += f"?year={season}"
-1110        url_elements += 1
-1111    elif season is not None:
-1112        url += f"&year={season}"
-1113        url_elements += 1
-1114
-1115    if team is not None and url_elements == 0:
-1116        url += f"?team={team}"
-1117        url_elements += 1
-1118    elif team is not None:
-1119        url += f"&team={team}"
-1120        url_elements += 1
-1121
-1122    if conference is not None and url_elements == 0:
-1123        url += f"?conference={conference}"
-1124        url_elements += 1
-1125    elif conference is not None:
-1126        url += f"&conference={conference}"
-1127        url_elements += 1
-1128
-1129    headers = {
-1130        "Authorization": f"{real_api_key}",
-1131        "accept": "application/json"
-1132    }
-1133
-1134    response = requests.get(url, headers=headers)
-1135
-1136    if response.status_code == 200:
-1137        pass
-1138    elif response.status_code == 401:
-1139        raise ConnectionRefusedError(
-1140            "Could not connect. The connection was refused." +
-1141            "\nHTTP Status Code 401."
-1142        )
-1143    else:
-1144        raise ConnectionError(
-1145            f"Could not connect.\nHTTP Status code {response.status_code}"
-1146        )
-1147
-1148    json_data = response.json()
-1149
-1150    if return_as_dict is True:
-1151        return json_data
-1152
-1153    team_df = pd.json_normalize(json_data)
-1154    team_df.rename(
-1155        columns={
-1156            "team": "team_name",
-1157            "conference": "conference_name",
-1158            "totalPPA": "returning_total_ppa",
-1159            "totalPassingPPA": "returning_total_passing_ppa",
-1160            "totalReceivingPPA": "returning_total_receiving_ppa",
-1161            "totalRushingPPA": "returning_total_rush_ppa",
-1162            "percentPPA": "returning_ppa_percent",
-1163            "percentPassingPPA": "returning_percent_passing_ppa",
-1164            "percentReceivingPPA": "returning_percent_receiving_ppa",
-1165            "percentRushingPPA": "returning_percent_rushing_ppa",
-1166            "usage": "returning_usage",
-1167            "passingUsage": "returning_passing_usage",
-1168            "receivingUsage": "returning_receiving_usage",
-1169            "rushingUsage": "returning_rushing_usage",
-1170        },
-1171        inplace=True,
-1172    )
-1173    return team_df
+1055    ```
+1056    Returns
+1057    ----------
+1058    A pandas `DataFrame` object with returning production data,
+1059    or (if `return_as_dict` is set to `True`)
+1060    a dictionary object with returning production data.
+1061
+1062    """
+1063    now = datetime.now()
+1064    team_df = pd.DataFrame()
+1065    # row_df = pd.DataFrame()
+1066    url = "https://api.collegefootballdata.com/player/returning"
+1067
+1068    ##########################################################################
+1069
+1070    if api_key is not None:
+1071        real_api_key = api_key
+1072        del api_key
+1073    else:
+1074        real_api_key = get_cfbd_api_token(api_key_dir=api_key_dir)
+1075
+1076    if real_api_key == "tigersAreAwesome":
+1077        raise ValueError(
+1078            "You actually need to change `cfbd_key` to your CFBD API key."
+1079        )
+1080    elif "Bearer " in real_api_key:
+1081        pass
+1082    elif "Bearer" in real_api_key:
+1083        real_api_key = real_api_key.replace("Bearer", "Bearer ")
+1084    else:
+1085        real_api_key = "Bearer " + real_api_key
+1086
+1087    if season is None and team is None:
+1088        raise ValueError(
+1089            "To use this function, `season` and/or `team` must be set to a "
+1090            + "non-null variable."
+1091        )
+1092
+1093    if season is None:
+1094        # Rare, but in this endpoint,
+1095        # you don't need to input the season.
+1096        pass
+1097    elif season > (now.year + 1):
+1098        raise ValueError(f"`season` cannot be greater than {season}.")
+1099    elif season < 1869:
+1100        raise ValueError("`season` cannot be less than 1869.")
+1101
+1102    # URL Builder
+1103    ##########################################################################
+1104
+1105    url_elements = 0
+1106
+1107    if season is not None and url_elements == 0:
+1108        url += f"?year={season}"
+1109        url_elements += 1
+1110    elif season is not None:
+1111        url += f"&year={season}"
+1112        url_elements += 1
+1113
+1114    if team is not None and url_elements == 0:
+1115        url += f"?team={team}"
+1116        url_elements += 1
+1117    elif team is not None:
+1118        url += f"&team={team}"
+1119        url_elements += 1
+1120
+1121    if conference is not None and url_elements == 0:
+1122        url += f"?conference={conference}"
+1123        url_elements += 1
+1124    elif conference is not None:
+1125        url += f"&conference={conference}"
+1126        url_elements += 1
+1127
+1128    headers = {
+1129        "Authorization": f"{real_api_key}",
+1130        "accept": "application/json"
+1131    }
+1132
+1133    response = requests.get(url, headers=headers)
+1134
+1135    if response.status_code == 200:
+1136        pass
+1137    elif response.status_code == 401:
+1138        raise ConnectionRefusedError(
+1139            "Could not connect. The connection was refused." +
+1140            "\nHTTP Status Code 401."
+1141        )
+1142    else:
+1143        raise ConnectionError(
+1144            f"Could not connect.\nHTTP Status code {response.status_code}"
+1145        )
+1146
+1147    json_data = response.json()
+1148
+1149    if return_as_dict is True:
+1150        return json_data
+1151
+1152    team_df = pd.json_normalize(json_data)
+1153    team_df.rename(
+1154        columns={
+1155            "team": "team_name",
+1156            "conference": "conference_name",
+1157            "totalPPA": "returning_total_ppa",
+1158            "totalPassingPPA": "returning_total_passing_ppa",
+1159            "totalReceivingPPA": "returning_total_receiving_ppa",
+1160            "totalRushingPPA": "returning_total_rush_ppa",
+1161            "percentPPA": "returning_ppa_percent",
+1162            "percentPassingPPA": "returning_percent_passing_ppa",
+1163            "percentReceivingPPA": "returning_percent_receiving_ppa",
+1164            "percentRushingPPA": "returning_percent_rushing_ppa",
+1165            "usage": "returning_usage",
+1166            "passingUsage": "returning_passing_usage",
+1167            "receivingUsage": "returning_receiving_usage",
+1168            "rushingUsage": "returning_rushing_usage",
+1169        },
+1170        inplace=True,
+1171    )
+1172    return team_df
 
@@ -6276,597 +6294,598 @@

Returns

-
1176def get_cfbd_player_season_stats(
-1177    season: int,
-1178    api_key: str = None,
-1179    api_key_dir: str = None,
-1180    team: str = None,
-1181    conference: str = None,
-1182    start_week: int = None,
-1183    end_week: int = None,
-1184    season_type: str = "both",  # "regular", "postseason", or "both"
-1185    stat_category: str = None,
-1186    return_as_dict: bool = False,
-1187):
-1188    """
-1189    Get player season stats,
-1190    or the stats of players in a specific time frame, from the CFBD API.
-1191
-1192    Parameters
-1193    ----------
-1194    `season` (int, mandatory):
-1195        Required argument.
-1196        Specifies the season you want CFB player season stats from.
-1197        This must be specified, otherwise this package, and by extension
-1198        the CFBD API, will not accept
-1199        the request to get CFB player season stats.
-1200
-1201    `api_key` (str, optional):
-1202        Semi-optional argument.
-1203        If `api_key` is null, this function will attempt to load a CFBD API key
-1204        from the python environment, or from a file on this computer.
-1205        If `api_key` is not null,
-1206        this function will automatically assume that the
-1207        inputted `api_key` is a valid CFBD API key.
-1208
-1209    `api_key_dir` (str, optional):
-1210        Optional argument.
-1211        If `api_key` is set to am empty string, this variable is ignored.
-1212        If `api_key_dir` is null, and `api_key` is null,
-1213        this function will try to find
-1214        a CFBD API key file in this user's home directory.
-1215        If `api_key_dir` is set to a string, and `api_key` is null,
-1216        this function will assume that `api_key_dir` is a directory,
-1217        and will try to find a CFBD API key file in that directory.
-1218
-1219    `team` (str, optional):
-1220        Optional argument.
-1221        If you only want CFB player season stats for a team,
-1222        regardless if they are the home/away team,
-1223        set `team` to the name of the team
-1224        you want CFB player season stats from.
-1225
-1226    `conference` (str, optional):
-1227        Optional argument.
-1228        If you only want player season stats from games
-1229        involving teams a specific conference,
-1230        set `conference` to the abbreviation
-1231        of the conference you want stats from.
-1232
-1233    `start_week` (int, semi-optional):
-1234        Optional argument.
-1235        If you only want player stats for a range of weeks,
-1236        set `start_week` and `end_week` to
-1237        the range of weeks you want season-level data for.
-1238
-1239    `end_week` (int, semi-optional):
-1240        Optional argument.
-1241        If you only want player stats for a range of weeks,
-1242        set `start_week` and `end_week` to
-1243        the range of weeks you want season-level data for.
-1244
-1245    **NOTE**: If the following conditions are `True`, a `ValueError()`
-1246    will be raised when calling this function:
-1247    - `start_week < 0`
-1248    - `end_week < 0`
-1249    - `start_week is not None and end_week is None`
-1250        (will be changed in a future version)
-1251    - `start_week is None and end_week is not None`
-1252        (will be changed in a future version)
-1253    - `end_week < start_week`
-1254    - `end_week = start_week`
-1255
-1256    `season_type` (str, semi-optional):
-1257        Semi-optional argument.
-1258        By default, this will be set to "regular", for the CFB regular season.
-1259        If you want CFB media information for non-regular season games,
-1260        set `season_type` to "postseason".
-1261        If you want ***both*** regular
-1262        and postseason stats, set `season_type = "both"`.
-1263        If `season_type` is set to anything but "regular",
-1264        "postseason",  or "both", a `ValueError()` will be raised.
-1265
-1266    `stat_category` (str, optional):
-1267        Optional argument.
-1268        If only want stats for a specific stat category,
-1269        set this variable to that category.
-1270
-1271        Valid inputs are:
-1272        - `passing`
-1273        - `rushing`
-1274        - `receiving`
-1275        - `fumbles`
-1276        - `defensive`
-1277        - `interceptions`
-1278        - `punting`
-1279        - `kicking`
-1280        - `kickReturns`
-1281        - `puntReturns`
-1282
-1283    `return_as_dict` (bool, semi-optional):
-1284        Semi-optional argument.
-1285        If you want this function to return
-1286        the data as a dictionary (read: JSON object),
-1287        instead of a pandas `DataFrame` object,
-1288        set `return_as_dict` to `True`.
-1289
-1290    Usage
-1291    ----------
-1292    ```
-1293    import time
-1294
-1295    from cfbd_json_py.players import get_cfbd_player_season_stats
+                
1175def get_cfbd_player_season_stats(
+1176    season: int,
+1177    api_key: str = None,
+1178    api_key_dir: str = None,
+1179    team: str = None,
+1180    conference: str = None,
+1181    start_week: int = None,
+1182    end_week: int = None,
+1183    season_type: str = "both",  # "regular", "postseason", or "both"
+1184    stat_category: str = None,
+1185    return_as_dict: bool = False,
+1186):
+1187    """
+1188    Get player season stats,
+1189    or the stats of players in a specific time frame, from the CFBD API.
+1190
+1191    Parameters
+1192    ----------
+1193    `season` (int, mandatory):
+1194        Required argument.
+1195        Specifies the season you want CFB player season stats from.
+1196        This must be specified, otherwise this package, and by extension
+1197        the CFBD API, will not accept
+1198        the request to get CFB player season stats.
+1199
+1200    `api_key` (str, optional):
+1201        Semi-optional argument.
+1202        If `api_key` is null, this function will attempt to load a CFBD API key
+1203        from the python environment, or from a file on this computer.
+1204        If `api_key` is not null,
+1205        this function will automatically assume that the
+1206        inputted `api_key` is a valid CFBD API key.
+1207
+1208    `api_key_dir` (str, optional):
+1209        Optional argument.
+1210        If `api_key` is set to am empty string, this variable is ignored.
+1211        If `api_key_dir` is null, and `api_key` is null,
+1212        this function will try to find
+1213        a CFBD API key file in this user's home directory.
+1214        If `api_key_dir` is set to a string, and `api_key` is null,
+1215        this function will assume that `api_key_dir` is a directory,
+1216        and will try to find a CFBD API key file in that directory.
+1217
+1218    `team` (str, optional):
+1219        Optional argument.
+1220        If you only want CFB player season stats for a team,
+1221        regardless if they are the home/away team,
+1222        set `team` to the name of the team
+1223        you want CFB player season stats from.
+1224
+1225    `conference` (str, optional):
+1226        Optional argument.
+1227        If you only want player season stats from games
+1228        involving teams a specific conference,
+1229        set `conference` to the abbreviation
+1230        of the conference you want stats from.
+1231
+1232    `start_week` (int, semi-optional):
+1233        Optional argument.
+1234        If you only want player stats for a range of weeks,
+1235        set `start_week` and `end_week` to
+1236        the range of weeks you want season-level data for.
+1237
+1238    `end_week` (int, semi-optional):
+1239        Optional argument.
+1240        If you only want player stats for a range of weeks,
+1241        set `start_week` and `end_week` to
+1242        the range of weeks you want season-level data for.
+1243
+1244    **NOTE**: If the following conditions are `True`, a `ValueError()`
+1245    will be raised when calling this function:
+1246    - `start_week < 0`
+1247    - `end_week < 0`
+1248    - `start_week is not None and end_week is None`
+1249        (will be changed in a future version)
+1250    - `start_week is None and end_week is not None`
+1251        (will be changed in a future version)
+1252    - `end_week < start_week`
+1253    - `end_week = start_week`
+1254
+1255    `season_type` (str, semi-optional):
+1256        Semi-optional argument.
+1257        By default, this will be set to "regular", for the CFB regular season.
+1258        If you want CFB media information for non-regular season games,
+1259        set `season_type` to "postseason".
+1260        If you want ***both*** regular
+1261        and postseason stats, set `season_type = "both"`.
+1262        If `season_type` is set to anything but "regular",
+1263        "postseason",  or "both", a `ValueError()` will be raised.
+1264
+1265    `stat_category` (str, optional):
+1266        Optional argument.
+1267        If only want stats for a specific stat category,
+1268        set this variable to that category.
+1269
+1270        Valid inputs are:
+1271        - `passing`
+1272        - `rushing`
+1273        - `receiving`
+1274        - `fumbles`
+1275        - `defensive`
+1276        - `interceptions`
+1277        - `punting`
+1278        - `kicking`
+1279        - `kickReturns`
+1280        - `puntReturns`
+1281
+1282    `return_as_dict` (bool, semi-optional):
+1283        Semi-optional argument.
+1284        If you want this function to return
+1285        the data as a dictionary (read: JSON object),
+1286        instead of a pandas `DataFrame` object,
+1287        set `return_as_dict` to `True`.
+1288
+1289    Usage
+1290    ----------
+1291    ```
+1292    import time
+1293
+1294    from cfbd_json_py.players import get_cfbd_player_season_stats
+1295
 1296
-1297
-1298    cfbd_key = "tigersAreAwesome"  # placeholder for your CFBD API Key.
-1299
-1300    if cfbd_key != "tigersAreAwesome":
-1301        print(
-1302            "Using the user's API key declared in this script " +
-1303            "for this example."
-1304        )
-1305
-1306        # Get player season stats for
-1307        # the Ohio Bobcats Football team in the 2020 CFB season.
-1308        print(
-1309            "Get player season stats for " +
-1310            "the Ohio Bobcats Football team in the 2020 CFB season."
-1311        )
-1312        json_data = get_cfbd_player_season_stats(
-1313            api_key=cfbd_key,
-1314            season=2020,
-1315            team="Ohio"
-1316        )
-1317        print(json_data)
-1318        time.sleep(5)
-1319
-1320        # Get player season stats for teams who competed in
-1321        # the Southeastern conference (SEC) in the 2023 CFB season.
-1322        print(
-1323            "Get player season stats for teams who competed " +
-1324            "in the Southeastern conference (SEC) in the 2023 CFB season."
-1325        )
-1326        json_data = get_cfbd_player_season_stats(
-1327            api_key=cfbd_key,
-1328            season=2020,
-1329            conference="SEC"
-1330        )
-1331        print(json_data)
-1332        time.sleep(5)
-1333
-1334        # Get player season stats for teams who competed in
-1335        # the Southeastern conference (SEC) in the 2023 CFB season,
-1336        # but only between weeks 1 and 5.
-1337        print(
-1338            "Get player season stats for teams who competed " +
-1339            "in the Southeastern conference (SEC) in the 2023 CFB season."
-1340        )
-1341        json_data = get_cfbd_player_season_stats(
-1342            api_key=cfbd_key,
-1343            season=2020,
-1344            conference="SEC",
-1345            start_week=1,
-1346            end_week=5
-1347        )
-1348        print(json_data)
-1349        time.sleep(5)
-1350
-1351        # Get player season stats for the 2020 CFB season.
-1352        print("Get player season stats for the 2020 CFB season.")
-1353        json_data = get_cfbd_player_season_stats(
-1354            api_key=cfbd_key,
-1355            season=2020
-1356        )
-1357        print(json_data)
-1358        time.sleep(5)
-1359
-1360        # Get player season stats for
-1361        # the Ohio Bobcats Football team in the 2022 CFB season,
-1362        # but only use regular season games when calculating season stats.
-1363        print(
-1364            "Get player season stats for the Ohio Bobcats Football team " +
-1365            "in the 2020 CFB season, but only use regular season games " +
-1366            "when calculating season stats."
-1367        )
-1368        json_data = get_cfbd_player_season_stats(
-1369            api_key=cfbd_key,
-1370            season=2022,
-1371            team="Ohio",
-1372            season_type="regular"
-1373        )
-1374        print(json_data)
-1375        time.sleep(5)
-1376
-1377        # Get passing stats for teams who competed in
-1378        # the Southeastern conference (SEC) in the 2023 CFB season.
-1379        print(
-1380            "Get passing stats for teams who competed " +
-1381            "in the Southeastern conference (SEC) in the 2023 CFB season."
-1382        )
-1383        json_data = get_cfbd_player_season_stats(
-1384            api_key=cfbd_key,
-1385            season=2020,
-1386            conference="SEC",
-1387            stat_category="passing"
-1388        )
-1389        print(json_data)
-1390        time.sleep(5)
-1391
-1392        # You can also tell this function to just return the API call as
-1393        # a Dictionary (read: JSON) object.
-1394        print(
-1395            "You can also tell this function to just return the API call " +
-1396            "as a Dictionary (read: JSON) object."
-1397        )
-1398        json_data = get_cfbd_player_season_stats(
-1399            api_key=cfbd_key,
-1400            season=2020,
-1401            team="LSU",
-1402            stat_category="kicking",
-1403            return_as_dict=True
-1404        )
-1405        print(json_data)
-1406
-1407    else:
-1408        # Alternatively, if the CFBD API key exists in this python environment,
-1409        # or it's been set by cfbd_json_py.utls.set_cfbd_api_token(),
-1410        # you could just call these functions directly,
-1411        # without setting the API key in the script.
-1412        print(
-1413            "Using the user's API key supposedly loaded " +
-1414            "into this python environment for this example."
-1415        )
-1416
-1417        # Get player season stats for
-1418        # the Ohio Bobcats Football team in the 2020 CFB season.
-1419        print(
-1420            "Get player season stats for " +
-1421            "the Ohio Bobcats Football team in the 2020 CFB season."
-1422        )
-1423        json_data = get_cfbd_player_season_stats(
-1424            season=2020,
-1425            team="Ohio"
-1426        )
-1427        print(json_data)
-1428        time.sleep(5)
-1429
-1430        # Get player season stats for teams who competed in
-1431        # the Southeastern conference (SEC) in the 2023 CFB season.
-1432        print(
-1433            "Get player season stats for teams who competed " +
-1434            "in the Southeastern conference (SEC) in the 2023 CFB season."
-1435        )
-1436        json_data = get_cfbd_player_season_stats(
-1437            season=2020,
-1438            conference="SEC"
-1439        )
-1440        print(json_data)
-1441        time.sleep(5)
-1442
-1443        # Get player season stats for teams who competed in
-1444        # the Southeastern conference (SEC) in the 2023 CFB season,
-1445        # but only between weeks 1 and 5.
-1446        print(
-1447            "Get player season stats for teams who competed " +
-1448            "in the Southeastern conference (SEC) in the 2023 CFB season."
-1449        )
-1450        json_data = get_cfbd_player_season_stats(
-1451            season=2020,
-1452            conference="SEC",
-1453            start_week=1,
-1454            end_week=5
-1455        )
-1456        print(json_data)
-1457        time.sleep(5)
-1458
-1459        # Get player season stats for the 2020 CFB season.
-1460        print("Get player season stats for the 2020 CFB season.")
-1461        json_data = get_cfbd_player_season_stats(
-1462            season=2020
-1463        )
-1464        print(json_data)
-1465        time.sleep(5)
-1466
-1467        # Get player season stats for
-1468        # the Ohio Bobcats Football team in the 2022 CFB season,
-1469        # but only use regular season games when calculating season stats.
-1470        print(
-1471            "Get player season stats for the Ohio Bobcats Football team " +
-1472            "in the 2020 CFB season, but only use regular season games " +
-1473            "when calculating season stats."
-1474        )
-1475        json_data = get_cfbd_player_season_stats(
-1476            season=2022,
-1477            team="Ohio",
-1478            season_type="regular"
-1479        )
-1480        print(json_data)
-1481        time.sleep(5)
-1482
-1483        # Get passing stats for teams who competed in
-1484        # the Southeastern conference (SEC) in the 2023 CFB season.
-1485        print(
-1486            "Get passing stats for teams who competed " +
-1487            "in the Southeastern conference (SEC) in the 2023 CFB season."
-1488        )
-1489        json_data = get_cfbd_player_season_stats(
-1490            season=2020,
-1491            conference="SEC",
-1492            stat_category="passing"
-1493        )
-1494        print(json_data)
-1495        time.sleep(5)
-1496
-1497        # You can also tell this function to just return the API call as
-1498        # a Dictionary (read: JSON) object.
-1499        print(
-1500            "You can also tell this function to just return the API call " +
-1501            "as a Dictionary (read: JSON) object."
-1502        )
-1503        json_data = get_cfbd_player_season_stats(
-1504            season=2020,
-1505            team="LSU",
-1506            stat_category="kicking",
-1507            return_as_dict=True
-1508        )
-1509        print(json_data)
-1510
-1511    ```
-1512    Returns
-1513    ----------
-1514    A pandas `DataFrame` object with
-1515    a list of players who matched the search string,
-1516    or (if `return_as_dict` is set to `True`)
-1517    a dictionary object with a list of players who matched the search string.
-1518
-1519    """
-1520
-1521    rebuilt_json = {}
-1522    stat_columns = [
-1523        "season",
-1524        "team_name",
-1525        "team_conference",
-1526        "player_id",
-1527        "player_name",
-1528        # PASS
-1529        "passing_COMP",
-1530        "passing_ATT",
-1531        "passing_COMP%",
-1532        "passing_YDS",
-1533        "passing_AVG",
-1534        "passing_TD",
-1535        "passing_INT",
-1536        # RUSH
-1537        "rushing_CAR",
-1538        "rushing_YDS",
-1539        "rushing_AVG",
-1540        "rushing_TD",
-1541        "rushing_LONG",
-1542        # REC
-1543        "receiving_REC",
-1544        "receiving_YDS",
-1545        "receiving_AVG",
-1546        "receiving_TD",
-1547        "receiving_LONG",
-1548        # FUM
-1549        "fumbles_FUM",
-1550        "fumbles_LOST",
-1551        "fumbles_REC",
-1552        # DEFENSE
-1553        "defensive_TOT",
-1554        "defensive_SOLO",
-1555        "defensive_TFL",
-1556        "defensive_QB HUR",
-1557        "defensive_SACKS",
-1558        "defensive_PD",
-1559        "defensive_TD",
-1560        # INT
-1561        "interceptions_INT",
-1562        "interceptions_YDS",
-1563        "interceptions_TD",
-1564        # PUNT
-1565        "punting_NO",
-1566        "punting_YDS",
-1567        "punting_AVG",
-1568        "punting_TB",
-1569        "punting_In 20",
-1570        "punting_LONG",
-1571        # KICK
-1572        "kicking_FGM",
-1573        "kicking_FGA",
-1574        "kicking_FG%",
-1575        "kicking_LONG",
-1576        "kicking_XPM",
-1577        "kicking_XPA",
-1578        "kicking_XP%",
-1579        # KR
-1580        "kickReturns_NO",
-1581        "kickReturns_YDS",
-1582        "kickReturns_AVG",
-1583        "kickReturns_TD",
-1584        "kickReturns_LONG",
-1585        # PR
-1586        "puntReturns_NO",
-1587        "puntReturns_YDS",
-1588        "puntReturns_AVG",
-1589        "puntReturns_TD",
-1590        "puntReturns_LONG",
-1591    ]
-1592
-1593    now = datetime.now()
-1594    url = "https://api.collegefootballdata.com/stats/player/season"
-1595
-1596    final_df = pd.DataFrame()
-1597
-1598    if api_key is not None:
-1599        real_api_key = api_key
-1600        del api_key
-1601    else:
-1602        real_api_key = get_cfbd_api_token(api_key_dir=api_key_dir)
-1603
-1604    if real_api_key == "tigersAreAwesome":
-1605        raise ValueError(
-1606            "You actually need to change `cfbd_key` to your CFBD API key."
-1607        )
-1608    elif "Bearer " in real_api_key:
-1609        pass
-1610    elif "Bearer" in real_api_key:
-1611        real_api_key = real_api_key.replace("Bearer", "Bearer ")
-1612    else:
-1613        real_api_key = "Bearer " + real_api_key
-1614
-1615    if season is None:
-1616        # This should never happen without user tampering, but if it does,
-1617        # we need to raise an error,
-1618        # because the CFBD API will refuse this call without a valid season.
-1619        raise SystemError(
-1620            "I don't know how, I don't know why, "
-1621            + "but you managed to call this function "
-1622            + "while `season` was `None` (NULL),"
-1623            + " and the function got to this point in the code."
-1624            + "\nIf you have a GitHub account, "
-1625            + "please raise an issue on this python package's GitHub page:\n"
-1626            + "https://github.com/armstjc/cfbd-json-py/issues"
-1627        )
-1628    elif season > (now.year + 1):
-1629        raise ValueError(f"`season` cannot be greater than {season}.")
-1630    elif season < 1869:
-1631        raise ValueError("`season` cannot be less than 1869.")
-1632
-1633    if (
-1634        season_type != "regular"
-1635        and season_type != "postseason"
-1636        and season_type != "both"
-1637    ):
-1638        raise ValueError(
-1639            '`season_type` must be set to either "regular" or '
-1640            + '"postseason" for this function to work.'
-1641        )
-1642
-1643    filter_by_stat_category = False
-1644
-1645    if stat_category is None:
-1646        pass
-1647    elif stat_category == "passing":
-1648        filter_by_stat_category = True
-1649    elif stat_category == "rushing":
-1650        filter_by_stat_category = True
-1651    elif stat_category == "receiving":
-1652        filter_by_stat_category = True
-1653    elif stat_category == "fumbles":
-1654        filter_by_stat_category = True
-1655    elif stat_category == "passing":
-1656        filter_by_stat_category = True
-1657    elif stat_category == "defensive":
-1658        filter_by_stat_category = True
-1659    elif stat_category == "interceptions":
-1660        filter_by_stat_category = True
-1661    elif stat_category == "punting":
-1662        filter_by_stat_category = True
-1663    elif stat_category == "kicking":
-1664        filter_by_stat_category = True
-1665    elif stat_category == "kickReturns":
-1666        filter_by_stat_category = True
-1667    elif stat_category == "puntReturns":
-1668        filter_by_stat_category = True
-1669    else:
-1670        raise ValueError(
-1671            "Invalid input for `stat_category`."
-1672            + "\nValid inputs are:"
-1673            + """
-1674            - `passing`
-1675            - `rushing`
-1676            - `receiving`
-1677            - `fumbles`
-1678            - `defensive`
-1679            - `interceptions`
-1680            - `punting`
-1681            - `kicking`
-1682            - `kickReturns`
-1683            - `puntReturns`
-1684            """
-1685        )
-1686
-1687    if start_week is not None and end_week is not None:
-1688        if start_week > end_week:
-1689            raise ValueError("`start_week` cannot be greater than `end_week`.")
-1690        elif start_week == end_week:
-1691            raise ValueError(
-1692                "`start_week` cannot be equal to `end_week`."
-1693                + "\n Use "
-1694                + "`cfbd_json_py.games.get_cfbd_player_game_stats()` instead "
-1695                + "if you want player stats for a specific week in ."
-1696            )
-1697        elif start_week < 0:
-1698            raise ValueError("`start_week` cannot be less than 0.")
-1699        elif end_week < 0:
-1700            raise ValueError("`end_week` cannot be less than 0.")
-1701
-1702    if filter_by_stat_category is True:
-1703        pass
-1704
-1705    # URL builder
-1706    ##########################################################################
-1707
-1708    # Required by the API
-1709    url += f"?year={season}"
-1710
-1711    if team is not None:
-1712        url += f"&team={team}"
-1713
-1714    if conference is not None:
-1715        url += f"&conference={conference}"
-1716
-1717    if season_type is not None:
-1718        url += f"&seasonType={season_type}"
-1719
-1720    if stat_category is not None:
-1721        url += f"&category={stat_category}"
-1722
-1723    if start_week is not None:
-1724        url += f"&startWeek={start_week}"
-1725
-1726    if end_week is not None:
-1727        url += f"&endWeek={end_week}"
-1728
-1729    headers = {
-1730        "Authorization": f"{real_api_key}",
-1731        "accept": "application/json"
-1732    }
-1733
-1734    response = requests.get(url, headers=headers)
-1735
-1736    if response.status_code == 200:
-1737        pass
-1738    elif response.status_code == 401:
-1739        raise ConnectionRefusedError(
-1740            "Could not connect. The connection was refused." +
-1741            "\nHTTP Status Code 401."
-1742        )
-1743    else:
-1744        raise ConnectionError(
-1745            f"Could not connect.\nHTTP Status code {response.status_code}"
-1746        )
-1747
-1748    json_data = response.json()
-1749
-1750    if return_as_dict is True:
-1751        return json_data
-1752
-1753    for player in tqdm(json_data):
-1754        player_id = int(player["playerId"])
-1755        player_name = player["player"]
-1756        team_name = player["team"]
-1757        team_conference = player["conference"]
-1758        s_category = player["category"]
-1759        s_type = player["statType"]
-1760        s_num = player["stat"]
-1761
-1762        if rebuilt_json.get(player_id) is None:
-1763            rebuilt_json[player_id] = {}
-1764
-1765        if s_category == "passing":
-1766            if s_type == "COMPLETIONS":
+1297    cfbd_key = "tigersAreAwesome"  # placeholder for your CFBD API Key.
+1298
+1299    if cfbd_key != "tigersAreAwesome":
+1300        print(
+1301            "Using the user's API key declared in this script " +
+1302            "for this example."
+1303        )
+1304
+1305        # Get player season stats for
+1306        # the Ohio Bobcats Football team in the 2020 CFB season.
+1307        print(
+1308            "Get player season stats for " +
+1309            "the Ohio Bobcats Football team in the 2020 CFB season."
+1310        )
+1311        json_data = get_cfbd_player_season_stats(
+1312            api_key=cfbd_key,
+1313            season=2020,
+1314            team="Ohio"
+1315        )
+1316        print(json_data)
+1317        time.sleep(5)
+1318
+1319        # Get player season stats for teams who competed in
+1320        # the Southeastern conference (SEC) in the 2023 CFB season.
+1321        print(
+1322            "Get player season stats for teams who competed " +
+1323            "in the Southeastern conference (SEC) in the 2023 CFB season."
+1324        )
+1325        json_data = get_cfbd_player_season_stats(
+1326            api_key=cfbd_key,
+1327            season=2020,
+1328            conference="SEC"
+1329        )
+1330        print(json_data)
+1331        time.sleep(5)
+1332
+1333        # Get player season stats for teams who competed in
+1334        # the Southeastern conference (SEC) in the 2023 CFB season,
+1335        # but only between weeks 1 and 5.
+1336        print(
+1337            "Get player season stats for teams who competed " +
+1338            "in the Southeastern conference (SEC) in the 2023 CFB season."
+1339        )
+1340        json_data = get_cfbd_player_season_stats(
+1341            api_key=cfbd_key,
+1342            season=2020,
+1343            conference="SEC",
+1344            start_week=1,
+1345            end_week=5
+1346        )
+1347        print(json_data)
+1348        time.sleep(5)
+1349
+1350        # Get player season stats for the 2020 CFB season.
+1351        print("Get player season stats for the 2020 CFB season.")
+1352        json_data = get_cfbd_player_season_stats(
+1353            api_key=cfbd_key,
+1354            season=2020
+1355        )
+1356        print(json_data)
+1357        time.sleep(5)
+1358
+1359        # Get player season stats for
+1360        # the Ohio Bobcats Football team in the 2022 CFB season,
+1361        # but only use regular season games when calculating season stats.
+1362        print(
+1363            "Get player season stats for the Ohio Bobcats Football team " +
+1364            "in the 2020 CFB season, but only use regular season games " +
+1365            "when calculating season stats."
+1366        )
+1367        json_data = get_cfbd_player_season_stats(
+1368            api_key=cfbd_key,
+1369            season=2022,
+1370            team="Ohio",
+1371            season_type="regular"
+1372        )
+1373        print(json_data)
+1374        time.sleep(5)
+1375
+1376        # Get passing stats for teams who competed in
+1377        # the Southeastern conference (SEC) in the 2023 CFB season.
+1378        print(
+1379            "Get passing stats for teams who competed " +
+1380            "in the Southeastern conference (SEC) in the 2023 CFB season."
+1381        )
+1382        json_data = get_cfbd_player_season_stats(
+1383            api_key=cfbd_key,
+1384            season=2020,
+1385            conference="SEC",
+1386            stat_category="passing"
+1387        )
+1388        print(json_data)
+1389        time.sleep(5)
+1390
+1391        # You can also tell this function to just return the API call as
+1392        # a Dictionary (read: JSON) object.
+1393        print(
+1394            "You can also tell this function to just return the API call " +
+1395            "as a Dictionary (read: JSON) object."
+1396        )
+1397        json_data = get_cfbd_player_season_stats(
+1398            api_key=cfbd_key,
+1399            season=2020,
+1400            team="LSU",
+1401            stat_category="kicking",
+1402            return_as_dict=True
+1403        )
+1404        print(json_data)
+1405
+1406    else:
+1407        # Alternatively, if the CFBD API key exists in this python environment,
+1408        # or it's been set by cfbd_json_py.utls.set_cfbd_api_token(),
+1409        # you could just call these functions directly,
+1410        # without setting the API key in the script.
+1411        print(
+1412            "Using the user's API key supposedly loaded " +
+1413            "into this python environment for this example."
+1414        )
+1415
+1416        # Get player season stats for
+1417        # the Ohio Bobcats Football team in the 2020 CFB season.
+1418        print(
+1419            "Get player season stats for " +
+1420            "the Ohio Bobcats Football team in the 2020 CFB season."
+1421        )
+1422        json_data = get_cfbd_player_season_stats(
+1423            season=2020,
+1424            team="Ohio"
+1425        )
+1426        print(json_data)
+1427        time.sleep(5)
+1428
+1429        # Get player season stats for teams who competed in
+1430        # the Southeastern conference (SEC) in the 2023 CFB season.
+1431        print(
+1432            "Get player season stats for teams who competed " +
+1433            "in the Southeastern conference (SEC) in the 2023 CFB season."
+1434        )
+1435        json_data = get_cfbd_player_season_stats(
+1436            season=2020,
+1437            conference="SEC"
+1438        )
+1439        print(json_data)
+1440        time.sleep(5)
+1441
+1442        # Get player season stats for teams who competed in
+1443        # the Southeastern conference (SEC) in the 2023 CFB season,
+1444        # but only between weeks 1 and 5.
+1445        print(
+1446            "Get player season stats for teams who competed " +
+1447            "in the Southeastern conference (SEC) in the 2023 CFB season."
+1448        )
+1449        json_data = get_cfbd_player_season_stats(
+1450            season=2020,
+1451            conference="SEC",
+1452            start_week=1,
+1453            end_week=5
+1454        )
+1455        print(json_data)
+1456        time.sleep(5)
+1457
+1458        # Get player season stats for the 2020 CFB season.
+1459        print("Get player season stats for the 2020 CFB season.")
+1460        json_data = get_cfbd_player_season_stats(
+1461            season=2020
+1462        )
+1463        print(json_data)
+1464        time.sleep(5)
+1465
+1466        # Get player season stats for
+1467        # the Ohio Bobcats Football team in the 2022 CFB season,
+1468        # but only use regular season games when calculating season stats.
+1469        print(
+1470            "Get player season stats for the Ohio Bobcats Football team " +
+1471            "in the 2020 CFB season, but only use regular season games " +
+1472            "when calculating season stats."
+1473        )
+1474        json_data = get_cfbd_player_season_stats(
+1475            season=2022,
+1476            team="Ohio",
+1477            season_type="regular"
+1478        )
+1479        print(json_data)
+1480        time.sleep(5)
+1481
+1482        # Get passing stats for teams who competed in
+1483        # the Southeastern conference (SEC) in the 2023 CFB season.
+1484        print(
+1485            "Get passing stats for teams who competed " +
+1486            "in the Southeastern conference (SEC) in the 2023 CFB season."
+1487        )
+1488        json_data = get_cfbd_player_season_stats(
+1489            season=2020,
+1490            conference="SEC",
+1491            stat_category="passing"
+1492        )
+1493        print(json_data)
+1494        time.sleep(5)
+1495
+1496        # You can also tell this function to just return the API call as
+1497        # a Dictionary (read: JSON) object.
+1498        print(
+1499            "You can also tell this function to just return the API call " +
+1500            "as a Dictionary (read: JSON) object."
+1501        )
+1502        json_data = get_cfbd_player_season_stats(
+1503            season=2020,
+1504            team="LSU",
+1505            stat_category="kicking",
+1506            return_as_dict=True
+1507        )
+1508        print(json_data)
+1509
+1510    ```
+1511    Returns
+1512    ----------
+1513    A pandas `DataFrame` object with
+1514    a list of players who matched the search string,
+1515    or (if `return_as_dict` is set to `True`)
+1516    a dictionary object with a list of players who matched the search string.
+1517
+1518    """
+1519
+1520    rebuilt_json = {}
+1521    stat_columns = [
+1522        "season",
+1523        "team_name",
+1524        "team_conference",
+1525        "player_id",
+1526        "player_name",
+1527        # PASS
+1528        "passing_COMP",
+1529        "passing_ATT",
+1530        "passing_COMP%",
+1531        "passing_YDS",
+1532        "passing_AVG",
+1533        "passing_TD",
+1534        "passing_INT",
+1535        # RUSH
+1536        "rushing_CAR",
+1537        "rushing_YDS",
+1538        "rushing_AVG",
+1539        "rushing_TD",
+1540        "rushing_LONG",
+1541        # REC
+1542        "receiving_REC",
+1543        "receiving_YDS",
+1544        "receiving_AVG",
+1545        "receiving_TD",
+1546        "receiving_LONG",
+1547        # FUM
+1548        "fumbles_FUM",
+1549        "fumbles_LOST",
+1550        "fumbles_REC",
+1551        # DEFENSE
+1552        "defensive_TOT",
+1553        "defensive_SOLO",
+1554        "defensive_TFL",
+1555        "defensive_QB HUR",
+1556        "defensive_SACKS",
+1557        "defensive_PD",
+1558        "defensive_TD",
+1559        # INT
+1560        "interceptions_INT",
+1561        "interceptions_YDS",
+1562        "interceptions_TD",
+1563        # PUNT
+1564        "punting_NO",
+1565        "punting_YDS",
+1566        "punting_AVG",
+1567        "punting_TB",
+1568        "punting_In 20",
+1569        "punting_LONG",
+1570        # KICK
+1571        "kicking_FGM",
+1572        "kicking_FGA",
+1573        "kicking_FG%",
+1574        "kicking_LONG",
+1575        "kicking_XPM",
+1576        "kicking_XPA",
+1577        "kicking_XP%",
+1578        # KR
+1579        "kickReturns_NO",
+1580        "kickReturns_YDS",
+1581        "kickReturns_AVG",
+1582        "kickReturns_TD",
+1583        "kickReturns_LONG",
+1584        # PR
+1585        "puntReturns_NO",
+1586        "puntReturns_YDS",
+1587        "puntReturns_AVG",
+1588        "puntReturns_TD",
+1589        "puntReturns_LONG",
+1590    ]
+1591
+1592    now = datetime.now()
+1593    url = "https://api.collegefootballdata.com/stats/player/season"
+1594
+1595    final_df = pd.DataFrame()
+1596
+1597    if api_key is not None:
+1598        real_api_key = api_key
+1599        del api_key
+1600    else:
+1601        real_api_key = get_cfbd_api_token(api_key_dir=api_key_dir)
+1602
+1603    if real_api_key == "tigersAreAwesome":
+1604        raise ValueError(
+1605            "You actually need to change `cfbd_key` to your CFBD API key."
+1606        )
+1607    elif "Bearer " in real_api_key:
+1608        pass
+1609    elif "Bearer" in real_api_key:
+1610        real_api_key = real_api_key.replace("Bearer", "Bearer ")
+1611    else:
+1612        real_api_key = "Bearer " + real_api_key
+1613
+1614    if season is None:
+1615        # This should never happen without user tampering, but if it does,
+1616        # we need to raise an error,
+1617        # because the CFBD API will refuse this call without a valid season.
+1618        raise SystemError(
+1619            "I don't know how, I don't know why, "
+1620            + "but you managed to call this function "
+1621            + "while `season` was `None` (NULL),"
+1622            + " and the function got to this point in the code."
+1623            + "\nIf you have a GitHub account, "
+1624            + "please raise an issue on this python package's GitHub page:\n"
+1625            + "https://github.com/armstjc/cfbd-json-py/issues"
+1626        )
+1627    elif season > (now.year + 1):
+1628        raise ValueError(f"`season` cannot be greater than {season}.")
+1629    elif season < 1869:
+1630        raise ValueError("`season` cannot be less than 1869.")
+1631
+1632    if (
+1633        season_type != "regular"
+1634        and season_type != "postseason"
+1635        and season_type != "both"
+1636    ):
+1637        raise ValueError(
+1638            '`season_type` must be set to either "regular" or '
+1639            + '"postseason" for this function to work.'
+1640        )
+1641
+1642    filter_by_stat_category = False
+1643
+1644    if stat_category is None:
+1645        pass
+1646    elif stat_category == "passing":
+1647        filter_by_stat_category = True
+1648    elif stat_category == "rushing":
+1649        filter_by_stat_category = True
+1650    elif stat_category == "receiving":
+1651        filter_by_stat_category = True
+1652    elif stat_category == "fumbles":
+1653        filter_by_stat_category = True
+1654    elif stat_category == "passing":
+1655        filter_by_stat_category = True
+1656    elif stat_category == "defensive":
+1657        filter_by_stat_category = True
+1658    elif stat_category == "interceptions":
+1659        filter_by_stat_category = True
+1660    elif stat_category == "punting":
+1661        filter_by_stat_category = True
+1662    elif stat_category == "kicking":
+1663        filter_by_stat_category = True
+1664    elif stat_category == "kickReturns":
+1665        filter_by_stat_category = True
+1666    elif stat_category == "puntReturns":
+1667        filter_by_stat_category = True
+1668    else:
+1669        raise ValueError(
+1670            "Invalid input for `stat_category`."
+1671            + "\nValid inputs are:"
+1672            + """
+1673            - `passing`
+1674            - `rushing`
+1675            - `receiving`
+1676            - `fumbles`
+1677            - `defensive`
+1678            - `interceptions`
+1679            - `punting`
+1680            - `kicking`
+1681            - `kickReturns`
+1682            - `puntReturns`
+1683            """
+1684        )
+1685
+1686    if start_week is not None and end_week is not None:
+1687        if start_week > end_week:
+1688            raise ValueError("`start_week` cannot be greater than `end_week`.")
+1689        elif start_week == end_week:
+1690            raise ValueError(
+1691                "`start_week` cannot be equal to `end_week`."
+1692                + "\n Use "
+1693                + "`cfbd_json_py.games.get_cfbd_player_game_stats()` instead "
+1694                + "if you want player stats for a specific week in ."
+1695            )
+1696        elif start_week < 0:
+1697            raise ValueError("`start_week` cannot be less than 0.")
+1698        elif end_week < 0:
+1699            raise ValueError("`end_week` cannot be less than 0.")
+1700
+1701    if filter_by_stat_category is True:
+1702        pass
+1703
+1704    # URL builder
+1705    ##########################################################################
+1706
+1707    # Required by the API
+1708    url += f"?year={season}"
+1709
+1710    if team is not None:
+1711        url += f"&team={team}"
+1712
+1713    if conference is not None:
+1714        url += f"&conference={conference}"
+1715
+1716    if season_type is not None:
+1717        url += f"&seasonType={season_type}"
+1718
+1719    if stat_category is not None:
+1720        url += f"&category={stat_category}"
+1721
+1722    if start_week is not None:
+1723        url += f"&startWeek={start_week}"
+1724
+1725    if end_week is not None:
+1726        url += f"&endWeek={end_week}"
+1727
+1728    headers = {
+1729        "Authorization": f"{real_api_key}",
+1730        "accept": "application/json"
+1731    }
+1732
+1733    response = requests.get(url, headers=headers)
+1734
+1735    if response.status_code == 200:
+1736        pass
+1737    elif response.status_code == 401:
+1738        raise ConnectionRefusedError(
+1739            "Could not connect. The connection was refused." +
+1740            "\nHTTP Status Code 401."
+1741        )
+1742    else:
+1743        raise ConnectionError(
+1744            f"Could not connect.\nHTTP Status code {response.status_code}"
+1745        )
+1746
+1747    json_data = response.json()
+1748
+1749    if return_as_dict is True:
+1750        return json_data
+1751
+1752    for player in json_data:
+1753        player_id = int(player["playerId"])
+1754        player_name = player["player"]
+1755        team_name = player["team"]
+1756        team_conference = player["conference"]
+1757        s_category = player["category"]
+1758        s_type = player["statType"]
+1759        s_num = player["stat"]
+1760
+1761        if rebuilt_json.get(player_id) is None:
+1762            rebuilt_json[player_id] = {}
+1763
+1764        if s_category == "passing":
+1765            if s_type == "COMPLETIONS":
+1766                rebuilt_json[player_id]["player_id"] = player_name
 1767                rebuilt_json[player_id]["player_name"] = player_name
 1768                rebuilt_json[player_id]["team_name"] = team_name
 1769                rebuilt_json[player_id]["team_conference"] = team_conference
@@ -7205,376 +7224,395 @@ 

Returns

2102 del player_id, player_name, team_name, \ 2103 team_conference, s_category, s_type, s_num 2104 -2105 for key, value in tqdm(rebuilt_json.items()): +2105 for key, value in rebuilt_json.items(): 2106 row_df = pd.json_normalize(value) -2107 final_df = pd.concat([final_df, row_df], ignore_index=True) -2108 del row_df -2109 -2110 final_df = final_df.fillna(0) -2111 -2112 final_df["season"] = season -2113 -2114 if filter_by_stat_category is False: -2115 final_df = final_df.reindex(columns=stat_columns) -2116 final_df = final_df.astype( -2117 { -2118 "passing_COMP": "int", -2119 "passing_ATT": "int", -2120 "rushing_CAR": "int", -2121 "rushing_YDS": "int", -2122 "receiving_REC": "int", -2123 "receiving_YDS": "int", -2124 "punting_NO": "int", -2125 "punting_YDS": "int", -2126 "kicking_FGM": "int", -2127 "kicking_FGA": "int", -2128 "kicking_XPM": "int", -2129 "kicking_XPA": "int", -2130 "kickReturns_NO": "int", -2131 "kickReturns_YDS": "int", -2132 "puntReturns_NO": "int", -2133 "puntReturns_YDS": "int", -2134 } -2135 ) -2136 -2137 final_df.loc[final_df["passing_ATT"] > 0, "passing_COMP%"] = ( -2138 final_df["passing_COMP"] / final_df["passing_ATT"] -2139 ) -2140 -2141 final_df.loc[final_df["rushing_CAR"] > 0, "rushing_AVG"] = ( -2142 final_df["rushing_YDS"] / final_df["rushing_CAR"] -2143 ) -2144 -2145 final_df.loc[final_df["receiving_REC"] > 0, "receiving_AVG"] = ( -2146 final_df["receiving_YDS"] / final_df["receiving_REC"] -2147 ) +2107 row_df["player_id"] = key +2108 final_df = pd.concat([final_df, row_df], ignore_index=True) +2109 del row_df +2110 +2111 final_df = final_df.fillna(0) +2112 +2113 final_df["season"] = season +2114 +2115 if filter_by_stat_category is False: +2116 final_df = final_df.reindex(columns=stat_columns) +2117 final_df = final_df.astype( +2118 { +2119 "passing_COMP": "int", +2120 "passing_ATT": "int", +2121 "rushing_CAR": "int", +2122 "rushing_YDS": "int", +2123 "receiving_REC": "int", +2124 "receiving_YDS": "int", +2125 "punting_NO": "int", +2126 "punting_YDS": "int", +2127 "kicking_FGM": "int", +2128 "kicking_FGA": "int", +2129 "kicking_XPM": "int", +2130 "kicking_XPA": "int", +2131 "kickReturns_NO": "int", +2132 "kickReturns_YDS": "int", +2133 "puntReturns_NO": "int", +2134 "puntReturns_YDS": "int", +2135 }, +2136 errors="ignore" +2137 ) +2138 +2139 final_df.loc[final_df["passing_ATT"] > 0, "passing_COMP%"] = ( +2140 final_df["passing_COMP"] / final_df["passing_ATT"] +2141 ) +2142 final_df["passing_COMP%"] = final_df["passing_COMP%"].round(3) +2143 +2144 final_df.loc[final_df["rushing_CAR"] > 0, "rushing_AVG"] = ( +2145 final_df["rushing_YDS"] / final_df["rushing_CAR"] +2146 ) +2147 final_df["rushing_AVG"] = final_df["rushing_AVG"].round(3) 2148 -2149 final_df.loc[final_df["punting_NO"] > 0, "punting_AVG"] = ( -2150 final_df["punting_YDS"] / final_df["punting_NO"] +2149 final_df.loc[final_df["receiving_REC"] > 0, "receiving_AVG"] = ( +2150 final_df["receiving_YDS"] / final_df["receiving_REC"] 2151 ) -2152 -2153 final_df.loc[final_df["kicking_FGA"] > 0, "kicking_FG%"] = ( -2154 final_df["kicking_FGM"] / final_df["kicking_FGA"] -2155 ) -2156 -2157 final_df.loc[final_df["kicking_XPA"] > 0, "kicking_XP%"] = ( -2158 final_df["kicking_XPM"] / final_df["kicking_XPA"] -2159 ) -2160 -2161 final_df.loc[final_df["kickReturns_NO"] > 0, "kickReturns_AVG"] = ( -2162 final_df["kickReturns_YDS"] / final_df["kickReturns_NO"] -2163 ) -2164 -2165 final_df.loc[final_df["puntReturns_NO"] > 0, "puntReturns_AVG"] = ( -2166 final_df["puntReturns_YDS"] / final_df["puntReturns_NO"] -2167 ) +2152 final_df["receiving_AVG"] = final_df["receiving_AVG"].round(3) +2153 +2154 final_df.loc[final_df["punting_NO"] > 0, "punting_AVG"] = ( +2155 final_df["punting_YDS"] / final_df["punting_NO"] +2156 ) +2157 final_df["punting_AVG"] = final_df["punting_AVG"].round(3) +2158 +2159 final_df.loc[final_df["kicking_FGA"] > 0, "kicking_FG%"] = ( +2160 final_df["kicking_FGM"] / final_df["kicking_FGA"] +2161 ) +2162 final_df["kicking_FG%"] = final_df["kicking_FG%"].round(5) +2163 +2164 final_df.loc[final_df["kicking_XPA"] > 0, "kicking_XP%"] = ( +2165 final_df["kicking_XPM"] / final_df["kicking_XPA"] +2166 ) +2167 final_df["kicking_XP%"] = final_df["kicking_XP%"].round(5) 2168 -2169 elif filter_by_stat_category is True and stat_category == "passing": -2170 try: -2171 final_df = final_df.astype( -2172 { -2173 "passing_COMP": "int", -2174 "passing_ATT": "int", -2175 } -2176 ) -2177 except Exception as e: -2178 logging.warning( -2179 "Could not reformat [passing_COMP]" -2180 + " and [passing_ATT] into integers. " -2181 + f"Full Exception: {e}" -2182 ) -2183 -2184 final_df.loc[final_df["passing_ATT"] >= 1, "passing_COMP%"] = ( -2185 final_df["passing_COMP"] / final_df["passing_ATT"] -2186 ) -2187 -2188 final_df = final_df[ -2189 [ -2190 "season", -2191 "team_name", -2192 "team_conference", -2193 # "player_id", -2194 "player_name", -2195 # PASS -2196 "passing_COMP", -2197 "passing_ATT", -2198 "passing_YDS", -2199 "passing_TD", -2200 "passing_INT", -2201 ] -2202 ] -2203 -2204 elif filter_by_stat_category is True and stat_category == "rushing": -2205 try: -2206 final_df = final_df.astype( -2207 { -2208 "rushing_CAR": "int", -2209 "rushing_YDS": "int", -2210 } -2211 ) -2212 except Exception as e: -2213 logging.warning( -2214 "Could not reformat [rushing_CAR] " -2215 + "and [rushing_YDS] into integers. " -2216 + f"Full Exception: {e}" -2217 ) -2218 -2219 final_df.loc[final_df["rushing_CAR"] >= 1, "rushing_AVG"] = ( -2220 final_df["rushing_YDS"] / final_df["rushing_CAR"] -2221 ) -2222 -2223 final_df = final_df[ -2224 [ -2225 "season", -2226 "team_name", -2227 "team_conference", -2228 "player_id", -2229 "player_name", -2230 # RUSH -2231 "rushing_CAR", -2232 "rushing_YDS", -2233 "rushing_AVG", -2234 "rushing_TD", -2235 "rushing_LONG", -2236 ] -2237 ] -2238 -2239 elif filter_by_stat_category is True and stat_category == "receiving": -2240 try: -2241 final_df = final_df.astype( -2242 { -2243 "receiving_REC": "int", -2244 "receiving_YDS": "int", -2245 } -2246 ) -2247 except Exception as e: -2248 logging.warning( -2249 "Could not reformat [receiving_REC] " -2250 + "and [receiving_YDS] into integers. " -2251 + f"Full Exception: {e}" -2252 ) -2253 -2254 final_df.loc[final_df["receiving_REC"] > 0, "receiving_AVG"] = ( -2255 final_df["receiving_YDS"] / final_df["receiving_REC"] -2256 ) -2257 -2258 final_df = final_df[ -2259 [ -2260 "season", -2261 "team_name", -2262 "team_conference", -2263 "player_id", -2264 "player_name", -2265 # REC -2266 "receiving_REC", -2267 "receiving_YDS", -2268 "receiving_AVG", -2269 "receiving_TD", -2270 "receiving_LONG", -2271 ] -2272 ] -2273 -2274 elif filter_by_stat_category is True and stat_category == "fumbles": -2275 final_df = final_df[ -2276 [ -2277 "season", -2278 "team_name", -2279 "team_conference", -2280 "player_id", -2281 "player_name", -2282 # FUM -2283 "fumbles_FUM", -2284 "fumbles_LOST", -2285 "fumbles_REC", -2286 ] -2287 ] -2288 -2289 elif filter_by_stat_category is True and stat_category == "defensive": -2290 final_df = final_df[ -2291 [ -2292 "season", -2293 "team_name", -2294 "team_conference", -2295 "player_id", -2296 "player_name", -2297 # DEFENSE -2298 "defensive_TOT", -2299 "defensive_SOLO", -2300 "defensive_TFL", -2301 "defensive_QB HUR", -2302 "defensive_SACKS", -2303 "defensive_PD", -2304 "defensive_TD", -2305 ] -2306 ] -2307 -2308 elif filter_by_stat_category is True and stat_category == "interceptions": -2309 final_df = final_df[ -2310 [ -2311 "season", -2312 "team_name", -2313 "team_conference", -2314 "player_id", -2315 "player_name", -2316 # INT -2317 "interceptions_INT", -2318 "interceptions_YDS", -2319 "interceptions_TD", -2320 ] -2321 ] -2322 -2323 elif filter_by_stat_category is True and stat_category == "punting": -2324 try: -2325 final_df = final_df.astype( -2326 { -2327 "punting_NO": "int", -2328 "punting_YDS": "int", -2329 } -2330 ) -2331 except Exception as e: -2332 logging.warning( -2333 "Could not reformat [punting_YDS] " -2334 + "and [punting_NO] into integers. " -2335 + f"Full Exception: {e}" -2336 ) -2337 -2338 final_df.loc[final_df["punting_NO"] > 0, "punting_AVG"] = ( -2339 final_df["punting_YDS"] / final_df["punting_NO"] -2340 ) -2341 -2342 final_df = final_df[ -2343 [ -2344 "season", -2345 "team_name", -2346 "team_conference", -2347 "player_id", -2348 "player_name", -2349 # PUNT -2350 "punting_NO", -2351 "punting_YDS", -2352 "punting_AVG", -2353 "punting_TB", -2354 "punting_In 20", -2355 "punting_LONG", -2356 ] -2357 ] -2358 -2359 elif filter_by_stat_category is True and stat_category == "kicking": -2360 try: -2361 final_df = final_df.astype( -2362 { -2363 "kicking_FGM": "int", -2364 "kicking_FGA": "int", -2365 "kicking_XPM": "int", -2366 "kicking_XPA": "int", -2367 } -2368 ) -2369 except Exception as e: -2370 logging.warning( -2371 "Could not reformat the following columns into integers.:" -2372 + "\n-[kicking_FGM]" -2373 + "\n-[kicking_FGA]" -2374 + "\n-[kicking_XPM]" -2375 + "\n-[kicking_XPA]" -2376 + f"\nFull Exception: {e}" -2377 ) -2378 -2379 final_df.loc[final_df["kicking_FGA"] > 0, "kicking_FG%"] = ( -2380 final_df["kicking_FGM"] / final_df["kicking_FGA"] -2381 ) -2382 -2383 final_df.loc[final_df["kicking_XPA"] > 0, "kicking_XP%"] = ( -2384 final_df["kicking_XPM"] / final_df["kicking_XPA"] -2385 ) -2386 -2387 final_df = final_df[ -2388 [ -2389 "season", -2390 "team_name", -2391 "team_conference", -2392 "player_id", -2393 "player_name", -2394 # KICK -2395 "kicking_FGM", -2396 "kicking_FGA", -2397 "kicking_FG%", -2398 "kicking_LONG", -2399 "kicking_XPM", -2400 "kicking_XPA" "kicking_XP%", -2401 ] -2402 ] +2169 final_df.loc[final_df["kickReturns_NO"] > 0, "kickReturns_AVG"] = ( +2170 final_df["kickReturns_YDS"] / final_df["kickReturns_NO"] +2171 ) +2172 final_df["kickReturns_AVG"] = final_df["kickReturns_AVG"].round(3) +2173 +2174 final_df.loc[final_df["puntReturns_NO"] > 0, "puntReturns_AVG"] = ( +2175 final_df["puntReturns_YDS"] / final_df["puntReturns_NO"] +2176 ) +2177 final_df["puntReturns_AVG"] = final_df["puntReturns_AVG"].round(3) +2178 +2179 elif filter_by_stat_category is True and stat_category == "passing": +2180 try: +2181 final_df = final_df.astype( +2182 { +2183 "passing_COMP": "int", +2184 "passing_ATT": "int", +2185 } +2186 ) +2187 except Exception as e: +2188 logging.warning( +2189 "Could not reformat [passing_COMP]" +2190 + " and [passing_ATT] into integers. " +2191 + f"Full Exception: {e}" +2192 ) +2193 +2194 final_df.loc[final_df["passing_ATT"] >= 1, "passing_COMP%"] = ( +2195 final_df["passing_COMP"] / final_df["passing_ATT"] +2196 ) +2197 +2198 final_df["passing_COMP%"] = final_df["passing_COMP%"].round(3) +2199 +2200 final_df = final_df[ +2201 [ +2202 "season", +2203 "team_name", +2204 "team_conference", +2205 "player_id", +2206 "player_name", +2207 # PASS +2208 "passing_COMP", +2209 "passing_ATT", +2210 "passing_YDS", +2211 "passing_TD", +2212 "passing_INT", +2213 ] +2214 ] +2215 +2216 elif filter_by_stat_category is True and stat_category == "rushing": +2217 try: +2218 final_df = final_df.astype( +2219 { +2220 "rushing_CAR": "int", +2221 "rushing_YDS": "int", +2222 } +2223 ) +2224 except Exception as e: +2225 logging.warning( +2226 "Could not reformat [rushing_CAR] " +2227 + "and [rushing_YDS] into integers. " +2228 + f"Full Exception: {e}" +2229 ) +2230 +2231 final_df.loc[final_df["rushing_CAR"] >= 1, "rushing_AVG"] = ( +2232 final_df["rushing_YDS"] / final_df["rushing_CAR"] +2233 ) +2234 final_df["rushing_AVG"] = final_df["rushing_AVG"].round(3) +2235 +2236 final_df = final_df[ +2237 [ +2238 "season", +2239 "team_name", +2240 "team_conference", +2241 "player_id", +2242 "player_name", +2243 # RUSH +2244 "rushing_CAR", +2245 "rushing_YDS", +2246 "rushing_AVG", +2247 "rushing_TD", +2248 "rushing_LONG", +2249 ] +2250 ] +2251 +2252 elif filter_by_stat_category is True and stat_category == "receiving": +2253 try: +2254 final_df = final_df.astype( +2255 { +2256 "receiving_REC": "int", +2257 "receiving_YDS": "int", +2258 } +2259 ) +2260 except Exception as e: +2261 logging.warning( +2262 "Could not reformat [receiving_REC] " +2263 + "and [receiving_YDS] into integers. " +2264 + f"Full Exception: {e}" +2265 ) +2266 +2267 final_df.loc[final_df["receiving_REC"] > 0, "receiving_AVG"] = ( +2268 final_df["receiving_YDS"] / final_df["receiving_REC"] +2269 ) +2270 final_df["receiving_AVG"] = final_df["receiving_AVG"].round(3) +2271 +2272 final_df = final_df[ +2273 [ +2274 "season", +2275 "team_name", +2276 "team_conference", +2277 "player_id", +2278 "player_name", +2279 # REC +2280 "receiving_REC", +2281 "receiving_YDS", +2282 "receiving_AVG", +2283 "receiving_TD", +2284 "receiving_LONG", +2285 ] +2286 ] +2287 +2288 elif filter_by_stat_category is True and stat_category == "fumbles": +2289 final_df = final_df[ +2290 [ +2291 "season", +2292 "team_name", +2293 "team_conference", +2294 "player_id", +2295 "player_name", +2296 # FUM +2297 "fumbles_FUM", +2298 "fumbles_LOST", +2299 "fumbles_REC", +2300 ] +2301 ] +2302 +2303 elif filter_by_stat_category is True and stat_category == "defensive": +2304 final_df = final_df[ +2305 [ +2306 "season", +2307 "team_name", +2308 "team_conference", +2309 "player_id", +2310 "player_name", +2311 # DEFENSE +2312 "defensive_TOT", +2313 "defensive_SOLO", +2314 "defensive_TFL", +2315 "defensive_QB HUR", +2316 "defensive_SACKS", +2317 "defensive_PD", +2318 "defensive_TD", +2319 ] +2320 ] +2321 +2322 elif filter_by_stat_category is True and stat_category == "interceptions": +2323 final_df = final_df[ +2324 [ +2325 "season", +2326 "team_name", +2327 "team_conference", +2328 "player_id", +2329 "player_name", +2330 # INT +2331 "interceptions_INT", +2332 "interceptions_YDS", +2333 "interceptions_TD", +2334 ] +2335 ] +2336 +2337 elif filter_by_stat_category is True and stat_category == "punting": +2338 try: +2339 final_df = final_df.astype( +2340 { +2341 "punting_NO": "int", +2342 "punting_YDS": "int", +2343 } +2344 ) +2345 except Exception as e: +2346 logging.warning( +2347 "Could not reformat [punting_YDS] " +2348 + "and [punting_NO] into integers. " +2349 + f"Full Exception: {e}" +2350 ) +2351 +2352 final_df.loc[final_df["punting_NO"] > 0, "punting_AVG"] = ( +2353 final_df["punting_YDS"] / final_df["punting_NO"] +2354 ) +2355 final_df["punting_AVG"] = final_df["punting_AVG"].round(3) +2356 +2357 final_df = final_df[ +2358 [ +2359 "season", +2360 "team_name", +2361 "team_conference", +2362 "player_id", +2363 "player_name", +2364 # PUNT +2365 "punting_NO", +2366 "punting_YDS", +2367 "punting_AVG", +2368 "punting_TB", +2369 "punting_In 20", +2370 "punting_LONG", +2371 ] +2372 ] +2373 +2374 elif filter_by_stat_category is True and stat_category == "kicking": +2375 try: +2376 final_df = final_df.astype( +2377 { +2378 "kicking_FGM": "int", +2379 "kicking_FGA": "int", +2380 "kicking_XPM": "int", +2381 "kicking_XPA": "int", +2382 } +2383 ) +2384 except Exception as e: +2385 logging.warning( +2386 "Could not reformat the following columns into integers.:" +2387 + "\n-[kicking_FGM]" +2388 + "\n-[kicking_FGA]" +2389 + "\n-[kicking_XPM]" +2390 + "\n-[kicking_XPA]" +2391 + f"\nFull Exception: {e}" +2392 ) +2393 +2394 final_df.loc[final_df["kicking_FGA"] > 0, "kicking_FG%"] = ( +2395 final_df["kicking_FGM"] / final_df["kicking_FGA"] +2396 ) +2397 final_df["kicking_FG%"] = final_df["kicking_FG%"].round(5) +2398 +2399 final_df.loc[final_df["kicking_XPA"] > 0, "kicking_XP%"] = ( +2400 final_df["kicking_XPM"] / final_df["kicking_XPA"] +2401 ) +2402 final_df["kicking_XP%"] = final_df["kicking_XP%"].round(5) 2403 -2404 elif filter_by_stat_category is True and stat_category == "kickReturns": -2405 try: -2406 final_df = final_df.astype( -2407 { -2408 "kickReturns_NO": "int", -2409 "kickReturns_YDS": "int", -2410 } -2411 ) -2412 except Exception as e: -2413 logging.warning( -2414 "Could not reformat [passing_COMP] " -2415 + "and [kickReturns_YDS] into integers. " -2416 + f"Full Exception: {e}" -2417 ) -2418 -2419 final_df.loc[final_df["kickReturns_NO"] > 0, "kickReturns_AVG"] = ( -2420 final_df["kickReturns_YDS"] / final_df["kickReturns_NO"] -2421 ) -2422 -2423 final_df = final_df[ -2424 [ -2425 "season", -2426 "team_name", -2427 "team_conference", -2428 "player_id", -2429 "player_name", -2430 # KR -2431 "kickReturns_NO", -2432 "kickReturns_YDS", -2433 "kickReturns_AVG", -2434 "kickReturns_TD", -2435 "kickReturns_LONG", -2436 ] -2437 ] -2438 -2439 elif filter_by_stat_category is True and stat_category == "puntReturns": -2440 try: -2441 final_df = final_df.astype( -2442 { -2443 "puntReturns_NO": "int", -2444 "puntReturns_YDS": "int", -2445 } -2446 ) -2447 except Exception as e: -2448 logging.warning( -2449 "Could not reformat [passing_COMP] " -2450 + "and [puntReturns_YDS] into integers." -2451 + f"Full Exception: {e}" -2452 ) -2453 -2454 final_df.loc[final_df["puntReturns_NO"] > 0, "puntReturns_AVG"] = ( -2455 final_df["puntReturns_YDS"] / final_df["puntReturns_NO"] -2456 ) -2457 -2458 final_df = final_df[ -2459 [ -2460 "season", -2461 "team_name", -2462 "team_conference", -2463 "player_id", -2464 "player_name", -2465 # KR -2466 "puntReturns_NO", -2467 "puntReturns_YDS", -2468 "puntReturns_AVG", -2469 "puntReturns_TD", -2470 "puntReturns_LONG", -2471 ] -2472 ] -2473 -2474 return final_df +2404 final_df = final_df[ +2405 [ +2406 "season", +2407 "team_name", +2408 "team_conference", +2409 "player_id", +2410 "player_name", +2411 # KICK +2412 "kicking_FGM", +2413 "kicking_FGA", +2414 "kicking_FG%", +2415 "kicking_LONG", +2416 "kicking_XPM", +2417 "kicking_XPA" "kicking_XP%", +2418 ] +2419 ] +2420 +2421 elif filter_by_stat_category is True and stat_category == "kickReturns": +2422 try: +2423 final_df = final_df.astype( +2424 { +2425 "kickReturns_NO": "int", +2426 "kickReturns_YDS": "int", +2427 } +2428 ) +2429 except Exception as e: +2430 logging.warning( +2431 "Could not reformat [passing_COMP] " +2432 + "and [kickReturns_YDS] into integers. " +2433 + f"Full Exception: {e}" +2434 ) +2435 +2436 final_df.loc[final_df["kickReturns_NO"] > 0, "kickReturns_AVG"] = ( +2437 final_df["kickReturns_YDS"] / final_df["kickReturns_NO"] +2438 ) +2439 final_df["kickReturns_AVG"] = final_df["kickReturns_AVG"].round(3) +2440 +2441 final_df = final_df[ +2442 [ +2443 "season", +2444 "team_name", +2445 "team_conference", +2446 "player_id", +2447 "player_name", +2448 # KR +2449 "kickReturns_NO", +2450 "kickReturns_YDS", +2451 "kickReturns_AVG", +2452 "kickReturns_TD", +2453 "kickReturns_LONG", +2454 ] +2455 ] +2456 +2457 elif filter_by_stat_category is True and stat_category == "puntReturns": +2458 try: +2459 final_df = final_df.astype( +2460 { +2461 "puntReturns_NO": "int", +2462 "puntReturns_YDS": "int", +2463 } +2464 ) +2465 except Exception as e: +2466 logging.warning( +2467 "Could not reformat [passing_COMP] " +2468 + "and [puntReturns_YDS] into integers." +2469 + f"Full Exception: {e}" +2470 ) +2471 +2472 final_df.loc[final_df["puntReturns_NO"] > 0, "puntReturns_AVG"] = ( +2473 final_df["puntReturns_YDS"] / final_df["puntReturns_NO"] +2474 ) +2475 final_df["puntReturns_AVG"] = final_df["puntReturns_AVG"].round(3) +2476 +2477 final_df = final_df[ +2478 [ +2479 "season", +2480 "team_name", +2481 "team_conference", +2482 "player_id", +2483 "player_name", +2484 # KR +2485 "puntReturns_NO", +2486 "puntReturns_YDS", +2487 "puntReturns_AVG", +2488 "puntReturns_TD", +2489 "puntReturns_LONG", +2490 ] +2491 ] +2492 +2493 return final_df
@@ -7940,214 +7978,214 @@

Returns

-
2477def get_cfbd_transfer_portal_data(
-2478    season: int,
-2479    api_key: str = None,
-2480    api_key_dir: str = None,
-2481    return_as_dict: bool = False,
-2482):
-2483    """
-2484    Get player usage data
-2485    (A.K.A., the percentages for how often a player touched the ball),
-2486    for a given season, from the CFBD API.
-2487
-2488    Parameters
-2489    ----------
-2490    `season` (int, mandatory):
-2491        Required argument.
-2492        Specifies the season you want CFB transfer portal data from.
-2493        This must be specified, otherwise this package, and by extension
-2494        the CFBD API, will not accept
-2495        the request to get CFB transfer portal data stats.
-2496
-2497    `api_key` (str, optional):
-2498        Semi-optional argument.
-2499        If `api_key` is null, this function will attempt to load a CFBD API key
-2500        from the python environment, or from a file on this computer.
-2501        If `api_key` is not null,
-2502        this function will automatically assume that the
-2503        inputted `api_key` is a valid CFBD API key.
-2504
-2505    `api_key_dir` (str, optional):
-2506        Optional argument.
-2507        If `api_key` is set to am empty string, this variable is ignored.
-2508        If `api_key_dir` is null, and `api_key` is null,
-2509        this function will try to find
-2510        a CFBD API key file in this user's home directory.
-2511        If `api_key_dir` is set to a string, and `api_key` is null,
-2512        this function will assume that `api_key_dir` is a directory,
-2513        and will try to find a CFBD API key file in that directory.
-2514
-2515    `return_as_dict` (bool, semi-optional):
-2516        Semi-optional argument.
-2517        If you want this function to return
-2518        the data as a dictionary (read: JSON object),
-2519        instead of a pandas `DataFrame` object,
-2520        set `return_as_dict` to `True`.
-2521
-2522    Usage
-2523    ----------
-2524    ```
-2525    import time
-2526
-2527    from cfbd_json_py.players import get_cfbd_transfer_portal_data
-2528
-2529
-2530    cfbd_key = "tigersAreAwesome"  # placeholder for your CFBD API Key.
-2531
-2532    if cfbd_key != "tigersAreAwesome":
-2533        print(
-2534            "Using the user's API key declared in this script " +
-2535            "for this example."
-2536        )
-2537
-2538        # Get Transfer Portal data for the 2021 CFB season.
-2539        print("Get Transfer Portal data for the 2021 CFB season.")
-2540        json_data = get_cfbd_transfer_portal_data(
-2541            api_key=cfbd_key,
-2542            season=2021
-2543        )
-2544        print(json_data)
-2545        time.sleep(5)
-2546
-2547        # You can also tell this function to just return the API call as
-2548        # a Dictionary (read: JSON) object.
-2549        print(
-2550            "You can also tell this function to just return the API call " +
-2551            "as a Dictionary (read: JSON) object."
-2552        )
-2553        json_data = get_cfbd_transfer_portal_data(
-2554            api_key=cfbd_key,
-2555            season=2021,
-2556            return_as_dict=True
-2557        )
-2558        print(json_data)
-2559
-2560    else:
-2561        # Alternatively, if the CFBD API key exists in this python environment,
-2562        # or it's been set by cfbd_json_py.utls.set_cfbd_api_token(),
-2563        # you could just call these functions directly,
-2564        # without setting the API key in the script.
-2565        print(
-2566            "Using the user's API key supposedly loaded " +
-2567            "into this python environment for this example."
-2568        )
-2569
-2570        # Get Transfer Portal data for the 2021 CFB season.
-2571        print("Get Transfer Portal data for the 2021 CFB season.")
+                
2496def get_cfbd_transfer_portal_data(
+2497    season: int,
+2498    api_key: str = None,
+2499    api_key_dir: str = None,
+2500    return_as_dict: bool = False,
+2501):
+2502    """
+2503    Get player usage data
+2504    (A.K.A., the percentages for how often a player touched the ball),
+2505    for a given season, from the CFBD API.
+2506
+2507    Parameters
+2508    ----------
+2509    `season` (int, mandatory):
+2510        Required argument.
+2511        Specifies the season you want CFB transfer portal data from.
+2512        This must be specified, otherwise this package, and by extension
+2513        the CFBD API, will not accept
+2514        the request to get CFB transfer portal data stats.
+2515
+2516    `api_key` (str, optional):
+2517        Semi-optional argument.
+2518        If `api_key` is null, this function will attempt to load a CFBD API key
+2519        from the python environment, or from a file on this computer.
+2520        If `api_key` is not null,
+2521        this function will automatically assume that the
+2522        inputted `api_key` is a valid CFBD API key.
+2523
+2524    `api_key_dir` (str, optional):
+2525        Optional argument.
+2526        If `api_key` is set to am empty string, this variable is ignored.
+2527        If `api_key_dir` is null, and `api_key` is null,
+2528        this function will try to find
+2529        a CFBD API key file in this user's home directory.
+2530        If `api_key_dir` is set to a string, and `api_key` is null,
+2531        this function will assume that `api_key_dir` is a directory,
+2532        and will try to find a CFBD API key file in that directory.
+2533
+2534    `return_as_dict` (bool, semi-optional):
+2535        Semi-optional argument.
+2536        If you want this function to return
+2537        the data as a dictionary (read: JSON object),
+2538        instead of a pandas `DataFrame` object,
+2539        set `return_as_dict` to `True`.
+2540
+2541    Usage
+2542    ----------
+2543    ```
+2544    import time
+2545
+2546    from cfbd_json_py.players import get_cfbd_transfer_portal_data
+2547
+2548
+2549    cfbd_key = "tigersAreAwesome"  # placeholder for your CFBD API Key.
+2550
+2551    if cfbd_key != "tigersAreAwesome":
+2552        print(
+2553            "Using the user's API key declared in this script " +
+2554            "for this example."
+2555        )
+2556
+2557        # Get Transfer Portal data for the 2021 CFB season.
+2558        print("Get Transfer Portal data for the 2021 CFB season.")
+2559        json_data = get_cfbd_transfer_portal_data(
+2560            api_key=cfbd_key,
+2561            season=2021
+2562        )
+2563        print(json_data)
+2564        time.sleep(5)
+2565
+2566        # You can also tell this function to just return the API call as
+2567        # a Dictionary (read: JSON) object.
+2568        print(
+2569            "You can also tell this function to just return the API call " +
+2570            "as a Dictionary (read: JSON) object."
+2571        )
 2572        json_data = get_cfbd_transfer_portal_data(
-2573            season=2021
-2574        )
-2575        print(json_data)
-2576        time.sleep(5)
-2577
-2578        # You can also tell this function to just return the API call as
-2579        # a Dictionary (read: JSON) object.
-2580        print(
-2581            "You can also tell this function to just return the API call " +
-2582            "as a Dictionary (read: JSON) object."
-2583        )
-2584        json_data = get_cfbd_transfer_portal_data(
-2585            season=2021,
-2586            return_as_dict=True
+2573            api_key=cfbd_key,
+2574            season=2021,
+2575            return_as_dict=True
+2576        )
+2577        print(json_data)
+2578
+2579    else:
+2580        # Alternatively, if the CFBD API key exists in this python environment,
+2581        # or it's been set by cfbd_json_py.utls.set_cfbd_api_token(),
+2582        # you could just call these functions directly,
+2583        # without setting the API key in the script.
+2584        print(
+2585            "Using the user's API key supposedly loaded " +
+2586            "into this python environment for this example."
 2587        )
-2588        print(json_data)
-2589
-2590    ```
-2591    Returns
-2592    ----------
-2593    A pandas `DataFrame` object with transfer portal data,
-2594    or (if `return_as_dict` is set to `True`)
-2595    a dictionary object with transfer portal data.
+2588
+2589        # Get Transfer Portal data for the 2021 CFB season.
+2590        print("Get Transfer Portal data for the 2021 CFB season.")
+2591        json_data = get_cfbd_transfer_portal_data(
+2592            season=2021
+2593        )
+2594        print(json_data)
+2595        time.sleep(5)
 2596
-2597    """
-2598    now = datetime.now()
-2599    url = "https://api.collegefootballdata.com/player/portal"
-2600
-2601    portal_df = pd.DataFrame()
-2602    # row_df = pd.DataFrame()
-2603
-2604    if api_key is not None:
-2605        real_api_key = api_key
-2606        del api_key
-2607    else:
-2608        real_api_key = get_cfbd_api_token(api_key_dir=api_key_dir)
-2609
-2610    if real_api_key == "tigersAreAwesome":
-2611        raise ValueError(
-2612            "You actually need to change `cfbd_key` to your CFBD API key."
-2613        )
-2614    elif "Bearer " in real_api_key:
-2615        pass
-2616    elif "Bearer" in real_api_key:
-2617        real_api_key = real_api_key.replace("Bearer", "Bearer ")
-2618    else:
-2619        real_api_key = "Bearer " + real_api_key
-2620
-2621    if season is None:
-2622        # This should never happen without user tampering, but if it does,
-2623        # we need to raise an error,
-2624        # because the CFBD API will refuse this call without a valid season.
-2625        raise SystemError(
-2626            "I don't know how, I don't know why, "
-2627            + "but you managed to call this function "
-2628            + "while `season` was `None` (NULL),"
-2629            + " and the function got to this point in the code."
-2630            + "\nIf you have a GitHub account, "
-2631            + "please raise an issue on this python package's GitHub page:\n"
-2632            + "https://github.com/armstjc/cfbd-json-py/issues"
-2633        )
-2634    elif season > (now.year + 1):
-2635        raise ValueError(f"`season` cannot be greater than {season}.")
-2636    elif season < 2017:
-2637        raise ValueError(f"Transfer portal wasn't really a thing in {season}.")
-2638
-2639    # URL builder
-2640    ##########################################################################
-2641
-2642    # required by API
-2643    url += f"?year={season}"
-2644
-2645    headers = {
-2646        "Authorization": f"{real_api_key}",
-2647        "accept": "application/json"
-2648    }
-2649
-2650    response = requests.get(url, headers=headers)
-2651
-2652    if response.status_code == 200:
-2653        pass
-2654    elif response.status_code == 401:
-2655        raise ConnectionRefusedError(
-2656            "Could not connect. The connection was refused." +
-2657            "\nHTTP Status Code 401."
-2658        )
-2659    else:
-2660        raise ConnectionError(
-2661            f"Could not connect.\nHTTP Status code {response.status_code}"
-2662        )
+2597        # You can also tell this function to just return the API call as
+2598        # a Dictionary (read: JSON) object.
+2599        print(
+2600            "You can also tell this function to just return the API call " +
+2601            "as a Dictionary (read: JSON) object."
+2602        )
+2603        json_data = get_cfbd_transfer_portal_data(
+2604            season=2021,
+2605            return_as_dict=True
+2606        )
+2607        print(json_data)
+2608
+2609    ```
+2610    Returns
+2611    ----------
+2612    A pandas `DataFrame` object with transfer portal data,
+2613    or (if `return_as_dict` is set to `True`)
+2614    a dictionary object with transfer portal data.
+2615
+2616    """
+2617    now = datetime.now()
+2618    url = "https://api.collegefootballdata.com/player/portal"
+2619
+2620    portal_df = pd.DataFrame()
+2621    # row_df = pd.DataFrame()
+2622
+2623    if api_key is not None:
+2624        real_api_key = api_key
+2625        del api_key
+2626    else:
+2627        real_api_key = get_cfbd_api_token(api_key_dir=api_key_dir)
+2628
+2629    if real_api_key == "tigersAreAwesome":
+2630        raise ValueError(
+2631            "You actually need to change `cfbd_key` to your CFBD API key."
+2632        )
+2633    elif "Bearer " in real_api_key:
+2634        pass
+2635    elif "Bearer" in real_api_key:
+2636        real_api_key = real_api_key.replace("Bearer", "Bearer ")
+2637    else:
+2638        real_api_key = "Bearer " + real_api_key
+2639
+2640    if season is None:
+2641        # This should never happen without user tampering, but if it does,
+2642        # we need to raise an error,
+2643        # because the CFBD API will refuse this call without a valid season.
+2644        raise SystemError(
+2645            "I don't know how, I don't know why, "
+2646            + "but you managed to call this function "
+2647            + "while `season` was `None` (NULL),"
+2648            + " and the function got to this point in the code."
+2649            + "\nIf you have a GitHub account, "
+2650            + "please raise an issue on this python package's GitHub page:\n"
+2651            + "https://github.com/armstjc/cfbd-json-py/issues"
+2652        )
+2653    elif season > (now.year + 1):
+2654        raise ValueError(f"`season` cannot be greater than {season}.")
+2655    elif season < 2017:
+2656        raise ValueError(f"Transfer portal wasn't really a thing in {season}.")
+2657
+2658    # URL builder
+2659    ##########################################################################
+2660
+2661    # required by API
+2662    url += f"?year={season}"
 2663
-2664    json_data = response.json()
-2665
-2666    if return_as_dict is True:
-2667        return json_data
+2664    headers = {
+2665        "Authorization": f"{real_api_key}",
+2666        "accept": "application/json"
+2667    }
 2668
-2669    portal_df = pd.json_normalize(json_data)
-2670    portal_df.rename(
-2671        columns={
-2672            "firstName": "first_name",
-2673            "lastName": "last_name",
-2674            "position": "position_abv",
-2675            "origin": "origin_team",
-2676            "destination": "destination_team",
-2677            "transferDate": "transfer_date",
-2678            "rating": "rating",
-2679            "stars": "stars",
-2680            "eligibility": "eligibility",
-2681        },
-2682        inplace=True,
-2683    )
-2684    return portal_df
+2669    response = requests.get(url, headers=headers)
+2670
+2671    if response.status_code == 200:
+2672        pass
+2673    elif response.status_code == 401:
+2674        raise ConnectionRefusedError(
+2675            "Could not connect. The connection was refused." +
+2676            "\nHTTP Status Code 401."
+2677        )
+2678    else:
+2679        raise ConnectionError(
+2680            f"Could not connect.\nHTTP Status code {response.status_code}"
+2681        )
+2682
+2683    json_data = response.json()
+2684
+2685    if return_as_dict is True:
+2686        return json_data
+2687
+2688    portal_df = pd.json_normalize(json_data)
+2689    portal_df.rename(
+2690        columns={
+2691            "firstName": "first_name",
+2692            "lastName": "last_name",
+2693            "position": "position_abv",
+2694            "origin": "origin_team",
+2695            "destination": "destination_team",
+2696            "transferDate": "transfer_date",
+2697            "rating": "rating",
+2698            "stars": "stars",
+2699            "eligibility": "eligibility",
+2700        },
+2701        inplace=True,
+2702    )
+2703    return portal_df
 
@@ -8454,4 +8492,4 @@

Returns

- \ No newline at end of file + diff --git a/docs/cfbd_json_py/plays.html b/docs/cfbd_json_py/plays.html index b36117d..61547f8 100644 --- a/docs/cfbd_json_py/plays.html +++ b/docs/cfbd_json_py/plays.html @@ -1498,7 +1498,7 @@

10 11import pandas as pd 12import requests - 13from tqdm import tqdm + 13# from tqdm import tqdm 14 15from cfbd_json_py.utls import get_cfbd_api_token 16 @@ -2122,746 +2122,763 @@

634 635 636def get_cfbd_pbp_play_types( - 637 api_key: str = None, api_key_dir: str = None, return_as_dict: bool = False - 638): - 639 """ - 640 Allows you to get CFBD PBP play types from the CFBD API. - 641 - 642 Parameters - 643 ---------- - 644 - 645 `api_key` (str, optional): - 646 Semi-optional argument. - 647 If `api_key` is null, this function will attempt to load a CFBD API key - 648 from the python environment, or from a file on this computer. - 649 If `api_key` is not null, - 650 this function will automatically assume that the - 651 inputted `api_key` is a valid CFBD API key. - 652 - 653 `api_key_dir` (str, optional): - 654 Optional argument. - 655 If `api_key` is set to am empty string, this variable is ignored. - 656 If `api_key_dir` is null, and `api_key` is null, - 657 this function will try to find - 658 a CFBD API key file in this user's home directory. - 659 If `api_key_dir` is set to a string, and `api_key` is null, - 660 this function will assume that `api_key_dir` is a directory, - 661 and will try to find a CFBD API key file in that directory. - 662 - 663 `return_as_dict` (bool, semi-optional): - 664 Semi-optional argument. - 665 If you want this function to return - 666 the data as a dictionary (read: JSON object), - 667 instead of a pandas `DataFrame` object, - 668 set `return_as_dict` to `True`. - 669 - 670 Usage - 671 ---------- - 672 ``` - 673 ``` - 674 Returns - 675 ---------- - 676 A pandas `DataFrame` object with CFBD PBP play types, - 677 or (if `return_as_dict` is set to `True`) - 678 a dictionary object with CFBD PBP play types. - 679 - 680 """ - 681 # now = datetime.now() - 682 plays_df = pd.DataFrame() - 683 row_df = pd.DataFrame() - 684 url = "https://api.collegefootballdata.com/play/types" - 685 - 686 # Input validation - 687 ########################################################################## + 637 api_key: str = None, + 638 api_key_dir: str = None, + 639 return_as_dict: bool = False + 640): + 641 """ + 642 Allows you to get CFBD PBP play types from the CFBD API. + 643 + 644 Parameters + 645 ---------- + 646 + 647 `api_key` (str, optional): + 648 Semi-optional argument. + 649 If `api_key` is null, this function will attempt to load a CFBD API key + 650 from the python environment, or from a file on this computer. + 651 If `api_key` is not null, + 652 this function will automatically assume that the + 653 inputted `api_key` is a valid CFBD API key. + 654 + 655 `api_key_dir` (str, optional): + 656 Optional argument. + 657 If `api_key` is set to am empty string, this variable is ignored. + 658 If `api_key_dir` is null, and `api_key` is null, + 659 this function will try to find + 660 a CFBD API key file in this user's home directory. + 661 If `api_key_dir` is set to a string, and `api_key` is null, + 662 this function will assume that `api_key_dir` is a directory, + 663 and will try to find a CFBD API key file in that directory. + 664 + 665 `return_as_dict` (bool, semi-optional): + 666 Semi-optional argument. + 667 If you want this function to return + 668 the data as a dictionary (read: JSON object), + 669 instead of a pandas `DataFrame` object, + 670 set `return_as_dict` to `True`. + 671 + 672 Usage + 673 ---------- + 674 ``` + 675 ``` + 676 Returns + 677 ---------- + 678 A pandas `DataFrame` object with CFBD PBP play types, + 679 or (if `return_as_dict` is set to `True`) + 680 a dictionary object with CFBD PBP play types. + 681 + 682 """ + 683 # now = datetime.now() + 684 plays_df = pd.DataFrame() + 685 plays_df_arr = [] + 686 row_df = pd.DataFrame() + 687 url = "https://api.collegefootballdata.com/play/types" 688 - 689 if api_key is not None: - 690 real_api_key = api_key - 691 del api_key - 692 else: - 693 real_api_key = get_cfbd_api_token(api_key_dir=api_key_dir) - 694 - 695 if real_api_key == "tigersAreAwesome": - 696 raise ValueError( - 697 "You actually need to change `cfbd_key` to your CFBD API key." - 698 ) - 699 elif "Bearer " in real_api_key: - 700 pass - 701 elif "Bearer" in real_api_key: - 702 real_api_key = real_api_key.replace("Bearer", "Bearer ") - 703 else: - 704 real_api_key = "Bearer " + real_api_key - 705 - 706 headers = { - 707 "Authorization": f"{real_api_key}", - 708 "accept": "application/json" - 709 } - 710 - 711 response = requests.get(url, headers=headers) - 712 - 713 if response.status_code == 200: - 714 pass - 715 elif response.status_code == 401: - 716 raise ConnectionRefusedError( - 717 "Could not connect. The connection was refused." + - 718 "\nHTTP Status Code 401." - 719 ) - 720 else: - 721 raise ConnectionError( - 722 f"Could not connect.\nHTTP Status code {response.status_code}" - 723 ) - 724 - 725 json_data = response.json() - 726 - 727 if return_as_dict is True: - 728 return json_data + 689 # Input validation + 690 ########################################################################## + 691 + 692 if api_key is not None: + 693 real_api_key = api_key + 694 del api_key + 695 else: + 696 real_api_key = get_cfbd_api_token(api_key_dir=api_key_dir) + 697 + 698 if real_api_key == "tigersAreAwesome": + 699 raise ValueError( + 700 "You actually need to change `cfbd_key` to your CFBD API key." + 701 ) + 702 elif "Bearer " in real_api_key: + 703 pass + 704 elif "Bearer" in real_api_key: + 705 real_api_key = real_api_key.replace("Bearer", "Bearer ") + 706 else: + 707 real_api_key = "Bearer " + real_api_key + 708 + 709 headers = { + 710 "Authorization": f"{real_api_key}", + 711 "accept": "application/json" + 712 } + 713 + 714 response = requests.get(url, headers=headers) + 715 + 716 if response.status_code == 200: + 717 pass + 718 elif response.status_code == 401: + 719 raise ConnectionRefusedError( + 720 "Could not connect. The connection was refused." + + 721 "\nHTTP Status Code 401." + 722 ) + 723 else: + 724 raise ConnectionError( + 725 f"Could not connect.\nHTTP Status code {response.status_code}" + 726 ) + 727 + 728 json_data = response.json() 729 - 730 for p in tqdm(json_data): - 731 p_id = p["id"] - 732 row_df = pd.DataFrame({"play_type_id": p_id}, index=[0]) - 733 row_df["play_type_text"] = p["text"] - 734 row_df["play_type_abv"] = p["abbreviation"] - 735 plays_df = pd.concat([plays_df, row_df], ignore_index=True) - 736 - 737 del row_df - 738 del p_id - 739 - 740 return plays_df - 741 + 730 if return_as_dict is True: + 731 return json_data + 732 + 733 for p in json_data: + 734 p_id = p["id"] + 735 row_df = pd.DataFrame({"play_type_id": p_id}, index=[0]) + 736 row_df["play_type_text"] = p["text"] + 737 row_df["play_type_abv"] = p["abbreviation"] + 738 # plays_df = pd.concat([plays_df, row_df], ignore_index=True) + 739 plays_df_arr.append(row_df) + 740 del row_df + 741 del p_id 742 - 743def get_cfbd_pbp_stats( - 744 api_key: str = None, - 745 api_key_dir: str = None, - 746 season: int = None, - 747 week: int = None, - 748 team: str = None, - 749 game_id: int = None, - 750 athlete_id: int = None, - 751 stat_type_id: int = None, - 752 season_type: str = "both", # "regular", "postseason", or "both" - 753 conference: str = None, - 754 return_as_dict: bool = False, - 755): - 756 """ - 757 Allows you to get stats for various players - 758 from CFB play-by-play (PBP) data within the CFBD API. - 759 Parameters - 760 ---------- - 761 - 762 `api_key` (str, optional): - 763 Semi-optional argument. - 764 If `api_key` is null, this function will attempt to load a CFBD API key - 765 from the python environment, or from a file on this computer. - 766 If `api_key` is not null, - 767 this function will automatically assume that the - 768 inputted `api_key` is a valid CFBD API key. - 769 - 770 `api_key_dir` (str, optional): - 771 Optional argument. - 772 If `api_key` is set to am empty string, this variable is ignored. - 773 If `api_key_dir` is null, and `api_key` is null, - 774 this function will try to find - 775 a CFBD API key file in this user's home directory. - 776 If `api_key_dir` is set to a string, and `api_key` is null, - 777 this function will assume that `api_key_dir` is a directory, - 778 and will try to find a CFBD API key file in that directory. - 779 - 780 `season` (int, optional): - 781 Semi-optional argument. - 782 Specifies the season you want CFB PBP data from. - 783 This must be specified, otherwise this package, and by extension - 784 the CFBD API, will not accept the request to get CFB PBP data. - 785 - 786 `week` (int, optional): - 787 Optional argument. - 788 If `week` is set to an integer, this function will attempt - 789 to load CFB poll rankings data from games in that season, - 790 and in that week. - 791 - 792 `team` (str, optional): - 793 Optional argument. - 794 If you only want stats for a specific team, - 795 set `team` to the name of that specific team. + 743 plays_df = pd.concat(plays_df_arr, ignore_index=True) + 744 return plays_df + 745 + 746 + 747def get_cfbd_pbp_stats( + 748 api_key: str = None, + 749 api_key_dir: str = None, + 750 season: int = None, + 751 week: int = None, + 752 team: str = None, + 753 game_id: int = None, + 754 athlete_id: int = None, + 755 stat_type_id: int = None, + 756 season_type: str = "both", # "regular", "postseason", or "both" + 757 conference: str = None, + 758 return_as_dict: bool = False, + 759): + 760 """ + 761 Allows you to get stats for various players + 762 from CFB play-by-play (PBP) data within the CFBD API. + 763 + 764 Parameters + 765 ---------- + 766 + 767 `api_key` (str, optional): + 768 Semi-optional argument. + 769 If `api_key` is null, this function will attempt to load a CFBD API key + 770 from the python environment, or from a file on this computer. + 771 If `api_key` is not null, + 772 this function will automatically assume that the + 773 inputted `api_key` is a valid CFBD API key. + 774 + 775 `api_key_dir` (str, optional): + 776 Optional argument. + 777 If `api_key` is set to am empty string, this variable is ignored. + 778 If `api_key_dir` is null, and `api_key` is null, + 779 this function will try to find + 780 a CFBD API key file in this user's home directory. + 781 If `api_key_dir` is set to a string, and `api_key` is null, + 782 this function will assume that `api_key_dir` is a directory, + 783 and will try to find a CFBD API key file in that directory. + 784 + 785 `season` (int, optional): + 786 Semi-optional argument. + 787 Specifies the season you want CFB PBP data from. + 788 This must be specified, otherwise this package, and by extension + 789 the CFBD API, will not accept the request to get CFB PBP data. + 790 + 791 `week` (int, optional): + 792 Optional argument. + 793 If `week` is set to an integer, this function will attempt + 794 to load CFB poll rankings data from games in that season, + 795 and in that week. 796 - 797 `game_id` (int, optional): + 797 `team` (str, optional): 798 Optional argument. - 799 If you only want stats for a specific game, - 800 set `game_id` to the ID of that specific game. + 799 If you only want stats for a specific team, + 800 set `team` to the name of that specific team. 801 - 802 `athlete_id` (int, optional): + 802 `game_id` (int, optional): 803 Optional argument. - 804 If you only want stats for a specific player, - 805 set `athlete_id` to the ID of the player you want stats for. + 804 If you only want stats for a specific game, + 805 set `game_id` to the ID of that specific game. 806 - 807 `stats_type_id` (int, optional): + 807 `athlete_id` (int, optional): 808 Optional argument. - 809 If want to drill down, and only get plays of a specific type, - 810 (like rushing, passing, kicking plays), - 811 set `play_type` to the ID for the play type you want returned. - 812 To retrieve a list of valid play type IDs, - 813 use `cfbd_json_py.plays.get_cfbd_pbp_play_types()`. - 814 - 815 `season_type` (str, semi-optional): - 816 Semi-optional argument. - 817 By default, this will be set to "regular", for the CFB regular season. - 818 If you want CFB poll rankings data for non-regular season games, - 819 set `season_type` to "postseason". - 820 If `season_type` is set to anything but "regular" or "postseason", - 821 a `ValueError()` will be raised. - 822 - 823 `conference` (str, optional): - 824 Optional argument. - 825 If you only want CFB drive data from games - 826 involving teams from a specific conference, - 827 set `conference` to the abbreviation - 828 of the conference you want CFB drive data from. - 829 For a list of conferences, - 830 use the `cfbd_json_py.conferences.get_cfbd_conference_info()` - 831 function. - 832 - 833 `return_as_dict` (bool, semi-optional): - 834 Semi-optional argument. - 835 If you want this function to return - 836 the data as a dictionary (read: JSON object), - 837 instead of a pandas `DataFrame` object, - 838 set `return_as_dict` to `True`. - 839 - 840 Usage - 841 ---------- - 842 ``` - 843 import time + 809 If you only want stats for a specific player, + 810 set `athlete_id` to the ID of the player you want stats for. + 811 + 812 `stats_type_id` (int, optional): + 813 Optional argument. + 814 If want to drill down, and only get plays of a specific type, + 815 (like rushing, passing, kicking plays), + 816 set `play_type` to the ID for the play type you want returned. + 817 To retrieve a list of valid play type IDs, + 818 use `cfbd_json_py.plays.get_cfbd_pbp_play_types()`. + 819 + 820 `season_type` (str, semi-optional): + 821 Semi-optional argument. + 822 By default, this will be set to "regular", for the CFB regular season. + 823 If you want CFB poll rankings data for non-regular season games, + 824 set `season_type` to "postseason". + 825 If `season_type` is set to anything but "regular" or "postseason", + 826 a `ValueError()` will be raised. + 827 + 828 `conference` (str, optional): + 829 Optional argument. + 830 If you only want CFB drive data from games + 831 involving teams from a specific conference, + 832 set `conference` to the abbreviation + 833 of the conference you want CFB drive data from. + 834 For a list of conferences, + 835 use the `cfbd_json_py.conferences.get_cfbd_conference_info()` + 836 function. + 837 + 838 `return_as_dict` (bool, semi-optional): + 839 Semi-optional argument. + 840 If you want this function to return + 841 the data as a dictionary (read: JSON object), + 842 instead of a pandas `DataFrame` object, + 843 set `return_as_dict` to `True`. 844 - 845 from cfbd_json_py.plays import get_cfbd_pbp_stats - 846 - 847 - 848 cfbd_key = "tigersAreAwesome" # placeholder for your CFBD API Key. + 845 Usage + 846 ---------- + 847 ``` + 848 import time 849 - 850 if cfbd_key != "tigersAreAwesome": - 851 print( - 852 "Using the user's API key declared in this script " + - 853 "for this example." - 854 ) - 855 - 856 # Get CFB PBP stats data for the 2020 CFB season. - 857 print("Get CFB PBP stats data for the 2020 CFB season.") - 858 json_data = get_cfbd_pbp_stats( - 859 api_key=cfbd_key, - 860 season=2020 - 861 ) - 862 print(json_data) - 863 time.sleep(5) - 864 - 865 # Get CFB PBP stats data for week 10 of the 2020 CFB season. - 866 print("Get CFB PBP stats data for week 10 of the 2020 CFB season.") - 867 json_data = get_cfbd_pbp_stats( - 868 api_key=cfbd_key, - 869 season=2020, - 870 week=10 - 871 ) - 872 print(json_data) - 873 time.sleep(5) - 874 - 875 # Get CFB PBP stats data for a 2019 game between - 876 # the Ohio State Buckeyes and Clemson Tigers football teams. - 877 print( - 878 "Get CFB PBP stats data for a 2019 game between " + - 879 "the Ohio State Buckeyes and Clemson Tigers football teams." - 880 ) - 881 json_data = get_cfbd_pbp_stats( - 882 api_key=cfbd_key, - 883 game_id=401135279 - 884 ) - 885 print(json_data) - 886 time.sleep(5) - 887 - 888 # Get CFB PBP stats data for Trevor Lawrence (athlete ID #4360310) - 889 # during the 2020 CFB Season. - 890 print("Get CFB PBP stats data for the 2020 CFB season.") - 891 json_data = get_cfbd_pbp_stats( - 892 api_key=cfbd_key, - 893 season=2020, - 894 athlete_id=4360310 - 895 ) - 896 print(json_data) - 897 time.sleep(5) - 898 - 899 # Get CFB PBP stats data for Trevor Lawrence (athlete ID #4360310) - 900 # during the 2020 CFB Season, - 901 # but only return plays where Lawrence scored a touchdown. - 902 print("Get CFB PBP stats data for the 2020 CFB season.") - 903 json_data = get_cfbd_pbp_stats( - 904 api_key=cfbd_key, - 905 season=2020, - 906 athlete_id=4360310, - 907 stat_type_id=22 - 908 ) - 909 print(json_data) - 910 time.sleep(5) - 911 - 912 # Get CFB PBP stats data for the 2020 CFB season, - 913 # but only for postseason games. - 914 print("Get CFB PBP stats data for the 2020 CFB season.") - 915 json_data = get_cfbd_pbp_stats( - 916 api_key=cfbd_key, - 917 season=2020, - 918 season_type="postseason" - 919 ) - 920 print(json_data) - 921 time.sleep(5) - 922 - 923 # Get CFB PBP stats data for the 2020 CFB season, - 924 # but only for Big 10 (B1G) games. - 925 print("Get CFB PBP stats data for the 2020 CFB season.") - 926 json_data = get_cfbd_pbp_stats( - 927 api_key=cfbd_key, - 928 season=2020, - 929 conference="B1G" - 930 ) - 931 print(json_data) - 932 time.sleep(5) - 933 - 934 # Get CFB PBP stats data for the 2020 CFB season. - 935 print("Get CFB PBP stats data for the 2020 CFB season.") - 936 json_data = get_cfbd_pbp_stats( - 937 api_key=cfbd_key, - 938 season=2020 - 939 ) - 940 print(json_data) - 941 time.sleep(5) - 942 - 943 # You can also tell this function to just return the API call as - 944 # a Dictionary (read: JSON) object. - 945 print( - 946 "You can also tell this function to just return the API call " + - 947 "as a Dictionary (read: JSON) object." - 948 ) - 949 json_data = get_cfbd_pbp_stats( - 950 api_key=cfbd_key, - 951 season=2020, - 952 week=10, - 953 return_as_dict=True - 954 ) - 955 print(json_data) - 956 - 957 else: - 958 # Alternatively, if the CFBD API key exists in this python environment, - 959 # or it's been set by cfbd_json_py.utls.set_cfbd_api_token(), - 960 # you could just call these functions directly, - 961 # without setting the API key in the script. - 962 print( - 963 "Using the user's API key supposedly loaded " + - 964 "into this python environment for this example." - 965 ) - 966 - 967 # Get CFB PBP stats data for the 2020 CFB season. - 968 print("Get CFB PBP stats data for the 2020 CFB season.") - 969 json_data = get_cfbd_pbp_stats( - 970 season=2020 - 971 ) - 972 print(json_data) - 973 time.sleep(5) - 974 - 975 # Get CFB PBP stats data for week 10 of the 2020 CFB season. - 976 print("Get CFB PBP stats data for week 10 of the 2020 CFB season.") - 977 json_data = get_cfbd_pbp_stats( - 978 season=2020, - 979 week=10 - 980 ) - 981 print(json_data) - 982 time.sleep(5) - 983 - 984 # Get CFB PBP stats data for a 2019 game between - 985 # the Ohio State Buckeyes and Clemson Tigers football teams. - 986 print( - 987 "Get CFB PBP stats data for a 2019 game between " + - 988 "the Ohio State Buckeyes and Clemson Tigers football teams." - 989 ) - 990 json_data = get_cfbd_pbp_stats( - 991 game_id=401135279 - 992 ) - 993 print(json_data) - 994 time.sleep(5) - 995 - 996 # Get CFB PBP stats data for Trevor Lawrence (athlete ID #4360310) - 997 # during the 2020 CFB Season. - 998 print("Get CFB PBP stats data for the 2020 CFB season.") - 999 json_data = get_cfbd_pbp_stats( -1000 season=2020, -1001 athlete_id=4360310 -1002 ) -1003 print(json_data) -1004 time.sleep(5) -1005 -1006 # Get CFB PBP stats data for Trevor Lawrence (athlete ID #4360310) -1007 # during the 2020 CFB Season, -1008 # but only return plays where Lawrence scored a touchdown. -1009 print("Get CFB PBP stats data for the 2020 CFB season.") -1010 json_data = get_cfbd_pbp_stats( -1011 season=2020, -1012 athlete_id=4360310, -1013 stat_type_id=22 -1014 ) -1015 print(json_data) -1016 time.sleep(5) -1017 -1018 # Get CFB PBP stats data for the 2020 CFB season, -1019 # but only for postseason games. -1020 print("Get CFB PBP stats data for the 2020 CFB season.") -1021 json_data = get_cfbd_pbp_stats( -1022 season=2020, -1023 season_type="postseason" -1024 ) -1025 print(json_data) -1026 time.sleep(5) -1027 -1028 # Get CFB PBP stats data for the 2020 CFB season, -1029 # but only for Big 10 (B1G) games. -1030 print("Get CFB PBP stats data for the 2020 CFB season.") -1031 json_data = get_cfbd_pbp_stats( -1032 season=2020, -1033 conference="B1G" -1034 ) -1035 print(json_data) -1036 time.sleep(5) -1037 -1038 # You can also tell this function to just return the API call as -1039 # a Dictionary (read: JSON) object. -1040 print( -1041 "You can also tell this function to just return the API call " + -1042 "as a Dictionary (read: JSON) object." -1043 ) -1044 json_data = get_cfbd_pbp_stats( -1045 season=2020, -1046 week=10, -1047 return_as_dict=True + 850 from cfbd_json_py.plays import get_cfbd_pbp_stats + 851 + 852 + 853 cfbd_key = "tigersAreAwesome" # placeholder for your CFBD API Key. + 854 + 855 if cfbd_key != "tigersAreAwesome": + 856 print( + 857 "Using the user's API key declared in this script " + + 858 "for this example." + 859 ) + 860 + 861 # Get CFB PBP stats data for the 2020 CFB season. + 862 print("Get CFB PBP stats data for the 2020 CFB season.") + 863 json_data = get_cfbd_pbp_stats( + 864 api_key=cfbd_key, + 865 season=2020 + 866 ) + 867 print(json_data) + 868 time.sleep(5) + 869 + 870 # Get CFB PBP stats data for week 10 of the 2020 CFB season. + 871 print("Get CFB PBP stats data for week 10 of the 2020 CFB season.") + 872 json_data = get_cfbd_pbp_stats( + 873 api_key=cfbd_key, + 874 season=2020, + 875 week=10 + 876 ) + 877 print(json_data) + 878 time.sleep(5) + 879 + 880 # Get CFB PBP stats data for a 2019 game between + 881 # the Ohio State Buckeyes and Clemson Tigers football teams. + 882 print( + 883 "Get CFB PBP stats data for a 2019 game between " + + 884 "the Ohio State Buckeyes and Clemson Tigers football teams." + 885 ) + 886 json_data = get_cfbd_pbp_stats( + 887 api_key=cfbd_key, + 888 game_id=401135279 + 889 ) + 890 print(json_data) + 891 time.sleep(5) + 892 + 893 # Get CFB PBP stats data for Trevor Lawrence (athlete ID #4360310) + 894 # during the 2020 CFB Season. + 895 print("Get CFB PBP stats data for the 2020 CFB season.") + 896 json_data = get_cfbd_pbp_stats( + 897 api_key=cfbd_key, + 898 season=2020, + 899 athlete_id=4360310 + 900 ) + 901 print(json_data) + 902 time.sleep(5) + 903 + 904 # Get CFB PBP stats data for Trevor Lawrence (athlete ID #4360310) + 905 # during the 2020 CFB Season, + 906 # but only return plays where Lawrence scored a touchdown. + 907 print("Get CFB PBP stats data for the 2020 CFB season.") + 908 json_data = get_cfbd_pbp_stats( + 909 api_key=cfbd_key, + 910 season=2020, + 911 athlete_id=4360310, + 912 stat_type_id=22 + 913 ) + 914 print(json_data) + 915 time.sleep(5) + 916 + 917 # Get CFB PBP stats data for the 2020 CFB season, + 918 # but only for postseason games. + 919 print("Get CFB PBP stats data for the 2020 CFB season.") + 920 json_data = get_cfbd_pbp_stats( + 921 api_key=cfbd_key, + 922 season=2020, + 923 season_type="postseason" + 924 ) + 925 print(json_data) + 926 time.sleep(5) + 927 + 928 # Get CFB PBP stats data for the 2020 CFB season, + 929 # but only for Big 10 (B1G) games. + 930 print("Get CFB PBP stats data for the 2020 CFB season.") + 931 json_data = get_cfbd_pbp_stats( + 932 api_key=cfbd_key, + 933 season=2020, + 934 conference="B1G" + 935 ) + 936 print(json_data) + 937 time.sleep(5) + 938 + 939 # Get CFB PBP stats data for the 2020 CFB season. + 940 print("Get CFB PBP stats data for the 2020 CFB season.") + 941 json_data = get_cfbd_pbp_stats( + 942 api_key=cfbd_key, + 943 season=2020 + 944 ) + 945 print(json_data) + 946 time.sleep(5) + 947 + 948 # You can also tell this function to just return the API call as + 949 # a Dictionary (read: JSON) object. + 950 print( + 951 "You can also tell this function to just return the API call " + + 952 "as a Dictionary (read: JSON) object." + 953 ) + 954 json_data = get_cfbd_pbp_stats( + 955 api_key=cfbd_key, + 956 season=2020, + 957 week=10, + 958 return_as_dict=True + 959 ) + 960 print(json_data) + 961 + 962 else: + 963 # Alternatively, if the CFBD API key exists in this python environment, + 964 # or it's been set by cfbd_json_py.utls.set_cfbd_api_token(), + 965 # you could just call these functions directly, + 966 # without setting the API key in the script. + 967 print( + 968 "Using the user's API key supposedly loaded " + + 969 "into this python environment for this example." + 970 ) + 971 + 972 # Get CFB PBP stats data for the 2020 CFB season. + 973 print("Get CFB PBP stats data for the 2020 CFB season.") + 974 json_data = get_cfbd_pbp_stats( + 975 season=2020 + 976 ) + 977 print(json_data) + 978 time.sleep(5) + 979 + 980 # Get CFB PBP stats data for week 10 of the 2020 CFB season. + 981 print("Get CFB PBP stats data for week 10 of the 2020 CFB season.") + 982 json_data = get_cfbd_pbp_stats( + 983 season=2020, + 984 week=10 + 985 ) + 986 print(json_data) + 987 time.sleep(5) + 988 + 989 # Get CFB PBP stats data for a 2019 game between + 990 # the Ohio State Buckeyes and Clemson Tigers football teams. + 991 print( + 992 "Get CFB PBP stats data for a 2019 game between " + + 993 "the Ohio State Buckeyes and Clemson Tigers football teams." + 994 ) + 995 json_data = get_cfbd_pbp_stats( + 996 game_id=401135279 + 997 ) + 998 print(json_data) + 999 time.sleep(5) +1000 +1001 # Get CFB PBP stats data for Trevor Lawrence (athlete ID #4360310) +1002 # during the 2020 CFB Season. +1003 print("Get CFB PBP stats data for the 2020 CFB season.") +1004 json_data = get_cfbd_pbp_stats( +1005 season=2020, +1006 athlete_id=4360310 +1007 ) +1008 print(json_data) +1009 time.sleep(5) +1010 +1011 # Get CFB PBP stats data for Trevor Lawrence (athlete ID #4360310) +1012 # during the 2020 CFB Season, +1013 # but only return plays where Lawrence scored a touchdown. +1014 print("Get CFB PBP stats data for the 2020 CFB season.") +1015 json_data = get_cfbd_pbp_stats( +1016 season=2020, +1017 athlete_id=4360310, +1018 stat_type_id=22 +1019 ) +1020 print(json_data) +1021 time.sleep(5) +1022 +1023 # Get CFB PBP stats data for the 2020 CFB season, +1024 # but only for postseason games. +1025 print("Get CFB PBP stats data for the 2020 CFB season.") +1026 json_data = get_cfbd_pbp_stats( +1027 season=2020, +1028 season_type="postseason" +1029 ) +1030 print(json_data) +1031 time.sleep(5) +1032 +1033 # Get CFB PBP stats data for the 2020 CFB season, +1034 # but only for Big 10 (B1G) games. +1035 print("Get CFB PBP stats data for the 2020 CFB season.") +1036 json_data = get_cfbd_pbp_stats( +1037 season=2020, +1038 conference="B1G" +1039 ) +1040 print(json_data) +1041 time.sleep(5) +1042 +1043 # You can also tell this function to just return the API call as +1044 # a Dictionary (read: JSON) object. +1045 print( +1046 "You can also tell this function to just return the API call " + +1047 "as a Dictionary (read: JSON) object." 1048 ) -1049 print(json_data) -1050 -1051 ``` -1052 Returns -1053 ---------- -1054 A pandas `DataFrame` object with CFB PBP data, -1055 or (if `return_as_dict` is set to `True`) -1056 a dictionary object with CFB PBP data. -1057 -1058 """ -1059 now = datetime.now() -1060 pbp_df = pd.DataFrame() -1061 url = "https://api.collegefootballdata.com/play/stats" +1049 json_data = get_cfbd_pbp_stats( +1050 season=2020, +1051 week=10, +1052 return_as_dict=True +1053 ) +1054 print(json_data) +1055 +1056 ``` +1057 Returns +1058 ---------- +1059 A pandas `DataFrame` object with CFB PBP data, +1060 or (if `return_as_dict` is set to `True`) +1061 a dictionary object with CFB PBP data. 1062 -1063 # Input validation -1064 ########################################################################## -1065 -1066 if api_key is not None: -1067 real_api_key = api_key -1068 del api_key -1069 else: -1070 real_api_key = get_cfbd_api_token(api_key_dir=api_key_dir) -1071 -1072 if real_api_key == "tigersAreAwesome": -1073 raise ValueError( -1074 "You actually need to change `cfbd_key` to your CFBD API key." -1075 ) -1076 elif "Bearer " in real_api_key: -1077 pass -1078 elif "Bearer" in real_api_key: -1079 real_api_key = real_api_key.replace("Bearer", "Bearer ") -1080 else: -1081 real_api_key = "Bearer " + real_api_key -1082 -1083 if season is not None and (season > (now.year + 1)): -1084 raise ValueError(f"`season` cannot be greater than {season}.") -1085 elif season is not None and season < 1869: -1086 raise ValueError("`season` cannot be less than 1869.") +1063 """ +1064 now = datetime.now() +1065 pbp_df = pd.DataFrame() +1066 url = "https://api.collegefootballdata.com/play/stats" +1067 +1068 # Input validation +1069 ########################################################################## +1070 +1071 if api_key is not None: +1072 real_api_key = api_key +1073 del api_key +1074 else: +1075 real_api_key = get_cfbd_api_token(api_key_dir=api_key_dir) +1076 +1077 if real_api_key == "tigersAreAwesome": +1078 raise ValueError( +1079 "You actually need to change `cfbd_key` to your CFBD API key." +1080 ) +1081 elif "Bearer " in real_api_key: +1082 pass +1083 elif "Bearer" in real_api_key: +1084 real_api_key = real_api_key.replace("Bearer", "Bearer ") +1085 else: +1086 real_api_key = "Bearer " + real_api_key 1087 -1088 if ( -1089 season_type != "regular" -1090 and season_type != "postseason" -1091 and season_type != "both" -1092 ): -1093 raise ValueError( -1094 '`season_type` must be set to either ' + -1095 '"regular", "postseason", or "both" for this function to work.' -1096 ) -1097 -1098 if season is None and game_id is None: -1099 logging.warn( -1100 "This endpoint only returns the top 1,000 results. " -1101 + "Not setting a value for `season` or `game_id` " -1102 + "is not a recommended practice." -1103 ) -1104 elif season is not None and game_id is None: -1105 logging.warn( -1106 "Setting a value for both `season` and `game_id` " -1107 + "may not yeld the results you want. " -1108 + "If you just want PBP stats for a valid game ID, " -1109 + "just set `game_id` to a valid game ID." -1110 ) -1111 -1112 # URL builder -1113 ########################################################################## -1114 -1115 url_elements = 0 -1116 -1117 if season_type is not None and url_elements == 0: -1118 url += f"?seasonType={season_type}" -1119 url_elements += 1 -1120 elif season_type is not None: -1121 url += f"&seasonType={season_type}" -1122 url_elements += 1 -1123 -1124 if season is not None and url_elements == 0: -1125 url += f"?year={season}" -1126 url_elements += 1 -1127 elif season is not None: -1128 url += f"&year={season}" -1129 url_elements += 1 -1130 -1131 if week is not None and url_elements == 0: -1132 url += f"?week={week}" -1133 url_elements += 1 -1134 elif week is not None: -1135 url += f"&week={week}" -1136 url_elements += 1 -1137 -1138 if team is not None and url_elements == 0: -1139 url += f"?team={team}" -1140 url_elements += 1 -1141 elif team is not None: -1142 url += f"&team={team}" -1143 url_elements += 1 -1144 -1145 if conference is not None and url_elements == 0: -1146 url += f"&conference={conference}" -1147 url_elements += 1 -1148 elif conference is not None: -1149 url += f"&conference={conference}" -1150 url_elements += 1 -1151 -1152 if game_id is not None and url_elements == 0: -1153 url += f"&gameId={game_id}" -1154 url_elements += 1 -1155 elif game_id is not None: -1156 url += f"&gameId={game_id}" -1157 url_elements += 1 -1158 -1159 if athlete_id is not None and url_elements == 0: -1160 url += f"&athleteId={athlete_id}" -1161 url_elements += 1 -1162 elif athlete_id is not None: -1163 url += f"&athleteId={athlete_id}" -1164 url_elements += 1 -1165 -1166 if stat_type_id is not None and url_elements == 0: -1167 url += f"&statTypeId={stat_type_id}" -1168 url_elements += 1 -1169 elif stat_type_id is not None: -1170 url += f"&statTypeId={stat_type_id}" -1171 url_elements += 1 -1172 -1173 headers = { -1174 "Authorization": f"{real_api_key}", -1175 "accept": "application/json" -1176 } -1177 -1178 response = requests.get(url, headers=headers) -1179 -1180 if response.status_code == 200: -1181 pass -1182 elif response.status_code == 401: -1183 raise ConnectionRefusedError( -1184 "Could not connect. The connection was refused." + -1185 "\nHTTP Status Code 401." -1186 ) -1187 else: -1188 raise ConnectionError( -1189 f"Could not connect.\nHTTP Status code {response.status_code}" -1190 ) -1191 -1192 json_data = response.json() -1193 -1194 if return_as_dict is True: -1195 return json_data -1196 -1197 pbp_df = pd.json_normalize(json_data) -1198 pbp_df.rename( -1199 columns={ -1200 "gameId": "game_id", -1201 "teamScore": "team_score", -1202 "opponentScore": "opponent_score", -1203 "driveId": "drive_id", -1204 "playId": "play_id", -1205 "yardsToGoal": "yards_to_goal", -1206 "athleteId": "athlete_id", -1207 "athleteName": "athlete_name", -1208 "statType": "stat_type", -1209 }, -1210 inplace=True, -1211 ) -1212 # TODO: Implement an option to put all stats for -1213 # a specific game on a single line. -1214 return pbp_df -1215 -1216 -1217def get_cfbd_pbp_stat_types( -1218 api_key: str = None, api_key_dir: str = None, return_as_dict: bool = False -1219): -1220 """ -1221 Allows you to get CFBD PBP stat types from the CFBD API. -1222 -1223 Parameters -1224 ---------- -1225 -1226 `api_key` (str, optional): -1227 Semi-optional argument. -1228 If `api_key` is null, this function will attempt to load a CFBD API key -1229 from the python environment, or from a file on this computer. -1230 If `api_key` is not null, -1231 this function will automatically assume that the -1232 inputted `api_key` is a valid CFBD API key. -1233 -1234 `api_key_dir` (str, optional): -1235 Optional argument. -1236 If `api_key` is set to am empty string, this variable is ignored. -1237 If `api_key_dir` is null, and `api_key` is null, -1238 this function will try to find -1239 a CFBD API key file in this user's home directory. -1240 If `api_key_dir` is set to a string, and `api_key` is null, -1241 this function will assume that `api_key_dir` is a directory, -1242 and will try to find a CFBD API key file in that directory. +1088 if season is not None and (season > (now.year + 1)): +1089 raise ValueError(f"`season` cannot be greater than {season}.") +1090 elif season is not None and season < 1869: +1091 raise ValueError("`season` cannot be less than 1869.") +1092 +1093 if ( +1094 season_type != "regular" +1095 and season_type != "postseason" +1096 and season_type != "both" +1097 ): +1098 raise ValueError( +1099 '`season_type` must be set to either ' + +1100 '"regular", "postseason", or "both" for this function to work.' +1101 ) +1102 +1103 if season is None and game_id is None: +1104 logging.warning( +1105 "This endpoint only returns the top 1,000 results. " +1106 + "Not setting a value for `season` or `game_id` " +1107 + "is not a recommended practice." +1108 ) +1109 elif ( +1110 (season is not None) and +1111 (game_id is not None) +1112 ): +1113 logging.warning( +1114 "Setting a value for both `season` and `game_id` " +1115 + "may not yeld the results you want. " +1116 + "If you just want PBP stats for a valid game ID, " +1117 + "just set `game_id` to a valid game ID." +1118 ) +1119 +1120 # URL builder +1121 ########################################################################## +1122 +1123 url_elements = 0 +1124 +1125 if season_type is not None and url_elements == 0: +1126 url += f"?seasonType={season_type}" +1127 url_elements += 1 +1128 elif season_type is not None: +1129 url += f"&seasonType={season_type}" +1130 url_elements += 1 +1131 +1132 if season is not None and url_elements == 0: +1133 url += f"?year={season}" +1134 url_elements += 1 +1135 elif season is not None: +1136 url += f"&year={season}" +1137 url_elements += 1 +1138 +1139 if week is not None and url_elements == 0: +1140 url += f"?week={week}" +1141 url_elements += 1 +1142 elif week is not None: +1143 url += f"&week={week}" +1144 url_elements += 1 +1145 +1146 if team is not None and url_elements == 0: +1147 url += f"?team={team}" +1148 url_elements += 1 +1149 elif team is not None: +1150 url += f"&team={team}" +1151 url_elements += 1 +1152 +1153 if conference is not None and url_elements == 0: +1154 url += f"&conference={conference}" +1155 url_elements += 1 +1156 elif conference is not None: +1157 url += f"&conference={conference}" +1158 url_elements += 1 +1159 +1160 if game_id is not None and url_elements == 0: +1161 url += f"&gameId={game_id}" +1162 url_elements += 1 +1163 elif game_id is not None: +1164 url += f"&gameId={game_id}" +1165 url_elements += 1 +1166 +1167 if athlete_id is not None and url_elements == 0: +1168 url += f"&athleteId={athlete_id}" +1169 url_elements += 1 +1170 elif athlete_id is not None: +1171 url += f"&athleteId={athlete_id}" +1172 url_elements += 1 +1173 +1174 if stat_type_id is not None and url_elements == 0: +1175 url += f"&statTypeId={stat_type_id}" +1176 url_elements += 1 +1177 elif stat_type_id is not None: +1178 url += f"&statTypeId={stat_type_id}" +1179 url_elements += 1 +1180 +1181 headers = { +1182 "Authorization": f"{real_api_key}", +1183 "accept": "application/json" +1184 } +1185 +1186 response = requests.get(url, headers=headers) +1187 +1188 if response.status_code == 200: +1189 pass +1190 elif response.status_code == 401: +1191 raise ConnectionRefusedError( +1192 "Could not connect. The connection was refused." + +1193 "\nHTTP Status Code 401." +1194 ) +1195 else: +1196 raise ConnectionError( +1197 f"Could not connect.\nHTTP Status code {response.status_code}" +1198 ) +1199 +1200 json_data = response.json() +1201 +1202 if return_as_dict is True: +1203 return json_data +1204 +1205 pbp_df = pd.json_normalize(json_data) +1206 pbp_df.rename( +1207 columns={ +1208 "gameId": "game_id", +1209 "teamScore": "team_score", +1210 "opponentScore": "opponent_score", +1211 "driveId": "drive_id", +1212 "playId": "play_id", +1213 "yardsToGoal": "yards_to_goal", +1214 "athleteId": "athlete_id", +1215 "athleteName": "athlete_name", +1216 "statType": "stat_type", +1217 }, +1218 inplace=True, +1219 ) +1220 # TODO: Implement an option to put all stats for +1221 # a specific game on a single line. +1222 return pbp_df +1223 +1224 +1225def get_cfbd_pbp_stat_types( +1226 api_key: str = None, +1227 api_key_dir: str = None, +1228 return_as_dict: bool = False +1229): +1230 """ +1231 Allows you to get CFBD PBP stat types from the CFBD API. +1232 +1233 Parameters +1234 ---------- +1235 +1236 `api_key` (str, optional): +1237 Semi-optional argument. +1238 If `api_key` is null, this function will attempt to load a CFBD API key +1239 from the python environment, or from a file on this computer. +1240 If `api_key` is not null, +1241 this function will automatically assume that the +1242 inputted `api_key` is a valid CFBD API key. 1243 -1244 `return_as_dict` (bool, semi-optional): -1245 Semi-optional argument. -1246 If you want this function to return -1247 the data as a dictionary (read: JSON object), -1248 instead of a pandas `DataFrame` object, -1249 set `return_as_dict` to `True`. -1250 -1251 Usage -1252 ---------- -1253 ``` -1254 ``` -1255 Returns -1256 ---------- -1257 A pandas `DataFrame` object with CFBD PBP stat types, -1258 or (if `return_as_dict` is set to `True`) -1259 a dictionary object with CFBD PBP stat types. +1244 `api_key_dir` (str, optional): +1245 Optional argument. +1246 If `api_key` is set to am empty string, this variable is ignored. +1247 If `api_key_dir` is null, and `api_key` is null, +1248 this function will try to find +1249 a CFBD API key file in this user's home directory. +1250 If `api_key_dir` is set to a string, and `api_key` is null, +1251 this function will assume that `api_key_dir` is a directory, +1252 and will try to find a CFBD API key file in that directory. +1253 +1254 `return_as_dict` (bool, semi-optional): +1255 Semi-optional argument. +1256 If you want this function to return +1257 the data as a dictionary (read: JSON object), +1258 instead of a pandas `DataFrame` object, +1259 set `return_as_dict` to `True`. 1260 -1261 """ -1262 # now = datetime.now() -1263 plays_df = pd.DataFrame() -1264 row_df = pd.DataFrame() -1265 url = "https://api.collegefootballdata.com/play/types" -1266 -1267 # Input validation -1268 ########################################################################## -1269 -1270 if api_key is not None: -1271 real_api_key = api_key -1272 del api_key -1273 else: -1274 real_api_key = get_cfbd_api_token(api_key_dir=api_key_dir) -1275 -1276 if real_api_key == "tigersAreAwesome": -1277 raise ValueError( -1278 "You actually need to change `cfbd_key` to your CFBD API key." -1279 ) -1280 elif "Bearer " in real_api_key: -1281 pass -1282 elif "Bearer" in real_api_key: -1283 real_api_key = real_api_key.replace("Bearer", "Bearer ") +1261 Usage +1262 ---------- +1263 ``` +1264 ``` +1265 Returns +1266 ---------- +1267 A pandas `DataFrame` object with CFBD PBP stat types, +1268 or (if `return_as_dict` is set to `True`) +1269 a dictionary object with CFBD PBP stat types. +1270 +1271 """ +1272 # now = datetime.now() +1273 plays_df = pd.DataFrame() +1274 plays_df_arr = [] +1275 row_df = pd.DataFrame() +1276 url = "https://api.collegefootballdata.com/play/types" +1277 +1278 # Input validation +1279 ########################################################################## +1280 +1281 if api_key is not None: +1282 real_api_key = api_key +1283 del api_key 1284 else: -1285 real_api_key = "Bearer " + real_api_key +1285 real_api_key = get_cfbd_api_token(api_key_dir=api_key_dir) 1286 -1287 headers = { -1288 "Authorization": f"{real_api_key}", -1289 "accept": "application/json" -1290 } -1291 -1292 response = requests.get(url, headers=headers) -1293 -1294 if response.status_code == 200: -1295 pass -1296 elif response.status_code == 401: -1297 raise ConnectionRefusedError( -1298 "Could not connect. The connection was refused." + -1299 "\nHTTP Status Code 401." -1300 ) -1301 else: -1302 raise ConnectionError( -1303 f"Could not connect.\nHTTP Status code {response.status_code}" -1304 ) -1305 -1306 json_data = response.json() -1307 -1308 if return_as_dict is True: -1309 return json_data -1310 -1311 for p in tqdm(json_data): -1312 p_id = p["id"] -1313 row_df = pd.DataFrame({"stat_type_id": p_id}, index=[0]) -1314 row_df["stat_type_text"] = p["name"] -1315 plays_df = pd.concat([plays_df, row_df], ignore_index=True) +1287 if real_api_key == "tigersAreAwesome": +1288 raise ValueError( +1289 "You actually need to change `cfbd_key` to your CFBD API key." +1290 ) +1291 elif "Bearer " in real_api_key: +1292 pass +1293 elif "Bearer" in real_api_key: +1294 real_api_key = real_api_key.replace("Bearer", "Bearer ") +1295 else: +1296 real_api_key = "Bearer " + real_api_key +1297 +1298 headers = { +1299 "Authorization": f"{real_api_key}", +1300 "accept": "application/json" +1301 } +1302 +1303 response = requests.get(url, headers=headers) +1304 +1305 if response.status_code == 200: +1306 pass +1307 elif response.status_code == 401: +1308 raise ConnectionRefusedError( +1309 "Could not connect. The connection was refused." + +1310 "\nHTTP Status Code 401." +1311 ) +1312 else: +1313 raise ConnectionError( +1314 f"Could not connect.\nHTTP Status code {response.status_code}" +1315 ) 1316 -1317 del row_df -1318 del p_id -1319 -1320 return plays_df +1317 json_data = response.json() +1318 +1319 if return_as_dict is True: +1320 return json_data 1321 -1322 -1323############################################################################### -1324# Patreon Only Functions. -1325# No caching, because the entire point of these functions are to get people -1326# data ASAP, and right before kickoff. -1327############################################################################### -1328 -1329 -1330def get_cfbd_live_pbp_data( -1331 game_id: int, -1332 api_key: str = None, -1333 api_key_dir: str = None, -1334 # return_as_dict: bool = False, -1335): -1336 """ """ -1337 url = f"https://api.collegefootballdata.com/live/plays?id={game_id}" +1322 for p in json_data: +1323 p_id = p["id"] +1324 row_df = pd.DataFrame({"stat_type_id": p_id}, index=[0]) +1325 row_df["stat_type_abv"] = p["abbreviation"] +1326 try: +1327 row_df["stat_type_text"] = p["name"] +1328 except KeyError: +1329 row_df["stat_type_text"] = p["text"] +1330 # plays_df = pd.concat([plays_df, row_df], ignore_index=True) +1331 plays_df_arr.append(row_df) +1332 +1333 del row_df +1334 del p_id +1335 +1336 plays_df = pd.concat(plays_df_arr, ignore_index=True) +1337 return plays_df 1338 -1339 if api_key is not None: -1340 real_api_key = api_key -1341 del api_key -1342 else: -1343 real_api_key = get_cfbd_api_token(api_key_dir=api_key_dir) -1344 -1345 if real_api_key == "tigersAreAwesome": -1346 raise ValueError( -1347 "You actually need to change `cfbd_key` to your CFBD API key." -1348 ) -1349 elif "Bearer " in real_api_key: -1350 pass -1351 elif "Bearer" in real_api_key: -1352 real_api_key = real_api_key.replace("Bearer", "Bearer ") -1353 else: -1354 real_api_key = "Bearer " + real_api_key +1339 +1340############################################################################### +1341# Patreon Only Functions. +1342# No caching, because the entire point of these functions are to get people +1343# data ASAP, and right before kickoff. +1344############################################################################### +1345 +1346 +1347def get_cfbd_live_pbp_data( +1348 game_id: int, +1349 api_key: str = None, +1350 api_key_dir: str = None, +1351 # return_as_dict: bool = False, +1352): +1353 """ """ +1354 url = f"https://api.collegefootballdata.com/live/plays?id={game_id}" 1355 -1356 headers = { -1357 "Authorization": f"{real_api_key}", -1358 "accept": "application/json" -1359 } -1360 -1361 response = requests.get(url, headers=headers) -1362 -1363 if response.status_code == 200: -1364 pass -1365 elif response.status_code == 401: -1366 raise ConnectionRefusedError( -1367 "Could not connect. The connection was refused.\n" + -1368 "HTTP Status Code 401." -1369 ) +1356 if api_key is not None: +1357 real_api_key = api_key +1358 del api_key +1359 else: +1360 real_api_key = get_cfbd_api_token(api_key_dir=api_key_dir) +1361 +1362 if real_api_key == "tigersAreAwesome": +1363 raise ValueError( +1364 "You actually need to change `cfbd_key` to your CFBD API key." +1365 ) +1366 elif "Bearer " in real_api_key: +1367 pass +1368 elif "Bearer" in real_api_key: +1369 real_api_key = real_api_key.replace("Bearer", "Bearer ") 1370 else: -1371 raise ConnectionError( -1372 f"Could not connect.\nHTTP Status code {response.status_code}" -1373 ) -1374 -1375 json_data = response.json() -1376 return json_data +1371 real_api_key = "Bearer " + real_api_key +1372 +1373 headers = { +1374 "Authorization": f"{real_api_key}", +1375 "accept": "application/json" +1376 } +1377 +1378 response = requests.get(url, headers=headers) +1379 +1380 if response.status_code == 200: +1381 pass +1382 elif response.status_code == 401: +1383 raise ConnectionRefusedError( +1384 "Could not connect. The connection was refused.\n" + +1385 "HTTP Status Code 401." +1386 ) +1387 else: +1388 raise ConnectionError( +1389 f"Could not connect.\nHTTP Status code {response.status_code}" +1390 ) +1391 +1392 json_data = response.json() +1393 return json_data @@ -4007,110 +4024,114 @@

Returns

637def get_cfbd_pbp_play_types(
-638    api_key: str = None, api_key_dir: str = None, return_as_dict: bool = False
-639):
-640    """
-641    Allows you to get CFBD PBP play types from the CFBD API.
-642
-643    Parameters
-644    ----------
-645
-646    `api_key` (str, optional):
-647        Semi-optional argument.
-648        If `api_key` is null, this function will attempt to load a CFBD API key
-649        from the python environment, or from a file on this computer.
-650        If `api_key` is not null,
-651        this function will automatically assume that the
-652        inputted `api_key` is a valid CFBD API key.
-653
-654    `api_key_dir` (str, optional):
-655        Optional argument.
-656        If `api_key` is set to am empty string, this variable is ignored.
-657        If `api_key_dir` is null, and `api_key` is null,
-658        this function will try to find
-659        a CFBD API key file in this user's home directory.
-660        If `api_key_dir` is set to a string, and `api_key` is null,
-661        this function will assume that `api_key_dir` is a directory,
-662        and will try to find a CFBD API key file in that directory.
-663
-664    `return_as_dict` (bool, semi-optional):
-665        Semi-optional argument.
-666        If you want this function to return
-667        the data as a dictionary (read: JSON object),
-668        instead of a pandas `DataFrame` object,
-669        set `return_as_dict` to `True`.
-670
-671    Usage
-672    ----------
-673    ```
-674    ```
-675    Returns
-676    ----------
-677    A pandas `DataFrame` object with CFBD PBP play types,
-678    or (if `return_as_dict` is set to `True`)
-679    a dictionary object with CFBD PBP play types.
-680
-681    """
-682    # now = datetime.now()
-683    plays_df = pd.DataFrame()
-684    row_df = pd.DataFrame()
-685    url = "https://api.collegefootballdata.com/play/types"
-686
-687    # Input validation
-688    ##########################################################################
+638    api_key: str = None,
+639    api_key_dir: str = None,
+640    return_as_dict: bool = False
+641):
+642    """
+643    Allows you to get CFBD PBP play types from the CFBD API.
+644
+645    Parameters
+646    ----------
+647
+648    `api_key` (str, optional):
+649        Semi-optional argument.
+650        If `api_key` is null, this function will attempt to load a CFBD API key
+651        from the python environment, or from a file on this computer.
+652        If `api_key` is not null,
+653        this function will automatically assume that the
+654        inputted `api_key` is a valid CFBD API key.
+655
+656    `api_key_dir` (str, optional):
+657        Optional argument.
+658        If `api_key` is set to am empty string, this variable is ignored.
+659        If `api_key_dir` is null, and `api_key` is null,
+660        this function will try to find
+661        a CFBD API key file in this user's home directory.
+662        If `api_key_dir` is set to a string, and `api_key` is null,
+663        this function will assume that `api_key_dir` is a directory,
+664        and will try to find a CFBD API key file in that directory.
+665
+666    `return_as_dict` (bool, semi-optional):
+667        Semi-optional argument.
+668        If you want this function to return
+669        the data as a dictionary (read: JSON object),
+670        instead of a pandas `DataFrame` object,
+671        set `return_as_dict` to `True`.
+672
+673    Usage
+674    ----------
+675    ```
+676    ```
+677    Returns
+678    ----------
+679    A pandas `DataFrame` object with CFBD PBP play types,
+680    or (if `return_as_dict` is set to `True`)
+681    a dictionary object with CFBD PBP play types.
+682
+683    """
+684    # now = datetime.now()
+685    plays_df = pd.DataFrame()
+686    plays_df_arr = []
+687    row_df = pd.DataFrame()
+688    url = "https://api.collegefootballdata.com/play/types"
 689
-690    if api_key is not None:
-691        real_api_key = api_key
-692        del api_key
-693    else:
-694        real_api_key = get_cfbd_api_token(api_key_dir=api_key_dir)
-695
-696    if real_api_key == "tigersAreAwesome":
-697        raise ValueError(
-698            "You actually need to change `cfbd_key` to your CFBD API key."
-699        )
-700    elif "Bearer " in real_api_key:
-701        pass
-702    elif "Bearer" in real_api_key:
-703        real_api_key = real_api_key.replace("Bearer", "Bearer ")
-704    else:
-705        real_api_key = "Bearer " + real_api_key
-706
-707    headers = {
-708        "Authorization": f"{real_api_key}",
-709        "accept": "application/json"
-710    }
-711
-712    response = requests.get(url, headers=headers)
-713
-714    if response.status_code == 200:
-715        pass
-716    elif response.status_code == 401:
-717        raise ConnectionRefusedError(
-718            "Could not connect. The connection was refused." +
-719            "\nHTTP Status Code 401."
-720        )
-721    else:
-722        raise ConnectionError(
-723            f"Could not connect.\nHTTP Status code {response.status_code}"
-724        )
-725
-726    json_data = response.json()
-727
-728    if return_as_dict is True:
-729        return json_data
+690    # Input validation
+691    ##########################################################################
+692
+693    if api_key is not None:
+694        real_api_key = api_key
+695        del api_key
+696    else:
+697        real_api_key = get_cfbd_api_token(api_key_dir=api_key_dir)
+698
+699    if real_api_key == "tigersAreAwesome":
+700        raise ValueError(
+701            "You actually need to change `cfbd_key` to your CFBD API key."
+702        )
+703    elif "Bearer " in real_api_key:
+704        pass
+705    elif "Bearer" in real_api_key:
+706        real_api_key = real_api_key.replace("Bearer", "Bearer ")
+707    else:
+708        real_api_key = "Bearer " + real_api_key
+709
+710    headers = {
+711        "Authorization": f"{real_api_key}",
+712        "accept": "application/json"
+713    }
+714
+715    response = requests.get(url, headers=headers)
+716
+717    if response.status_code == 200:
+718        pass
+719    elif response.status_code == 401:
+720        raise ConnectionRefusedError(
+721            "Could not connect. The connection was refused." +
+722            "\nHTTP Status Code 401."
+723        )
+724    else:
+725        raise ConnectionError(
+726            f"Could not connect.\nHTTP Status code {response.status_code}"
+727        )
+728
+729    json_data = response.json()
 730
-731    for p in tqdm(json_data):
-732        p_id = p["id"]
-733        row_df = pd.DataFrame({"play_type_id": p_id}, index=[0])
-734        row_df["play_type_text"] = p["text"]
-735        row_df["play_type_abv"] = p["abbreviation"]
-736        plays_df = pd.concat([plays_df, row_df], ignore_index=True)
-737
-738        del row_df
-739        del p_id
-740
-741    return plays_df
+731    if return_as_dict is True:
+732        return json_data
+733
+734    for p in json_data:
+735        p_id = p["id"]
+736        row_df = pd.DataFrame({"play_type_id": p_id}, index=[0])
+737        row_df["play_type_text"] = p["text"]
+738        row_df["play_type_abv"] = p["abbreviation"]
+739        # plays_df = pd.concat([plays_df, row_df], ignore_index=True)
+740        plays_df_arr.append(row_df)
+741        del row_df
+742        del p_id
+743
+744    plays_df = pd.concat(plays_df_arr, ignore_index=True)
+745    return plays_df
 
@@ -4195,478 +4216,482 @@

Returns

-
 744def get_cfbd_pbp_stats(
- 745    api_key: str = None,
- 746    api_key_dir: str = None,
- 747    season: int = None,
- 748    week: int = None,
- 749    team: str = None,
- 750    game_id: int = None,
- 751    athlete_id: int = None,
- 752    stat_type_id: int = None,
- 753    season_type: str = "both",  # "regular", "postseason", or "both"
- 754    conference: str = None,
- 755    return_as_dict: bool = False,
- 756):
- 757    """
- 758    Allows you to get stats for various players
- 759    from CFB play-by-play (PBP) data within the CFBD API.
- 760    Parameters
- 761    ----------
- 762
- 763    `api_key` (str, optional):
- 764        Semi-optional argument.
- 765        If `api_key` is null, this function will attempt to load a CFBD API key
- 766        from the python environment, or from a file on this computer.
- 767        If `api_key` is not null,
- 768        this function will automatically assume that the
- 769        inputted `api_key` is a valid CFBD API key.
- 770
- 771    `api_key_dir` (str, optional):
- 772        Optional argument.
- 773        If `api_key` is set to am empty string, this variable is ignored.
- 774        If `api_key_dir` is null, and `api_key` is null,
- 775        this function will try to find
- 776        a CFBD API key file in this user's home directory.
- 777        If `api_key_dir` is set to a string, and `api_key` is null,
- 778        this function will assume that `api_key_dir` is a directory,
- 779        and will try to find a CFBD API key file in that directory.
- 780
- 781    `season` (int, optional):
- 782        Semi-optional argument.
- 783        Specifies the season you want CFB PBP data from.
- 784        This must be specified, otherwise this package, and by extension
- 785        the CFBD API, will not accept the request to get CFB PBP data.
- 786
- 787    `week` (int, optional):
- 788        Optional argument.
- 789        If `week` is set to an integer, this function will attempt
- 790        to load CFB poll rankings data from games in that season,
- 791        and in that week.
- 792
- 793    `team` (str, optional):
- 794        Optional argument.
- 795        If you only want stats for a specific team,
- 796        set `team` to the name of that specific team.
+                
 748def get_cfbd_pbp_stats(
+ 749    api_key: str = None,
+ 750    api_key_dir: str = None,
+ 751    season: int = None,
+ 752    week: int = None,
+ 753    team: str = None,
+ 754    game_id: int = None,
+ 755    athlete_id: int = None,
+ 756    stat_type_id: int = None,
+ 757    season_type: str = "both",  # "regular", "postseason", or "both"
+ 758    conference: str = None,
+ 759    return_as_dict: bool = False,
+ 760):
+ 761    """
+ 762    Allows you to get stats for various players
+ 763    from CFB play-by-play (PBP) data within the CFBD API.
+ 764
+ 765    Parameters
+ 766    ----------
+ 767
+ 768    `api_key` (str, optional):
+ 769        Semi-optional argument.
+ 770        If `api_key` is null, this function will attempt to load a CFBD API key
+ 771        from the python environment, or from a file on this computer.
+ 772        If `api_key` is not null,
+ 773        this function will automatically assume that the
+ 774        inputted `api_key` is a valid CFBD API key.
+ 775
+ 776    `api_key_dir` (str, optional):
+ 777        Optional argument.
+ 778        If `api_key` is set to am empty string, this variable is ignored.
+ 779        If `api_key_dir` is null, and `api_key` is null,
+ 780        this function will try to find
+ 781        a CFBD API key file in this user's home directory.
+ 782        If `api_key_dir` is set to a string, and `api_key` is null,
+ 783        this function will assume that `api_key_dir` is a directory,
+ 784        and will try to find a CFBD API key file in that directory.
+ 785
+ 786    `season` (int, optional):
+ 787        Semi-optional argument.
+ 788        Specifies the season you want CFB PBP data from.
+ 789        This must be specified, otherwise this package, and by extension
+ 790        the CFBD API, will not accept the request to get CFB PBP data.
+ 791
+ 792    `week` (int, optional):
+ 793        Optional argument.
+ 794        If `week` is set to an integer, this function will attempt
+ 795        to load CFB poll rankings data from games in that season,
+ 796        and in that week.
  797
- 798    `game_id` (int, optional):
+ 798    `team` (str, optional):
  799        Optional argument.
- 800        If you only want stats for a specific game,
- 801        set `game_id` to the ID of that specific game.
+ 800        If you only want stats for a specific team,
+ 801        set `team` to the name of that specific team.
  802
- 803    `athlete_id` (int, optional):
+ 803    `game_id` (int, optional):
  804        Optional argument.
- 805        If you only want stats for a specific player,
- 806        set `athlete_id` to the ID of the player you want stats for.
+ 805        If you only want stats for a specific game,
+ 806        set `game_id` to the ID of that specific game.
  807
- 808    `stats_type_id` (int, optional):
+ 808    `athlete_id` (int, optional):
  809        Optional argument.
- 810        If want to drill down, and only get plays of a specific type,
- 811        (like rushing, passing, kicking plays),
- 812        set `play_type` to the ID for the play type you want returned.
- 813        To retrieve a list of valid play type IDs,
- 814        use `cfbd_json_py.plays.get_cfbd_pbp_play_types()`.
- 815
- 816    `season_type` (str, semi-optional):
- 817        Semi-optional argument.
- 818        By default, this will be set to "regular", for the CFB regular season.
- 819        If you want CFB poll rankings data for non-regular season games,
- 820        set `season_type` to "postseason".
- 821        If `season_type` is set to anything but "regular" or "postseason",
- 822        a `ValueError()` will be raised.
- 823
- 824    `conference` (str, optional):
- 825        Optional argument.
- 826        If you only want CFB drive data from games
- 827        involving teams from a specific conference,
- 828        set `conference` to the abbreviation
- 829        of the conference you want CFB drive data from.
- 830        For a list of conferences,
- 831        use the `cfbd_json_py.conferences.get_cfbd_conference_info()`
- 832        function.
- 833
- 834    `return_as_dict` (bool, semi-optional):
- 835        Semi-optional argument.
- 836        If you want this function to return
- 837        the data as a dictionary (read: JSON object),
- 838        instead of a pandas `DataFrame` object,
- 839        set `return_as_dict` to `True`.
- 840
- 841    Usage
- 842    ----------
- 843    ```
- 844    import time
+ 810        If you only want stats for a specific player,
+ 811        set `athlete_id` to the ID of the player you want stats for.
+ 812
+ 813    `stats_type_id` (int, optional):
+ 814        Optional argument.
+ 815        If want to drill down, and only get plays of a specific type,
+ 816        (like rushing, passing, kicking plays),
+ 817        set `play_type` to the ID for the play type you want returned.
+ 818        To retrieve a list of valid play type IDs,
+ 819        use `cfbd_json_py.plays.get_cfbd_pbp_play_types()`.
+ 820
+ 821    `season_type` (str, semi-optional):
+ 822        Semi-optional argument.
+ 823        By default, this will be set to "regular", for the CFB regular season.
+ 824        If you want CFB poll rankings data for non-regular season games,
+ 825        set `season_type` to "postseason".
+ 826        If `season_type` is set to anything but "regular" or "postseason",
+ 827        a `ValueError()` will be raised.
+ 828
+ 829    `conference` (str, optional):
+ 830        Optional argument.
+ 831        If you only want CFB drive data from games
+ 832        involving teams from a specific conference,
+ 833        set `conference` to the abbreviation
+ 834        of the conference you want CFB drive data from.
+ 835        For a list of conferences,
+ 836        use the `cfbd_json_py.conferences.get_cfbd_conference_info()`
+ 837        function.
+ 838
+ 839    `return_as_dict` (bool, semi-optional):
+ 840        Semi-optional argument.
+ 841        If you want this function to return
+ 842        the data as a dictionary (read: JSON object),
+ 843        instead of a pandas `DataFrame` object,
+ 844        set `return_as_dict` to `True`.
  845
- 846    from cfbd_json_py.plays import get_cfbd_pbp_stats
- 847
- 848
- 849    cfbd_key = "tigersAreAwesome"  # placeholder for your CFBD API Key.
+ 846    Usage
+ 847    ----------
+ 848    ```
+ 849    import time
  850
- 851    if cfbd_key != "tigersAreAwesome":
- 852        print(
- 853            "Using the user's API key declared in this script " +
- 854            "for this example."
- 855        )
- 856
- 857        # Get CFB PBP stats data for the 2020 CFB season.
- 858        print("Get CFB PBP stats data for the 2020 CFB season.")
- 859        json_data = get_cfbd_pbp_stats(
- 860            api_key=cfbd_key,
- 861            season=2020
- 862        )
- 863        print(json_data)
- 864        time.sleep(5)
- 865
- 866        # Get CFB PBP stats data for week 10 of the 2020 CFB season.
- 867        print("Get CFB PBP stats data for week 10 of the 2020 CFB season.")
- 868        json_data = get_cfbd_pbp_stats(
- 869            api_key=cfbd_key,
- 870            season=2020,
- 871            week=10
- 872        )
- 873        print(json_data)
- 874        time.sleep(5)
- 875
- 876        # Get CFB PBP stats data for a 2019 game between
- 877        # the Ohio State Buckeyes and Clemson Tigers football teams.
- 878        print(
- 879            "Get CFB PBP stats data for a 2019 game between " +
- 880            "the Ohio State Buckeyes and Clemson Tigers football teams."
- 881        )
- 882        json_data = get_cfbd_pbp_stats(
- 883            api_key=cfbd_key,
- 884            game_id=401135279
- 885        )
- 886        print(json_data)
- 887        time.sleep(5)
- 888
- 889        # Get CFB PBP stats data for Trevor Lawrence (athlete ID #4360310)
- 890        # during the 2020 CFB Season.
- 891        print("Get CFB PBP stats data for the 2020 CFB season.")
- 892        json_data = get_cfbd_pbp_stats(
- 893            api_key=cfbd_key,
- 894            season=2020,
- 895            athlete_id=4360310
- 896        )
- 897        print(json_data)
- 898        time.sleep(5)
- 899
- 900        # Get CFB PBP stats data for Trevor Lawrence (athlete ID #4360310)
- 901        # during the 2020 CFB Season,
- 902        # but only return plays where Lawrence scored a touchdown.
- 903        print("Get CFB PBP stats data for the 2020 CFB season.")
- 904        json_data = get_cfbd_pbp_stats(
- 905            api_key=cfbd_key,
- 906            season=2020,
- 907            athlete_id=4360310,
- 908            stat_type_id=22
- 909        )
- 910        print(json_data)
- 911        time.sleep(5)
- 912
- 913        # Get CFB PBP stats data for the 2020 CFB season,
- 914        # but only for postseason games.
- 915        print("Get CFB PBP stats data for the 2020 CFB season.")
- 916        json_data = get_cfbd_pbp_stats(
- 917            api_key=cfbd_key,
- 918            season=2020,
- 919            season_type="postseason"
- 920        )
- 921        print(json_data)
- 922        time.sleep(5)
- 923
- 924        # Get CFB PBP stats data for the 2020 CFB season,
- 925        # but only for Big 10 (B1G) games.
- 926        print("Get CFB PBP stats data for the 2020 CFB season.")
- 927        json_data = get_cfbd_pbp_stats(
- 928            api_key=cfbd_key,
- 929            season=2020,
- 930            conference="B1G"
- 931        )
- 932        print(json_data)
- 933        time.sleep(5)
- 934
- 935        # Get CFB PBP stats data for the 2020 CFB season.
- 936        print("Get CFB PBP stats data for the 2020 CFB season.")
- 937        json_data = get_cfbd_pbp_stats(
- 938            api_key=cfbd_key,
- 939            season=2020
- 940        )
- 941        print(json_data)
- 942        time.sleep(5)
- 943
- 944        # You can also tell this function to just return the API call as
- 945        # a Dictionary (read: JSON) object.
- 946        print(
- 947            "You can also tell this function to just return the API call " +
- 948            "as a Dictionary (read: JSON) object."
- 949        )
- 950        json_data = get_cfbd_pbp_stats(
- 951            api_key=cfbd_key,
- 952            season=2020,
- 953            week=10,
- 954            return_as_dict=True
- 955        )
- 956        print(json_data)
- 957
- 958    else:
- 959        # Alternatively, if the CFBD API key exists in this python environment,
- 960        # or it's been set by cfbd_json_py.utls.set_cfbd_api_token(),
- 961        # you could just call these functions directly,
- 962        # without setting the API key in the script.
- 963        print(
- 964            "Using the user's API key supposedly loaded " +
- 965            "into this python environment for this example."
- 966        )
- 967
- 968        # Get CFB PBP stats data for the 2020 CFB season.
- 969        print("Get CFB PBP stats data for the 2020 CFB season.")
- 970        json_data = get_cfbd_pbp_stats(
- 971            season=2020
- 972        )
- 973        print(json_data)
- 974        time.sleep(5)
- 975
- 976        # Get CFB PBP stats data for week 10 of the 2020 CFB season.
- 977        print("Get CFB PBP stats data for week 10 of the 2020 CFB season.")
- 978        json_data = get_cfbd_pbp_stats(
- 979            season=2020,
- 980            week=10
- 981        )
- 982        print(json_data)
- 983        time.sleep(5)
- 984
- 985        # Get CFB PBP stats data for a 2019 game between
- 986        # the Ohio State Buckeyes and Clemson Tigers football teams.
- 987        print(
- 988            "Get CFB PBP stats data for a 2019 game between " +
- 989            "the Ohio State Buckeyes and Clemson Tigers football teams."
- 990        )
- 991        json_data = get_cfbd_pbp_stats(
- 992            game_id=401135279
- 993        )
- 994        print(json_data)
- 995        time.sleep(5)
- 996
- 997        # Get CFB PBP stats data for Trevor Lawrence (athlete ID #4360310)
- 998        # during the 2020 CFB Season.
- 999        print("Get CFB PBP stats data for the 2020 CFB season.")
-1000        json_data = get_cfbd_pbp_stats(
-1001            season=2020,
-1002            athlete_id=4360310
-1003        )
-1004        print(json_data)
-1005        time.sleep(5)
-1006
-1007        # Get CFB PBP stats data for Trevor Lawrence (athlete ID #4360310)
-1008        # during the 2020 CFB Season,
-1009        # but only return plays where Lawrence scored a touchdown.
-1010        print("Get CFB PBP stats data for the 2020 CFB season.")
-1011        json_data = get_cfbd_pbp_stats(
-1012            season=2020,
-1013            athlete_id=4360310,
-1014            stat_type_id=22
-1015        )
-1016        print(json_data)
-1017        time.sleep(5)
-1018
-1019        # Get CFB PBP stats data for the 2020 CFB season,
-1020        # but only for postseason games.
-1021        print("Get CFB PBP stats data for the 2020 CFB season.")
-1022        json_data = get_cfbd_pbp_stats(
-1023            season=2020,
-1024            season_type="postseason"
-1025        )
-1026        print(json_data)
-1027        time.sleep(5)
-1028
-1029        # Get CFB PBP stats data for the 2020 CFB season,
-1030        # but only for Big 10 (B1G) games.
-1031        print("Get CFB PBP stats data for the 2020 CFB season.")
-1032        json_data = get_cfbd_pbp_stats(
-1033            season=2020,
-1034            conference="B1G"
-1035        )
-1036        print(json_data)
-1037        time.sleep(5)
-1038
-1039        # You can also tell this function to just return the API call as
-1040        # a Dictionary (read: JSON) object.
-1041        print(
-1042            "You can also tell this function to just return the API call " +
-1043            "as a Dictionary (read: JSON) object."
-1044        )
-1045        json_data = get_cfbd_pbp_stats(
-1046            season=2020,
-1047            week=10,
-1048            return_as_dict=True
+ 851    from cfbd_json_py.plays import get_cfbd_pbp_stats
+ 852
+ 853
+ 854    cfbd_key = "tigersAreAwesome"  # placeholder for your CFBD API Key.
+ 855
+ 856    if cfbd_key != "tigersAreAwesome":
+ 857        print(
+ 858            "Using the user's API key declared in this script " +
+ 859            "for this example."
+ 860        )
+ 861
+ 862        # Get CFB PBP stats data for the 2020 CFB season.
+ 863        print("Get CFB PBP stats data for the 2020 CFB season.")
+ 864        json_data = get_cfbd_pbp_stats(
+ 865            api_key=cfbd_key,
+ 866            season=2020
+ 867        )
+ 868        print(json_data)
+ 869        time.sleep(5)
+ 870
+ 871        # Get CFB PBP stats data for week 10 of the 2020 CFB season.
+ 872        print("Get CFB PBP stats data for week 10 of the 2020 CFB season.")
+ 873        json_data = get_cfbd_pbp_stats(
+ 874            api_key=cfbd_key,
+ 875            season=2020,
+ 876            week=10
+ 877        )
+ 878        print(json_data)
+ 879        time.sleep(5)
+ 880
+ 881        # Get CFB PBP stats data for a 2019 game between
+ 882        # the Ohio State Buckeyes and Clemson Tigers football teams.
+ 883        print(
+ 884            "Get CFB PBP stats data for a 2019 game between " +
+ 885            "the Ohio State Buckeyes and Clemson Tigers football teams."
+ 886        )
+ 887        json_data = get_cfbd_pbp_stats(
+ 888            api_key=cfbd_key,
+ 889            game_id=401135279
+ 890        )
+ 891        print(json_data)
+ 892        time.sleep(5)
+ 893
+ 894        # Get CFB PBP stats data for Trevor Lawrence (athlete ID #4360310)
+ 895        # during the 2020 CFB Season.
+ 896        print("Get CFB PBP stats data for the 2020 CFB season.")
+ 897        json_data = get_cfbd_pbp_stats(
+ 898            api_key=cfbd_key,
+ 899            season=2020,
+ 900            athlete_id=4360310
+ 901        )
+ 902        print(json_data)
+ 903        time.sleep(5)
+ 904
+ 905        # Get CFB PBP stats data for Trevor Lawrence (athlete ID #4360310)
+ 906        # during the 2020 CFB Season,
+ 907        # but only return plays where Lawrence scored a touchdown.
+ 908        print("Get CFB PBP stats data for the 2020 CFB season.")
+ 909        json_data = get_cfbd_pbp_stats(
+ 910            api_key=cfbd_key,
+ 911            season=2020,
+ 912            athlete_id=4360310,
+ 913            stat_type_id=22
+ 914        )
+ 915        print(json_data)
+ 916        time.sleep(5)
+ 917
+ 918        # Get CFB PBP stats data for the 2020 CFB season,
+ 919        # but only for postseason games.
+ 920        print("Get CFB PBP stats data for the 2020 CFB season.")
+ 921        json_data = get_cfbd_pbp_stats(
+ 922            api_key=cfbd_key,
+ 923            season=2020,
+ 924            season_type="postseason"
+ 925        )
+ 926        print(json_data)
+ 927        time.sleep(5)
+ 928
+ 929        # Get CFB PBP stats data for the 2020 CFB season,
+ 930        # but only for Big 10 (B1G) games.
+ 931        print("Get CFB PBP stats data for the 2020 CFB season.")
+ 932        json_data = get_cfbd_pbp_stats(
+ 933            api_key=cfbd_key,
+ 934            season=2020,
+ 935            conference="B1G"
+ 936        )
+ 937        print(json_data)
+ 938        time.sleep(5)
+ 939
+ 940        # Get CFB PBP stats data for the 2020 CFB season.
+ 941        print("Get CFB PBP stats data for the 2020 CFB season.")
+ 942        json_data = get_cfbd_pbp_stats(
+ 943            api_key=cfbd_key,
+ 944            season=2020
+ 945        )
+ 946        print(json_data)
+ 947        time.sleep(5)
+ 948
+ 949        # You can also tell this function to just return the API call as
+ 950        # a Dictionary (read: JSON) object.
+ 951        print(
+ 952            "You can also tell this function to just return the API call " +
+ 953            "as a Dictionary (read: JSON) object."
+ 954        )
+ 955        json_data = get_cfbd_pbp_stats(
+ 956            api_key=cfbd_key,
+ 957            season=2020,
+ 958            week=10,
+ 959            return_as_dict=True
+ 960        )
+ 961        print(json_data)
+ 962
+ 963    else:
+ 964        # Alternatively, if the CFBD API key exists in this python environment,
+ 965        # or it's been set by cfbd_json_py.utls.set_cfbd_api_token(),
+ 966        # you could just call these functions directly,
+ 967        # without setting the API key in the script.
+ 968        print(
+ 969            "Using the user's API key supposedly loaded " +
+ 970            "into this python environment for this example."
+ 971        )
+ 972
+ 973        # Get CFB PBP stats data for the 2020 CFB season.
+ 974        print("Get CFB PBP stats data for the 2020 CFB season.")
+ 975        json_data = get_cfbd_pbp_stats(
+ 976            season=2020
+ 977        )
+ 978        print(json_data)
+ 979        time.sleep(5)
+ 980
+ 981        # Get CFB PBP stats data for week 10 of the 2020 CFB season.
+ 982        print("Get CFB PBP stats data for week 10 of the 2020 CFB season.")
+ 983        json_data = get_cfbd_pbp_stats(
+ 984            season=2020,
+ 985            week=10
+ 986        )
+ 987        print(json_data)
+ 988        time.sleep(5)
+ 989
+ 990        # Get CFB PBP stats data for a 2019 game between
+ 991        # the Ohio State Buckeyes and Clemson Tigers football teams.
+ 992        print(
+ 993            "Get CFB PBP stats data for a 2019 game between " +
+ 994            "the Ohio State Buckeyes and Clemson Tigers football teams."
+ 995        )
+ 996        json_data = get_cfbd_pbp_stats(
+ 997            game_id=401135279
+ 998        )
+ 999        print(json_data)
+1000        time.sleep(5)
+1001
+1002        # Get CFB PBP stats data for Trevor Lawrence (athlete ID #4360310)
+1003        # during the 2020 CFB Season.
+1004        print("Get CFB PBP stats data for the 2020 CFB season.")
+1005        json_data = get_cfbd_pbp_stats(
+1006            season=2020,
+1007            athlete_id=4360310
+1008        )
+1009        print(json_data)
+1010        time.sleep(5)
+1011
+1012        # Get CFB PBP stats data for Trevor Lawrence (athlete ID #4360310)
+1013        # during the 2020 CFB Season,
+1014        # but only return plays where Lawrence scored a touchdown.
+1015        print("Get CFB PBP stats data for the 2020 CFB season.")
+1016        json_data = get_cfbd_pbp_stats(
+1017            season=2020,
+1018            athlete_id=4360310,
+1019            stat_type_id=22
+1020        )
+1021        print(json_data)
+1022        time.sleep(5)
+1023
+1024        # Get CFB PBP stats data for the 2020 CFB season,
+1025        # but only for postseason games.
+1026        print("Get CFB PBP stats data for the 2020 CFB season.")
+1027        json_data = get_cfbd_pbp_stats(
+1028            season=2020,
+1029            season_type="postseason"
+1030        )
+1031        print(json_data)
+1032        time.sleep(5)
+1033
+1034        # Get CFB PBP stats data for the 2020 CFB season,
+1035        # but only for Big 10 (B1G) games.
+1036        print("Get CFB PBP stats data for the 2020 CFB season.")
+1037        json_data = get_cfbd_pbp_stats(
+1038            season=2020,
+1039            conference="B1G"
+1040        )
+1041        print(json_data)
+1042        time.sleep(5)
+1043
+1044        # You can also tell this function to just return the API call as
+1045        # a Dictionary (read: JSON) object.
+1046        print(
+1047            "You can also tell this function to just return the API call " +
+1048            "as a Dictionary (read: JSON) object."
 1049        )
-1050        print(json_data)
-1051
-1052    ```
-1053    Returns
-1054    ----------
-1055    A pandas `DataFrame` object with CFB PBP data,
-1056    or (if `return_as_dict` is set to `True`)
-1057    a dictionary object with CFB PBP data.
-1058
-1059    """
-1060    now = datetime.now()
-1061    pbp_df = pd.DataFrame()
-1062    url = "https://api.collegefootballdata.com/play/stats"
+1050        json_data = get_cfbd_pbp_stats(
+1051            season=2020,
+1052            week=10,
+1053            return_as_dict=True
+1054        )
+1055        print(json_data)
+1056
+1057    ```
+1058    Returns
+1059    ----------
+1060    A pandas `DataFrame` object with CFB PBP data,
+1061    or (if `return_as_dict` is set to `True`)
+1062    a dictionary object with CFB PBP data.
 1063
-1064    # Input validation
-1065    ##########################################################################
-1066
-1067    if api_key is not None:
-1068        real_api_key = api_key
-1069        del api_key
-1070    else:
-1071        real_api_key = get_cfbd_api_token(api_key_dir=api_key_dir)
-1072
-1073    if real_api_key == "tigersAreAwesome":
-1074        raise ValueError(
-1075            "You actually need to change `cfbd_key` to your CFBD API key."
-1076        )
-1077    elif "Bearer " in real_api_key:
-1078        pass
-1079    elif "Bearer" in real_api_key:
-1080        real_api_key = real_api_key.replace("Bearer", "Bearer ")
-1081    else:
-1082        real_api_key = "Bearer " + real_api_key
-1083
-1084    if season is not None and (season > (now.year + 1)):
-1085        raise ValueError(f"`season` cannot be greater than {season}.")
-1086    elif season is not None and season < 1869:
-1087        raise ValueError("`season` cannot be less than 1869.")
+1064    """
+1065    now = datetime.now()
+1066    pbp_df = pd.DataFrame()
+1067    url = "https://api.collegefootballdata.com/play/stats"
+1068
+1069    # Input validation
+1070    ##########################################################################
+1071
+1072    if api_key is not None:
+1073        real_api_key = api_key
+1074        del api_key
+1075    else:
+1076        real_api_key = get_cfbd_api_token(api_key_dir=api_key_dir)
+1077
+1078    if real_api_key == "tigersAreAwesome":
+1079        raise ValueError(
+1080            "You actually need to change `cfbd_key` to your CFBD API key."
+1081        )
+1082    elif "Bearer " in real_api_key:
+1083        pass
+1084    elif "Bearer" in real_api_key:
+1085        real_api_key = real_api_key.replace("Bearer", "Bearer ")
+1086    else:
+1087        real_api_key = "Bearer " + real_api_key
 1088
-1089    if (
-1090        season_type != "regular"
-1091        and season_type != "postseason"
-1092        and season_type != "both"
-1093    ):
-1094        raise ValueError(
-1095            '`season_type` must be set to either ' +
-1096            '"regular", "postseason", or "both" for this function to work.'
-1097        )
-1098
-1099    if season is None and game_id is None:
-1100        logging.warn(
-1101            "This endpoint only returns the top 1,000 results. "
-1102            + "Not setting a value for `season` or `game_id` "
-1103            + "is not a recommended practice."
-1104        )
-1105    elif season is not None and game_id is None:
-1106        logging.warn(
-1107            "Setting a value for both `season` and `game_id` "
-1108            + "may not yeld the results you want. "
-1109            + "If you just want PBP stats for a valid game ID, "
-1110            + "just set `game_id` to a valid game ID."
-1111        )
-1112
-1113    # URL builder
-1114    ##########################################################################
-1115
-1116    url_elements = 0
-1117
-1118    if season_type is not None and url_elements == 0:
-1119        url += f"?seasonType={season_type}"
-1120        url_elements += 1
-1121    elif season_type is not None:
-1122        url += f"&seasonType={season_type}"
-1123        url_elements += 1
-1124
-1125    if season is not None and url_elements == 0:
-1126        url += f"?year={season}"
-1127        url_elements += 1
-1128    elif season is not None:
-1129        url += f"&year={season}"
-1130        url_elements += 1
-1131
-1132    if week is not None and url_elements == 0:
-1133        url += f"?week={week}"
-1134        url_elements += 1
-1135    elif week is not None:
-1136        url += f"&week={week}"
-1137        url_elements += 1
-1138
-1139    if team is not None and url_elements == 0:
-1140        url += f"?team={team}"
-1141        url_elements += 1
-1142    elif team is not None:
-1143        url += f"&team={team}"
-1144        url_elements += 1
-1145
-1146    if conference is not None and url_elements == 0:
-1147        url += f"&conference={conference}"
-1148        url_elements += 1
-1149    elif conference is not None:
-1150        url += f"&conference={conference}"
-1151        url_elements += 1
-1152
-1153    if game_id is not None and url_elements == 0:
-1154        url += f"&gameId={game_id}"
-1155        url_elements += 1
-1156    elif game_id is not None:
-1157        url += f"&gameId={game_id}"
-1158        url_elements += 1
-1159
-1160    if athlete_id is not None and url_elements == 0:
-1161        url += f"&athleteId={athlete_id}"
-1162        url_elements += 1
-1163    elif athlete_id is not None:
-1164        url += f"&athleteId={athlete_id}"
-1165        url_elements += 1
-1166
-1167    if stat_type_id is not None and url_elements == 0:
-1168        url += f"&statTypeId={stat_type_id}"
-1169        url_elements += 1
-1170    elif stat_type_id is not None:
-1171        url += f"&statTypeId={stat_type_id}"
-1172        url_elements += 1
-1173
-1174    headers = {
-1175        "Authorization": f"{real_api_key}",
-1176        "accept": "application/json"
-1177    }
-1178
-1179    response = requests.get(url, headers=headers)
-1180
-1181    if response.status_code == 200:
-1182        pass
-1183    elif response.status_code == 401:
-1184        raise ConnectionRefusedError(
-1185            "Could not connect. The connection was refused." +
-1186            "\nHTTP Status Code 401."
-1187        )
-1188    else:
-1189        raise ConnectionError(
-1190            f"Could not connect.\nHTTP Status code {response.status_code}"
-1191        )
-1192
-1193    json_data = response.json()
-1194
-1195    if return_as_dict is True:
-1196        return json_data
-1197
-1198    pbp_df = pd.json_normalize(json_data)
-1199    pbp_df.rename(
-1200        columns={
-1201            "gameId": "game_id",
-1202            "teamScore": "team_score",
-1203            "opponentScore": "opponent_score",
-1204            "driveId": "drive_id",
-1205            "playId": "play_id",
-1206            "yardsToGoal": "yards_to_goal",
-1207            "athleteId": "athlete_id",
-1208            "athleteName": "athlete_name",
-1209            "statType": "stat_type",
-1210        },
-1211        inplace=True,
-1212    )
-1213    # TODO: Implement an option to put all stats for
-1214    # a specific game on a single line.
-1215    return pbp_df
+1089    if season is not None and (season > (now.year + 1)):
+1090        raise ValueError(f"`season` cannot be greater than {season}.")
+1091    elif season is not None and season < 1869:
+1092        raise ValueError("`season` cannot be less than 1869.")
+1093
+1094    if (
+1095        season_type != "regular"
+1096        and season_type != "postseason"
+1097        and season_type != "both"
+1098    ):
+1099        raise ValueError(
+1100            '`season_type` must be set to either ' +
+1101            '"regular", "postseason", or "both" for this function to work.'
+1102        )
+1103
+1104    if season is None and game_id is None:
+1105        logging.warning(
+1106            "This endpoint only returns the top 1,000 results. "
+1107            + "Not setting a value for `season` or `game_id` "
+1108            + "is not a recommended practice."
+1109        )
+1110    elif (
+1111        (season is not None) and
+1112        (game_id is not None)
+1113    ):
+1114        logging.warning(
+1115            "Setting a value for both `season` and `game_id` "
+1116            + "may not yeld the results you want. "
+1117            + "If you just want PBP stats for a valid game ID, "
+1118            + "just set `game_id` to a valid game ID."
+1119        )
+1120
+1121    # URL builder
+1122    ##########################################################################
+1123
+1124    url_elements = 0
+1125
+1126    if season_type is not None and url_elements == 0:
+1127        url += f"?seasonType={season_type}"
+1128        url_elements += 1
+1129    elif season_type is not None:
+1130        url += f"&seasonType={season_type}"
+1131        url_elements += 1
+1132
+1133    if season is not None and url_elements == 0:
+1134        url += f"?year={season}"
+1135        url_elements += 1
+1136    elif season is not None:
+1137        url += f"&year={season}"
+1138        url_elements += 1
+1139
+1140    if week is not None and url_elements == 0:
+1141        url += f"?week={week}"
+1142        url_elements += 1
+1143    elif week is not None:
+1144        url += f"&week={week}"
+1145        url_elements += 1
+1146
+1147    if team is not None and url_elements == 0:
+1148        url += f"?team={team}"
+1149        url_elements += 1
+1150    elif team is not None:
+1151        url += f"&team={team}"
+1152        url_elements += 1
+1153
+1154    if conference is not None and url_elements == 0:
+1155        url += f"&conference={conference}"
+1156        url_elements += 1
+1157    elif conference is not None:
+1158        url += f"&conference={conference}"
+1159        url_elements += 1
+1160
+1161    if game_id is not None and url_elements == 0:
+1162        url += f"&gameId={game_id}"
+1163        url_elements += 1
+1164    elif game_id is not None:
+1165        url += f"&gameId={game_id}"
+1166        url_elements += 1
+1167
+1168    if athlete_id is not None and url_elements == 0:
+1169        url += f"&athleteId={athlete_id}"
+1170        url_elements += 1
+1171    elif athlete_id is not None:
+1172        url += f"&athleteId={athlete_id}"
+1173        url_elements += 1
+1174
+1175    if stat_type_id is not None and url_elements == 0:
+1176        url += f"&statTypeId={stat_type_id}"
+1177        url_elements += 1
+1178    elif stat_type_id is not None:
+1179        url += f"&statTypeId={stat_type_id}"
+1180        url_elements += 1
+1181
+1182    headers = {
+1183        "Authorization": f"{real_api_key}",
+1184        "accept": "application/json"
+1185    }
+1186
+1187    response = requests.get(url, headers=headers)
+1188
+1189    if response.status_code == 200:
+1190        pass
+1191    elif response.status_code == 401:
+1192        raise ConnectionRefusedError(
+1193            "Could not connect. The connection was refused." +
+1194            "\nHTTP Status Code 401."
+1195        )
+1196    else:
+1197        raise ConnectionError(
+1198            f"Could not connect.\nHTTP Status code {response.status_code}"
+1199        )
+1200
+1201    json_data = response.json()
+1202
+1203    if return_as_dict is True:
+1204        return json_data
+1205
+1206    pbp_df = pd.json_normalize(json_data)
+1207    pbp_df.rename(
+1208        columns={
+1209            "gameId": "game_id",
+1210            "teamScore": "team_score",
+1211            "opponentScore": "opponent_score",
+1212            "driveId": "drive_id",
+1213            "playId": "play_id",
+1214            "yardsToGoal": "yards_to_goal",
+1215            "athleteId": "athlete_id",
+1216            "athleteName": "athlete_name",
+1217            "statType": "stat_type",
+1218        },
+1219        inplace=True,
+1220    )
+1221    # TODO: Implement an option to put all stats for
+1222    # a specific game on a single line.
+1223    return pbp_df
 
@@ -4998,110 +5023,119 @@

Returns

-
1218def get_cfbd_pbp_stat_types(
-1219    api_key: str = None, api_key_dir: str = None, return_as_dict: bool = False
-1220):
-1221    """
-1222    Allows you to get CFBD PBP stat types from the CFBD API.
-1223
-1224    Parameters
-1225    ----------
-1226
-1227    `api_key` (str, optional):
-1228        Semi-optional argument.
-1229        If `api_key` is null, this function will attempt to load a CFBD API key
-1230        from the python environment, or from a file on this computer.
-1231        If `api_key` is not null,
-1232        this function will automatically assume that the
-1233        inputted `api_key` is a valid CFBD API key.
-1234
-1235    `api_key_dir` (str, optional):
-1236        Optional argument.
-1237        If `api_key` is set to am empty string, this variable is ignored.
-1238        If `api_key_dir` is null, and `api_key` is null,
-1239        this function will try to find
-1240        a CFBD API key file in this user's home directory.
-1241        If `api_key_dir` is set to a string, and `api_key` is null,
-1242        this function will assume that `api_key_dir` is a directory,
-1243        and will try to find a CFBD API key file in that directory.
+                
1226def get_cfbd_pbp_stat_types(
+1227    api_key: str = None,
+1228    api_key_dir: str = None,
+1229    return_as_dict: bool = False
+1230):
+1231    """
+1232    Allows you to get CFBD PBP stat types from the CFBD API.
+1233
+1234    Parameters
+1235    ----------
+1236
+1237    `api_key` (str, optional):
+1238        Semi-optional argument.
+1239        If `api_key` is null, this function will attempt to load a CFBD API key
+1240        from the python environment, or from a file on this computer.
+1241        If `api_key` is not null,
+1242        this function will automatically assume that the
+1243        inputted `api_key` is a valid CFBD API key.
 1244
-1245    `return_as_dict` (bool, semi-optional):
-1246        Semi-optional argument.
-1247        If you want this function to return
-1248        the data as a dictionary (read: JSON object),
-1249        instead of a pandas `DataFrame` object,
-1250        set `return_as_dict` to `True`.
-1251
-1252    Usage
-1253    ----------
-1254    ```
-1255    ```
-1256    Returns
-1257    ----------
-1258    A pandas `DataFrame` object with CFBD PBP stat types,
-1259    or (if `return_as_dict` is set to `True`)
-1260    a dictionary object with CFBD PBP stat types.
+1245    `api_key_dir` (str, optional):
+1246        Optional argument.
+1247        If `api_key` is set to am empty string, this variable is ignored.
+1248        If `api_key_dir` is null, and `api_key` is null,
+1249        this function will try to find
+1250        a CFBD API key file in this user's home directory.
+1251        If `api_key_dir` is set to a string, and `api_key` is null,
+1252        this function will assume that `api_key_dir` is a directory,
+1253        and will try to find a CFBD API key file in that directory.
+1254
+1255    `return_as_dict` (bool, semi-optional):
+1256        Semi-optional argument.
+1257        If you want this function to return
+1258        the data as a dictionary (read: JSON object),
+1259        instead of a pandas `DataFrame` object,
+1260        set `return_as_dict` to `True`.
 1261
-1262    """
-1263    # now = datetime.now()
-1264    plays_df = pd.DataFrame()
-1265    row_df = pd.DataFrame()
-1266    url = "https://api.collegefootballdata.com/play/types"
-1267
-1268    # Input validation
-1269    ##########################################################################
-1270
-1271    if api_key is not None:
-1272        real_api_key = api_key
-1273        del api_key
-1274    else:
-1275        real_api_key = get_cfbd_api_token(api_key_dir=api_key_dir)
-1276
-1277    if real_api_key == "tigersAreAwesome":
-1278        raise ValueError(
-1279            "You actually need to change `cfbd_key` to your CFBD API key."
-1280        )
-1281    elif "Bearer " in real_api_key:
-1282        pass
-1283    elif "Bearer" in real_api_key:
-1284        real_api_key = real_api_key.replace("Bearer", "Bearer ")
+1262    Usage
+1263    ----------
+1264    ```
+1265    ```
+1266    Returns
+1267    ----------
+1268    A pandas `DataFrame` object with CFBD PBP stat types,
+1269    or (if `return_as_dict` is set to `True`)
+1270    a dictionary object with CFBD PBP stat types.
+1271
+1272    """
+1273    # now = datetime.now()
+1274    plays_df = pd.DataFrame()
+1275    plays_df_arr = []
+1276    row_df = pd.DataFrame()
+1277    url = "https://api.collegefootballdata.com/play/types"
+1278
+1279    # Input validation
+1280    ##########################################################################
+1281
+1282    if api_key is not None:
+1283        real_api_key = api_key
+1284        del api_key
 1285    else:
-1286        real_api_key = "Bearer " + real_api_key
+1286        real_api_key = get_cfbd_api_token(api_key_dir=api_key_dir)
 1287
-1288    headers = {
-1289        "Authorization": f"{real_api_key}",
-1290        "accept": "application/json"
-1291    }
-1292
-1293    response = requests.get(url, headers=headers)
-1294
-1295    if response.status_code == 200:
-1296        pass
-1297    elif response.status_code == 401:
-1298        raise ConnectionRefusedError(
-1299            "Could not connect. The connection was refused." +
-1300            "\nHTTP Status Code 401."
-1301        )
-1302    else:
-1303        raise ConnectionError(
-1304            f"Could not connect.\nHTTP Status code {response.status_code}"
-1305        )
-1306
-1307    json_data = response.json()
-1308
-1309    if return_as_dict is True:
-1310        return json_data
-1311
-1312    for p in tqdm(json_data):
-1313        p_id = p["id"]
-1314        row_df = pd.DataFrame({"stat_type_id": p_id}, index=[0])
-1315        row_df["stat_type_text"] = p["name"]
-1316        plays_df = pd.concat([plays_df, row_df], ignore_index=True)
+1288    if real_api_key == "tigersAreAwesome":
+1289        raise ValueError(
+1290            "You actually need to change `cfbd_key` to your CFBD API key."
+1291        )
+1292    elif "Bearer " in real_api_key:
+1293        pass
+1294    elif "Bearer" in real_api_key:
+1295        real_api_key = real_api_key.replace("Bearer", "Bearer ")
+1296    else:
+1297        real_api_key = "Bearer " + real_api_key
+1298
+1299    headers = {
+1300        "Authorization": f"{real_api_key}",
+1301        "accept": "application/json"
+1302    }
+1303
+1304    response = requests.get(url, headers=headers)
+1305
+1306    if response.status_code == 200:
+1307        pass
+1308    elif response.status_code == 401:
+1309        raise ConnectionRefusedError(
+1310            "Could not connect. The connection was refused." +
+1311            "\nHTTP Status Code 401."
+1312        )
+1313    else:
+1314        raise ConnectionError(
+1315            f"Could not connect.\nHTTP Status code {response.status_code}"
+1316        )
 1317
-1318        del row_df
-1319        del p_id
-1320
-1321    return plays_df
+1318    json_data = response.json()
+1319
+1320    if return_as_dict is True:
+1321        return json_data
+1322
+1323    for p in json_data:
+1324        p_id = p["id"]
+1325        row_df = pd.DataFrame({"stat_type_id": p_id}, index=[0])
+1326        row_df["stat_type_abv"] = p["abbreviation"]
+1327        try:
+1328            row_df["stat_type_text"] = p["name"]
+1329        except KeyError:
+1330            row_df["stat_type_text"] = p["text"]
+1331        # plays_df = pd.concat([plays_df, row_df], ignore_index=True)
+1332        plays_df_arr.append(row_df)
+1333
+1334        del row_df
+1335        del p_id
+1336
+1337    plays_df = pd.concat(plays_df_arr, ignore_index=True)
+1338    return plays_df
 
@@ -5170,53 +5204,53 @@

Returns

-
1331def get_cfbd_live_pbp_data(
-1332    game_id: int,
-1333    api_key: str = None,
-1334    api_key_dir: str = None,
-1335    # return_as_dict: bool = False,
-1336):
-1337    """ """
-1338    url = f"https://api.collegefootballdata.com/live/plays?id={game_id}"
-1339
-1340    if api_key is not None:
-1341        real_api_key = api_key
-1342        del api_key
-1343    else:
-1344        real_api_key = get_cfbd_api_token(api_key_dir=api_key_dir)
-1345
-1346    if real_api_key == "tigersAreAwesome":
-1347        raise ValueError(
-1348            "You actually need to change `cfbd_key` to your CFBD API key."
-1349        )
-1350    elif "Bearer " in real_api_key:
-1351        pass
-1352    elif "Bearer" in real_api_key:
-1353        real_api_key = real_api_key.replace("Bearer", "Bearer ")
-1354    else:
-1355        real_api_key = "Bearer " + real_api_key
+                
1348def get_cfbd_live_pbp_data(
+1349    game_id: int,
+1350    api_key: str = None,
+1351    api_key_dir: str = None,
+1352    # return_as_dict: bool = False,
+1353):
+1354    """ """
+1355    url = f"https://api.collegefootballdata.com/live/plays?id={game_id}"
 1356
-1357    headers = {
-1358        "Authorization": f"{real_api_key}",
-1359        "accept": "application/json"
-1360    }
-1361
-1362    response = requests.get(url, headers=headers)
-1363
-1364    if response.status_code == 200:
-1365        pass
-1366    elif response.status_code == 401:
-1367        raise ConnectionRefusedError(
-1368            "Could not connect. The connection was refused.\n" +
-1369            "HTTP Status Code 401."
-1370        )
+1357    if api_key is not None:
+1358        real_api_key = api_key
+1359        del api_key
+1360    else:
+1361        real_api_key = get_cfbd_api_token(api_key_dir=api_key_dir)
+1362
+1363    if real_api_key == "tigersAreAwesome":
+1364        raise ValueError(
+1365            "You actually need to change `cfbd_key` to your CFBD API key."
+1366        )
+1367    elif "Bearer " in real_api_key:
+1368        pass
+1369    elif "Bearer" in real_api_key:
+1370        real_api_key = real_api_key.replace("Bearer", "Bearer ")
 1371    else:
-1372        raise ConnectionError(
-1373            f"Could not connect.\nHTTP Status code {response.status_code}"
-1374        )
-1375
-1376    json_data = response.json()
-1377    return json_data
+1372        real_api_key = "Bearer " + real_api_key
+1373
+1374    headers = {
+1375        "Authorization": f"{real_api_key}",
+1376        "accept": "application/json"
+1377    }
+1378
+1379    response = requests.get(url, headers=headers)
+1380
+1381    if response.status_code == 200:
+1382        pass
+1383    elif response.status_code == 401:
+1384        raise ConnectionRefusedError(
+1385            "Could not connect. The connection was refused.\n" +
+1386            "HTTP Status Code 401."
+1387        )
+1388    else:
+1389        raise ConnectionError(
+1390            f"Could not connect.\nHTTP Status code {response.status_code}"
+1391        )
+1392
+1393    json_data = response.json()
+1394    return json_data
 
@@ -5409,4 +5443,4 @@

Returns

- \ No newline at end of file + diff --git a/docs/cfbd_json_py/rankings.html b/docs/cfbd_json_py/rankings.html index 909e2e0..54822bd 100644 --- a/docs/cfbd_json_py/rankings.html +++ b/docs/cfbd_json_py/rankings.html @@ -1485,7 +1485,7 @@

9 10import pandas as pd 11import requests - 12from tqdm import tqdm + 12# from tqdm import tqdm 13 14from cfbd_json_py.utls import get_cfbd_api_token 15 @@ -1760,7 +1760,7 @@

284 if return_as_dict is True: 285 return json_data 286 -287 for week in tqdm(json_data): +287 for week in json_data: 288 w_season = week["season"] 289 w_season_type = week["seasonType"] 290 w_week = week["week"] @@ -2097,7 +2097,7 @@

285 if return_as_dict is True: 286 return json_data 287 -288 for week in tqdm(json_data): +288 for week in json_data: 289 w_season = week["season"] 290 w_season_type = week["seasonType"] 291 w_week = week["week"] @@ -2494,4 +2494,4 @@

Returns

- \ No newline at end of file + diff --git a/docs/cfbd_json_py/ratings.html b/docs/cfbd_json_py/ratings.html index 4b589b2..7628a4d 100644 --- a/docs/cfbd_json_py/ratings.html +++ b/docs/cfbd_json_py/ratings.html @@ -5790,4 +5790,4 @@

Returns

- \ No newline at end of file + diff --git a/docs/cfbd_json_py/recruiting.html b/docs/cfbd_json_py/recruiting.html index 9cb5d08..61811a8 100644 --- a/docs/cfbd_json_py/recruiting.html +++ b/docs/cfbd_json_py/recruiting.html @@ -1774,7 +1774,7 @@

291 292 """ 293 - 294 now = datetime.now() + 294 # now = datetime.now() 295 recruit_df = pd.DataFrame() 296 # row_df = pd.DataFrame() 297 url = "https://api.collegefootballdata.com/recruiting/players" @@ -1798,713 +1798,719 @@

315 else: 316 real_api_key = "Bearer " + real_api_key 317 - 318 if season > (now.year + 1): - 319 raise ValueError(f"`season` cannot be greater than {season}.") - 320 elif season < 1869: - 321 raise ValueError("`season` cannot be less than 1869.") + 318 # if season > (now.year + 1): + 319 # raise ValueError(f"`season` cannot be greater than {season}.") + 320 # elif season < 1869: + 321 # raise ValueError("`season` cannot be less than 1869.") 322 - 323 if ( - 324 recruit_classification == "HighSchool" - 325 or recruit_classification == "JUCO" - 326 or recruit_classification == "PrepSchool" - 327 ): - 328 logging.info("Correct `recruit_classification` inputted.") - 329 elif recruit_classification is None: - 330 logging.info( - 331 "`recruit_classification` is skipped in this function call." - 332 ) - 333 else: - 334 raise ValueError( - 335 "`recruit_classification` must be set " - 336 + "to one of the following values " - 337 + "\n\t- `HighSchool`" - 338 + "\n\t- `JUCO`" - 339 + "\n\t- `PrepSchool`" - 340 ) - 341 - 342 if season is None and team is None: - 343 raise ValueError( - 344 "`season` and/or `team` must be set to " - 345 + "valid non-null values for this function to work." - 346 ) - 347 - 348 # URL builder - 349 ########################################################################## + 323 if season < 1869: + 324 raise ValueError("`season` cannot be less than 1869.") + 325 + 326 if ( + 327 recruit_classification == "HighSchool" + 328 or recruit_classification == "JUCO" + 329 or recruit_classification == "PrepSchool" + 330 ): + 331 logging.info("Correct `recruit_classification` inputted.") + 332 elif recruit_classification is None: + 333 logging.info( + 334 "`recruit_classification` is skipped in this function call." + 335 ) + 336 else: + 337 raise ValueError( + 338 "`recruit_classification` must be set " + 339 + "to one of the following values " + 340 + "\n\t- `HighSchool`" + 341 + "\n\t- `JUCO`" + 342 + "\n\t- `PrepSchool`" + 343 ) + 344 + 345 if season is None and team is None: + 346 raise ValueError( + 347 "`season` and/or `team` must be set to " + 348 + "valid non-null values for this function to work." + 349 ) 350 - 351 # Required by API - 352 if team is not None and season is None: - 353 url += f"?team={team}" - 354 elif season is not None and team is None: - 355 url += f"?year={season}" - 356 elif season is not None and team is not None: - 357 url += f"?year={season}&team={team}" - 358 - 359 if recruit_classification is not None: - 360 url += f"&classification={recruit_classification}" + 351 # URL builder + 352 ########################################################################## + 353 + 354 # Required by API + 355 if team is not None and season is None: + 356 url += f"?team={team}" + 357 elif season is not None and team is None: + 358 url += f"?year={season}" + 359 elif season is not None and team is not None: + 360 url += f"?year={season}&team={team}" 361 - 362 if position is not None: - 363 url += f"&position={position}" + 362 if recruit_classification is not None: + 363 url += f"&classification={recruit_classification}" 364 - 365 if state is not None: - 366 url += f"&state={state}" + 365 if position is not None: + 366 url += f"&position={position}" 367 - 368 headers = { - 369 "Authorization": f"{real_api_key}", - 370 "accept": "application/json" - 371 } - 372 response = requests.get(url, headers=headers) - 373 - 374 if response.status_code == 200: - 375 pass - 376 elif response.status_code == 401: - 377 raise ConnectionRefusedError( - 378 "Could not connect. The connection was refused." + - 379 "\nHTTP Status Code 401." - 380 ) - 381 else: - 382 raise ConnectionError( - 383 f"Could not connect.\nHTTP Status code {response.status_code}" - 384 ) - 385 - 386 json_data = response.json() - 387 - 388 if return_as_dict is True: - 389 return json_data + 368 if state is not None: + 369 url += f"&state={state}" + 370 + 371 headers = { + 372 "Authorization": f"{real_api_key}", + 373 "accept": "application/json" + 374 } + 375 response = requests.get(url, headers=headers) + 376 + 377 if response.status_code == 200: + 378 pass + 379 elif response.status_code == 401: + 380 raise ConnectionRefusedError( + 381 "Could not connect. The connection was refused." + + 382 "\nHTTP Status Code 401." + 383 ) + 384 else: + 385 raise ConnectionError( + 386 f"Could not connect.\nHTTP Status code {response.status_code}" + 387 ) + 388 + 389 json_data = response.json() 390 - 391 # for player in tqdm(json_data): - 392 # pass - 393 recruit_df = pd.json_normalize(json_data) - 394 - 395 recruit_df.rename( - 396 columns={ - 397 "id": "recruit_id", - 398 "athleteId": "athlete_id", - 399 "recruitType": "recruit_type", - 400 "year": "season", - 401 "name": "player_name", - 402 "school": "previous_school", - 403 "committedTo": "college_commit_team", - 404 "stateProvince": "state_province", - 405 "hometownInfo.latitude": "hometown_latitude", - 406 "hometownInfo.longitude": "hometown_longitude", - 407 "hometownInfo.fipsCode": "hometown_fips_code", - 408 }, - 409 inplace=True, - 410 ) - 411 - 412 return recruit_df - 413 + 391 if return_as_dict is True: + 392 return json_data + 393 + 394 # for player in tqdm(json_data): + 395 # pass + 396 recruit_df = pd.json_normalize(json_data) + 397 + 398 recruit_df.rename( + 399 columns={ + 400 "id": "recruit_id", + 401 "athleteId": "athlete_id", + 402 "recruitType": "recruit_type", + 403 "year": "season", + 404 "name": "player_name", + 405 "school": "previous_school", + 406 "committedTo": "college_commit_team", + 407 "stateProvince": "state_province", + 408 "hometownInfo.latitude": "hometown_latitude", + 409 "hometownInfo.longitude": "hometown_longitude", + 410 "hometownInfo.fipsCode": "hometown_fips_code", + 411 }, + 412 inplace=True, + 413 ) 414 - 415def get_cfbd_team_recruiting_ratings( - 416 api_key: str = None, - 417 api_key_dir: str = None, - 418 season: int = None, - 419 team: str = None, - 420 return_as_dict: bool = False, - 421): - 422 """ - 423 Allows you to get CFB team recruiting rankings data from the CFBD API. - 424 - 425 Parameters - 426 ---------- + 415 return recruit_df + 416 + 417 + 418def get_cfbd_team_recruiting_ratings( + 419 api_key: str = None, + 420 api_key_dir: str = None, + 421 season: int = None, + 422 team: str = None, + 423 return_as_dict: bool = False, + 424): + 425 """ + 426 Allows you to get CFB team recruiting rankings data from the CFBD API. 427 - 428 `api_key` (str, optional): - 429 Semi-optional argument. - 430 If `api_key` is null, this function will attempt to load a CFBD API key - 431 from the python environment, or from a file on this computer. - 432 If `api_key` is not null, - 433 this function will automatically assume that the - 434 inputted `api_key` is a valid CFBD API key. - 435 - 436 `api_key_dir` (str, optional): - 437 Optional argument. - 438 If `api_key` is set to am empty string, this variable is ignored. - 439 If `api_key_dir` is null, and `api_key` is null, - 440 this function will try to find - 441 a CFBD API key file in this user's home directory. - 442 If `api_key_dir` is set to a string, and `api_key` is null, - 443 this function will assume that `api_key_dir` is a directory, - 444 and will try to find a CFBD API key file in that directory. - 445 - 446 `season` (int, semi-mandatory): - 447 Semi-required argument. - 448 Specifies the season you want CFB recruiting data from. - 449 This must be specified, otherwise this package, and by extension - 450 the CFBD API, will not accept the request to get CFB recruiting data. - 451 This or `team` must be set to a valid non-null variable - 452 for this to function. - 453 - 454 `team` (str, semi-mandatory): - 455 Semi-required argument. - 456 Specifies the season you want CFB recruiting data from. - 457 This must be specified, otherwise this package, and by extension - 458 the CFBD API, will not accept the request to get CFB recruiting data. - 459 This or `season` must be set to a valid non-null variable - 460 for this to function. - 461 - 462 `return_as_dict` (bool, semi-optional): - 463 Semi-optional argument. - 464 If you want this function to return - 465 the data as a dictionary (read: JSON object), - 466 instead of a pandas `DataFrame` object, - 467 set `return_as_dict` to `True`. - 468 - 469 Usage - 470 ---------- - 471 ``` - 472 import time - 473 - 474 from cfbd_json_py.recruiting import get_cfbd_team_recruiting_ratings - 475 + 428 Parameters + 429 ---------- + 430 + 431 `api_key` (str, optional): + 432 Semi-optional argument. + 433 If `api_key` is null, this function will attempt to load a CFBD API key + 434 from the python environment, or from a file on this computer. + 435 If `api_key` is not null, + 436 this function will automatically assume that the + 437 inputted `api_key` is a valid CFBD API key. + 438 + 439 `api_key_dir` (str, optional): + 440 Optional argument. + 441 If `api_key` is set to am empty string, this variable is ignored. + 442 If `api_key_dir` is null, and `api_key` is null, + 443 this function will try to find + 444 a CFBD API key file in this user's home directory. + 445 If `api_key_dir` is set to a string, and `api_key` is null, + 446 this function will assume that `api_key_dir` is a directory, + 447 and will try to find a CFBD API key file in that directory. + 448 + 449 `season` (int, semi-mandatory): + 450 Semi-required argument. + 451 Specifies the season you want CFB recruiting data from. + 452 This must be specified, otherwise this package, and by extension + 453 the CFBD API, will not accept the request to get CFB recruiting data. + 454 This or `team` must be set to a valid non-null variable + 455 for this to function. + 456 + 457 `team` (str, semi-mandatory): + 458 Semi-required argument. + 459 Specifies the season you want CFB recruiting data from. + 460 This must be specified, otherwise this package, and by extension + 461 the CFBD API, will not accept the request to get CFB recruiting data. + 462 This or `season` must be set to a valid non-null variable + 463 for this to function. + 464 + 465 `return_as_dict` (bool, semi-optional): + 466 Semi-optional argument. + 467 If you want this function to return + 468 the data as a dictionary (read: JSON object), + 469 instead of a pandas `DataFrame` object, + 470 set `return_as_dict` to `True`. + 471 + 472 Usage + 473 ---------- + 474 ``` + 475 import time 476 - 477 cfbd_key = "tigersAreAwesome" # placeholder for your CFBD API Key. + 477 from cfbd_json_py.recruiting import get_cfbd_team_recruiting_ratings 478 - 479 if cfbd_key != "tigersAreAwesome": - 480 print( - 481 "Using the user's API key declared in this script " + - 482 "for this example." - 483 ) - 484 - 485 # Get a team recruiting rankings for the 2020 CFB season. - 486 print("Get a team recruiting rankings for the 2020 CFB season.") - 487 json_data = get_cfbd_team_recruiting_ratings( - 488 api_key=cfbd_key, - 489 season=2020 - 490 ) - 491 print(json_data) - 492 time.sleep(5) - 493 - 494 # Get a historical team recruiting rankings for - 495 # the Ohio State Buckeyes Football team. - 496 print( - 497 "Get a historical team recruiting rankings for " + - 498 "the Ohio State Buckeyes Football team." - 499 ) - 500 json_data = get_cfbd_team_recruiting_ratings( - 501 api_key=cfbd_key, - 502 team="Ohio State" - 503 ) - 504 print(json_data) - 505 time.sleep(5) - 506 - 507 # You can also tell this function to just return the API call as - 508 # a Dictionary (read: JSON) object. - 509 print( - 510 "You can also tell this function to just return the API call " + - 511 "as a Dictionary (read: JSON) object." - 512 ) - 513 json_data = get_cfbd_team_recruiting_ratings( - 514 api_key=cfbd_key, - 515 season=2020, - 516 team="Ohio", - 517 return_as_dict=True - 518 ) - 519 print(json_data) - 520 - 521 else: - 522 # Alternatively, if the CFBD API key exists in this python environment, - 523 # or it's been set by cfbd_json_py.utls.set_cfbd_api_token(), - 524 # you could just call these functions directly, - 525 # without setting the API key in the script. - 526 print( - 527 "Using the user's API key supposedly loaded " + - 528 "into this python environment for this example." - 529 ) - 530 - 531 - 532 # Get a team recruiting rankings for the 2020 CFB season. - 533 print("Get a team recruiting rankings for the 2020 CFB season.") - 534 json_data = get_cfbd_team_recruiting_ratings( - 535 season=2020 - 536 ) - 537 print(json_data) - 538 time.sleep(5) - 539 - 540 # Get a historical team recruiting rankings for - 541 # the Ohio State Buckeyes Football team. - 542 print( - 543 "Get a historical team recruiting rankings for " + - 544 "the Ohio State Buckeyes Football team." - 545 ) - 546 json_data = get_cfbd_team_recruiting_ratings( - 547 team="Ohio State" + 479 + 480 cfbd_key = "tigersAreAwesome" # placeholder for your CFBD API Key. + 481 + 482 if cfbd_key != "tigersAreAwesome": + 483 print( + 484 "Using the user's API key declared in this script " + + 485 "for this example." + 486 ) + 487 + 488 # Get a team recruiting rankings for the 2020 CFB season. + 489 print("Get a team recruiting rankings for the 2020 CFB season.") + 490 json_data = get_cfbd_team_recruiting_ratings( + 491 api_key=cfbd_key, + 492 season=2020 + 493 ) + 494 print(json_data) + 495 time.sleep(5) + 496 + 497 # Get a historical team recruiting rankings for + 498 # the Ohio State Buckeyes Football team. + 499 print( + 500 "Get a historical team recruiting rankings for " + + 501 "the Ohio State Buckeyes Football team." + 502 ) + 503 json_data = get_cfbd_team_recruiting_ratings( + 504 api_key=cfbd_key, + 505 team="Ohio State" + 506 ) + 507 print(json_data) + 508 time.sleep(5) + 509 + 510 # You can also tell this function to just return the API call as + 511 # a Dictionary (read: JSON) object. + 512 print( + 513 "You can also tell this function to just return the API call " + + 514 "as a Dictionary (read: JSON) object." + 515 ) + 516 json_data = get_cfbd_team_recruiting_ratings( + 517 api_key=cfbd_key, + 518 season=2020, + 519 team="Ohio", + 520 return_as_dict=True + 521 ) + 522 print(json_data) + 523 + 524 else: + 525 # Alternatively, if the CFBD API key exists in this python environment, + 526 # or it's been set by cfbd_json_py.utls.set_cfbd_api_token(), + 527 # you could just call these functions directly, + 528 # without setting the API key in the script. + 529 print( + 530 "Using the user's API key supposedly loaded " + + 531 "into this python environment for this example." + 532 ) + 533 + 534 + 535 # Get a team recruiting rankings for the 2020 CFB season. + 536 print("Get a team recruiting rankings for the 2020 CFB season.") + 537 json_data = get_cfbd_team_recruiting_ratings( + 538 season=2020 + 539 ) + 540 print(json_data) + 541 time.sleep(5) + 542 + 543 # Get a historical team recruiting rankings for + 544 # the Ohio State Buckeyes Football team. + 545 print( + 546 "Get a historical team recruiting rankings for " + + 547 "the Ohio State Buckeyes Football team." 548 ) - 549 print(json_data) - 550 time.sleep(5) - 551 - 552 # You can also tell this function to just return the API call as - 553 # a Dictionary (read: JSON) object. - 554 print( - 555 "You can also tell this function to just return the API call " + - 556 "as a Dictionary (read: JSON) object." - 557 ) - 558 json_data = get_cfbd_team_recruiting_ratings( - 559 season=2020, - 560 team="Ohio", - 561 return_as_dict=True - 562 ) - 563 print(json_data) - 564 - 565 ``` - 566 Returns - 567 ---------- - 568 A pandas `DataFrame` object with CFB Poll data, - 569 or (if `return_as_dict` is set to `True`) - 570 a dictionary object with CFB Poll data. - 571 """ - 572 - 573 now = datetime.now() - 574 recruit_df = pd.DataFrame() - 575 # row_df = pd.DataFrame() - 576 url = "https://api.collegefootballdata.com/recruiting/teams" - 577 - 578 ########################################################################## - 579 - 580 if api_key is not None: - 581 real_api_key = api_key - 582 del api_key - 583 else: - 584 real_api_key = get_cfbd_api_token(api_key_dir=api_key_dir) - 585 - 586 if real_api_key == "tigersAreAwesome": - 587 raise ValueError( - 588 "You actually need to change `cfbd_key` to your CFBD API key." - 589 ) - 590 elif "Bearer " in real_api_key: - 591 pass - 592 elif "Bearer" in real_api_key: - 593 real_api_key = real_api_key.replace("Bearer", "Bearer ") - 594 else: - 595 real_api_key = "Bearer " + real_api_key - 596 - 597 if season is not None and season > (now.year + 1): - 598 raise ValueError(f"`season` cannot be greater than {season}.") - 599 elif season is not None and season < 1869: - 600 raise ValueError("`season` cannot be less than 1869.") - 601 - 602 if season is None and team is None: - 603 raise ValueError( - 604 "`season` and/or `team` must be set to " - 605 + "valid non-null values for this function to work." - 606 ) + 549 json_data = get_cfbd_team_recruiting_ratings( + 550 team="Ohio State" + 551 ) + 552 print(json_data) + 553 time.sleep(5) + 554 + 555 # You can also tell this function to just return the API call as + 556 # a Dictionary (read: JSON) object. + 557 print( + 558 "You can also tell this function to just return the API call " + + 559 "as a Dictionary (read: JSON) object." + 560 ) + 561 json_data = get_cfbd_team_recruiting_ratings( + 562 season=2020, + 563 team="Ohio", + 564 return_as_dict=True + 565 ) + 566 print(json_data) + 567 + 568 ``` + 569 Returns + 570 ---------- + 571 A pandas `DataFrame` object with CFB Poll data, + 572 or (if `return_as_dict` is set to `True`) + 573 a dictionary object with CFB Poll data. + 574 """ + 575 + 576 # now = datetime.now() + 577 recruit_df = pd.DataFrame() + 578 # row_df = pd.DataFrame() + 579 url = "https://api.collegefootballdata.com/recruiting/teams" + 580 + 581 ########################################################################## + 582 + 583 if api_key is not None: + 584 real_api_key = api_key + 585 del api_key + 586 else: + 587 real_api_key = get_cfbd_api_token(api_key_dir=api_key_dir) + 588 + 589 if real_api_key == "tigersAreAwesome": + 590 raise ValueError( + 591 "You actually need to change `cfbd_key` to your CFBD API key." + 592 ) + 593 elif "Bearer " in real_api_key: + 594 pass + 595 elif "Bearer" in real_api_key: + 596 real_api_key = real_api_key.replace("Bearer", "Bearer ") + 597 else: + 598 real_api_key = "Bearer " + real_api_key + 599 + 600 # if season > (now.year + 1): + 601 # raise ValueError(f"`season` cannot be greater than {season}.") + 602 # elif season < 1869: + 603 # raise ValueError("`season` cannot be less than 1869.") + 604 + 605 if season < 1869: + 606 raise ValueError("`season` cannot be less than 1869.") 607 - 608 # URL builder - 609 ########################################################################## - 610 - 611 url_elements = 0 - 612 - 613 if season is not None and url_elements == 0: - 614 url += f"?year={season}" - 615 url_elements += 1 - 616 elif season is not None: - 617 url += f"&year={season}" - 618 url_elements += 1 - 619 - 620 if team is not None and url_elements == 0: - 621 url += f"?team={team}" - 622 url_elements += 1 - 623 elif team is not None: - 624 url += f"&team={team}" - 625 url_elements += 1 - 626 - 627 headers = { - 628 "Authorization": f"{real_api_key}", - 629 "accept": "application/json" - 630 } - 631 response = requests.get(url, headers=headers) + 608 if season is None and team is None: + 609 raise ValueError( + 610 "`season` and/or `team` must be set to " + 611 + "valid non-null values for this function to work." + 612 ) + 613 + 614 # URL builder + 615 ########################################################################## + 616 + 617 url_elements = 0 + 618 + 619 if season is not None and url_elements == 0: + 620 url += f"?year={season}" + 621 url_elements += 1 + 622 elif season is not None: + 623 url += f"&year={season}" + 624 url_elements += 1 + 625 + 626 if team is not None and url_elements == 0: + 627 url += f"?team={team}" + 628 url_elements += 1 + 629 elif team is not None: + 630 url += f"&team={team}" + 631 url_elements += 1 632 - 633 if response.status_code == 200: - 634 pass - 635 elif response.status_code == 401: - 636 raise ConnectionRefusedError( - 637 "Could not connect. The connection was refused." + - 638 "\nHTTP Status Code 401." - 639 ) - 640 else: - 641 raise ConnectionError( - 642 f"Could not connect.\nHTTP Status code {response.status_code}" - 643 ) - 644 - 645 json_data = response.json() - 646 - 647 if return_as_dict is True: - 648 return json_data - 649 - 650 # for player in tqdm(json_data): - 651 # pass - 652 recruit_df = pd.json_normalize(json_data) - 653 - 654 return recruit_df + 633 headers = { + 634 "Authorization": f"{real_api_key}", + 635 "accept": "application/json" + 636 } + 637 response = requests.get(url, headers=headers) + 638 + 639 if response.status_code == 200: + 640 pass + 641 elif response.status_code == 401: + 642 raise ConnectionRefusedError( + 643 "Could not connect. The connection was refused." + + 644 "\nHTTP Status Code 401." + 645 ) + 646 else: + 647 raise ConnectionError( + 648 f"Could not connect.\nHTTP Status code {response.status_code}" + 649 ) + 650 + 651 json_data = response.json() + 652 + 653 if return_as_dict is True: + 654 return json_data 655 - 656 - 657def get_cfbd_team_recruiting_group_ratings( - 658 api_key: str = None, - 659 api_key_dir: str = None, - 660 start_season: int = None, - 661 end_season: int = None, - 662 team: str = None, - 663 conference: str = None, - 664 return_as_dict: bool = False, - 665): - 666 """ - 667 Allows you to get CFB player recruiting data, - 668 grouped by the team and position, - 669 from the CFBD API. - 670 - 671 Parameters - 672 ---------- - 673 - 674 `api_key` (str, optional): - 675 Semi-optional argument. - 676 If `api_key` is null, this function will attempt to load a CFBD API key - 677 from the python environment, or from a file on this computer. - 678 If `api_key` is not null, - 679 this function will automatically assume that the - 680 inputted `api_key` is a valid CFBD API key. - 681 - 682 `api_key_dir` (str, optional): - 683 Optional argument. - 684 If `api_key` is set to am empty string, this variable is ignored. - 685 If `api_key_dir` is null, and `api_key` is null, - 686 this function will try to find - 687 a CFBD API key file in this user's home directory. - 688 If `api_key_dir` is set to a string, and `api_key` is null, - 689 this function will assume that `api_key_dir` is a directory, - 690 and will try to find a CFBD API key file in that directory. - 691 - 692 `start_season` (int, optional): - 693 Optional argument. - 694 If `start_season` is set to a valid integer, - 695 the API will filter out every recruiting season that - 696 is less than `start_season`. + 656 # for player in tqdm(json_data): + 657 # pass + 658 recruit_df = pd.json_normalize(json_data) + 659 + 660 return recruit_df + 661 + 662 + 663def get_cfbd_team_recruiting_group_ratings( + 664 api_key: str = None, + 665 api_key_dir: str = None, + 666 start_season: int = None, + 667 end_season: int = None, + 668 team: str = None, + 669 conference: str = None, + 670 return_as_dict: bool = False, + 671): + 672 """ + 673 Allows you to get CFB player recruiting data, + 674 grouped by the team and position, + 675 from the CFBD API. + 676 + 677 Parameters + 678 ---------- + 679 + 680 `api_key` (str, optional): + 681 Semi-optional argument. + 682 If `api_key` is null, this function will attempt to load a CFBD API key + 683 from the python environment, or from a file on this computer. + 684 If `api_key` is not null, + 685 this function will automatically assume that the + 686 inputted `api_key` is a valid CFBD API key. + 687 + 688 `api_key_dir` (str, optional): + 689 Optional argument. + 690 If `api_key` is set to am empty string, this variable is ignored. + 691 If `api_key_dir` is null, and `api_key` is null, + 692 this function will try to find + 693 a CFBD API key file in this user's home directory. + 694 If `api_key_dir` is set to a string, and `api_key` is null, + 695 this function will assume that `api_key_dir` is a directory, + 696 and will try to find a CFBD API key file in that directory. 697 - 698 `end_season` (int, optional): + 698 `start_season` (int, optional): 699 Optional argument. 700 If `start_season` is set to a valid integer, 701 the API will filter out every recruiting season that - 702 is greater than `end_season`. + 702 is less than `start_season`. 703 - 704 `team` (str, semi-mandatory): - 705 Semi-required argument. - 706 Specifies the season you want CFB recruiting data from. - 707 This must be specified, otherwise this package, and by extension - 708 the CFBD API, will not accept the request to get CFB recruiting data. - 709 This or `season` must be set to a valid non-null variable - 710 for this to function. - 711 - 712 `conference` (str, optional): - 713 Optional argument. - 714 If you only want CFB recruiting data - 715 from teams in a specific conference, - 716 set `conference` to the abbreviation - 717 of the conference you want CFB recruiting data from. - 718 For a list of conferences, - 719 use the `cfbd_json_py.conferences.get_cfbd_conference_info()` - 720 function. - 721 - 722 `return_as_dict` (bool, semi-optional): - 723 Semi-optional argument. - 724 If you want this function to return - 725 the data as a dictionary (read: JSON object), - 726 instead of a pandas `DataFrame` object, - 727 set `return_as_dict` to `True`. - 728 - 729 Usage - 730 ---------- - 731 ``` - 732 import time - 733 - 734 from cfbd_json_py.recruiting import get_cfbd_team_recruiting_group_ratings - 735 - 736 - 737 cfbd_key = "tigersAreAwesome" # placeholder for your CFBD API Key. - 738 - 739 if cfbd_key != "tigersAreAwesome": - 740 print( - 741 "Using the user's API key declared in this script " + - 742 "for this example." - 743 ) + 704 `end_season` (int, optional): + 705 Optional argument. + 706 If `start_season` is set to a valid integer, + 707 the API will filter out every recruiting season that + 708 is greater than `end_season`. + 709 + 710 `team` (str, semi-mandatory): + 711 Semi-required argument. + 712 Specifies the season you want CFB recruiting data from. + 713 This must be specified, otherwise this package, and by extension + 714 the CFBD API, will not accept the request to get CFB recruiting data. + 715 This or `season` must be set to a valid non-null variable + 716 for this to function. + 717 + 718 `conference` (str, optional): + 719 Optional argument. + 720 If you only want CFB recruiting data + 721 from teams in a specific conference, + 722 set `conference` to the abbreviation + 723 of the conference you want CFB recruiting data from. + 724 For a list of conferences, + 725 use the `cfbd_json_py.conferences.get_cfbd_conference_info()` + 726 function. + 727 + 728 `return_as_dict` (bool, semi-optional): + 729 Semi-optional argument. + 730 If you want this function to return + 731 the data as a dictionary (read: JSON object), + 732 instead of a pandas `DataFrame` object, + 733 set `return_as_dict` to `True`. + 734 + 735 Usage + 736 ---------- + 737 ``` + 738 import time + 739 + 740 from cfbd_json_py.recruiting import get_cfbd_team_recruiting_group_ratings + 741 + 742 + 743 cfbd_key = "tigersAreAwesome" # placeholder for your CFBD API Key. 744 - 745 # Get recruiting data between 2020 and 2023, - 746 # grouped by team and position. - 747 print( - 748 "Get recruiting data between 2020 and 2023, " + - 749 "grouped by team and position." - 750 ) - 751 json_data = get_cfbd_team_recruiting_group_ratings( - 752 api_key=cfbd_key, - 753 start_season=2020, - 754 end_season=2023 - 755 ) - 756 print(json_data) - 757 time.sleep(5) - 758 - 759 # Get recruiting data between 2020 and 2023, - 760 # grouped by team and position, - 761 # for the Ohio State Buckeyes Football team. - 762 print( - 763 "Get recruiting data between 2020 and 2023, " + - 764 "grouped by team and position, " + - 765 "for the Ohio State Buckeyes Football team." - 766 ) - 767 json_data = get_cfbd_team_recruiting_group_ratings( - 768 api_key=cfbd_key, - 769 start_season=2020, - 770 end_season=2023, - 771 team="Ohio State" + 745 if cfbd_key != "tigersAreAwesome": + 746 print( + 747 "Using the user's API key declared in this script " + + 748 "for this example." + 749 ) + 750 + 751 # Get recruiting data between 2020 and 2023, + 752 # grouped by team and position. + 753 print( + 754 "Get recruiting data between 2020 and 2023, " + + 755 "grouped by team and position." + 756 ) + 757 json_data = get_cfbd_team_recruiting_group_ratings( + 758 api_key=cfbd_key, + 759 start_season=2020, + 760 end_season=2023 + 761 ) + 762 print(json_data) + 763 time.sleep(5) + 764 + 765 # Get recruiting data between 2020 and 2023, + 766 # grouped by team and position, + 767 # for the Ohio State Buckeyes Football team. + 768 print( + 769 "Get recruiting data between 2020 and 2023, " + + 770 "grouped by team and position, " + + 771 "for the Ohio State Buckeyes Football team." 772 ) - 773 print(json_data) - 774 time.sleep(5) - 775 - 776 # Get recruiting data starting in 2020, - 777 # grouped by team and position. - 778 print( - 779 "Get recruiting data starting in 2020, " + - 780 "grouped by team and position." - 781 ) - 782 json_data = get_cfbd_team_recruiting_group_ratings( - 783 api_key=cfbd_key, - 784 start_season=2020 - 785 ) - 786 print(json_data) - 787 time.sleep(5) - 788 - 789 # Get recruiting data ending in 2018, - 790 # grouped by team and position. - 791 print( - 792 "Get recruiting data ending in 2018, grouped by team and position." - 793 ) - 794 json_data = get_cfbd_team_recruiting_group_ratings( - 795 api_key=cfbd_key, - 796 start_season=2020 - 797 ) - 798 print(json_data) - 799 time.sleep(5) - 800 - 801 # Get recruiting data starting in 2020, - 802 # grouped by team and position, - 803 # but only for Mountain West conference (MWC) teams. - 804 print( - 805 "Get recruiting data starting in 2020, " + - 806 "grouped by team and position, " + - 807 "but only for Mountain West conference (MWC) teams." - 808 ) - 809 json_data = get_cfbd_team_recruiting_group_ratings( - 810 api_key=cfbd_key, - 811 start_season=2020, - 812 conference="MWC" - 813 ) - 814 print(json_data) - 815 time.sleep(5) - 816 - 817 # You can also tell this function to just return the API call as - 818 # a Dictionary (read: JSON) object. - 819 print( - 820 "You can also tell this function to just return the API call " + - 821 "as a Dictionary (read: JSON) object." - 822 ) - 823 json_data = get_cfbd_team_recruiting_group_ratings( - 824 api_key=cfbd_key, - 825 start_season=2020, - 826 end_season=2023, - 827 team="Ohio", - 828 return_as_dict=True - 829 ) - 830 print(json_data) - 831 - 832 else: - 833 # Alternatively, if the CFBD API key exists in this python environment, - 834 # or it's been set by cfbd_json_py.utls.set_cfbd_api_token(), - 835 # you could just call these functions directly, - 836 # without setting the API key in the script. - 837 print( - 838 "Using the user's API key supposedly loaded " + - 839 "into this python environment for this example." - 840 ) - 841 - 842 - 843 # Get recruiting data between 2020 and 2023, - 844 # grouped by team and position. - 845 print( - 846 "Get recruiting data between 2020 and 2023, " + - 847 "grouped by team and position." - 848 ) - 849 json_data = get_cfbd_team_recruiting_group_ratings( - 850 start_season=2020, - 851 end_season=2023 - 852 ) - 853 print(json_data) - 854 time.sleep(5) - 855 - 856 # Get recruiting data between 2020 and 2023, - 857 # grouped by team and position, - 858 # for the Ohio State Buckeyes Football team. - 859 print( - 860 "Get recruiting data between 2020 and 2023, " + - 861 "grouped by team and position, " + - 862 "for the Ohio State Buckeyes Football team." - 863 ) - 864 json_data = get_cfbd_team_recruiting_group_ratings( - 865 start_season=2020, - 866 end_season=2023, - 867 team="Ohio State" - 868 ) - 869 print(json_data) - 870 time.sleep(5) - 871 - 872 # Get recruiting data starting in 2020, - 873 # grouped by team and position. - 874 print( - 875 "Get recruiting data starting in 2020, " + - 876 "grouped by team and position." - 877 ) - 878 json_data = get_cfbd_team_recruiting_group_ratings( - 879 start_season=2020 - 880 ) - 881 print(json_data) - 882 time.sleep(5) - 883 - 884 # Get recruiting data ending in 2018, - 885 # grouped by team and position. - 886 print( - 887 "Get recruiting data ending in 2018, grouped by team and position." - 888 ) - 889 json_data = get_cfbd_team_recruiting_group_ratings( - 890 end_season=2018 - 891 ) - 892 print(json_data) - 893 time.sleep(5) - 894 - 895 # Get recruiting data starting in 2020, - 896 # grouped by team and position, - 897 # but only for Mountain West conference (MWC) teams. - 898 print( - 899 "Get recruiting data starting in 2020, " + - 900 "grouped by team and position, " + - 901 "but only for Mountain West conference (MWC) teams." - 902 ) - 903 json_data = get_cfbd_team_recruiting_group_ratings( - 904 start_season=2020, - 905 conference="MWC" - 906 ) - 907 print(json_data) - 908 time.sleep(5) - 909 - 910 # You can also tell this function to just return the API call as - 911 # a Dictionary (read: JSON) object. - 912 print( - 913 "You can also tell this function to just return the API call " + - 914 "as a Dictionary (read: JSON) object." - 915 ) - 916 json_data = get_cfbd_team_recruiting_group_ratings( - 917 start_season=2020, - 918 end_season=2023, - 919 team="Ohio", - 920 return_as_dict=True + 773 json_data = get_cfbd_team_recruiting_group_ratings( + 774 api_key=cfbd_key, + 775 start_season=2020, + 776 end_season=2023, + 777 team="Ohio State" + 778 ) + 779 print(json_data) + 780 time.sleep(5) + 781 + 782 # Get recruiting data starting in 2020, + 783 # grouped by team and position. + 784 print( + 785 "Get recruiting data starting in 2020, " + + 786 "grouped by team and position." + 787 ) + 788 json_data = get_cfbd_team_recruiting_group_ratings( + 789 api_key=cfbd_key, + 790 start_season=2020 + 791 ) + 792 print(json_data) + 793 time.sleep(5) + 794 + 795 # Get recruiting data ending in 2018, + 796 # grouped by team and position. + 797 print( + 798 "Get recruiting data ending in 2018, grouped by team and position." + 799 ) + 800 json_data = get_cfbd_team_recruiting_group_ratings( + 801 api_key=cfbd_key, + 802 start_season=2020 + 803 ) + 804 print(json_data) + 805 time.sleep(5) + 806 + 807 # Get recruiting data starting in 2020, + 808 # grouped by team and position, + 809 # but only for Mountain West conference (MWC) teams. + 810 print( + 811 "Get recruiting data starting in 2020, " + + 812 "grouped by team and position, " + + 813 "but only for Mountain West conference (MWC) teams." + 814 ) + 815 json_data = get_cfbd_team_recruiting_group_ratings( + 816 api_key=cfbd_key, + 817 start_season=2020, + 818 conference="MWC" + 819 ) + 820 print(json_data) + 821 time.sleep(5) + 822 + 823 # You can also tell this function to just return the API call as + 824 # a Dictionary (read: JSON) object. + 825 print( + 826 "You can also tell this function to just return the API call " + + 827 "as a Dictionary (read: JSON) object." + 828 ) + 829 json_data = get_cfbd_team_recruiting_group_ratings( + 830 api_key=cfbd_key, + 831 start_season=2020, + 832 end_season=2023, + 833 team="Ohio", + 834 return_as_dict=True + 835 ) + 836 print(json_data) + 837 + 838 else: + 839 # Alternatively, if the CFBD API key exists in this python environment, + 840 # or it's been set by cfbd_json_py.utls.set_cfbd_api_token(), + 841 # you could just call these functions directly, + 842 # without setting the API key in the script. + 843 print( + 844 "Using the user's API key supposedly loaded " + + 845 "into this python environment for this example." + 846 ) + 847 + 848 + 849 # Get recruiting data between 2020 and 2023, + 850 # grouped by team and position. + 851 print( + 852 "Get recruiting data between 2020 and 2023, " + + 853 "grouped by team and position." + 854 ) + 855 json_data = get_cfbd_team_recruiting_group_ratings( + 856 start_season=2020, + 857 end_season=2023 + 858 ) + 859 print(json_data) + 860 time.sleep(5) + 861 + 862 # Get recruiting data between 2020 and 2023, + 863 # grouped by team and position, + 864 # for the Ohio State Buckeyes Football team. + 865 print( + 866 "Get recruiting data between 2020 and 2023, " + + 867 "grouped by team and position, " + + 868 "for the Ohio State Buckeyes Football team." + 869 ) + 870 json_data = get_cfbd_team_recruiting_group_ratings( + 871 start_season=2020, + 872 end_season=2023, + 873 team="Ohio State" + 874 ) + 875 print(json_data) + 876 time.sleep(5) + 877 + 878 # Get recruiting data starting in 2020, + 879 # grouped by team and position. + 880 print( + 881 "Get recruiting data starting in 2020, " + + 882 "grouped by team and position." + 883 ) + 884 json_data = get_cfbd_team_recruiting_group_ratings( + 885 start_season=2020 + 886 ) + 887 print(json_data) + 888 time.sleep(5) + 889 + 890 # Get recruiting data ending in 2018, + 891 # grouped by team and position. + 892 print( + 893 "Get recruiting data ending in 2018, grouped by team and position." + 894 ) + 895 json_data = get_cfbd_team_recruiting_group_ratings( + 896 end_season=2018 + 897 ) + 898 print(json_data) + 899 time.sleep(5) + 900 + 901 # Get recruiting data starting in 2020, + 902 # grouped by team and position, + 903 # but only for Mountain West conference (MWC) teams. + 904 print( + 905 "Get recruiting data starting in 2020, " + + 906 "grouped by team and position, " + + 907 "but only for Mountain West conference (MWC) teams." + 908 ) + 909 json_data = get_cfbd_team_recruiting_group_ratings( + 910 start_season=2020, + 911 conference="MWC" + 912 ) + 913 print(json_data) + 914 time.sleep(5) + 915 + 916 # You can also tell this function to just return the API call as + 917 # a Dictionary (read: JSON) object. + 918 print( + 919 "You can also tell this function to just return the API call " + + 920 "as a Dictionary (read: JSON) object." 921 ) - 922 print(json_data) - 923 ``` - 924 Returns - 925 ---------- - 926 A pandas `DataFrame` object with CFB team recruiting ratings, - 927 or (if `return_as_dict` is set to `True`) - 928 a dictionary object with CFB team recruiting ratings. - 929 """ - 930 now = datetime.now() - 931 recruit_df = pd.DataFrame() - 932 # row_df = pd.DataFrame() - 933 url = "https://api.collegefootballdata.com/recruiting/groups" - 934 - 935 ########################################################################## - 936 - 937 if api_key is not None: - 938 real_api_key = api_key - 939 del api_key - 940 else: - 941 real_api_key = get_cfbd_api_token(api_key_dir=api_key_dir) + 922 json_data = get_cfbd_team_recruiting_group_ratings( + 923 start_season=2020, + 924 end_season=2023, + 925 team="Ohio", + 926 return_as_dict=True + 927 ) + 928 print(json_data) + 929 ``` + 930 Returns + 931 ---------- + 932 A pandas `DataFrame` object with CFB team recruiting ratings, + 933 or (if `return_as_dict` is set to `True`) + 934 a dictionary object with CFB team recruiting ratings. + 935 """ + 936 now = datetime.now() + 937 recruit_df = pd.DataFrame() + 938 # row_df = pd.DataFrame() + 939 url = "https://api.collegefootballdata.com/recruiting/groups" + 940 + 941 ########################################################################## 942 - 943 if real_api_key == "tigersAreAwesome": - 944 raise ValueError( - 945 "You actually need to change `cfbd_key` to your CFBD API key." - 946 ) - 947 elif "Bearer " in real_api_key: - 948 pass - 949 elif "Bearer" in real_api_key: - 950 real_api_key = real_api_key.replace("Bearer", "Bearer ") - 951 else: - 952 real_api_key = "Bearer " + real_api_key - 953 - 954 if start_season is not None and start_season > (now.year + 1): - 955 raise ValueError(f"`season` cannot be greater than {start_season}.") - 956 elif start_season is not None and start_season < 1869: - 957 raise ValueError("`season` cannot be less than 1869.") - 958 - 959 if end_season is not None and end_season > (now.year + 1): - 960 raise ValueError(f"`season` cannot be greater than {end_season}.") - 961 elif end_season is not None and end_season < 1869: - 962 raise ValueError("`season` cannot be less than 1869.") - 963 - 964 # URL builder - 965 ########################################################################## - 966 - 967 url_elements = 0 - 968 - 969 if start_season is not None and url_elements == 0: - 970 url += f"?startYear={start_season}" - 971 url_elements += 1 - 972 elif start_season is not None: - 973 url += f"&startYear={start_season}" - 974 url_elements += 1 - 975 - 976 if end_season is not None and url_elements == 0: - 977 url += f"?endYear={end_season}" - 978 url_elements += 1 - 979 elif end_season is not None: - 980 url += f"&endYear={end_season}" - 981 url_elements += 1 - 982 - 983 if team is not None and url_elements == 0: - 984 url += f"?team={team}" - 985 url_elements += 1 - 986 elif team is not None: - 987 url += f"&team={team}" - 988 url_elements += 1 - 989 - 990 if conference is not None and url_elements == 0: - 991 url += f"?conference={conference}" - 992 url_elements += 1 - 993 elif conference is not None: - 994 url += f"&conference={conference}" - 995 url_elements += 1 - 996 - 997 headers = { - 998 "Authorization": f"{real_api_key}", - 999 "accept": "application/json" -1000 } -1001 response = requests.get(url, headers=headers) + 943 if api_key is not None: + 944 real_api_key = api_key + 945 del api_key + 946 else: + 947 real_api_key = get_cfbd_api_token(api_key_dir=api_key_dir) + 948 + 949 if real_api_key == "tigersAreAwesome": + 950 raise ValueError( + 951 "You actually need to change `cfbd_key` to your CFBD API key." + 952 ) + 953 elif "Bearer " in real_api_key: + 954 pass + 955 elif "Bearer" in real_api_key: + 956 real_api_key = real_api_key.replace("Bearer", "Bearer ") + 957 else: + 958 real_api_key = "Bearer " + real_api_key + 959 + 960 if start_season is not None and start_season > (now.year + 1): + 961 raise ValueError(f"`season` cannot be greater than {start_season}.") + 962 elif start_season is not None and start_season < 1869: + 963 raise ValueError("`season` cannot be less than 1869.") + 964 + 965 if end_season is not None and end_season > (now.year + 1): + 966 raise ValueError(f"`season` cannot be greater than {end_season}.") + 967 elif end_season is not None and end_season < 1869: + 968 raise ValueError("`season` cannot be less than 1869.") + 969 + 970 # URL builder + 971 ########################################################################## + 972 + 973 url_elements = 0 + 974 + 975 if start_season is not None and url_elements == 0: + 976 url += f"?startYear={start_season}" + 977 url_elements += 1 + 978 elif start_season is not None: + 979 url += f"&startYear={start_season}" + 980 url_elements += 1 + 981 + 982 if end_season is not None and url_elements == 0: + 983 url += f"?endYear={end_season}" + 984 url_elements += 1 + 985 elif end_season is not None: + 986 url += f"&endYear={end_season}" + 987 url_elements += 1 + 988 + 989 if team is not None and url_elements == 0: + 990 url += f"?team={team}" + 991 url_elements += 1 + 992 elif team is not None: + 993 url += f"&team={team}" + 994 url_elements += 1 + 995 + 996 if conference is not None and url_elements == 0: + 997 url += f"?conference={conference}" + 998 url_elements += 1 + 999 elif conference is not None: +1000 url += f"&conference={conference}" +1001 url_elements += 1 1002 -1003 if response.status_code == 200: -1004 pass -1005 elif response.status_code == 401: -1006 raise ConnectionRefusedError( -1007 "Could not connect. The connection was refused." + -1008 "\nHTTP Status Code 401." -1009 ) -1010 else: -1011 raise ConnectionError( -1012 f"Could not connect.\nHTTP Status code {response.status_code}" -1013 ) -1014 -1015 json_data = response.json() -1016 -1017 if return_as_dict is True: -1018 return json_data -1019 -1020 # for player in tqdm(json_data): -1021 # pass -1022 recruit_df = pd.json_normalize(json_data) -1023 -1024 return recruit_df +1003 headers = { +1004 "Authorization": f"{real_api_key}", +1005 "accept": "application/json" +1006 } +1007 response = requests.get(url, headers=headers) +1008 +1009 if response.status_code == 200: +1010 pass +1011 elif response.status_code == 401: +1012 raise ConnectionRefusedError( +1013 "Could not connect. The connection was refused." + +1014 "\nHTTP Status Code 401." +1015 ) +1016 else: +1017 raise ConnectionError( +1018 f"Could not connect.\nHTTP Status code {response.status_code}" +1019 ) +1020 +1021 json_data = response.json() +1022 +1023 if return_as_dict is True: +1024 return json_data +1025 +1026 # for player in tqdm(json_data): +1027 # pass +1028 recruit_df = pd.json_normalize(json_data) +1029 +1030 return recruit_df @@ -2818,7 +2824,7 @@

292 293 """ 294 -295 now = datetime.now() +295 # now = datetime.now() 296 recruit_df = pd.DataFrame() 297 # row_df = pd.DataFrame() 298 url = "https://api.collegefootballdata.com/recruiting/players" @@ -2842,101 +2848,104 @@

316 else: 317 real_api_key = "Bearer " + real_api_key 318 -319 if season > (now.year + 1): -320 raise ValueError(f"`season` cannot be greater than {season}.") -321 elif season < 1869: -322 raise ValueError("`season` cannot be less than 1869.") +319 # if season > (now.year + 1): +320 # raise ValueError(f"`season` cannot be greater than {season}.") +321 # elif season < 1869: +322 # raise ValueError("`season` cannot be less than 1869.") 323 -324 if ( -325 recruit_classification == "HighSchool" -326 or recruit_classification == "JUCO" -327 or recruit_classification == "PrepSchool" -328 ): -329 logging.info("Correct `recruit_classification` inputted.") -330 elif recruit_classification is None: -331 logging.info( -332 "`recruit_classification` is skipped in this function call." -333 ) -334 else: -335 raise ValueError( -336 "`recruit_classification` must be set " -337 + "to one of the following values " -338 + "\n\t- `HighSchool`" -339 + "\n\t- `JUCO`" -340 + "\n\t- `PrepSchool`" -341 ) -342 -343 if season is None and team is None: -344 raise ValueError( -345 "`season` and/or `team` must be set to " -346 + "valid non-null values for this function to work." -347 ) -348 -349 # URL builder -350 ########################################################################## +324 if season < 1869: +325 raise ValueError("`season` cannot be less than 1869.") +326 +327 if ( +328 recruit_classification == "HighSchool" +329 or recruit_classification == "JUCO" +330 or recruit_classification == "PrepSchool" +331 ): +332 logging.info("Correct `recruit_classification` inputted.") +333 elif recruit_classification is None: +334 logging.info( +335 "`recruit_classification` is skipped in this function call." +336 ) +337 else: +338 raise ValueError( +339 "`recruit_classification` must be set " +340 + "to one of the following values " +341 + "\n\t- `HighSchool`" +342 + "\n\t- `JUCO`" +343 + "\n\t- `PrepSchool`" +344 ) +345 +346 if season is None and team is None: +347 raise ValueError( +348 "`season` and/or `team` must be set to " +349 + "valid non-null values for this function to work." +350 ) 351 -352 # Required by API -353 if team is not None and season is None: -354 url += f"?team={team}" -355 elif season is not None and team is None: -356 url += f"?year={season}" -357 elif season is not None and team is not None: -358 url += f"?year={season}&team={team}" -359 -360 if recruit_classification is not None: -361 url += f"&classification={recruit_classification}" +352 # URL builder +353 ########################################################################## +354 +355 # Required by API +356 if team is not None and season is None: +357 url += f"?team={team}" +358 elif season is not None and team is None: +359 url += f"?year={season}" +360 elif season is not None and team is not None: +361 url += f"?year={season}&team={team}" 362 -363 if position is not None: -364 url += f"&position={position}" +363 if recruit_classification is not None: +364 url += f"&classification={recruit_classification}" 365 -366 if state is not None: -367 url += f"&state={state}" +366 if position is not None: +367 url += f"&position={position}" 368 -369 headers = { -370 "Authorization": f"{real_api_key}", -371 "accept": "application/json" -372 } -373 response = requests.get(url, headers=headers) -374 -375 if response.status_code == 200: -376 pass -377 elif response.status_code == 401: -378 raise ConnectionRefusedError( -379 "Could not connect. The connection was refused." + -380 "\nHTTP Status Code 401." -381 ) -382 else: -383 raise ConnectionError( -384 f"Could not connect.\nHTTP Status code {response.status_code}" -385 ) -386 -387 json_data = response.json() -388 -389 if return_as_dict is True: -390 return json_data +369 if state is not None: +370 url += f"&state={state}" +371 +372 headers = { +373 "Authorization": f"{real_api_key}", +374 "accept": "application/json" +375 } +376 response = requests.get(url, headers=headers) +377 +378 if response.status_code == 200: +379 pass +380 elif response.status_code == 401: +381 raise ConnectionRefusedError( +382 "Could not connect. The connection was refused." + +383 "\nHTTP Status Code 401." +384 ) +385 else: +386 raise ConnectionError( +387 f"Could not connect.\nHTTP Status code {response.status_code}" +388 ) +389 +390 json_data = response.json() 391 -392 # for player in tqdm(json_data): -393 # pass -394 recruit_df = pd.json_normalize(json_data) -395 -396 recruit_df.rename( -397 columns={ -398 "id": "recruit_id", -399 "athleteId": "athlete_id", -400 "recruitType": "recruit_type", -401 "year": "season", -402 "name": "player_name", -403 "school": "previous_school", -404 "committedTo": "college_commit_team", -405 "stateProvince": "state_province", -406 "hometownInfo.latitude": "hometown_latitude", -407 "hometownInfo.longitude": "hometown_longitude", -408 "hometownInfo.fipsCode": "hometown_fips_code", -409 }, -410 inplace=True, -411 ) -412 -413 return recruit_df +392 if return_as_dict is True: +393 return json_data +394 +395 # for player in tqdm(json_data): +396 # pass +397 recruit_df = pd.json_normalize(json_data) +398 +399 recruit_df.rename( +400 columns={ +401 "id": "recruit_id", +402 "athleteId": "athlete_id", +403 "recruitType": "recruit_type", +404 "year": "season", +405 "name": "player_name", +406 "school": "previous_school", +407 "committedTo": "college_commit_team", +408 "stateProvince": "state_province", +409 "hometownInfo.latitude": "hometown_latitude", +410 "hometownInfo.longitude": "hometown_longitude", +411 "hometownInfo.fipsCode": "hometown_fips_code", +412 }, +413 inplace=True, +414 ) +415 +416 return recruit_df @@ -3232,246 +3241,249 @@

Returns

-
416def get_cfbd_team_recruiting_ratings(
-417    api_key: str = None,
-418    api_key_dir: str = None,
-419    season: int = None,
-420    team: str = None,
-421    return_as_dict: bool = False,
-422):
-423    """
-424    Allows you to get CFB team recruiting rankings data from the CFBD API.
-425
-426    Parameters
-427    ----------
+                
419def get_cfbd_team_recruiting_ratings(
+420    api_key: str = None,
+421    api_key_dir: str = None,
+422    season: int = None,
+423    team: str = None,
+424    return_as_dict: bool = False,
+425):
+426    """
+427    Allows you to get CFB team recruiting rankings data from the CFBD API.
 428
-429    `api_key` (str, optional):
-430        Semi-optional argument.
-431        If `api_key` is null, this function will attempt to load a CFBD API key
-432        from the python environment, or from a file on this computer.
-433        If `api_key` is not null,
-434        this function will automatically assume that the
-435        inputted `api_key` is a valid CFBD API key.
-436
-437    `api_key_dir` (str, optional):
-438        Optional argument.
-439        If `api_key` is set to am empty string, this variable is ignored.
-440        If `api_key_dir` is null, and `api_key` is null,
-441        this function will try to find
-442        a CFBD API key file in this user's home directory.
-443        If `api_key_dir` is set to a string, and `api_key` is null,
-444        this function will assume that `api_key_dir` is a directory,
-445        and will try to find a CFBD API key file in that directory.
-446
-447    `season` (int, semi-mandatory):
-448        Semi-required argument.
-449        Specifies the season you want CFB recruiting data from.
-450        This must be specified, otherwise this package, and by extension
-451        the CFBD API, will not accept the request to get CFB recruiting data.
-452        This or `team` must be set to a valid non-null variable
-453        for this to function.
-454
-455    `team` (str, semi-mandatory):
-456        Semi-required argument.
-457        Specifies the season you want CFB recruiting data from.
-458        This must be specified, otherwise this package, and by extension
-459        the CFBD API, will not accept the request to get CFB recruiting data.
-460        This or `season` must be set to a valid non-null variable
-461        for this to function.
-462
-463    `return_as_dict` (bool, semi-optional):
-464        Semi-optional argument.
-465        If you want this function to return
-466        the data as a dictionary (read: JSON object),
-467        instead of a pandas `DataFrame` object,
-468        set `return_as_dict` to `True`.
-469
-470    Usage
-471    ----------
-472    ```
-473    import time
-474
-475    from cfbd_json_py.recruiting import get_cfbd_team_recruiting_ratings
-476
+429    Parameters
+430    ----------
+431
+432    `api_key` (str, optional):
+433        Semi-optional argument.
+434        If `api_key` is null, this function will attempt to load a CFBD API key
+435        from the python environment, or from a file on this computer.
+436        If `api_key` is not null,
+437        this function will automatically assume that the
+438        inputted `api_key` is a valid CFBD API key.
+439
+440    `api_key_dir` (str, optional):
+441        Optional argument.
+442        If `api_key` is set to am empty string, this variable is ignored.
+443        If `api_key_dir` is null, and `api_key` is null,
+444        this function will try to find
+445        a CFBD API key file in this user's home directory.
+446        If `api_key_dir` is set to a string, and `api_key` is null,
+447        this function will assume that `api_key_dir` is a directory,
+448        and will try to find a CFBD API key file in that directory.
+449
+450    `season` (int, semi-mandatory):
+451        Semi-required argument.
+452        Specifies the season you want CFB recruiting data from.
+453        This must be specified, otherwise this package, and by extension
+454        the CFBD API, will not accept the request to get CFB recruiting data.
+455        This or `team` must be set to a valid non-null variable
+456        for this to function.
+457
+458    `team` (str, semi-mandatory):
+459        Semi-required argument.
+460        Specifies the season you want CFB recruiting data from.
+461        This must be specified, otherwise this package, and by extension
+462        the CFBD API, will not accept the request to get CFB recruiting data.
+463        This or `season` must be set to a valid non-null variable
+464        for this to function.
+465
+466    `return_as_dict` (bool, semi-optional):
+467        Semi-optional argument.
+468        If you want this function to return
+469        the data as a dictionary (read: JSON object),
+470        instead of a pandas `DataFrame` object,
+471        set `return_as_dict` to `True`.
+472
+473    Usage
+474    ----------
+475    ```
+476    import time
 477
-478    cfbd_key = "tigersAreAwesome"  # placeholder for your CFBD API Key.
+478    from cfbd_json_py.recruiting import get_cfbd_team_recruiting_ratings
 479
-480    if cfbd_key != "tigersAreAwesome":
-481        print(
-482            "Using the user's API key declared in this script " +
-483            "for this example."
-484        )
-485
-486        # Get a team recruiting rankings for the 2020 CFB season.
-487        print("Get a team recruiting rankings for the 2020 CFB season.")
-488        json_data = get_cfbd_team_recruiting_ratings(
-489            api_key=cfbd_key,
-490            season=2020
-491        )
-492        print(json_data)
-493        time.sleep(5)
-494
-495        # Get a historical team recruiting rankings for
-496        # the Ohio State Buckeyes Football team.
-497        print(
-498            "Get a historical team recruiting rankings for " +
-499            "the Ohio State Buckeyes Football team."
-500        )
-501        json_data = get_cfbd_team_recruiting_ratings(
-502            api_key=cfbd_key,
-503            team="Ohio State"
-504        )
-505        print(json_data)
-506        time.sleep(5)
-507
-508        # You can also tell this function to just return the API call as
-509        # a Dictionary (read: JSON) object.
-510        print(
-511            "You can also tell this function to just return the API call " +
-512            "as a Dictionary (read: JSON) object."
-513        )
-514        json_data = get_cfbd_team_recruiting_ratings(
-515            api_key=cfbd_key,
-516            season=2020,
-517            team="Ohio",
-518            return_as_dict=True
-519        )
-520        print(json_data)
-521
-522    else:
-523        # Alternatively, if the CFBD API key exists in this python environment,
-524        # or it's been set by cfbd_json_py.utls.set_cfbd_api_token(),
-525        # you could just call these functions directly,
-526        # without setting the API key in the script.
-527        print(
-528            "Using the user's API key supposedly loaded " +
-529            "into this python environment for this example."
-530        )
-531
-532
-533        # Get a team recruiting rankings for the 2020 CFB season.
-534        print("Get a team recruiting rankings for the 2020 CFB season.")
-535        json_data = get_cfbd_team_recruiting_ratings(
-536            season=2020
-537        )
-538        print(json_data)
-539        time.sleep(5)
-540
-541        # Get a historical team recruiting rankings for
-542        # the Ohio State Buckeyes Football team.
-543        print(
-544            "Get a historical team recruiting rankings for " +
-545            "the Ohio State Buckeyes Football team."
-546        )
-547        json_data = get_cfbd_team_recruiting_ratings(
-548            team="Ohio State"
+480
+481    cfbd_key = "tigersAreAwesome"  # placeholder for your CFBD API Key.
+482
+483    if cfbd_key != "tigersAreAwesome":
+484        print(
+485            "Using the user's API key declared in this script " +
+486            "for this example."
+487        )
+488
+489        # Get a team recruiting rankings for the 2020 CFB season.
+490        print("Get a team recruiting rankings for the 2020 CFB season.")
+491        json_data = get_cfbd_team_recruiting_ratings(
+492            api_key=cfbd_key,
+493            season=2020
+494        )
+495        print(json_data)
+496        time.sleep(5)
+497
+498        # Get a historical team recruiting rankings for
+499        # the Ohio State Buckeyes Football team.
+500        print(
+501            "Get a historical team recruiting rankings for " +
+502            "the Ohio State Buckeyes Football team."
+503        )
+504        json_data = get_cfbd_team_recruiting_ratings(
+505            api_key=cfbd_key,
+506            team="Ohio State"
+507        )
+508        print(json_data)
+509        time.sleep(5)
+510
+511        # You can also tell this function to just return the API call as
+512        # a Dictionary (read: JSON) object.
+513        print(
+514            "You can also tell this function to just return the API call " +
+515            "as a Dictionary (read: JSON) object."
+516        )
+517        json_data = get_cfbd_team_recruiting_ratings(
+518            api_key=cfbd_key,
+519            season=2020,
+520            team="Ohio",
+521            return_as_dict=True
+522        )
+523        print(json_data)
+524
+525    else:
+526        # Alternatively, if the CFBD API key exists in this python environment,
+527        # or it's been set by cfbd_json_py.utls.set_cfbd_api_token(),
+528        # you could just call these functions directly,
+529        # without setting the API key in the script.
+530        print(
+531            "Using the user's API key supposedly loaded " +
+532            "into this python environment for this example."
+533        )
+534
+535
+536        # Get a team recruiting rankings for the 2020 CFB season.
+537        print("Get a team recruiting rankings for the 2020 CFB season.")
+538        json_data = get_cfbd_team_recruiting_ratings(
+539            season=2020
+540        )
+541        print(json_data)
+542        time.sleep(5)
+543
+544        # Get a historical team recruiting rankings for
+545        # the Ohio State Buckeyes Football team.
+546        print(
+547            "Get a historical team recruiting rankings for " +
+548            "the Ohio State Buckeyes Football team."
 549        )
-550        print(json_data)
-551        time.sleep(5)
-552
-553        # You can also tell this function to just return the API call as
-554        # a Dictionary (read: JSON) object.
-555        print(
-556            "You can also tell this function to just return the API call " +
-557            "as a Dictionary (read: JSON) object."
-558        )
-559        json_data = get_cfbd_team_recruiting_ratings(
-560            season=2020,
-561            team="Ohio",
-562            return_as_dict=True
-563        )
-564        print(json_data)
-565
-566    ```
-567    Returns
-568    ----------
-569    A pandas `DataFrame` object with CFB Poll data,
-570    or (if `return_as_dict` is set to `True`)
-571    a dictionary object with CFB Poll data.
-572    """
-573
-574    now = datetime.now()
-575    recruit_df = pd.DataFrame()
-576    # row_df = pd.DataFrame()
-577    url = "https://api.collegefootballdata.com/recruiting/teams"
-578
-579    ##########################################################################
-580
-581    if api_key is not None:
-582        real_api_key = api_key
-583        del api_key
-584    else:
-585        real_api_key = get_cfbd_api_token(api_key_dir=api_key_dir)
-586
-587    if real_api_key == "tigersAreAwesome":
-588        raise ValueError(
-589            "You actually need to change `cfbd_key` to your CFBD API key."
-590        )
-591    elif "Bearer " in real_api_key:
-592        pass
-593    elif "Bearer" in real_api_key:
-594        real_api_key = real_api_key.replace("Bearer", "Bearer ")
-595    else:
-596        real_api_key = "Bearer " + real_api_key
-597
-598    if season is not None and season > (now.year + 1):
-599        raise ValueError(f"`season` cannot be greater than {season}.")
-600    elif season is not None and season < 1869:
-601        raise ValueError("`season` cannot be less than 1869.")
-602
-603    if season is None and team is None:
-604        raise ValueError(
-605            "`season` and/or `team` must be set to "
-606            + "valid non-null values for this function to work."
-607        )
+550        json_data = get_cfbd_team_recruiting_ratings(
+551            team="Ohio State"
+552        )
+553        print(json_data)
+554        time.sleep(5)
+555
+556        # You can also tell this function to just return the API call as
+557        # a Dictionary (read: JSON) object.
+558        print(
+559            "You can also tell this function to just return the API call " +
+560            "as a Dictionary (read: JSON) object."
+561        )
+562        json_data = get_cfbd_team_recruiting_ratings(
+563            season=2020,
+564            team="Ohio",
+565            return_as_dict=True
+566        )
+567        print(json_data)
+568
+569    ```
+570    Returns
+571    ----------
+572    A pandas `DataFrame` object with CFB Poll data,
+573    or (if `return_as_dict` is set to `True`)
+574    a dictionary object with CFB Poll data.
+575    """
+576
+577    # now = datetime.now()
+578    recruit_df = pd.DataFrame()
+579    # row_df = pd.DataFrame()
+580    url = "https://api.collegefootballdata.com/recruiting/teams"
+581
+582    ##########################################################################
+583
+584    if api_key is not None:
+585        real_api_key = api_key
+586        del api_key
+587    else:
+588        real_api_key = get_cfbd_api_token(api_key_dir=api_key_dir)
+589
+590    if real_api_key == "tigersAreAwesome":
+591        raise ValueError(
+592            "You actually need to change `cfbd_key` to your CFBD API key."
+593        )
+594    elif "Bearer " in real_api_key:
+595        pass
+596    elif "Bearer" in real_api_key:
+597        real_api_key = real_api_key.replace("Bearer", "Bearer ")
+598    else:
+599        real_api_key = "Bearer " + real_api_key
+600
+601    # if season > (now.year + 1):
+602    #     raise ValueError(f"`season` cannot be greater than {season}.")
+603    # elif season < 1869:
+604    #     raise ValueError("`season` cannot be less than 1869.")
+605
+606    if season < 1869:
+607        raise ValueError("`season` cannot be less than 1869.")
 608
-609    # URL builder
-610    ##########################################################################
-611
-612    url_elements = 0
-613
-614    if season is not None and url_elements == 0:
-615        url += f"?year={season}"
-616        url_elements += 1
-617    elif season is not None:
-618        url += f"&year={season}"
-619        url_elements += 1
-620
-621    if team is not None and url_elements == 0:
-622        url += f"?team={team}"
-623        url_elements += 1
-624    elif team is not None:
-625        url += f"&team={team}"
-626        url_elements += 1
-627
-628    headers = {
-629        "Authorization": f"{real_api_key}",
-630        "accept": "application/json"
-631    }
-632    response = requests.get(url, headers=headers)
+609    if season is None and team is None:
+610        raise ValueError(
+611            "`season` and/or `team` must be set to "
+612            + "valid non-null values for this function to work."
+613        )
+614
+615    # URL builder
+616    ##########################################################################
+617
+618    url_elements = 0
+619
+620    if season is not None and url_elements == 0:
+621        url += f"?year={season}"
+622        url_elements += 1
+623    elif season is not None:
+624        url += f"&year={season}"
+625        url_elements += 1
+626
+627    if team is not None and url_elements == 0:
+628        url += f"?team={team}"
+629        url_elements += 1
+630    elif team is not None:
+631        url += f"&team={team}"
+632        url_elements += 1
 633
-634    if response.status_code == 200:
-635        pass
-636    elif response.status_code == 401:
-637        raise ConnectionRefusedError(
-638            "Could not connect. The connection was refused." +
-639            "\nHTTP Status Code 401."
-640        )
-641    else:
-642        raise ConnectionError(
-643            f"Could not connect.\nHTTP Status code {response.status_code}"
-644        )
-645
-646    json_data = response.json()
-647
-648    if return_as_dict is True:
-649        return json_data
-650
-651    # for player in tqdm(json_data):
-652    #     pass
-653    recruit_df = pd.json_normalize(json_data)
-654
-655    return recruit_df
+634    headers = {
+635        "Authorization": f"{real_api_key}",
+636        "accept": "application/json"
+637    }
+638    response = requests.get(url, headers=headers)
+639
+640    if response.status_code == 200:
+641        pass
+642    elif response.status_code == 401:
+643        raise ConnectionRefusedError(
+644            "Could not connect. The connection was refused." +
+645            "\nHTTP Status Code 401."
+646        )
+647    else:
+648        raise ConnectionError(
+649            f"Could not connect.\nHTTP Status code {response.status_code}"
+650        )
+651
+652    json_data = response.json()
+653
+654    if return_as_dict is True:
+655        return json_data
+656
+657    # for player in tqdm(json_data):
+658    #     pass
+659    recruit_df = pd.json_normalize(json_data)
+660
+661    return recruit_df
 
@@ -3658,374 +3670,374 @@

Returns

-
 658def get_cfbd_team_recruiting_group_ratings(
- 659    api_key: str = None,
- 660    api_key_dir: str = None,
- 661    start_season: int = None,
- 662    end_season: int = None,
- 663    team: str = None,
- 664    conference: str = None,
- 665    return_as_dict: bool = False,
- 666):
- 667    """
- 668    Allows you to get CFB player recruiting data,
- 669    grouped by the team and position,
- 670    from the CFBD API.
- 671
- 672    Parameters
- 673    ----------
- 674
- 675    `api_key` (str, optional):
- 676        Semi-optional argument.
- 677        If `api_key` is null, this function will attempt to load a CFBD API key
- 678        from the python environment, or from a file on this computer.
- 679        If `api_key` is not null,
- 680        this function will automatically assume that the
- 681        inputted `api_key` is a valid CFBD API key.
- 682
- 683    `api_key_dir` (str, optional):
- 684        Optional argument.
- 685        If `api_key` is set to am empty string, this variable is ignored.
- 686        If `api_key_dir` is null, and `api_key` is null,
- 687        this function will try to find
- 688        a CFBD API key file in this user's home directory.
- 689        If `api_key_dir` is set to a string, and `api_key` is null,
- 690        this function will assume that `api_key_dir` is a directory,
- 691        and will try to find a CFBD API key file in that directory.
- 692
- 693    `start_season` (int, optional):
- 694        Optional argument.
- 695        If `start_season` is set to a valid integer,
- 696        the API will filter out every recruiting season that
- 697        is less than `start_season`.
+                
 664def get_cfbd_team_recruiting_group_ratings(
+ 665    api_key: str = None,
+ 666    api_key_dir: str = None,
+ 667    start_season: int = None,
+ 668    end_season: int = None,
+ 669    team: str = None,
+ 670    conference: str = None,
+ 671    return_as_dict: bool = False,
+ 672):
+ 673    """
+ 674    Allows you to get CFB player recruiting data,
+ 675    grouped by the team and position,
+ 676    from the CFBD API.
+ 677
+ 678    Parameters
+ 679    ----------
+ 680
+ 681    `api_key` (str, optional):
+ 682        Semi-optional argument.
+ 683        If `api_key` is null, this function will attempt to load a CFBD API key
+ 684        from the python environment, or from a file on this computer.
+ 685        If `api_key` is not null,
+ 686        this function will automatically assume that the
+ 687        inputted `api_key` is a valid CFBD API key.
+ 688
+ 689    `api_key_dir` (str, optional):
+ 690        Optional argument.
+ 691        If `api_key` is set to am empty string, this variable is ignored.
+ 692        If `api_key_dir` is null, and `api_key` is null,
+ 693        this function will try to find
+ 694        a CFBD API key file in this user's home directory.
+ 695        If `api_key_dir` is set to a string, and `api_key` is null,
+ 696        this function will assume that `api_key_dir` is a directory,
+ 697        and will try to find a CFBD API key file in that directory.
  698
- 699    `end_season` (int, optional):
+ 699    `start_season` (int, optional):
  700        Optional argument.
  701        If `start_season` is set to a valid integer,
  702        the API will filter out every recruiting season that
- 703        is greater than `end_season`.
+ 703        is less than `start_season`.
  704
- 705    `team` (str, semi-mandatory):
- 706        Semi-required argument.
- 707        Specifies the season you want CFB recruiting data from.
- 708        This must be specified, otherwise this package, and by extension
- 709        the CFBD API, will not accept the request to get CFB recruiting data.
- 710        This or `season` must be set to a valid non-null variable
- 711        for this to function.
- 712
- 713    `conference` (str, optional):
- 714        Optional argument.
- 715        If you only want CFB recruiting data
- 716        from teams in a specific conference,
- 717        set `conference` to the abbreviation
- 718        of the conference you want CFB recruiting data from.
- 719        For a list of conferences,
- 720        use the `cfbd_json_py.conferences.get_cfbd_conference_info()`
- 721        function.
- 722
- 723    `return_as_dict` (bool, semi-optional):
- 724        Semi-optional argument.
- 725        If you want this function to return
- 726        the data as a dictionary (read: JSON object),
- 727        instead of a pandas `DataFrame` object,
- 728        set `return_as_dict` to `True`.
- 729
- 730    Usage
- 731    ----------
- 732    ```
- 733    import time
- 734
- 735    from cfbd_json_py.recruiting import get_cfbd_team_recruiting_group_ratings
- 736
- 737
- 738    cfbd_key = "tigersAreAwesome"  # placeholder for your CFBD API Key.
- 739
- 740    if cfbd_key != "tigersAreAwesome":
- 741        print(
- 742            "Using the user's API key declared in this script " +
- 743            "for this example."
- 744        )
+ 705    `end_season` (int, optional):
+ 706        Optional argument.
+ 707        If `start_season` is set to a valid integer,
+ 708        the API will filter out every recruiting season that
+ 709        is greater than `end_season`.
+ 710
+ 711    `team` (str, semi-mandatory):
+ 712        Semi-required argument.
+ 713        Specifies the season you want CFB recruiting data from.
+ 714        This must be specified, otherwise this package, and by extension
+ 715        the CFBD API, will not accept the request to get CFB recruiting data.
+ 716        This or `season` must be set to a valid non-null variable
+ 717        for this to function.
+ 718
+ 719    `conference` (str, optional):
+ 720        Optional argument.
+ 721        If you only want CFB recruiting data
+ 722        from teams in a specific conference,
+ 723        set `conference` to the abbreviation
+ 724        of the conference you want CFB recruiting data from.
+ 725        For a list of conferences,
+ 726        use the `cfbd_json_py.conferences.get_cfbd_conference_info()`
+ 727        function.
+ 728
+ 729    `return_as_dict` (bool, semi-optional):
+ 730        Semi-optional argument.
+ 731        If you want this function to return
+ 732        the data as a dictionary (read: JSON object),
+ 733        instead of a pandas `DataFrame` object,
+ 734        set `return_as_dict` to `True`.
+ 735
+ 736    Usage
+ 737    ----------
+ 738    ```
+ 739    import time
+ 740
+ 741    from cfbd_json_py.recruiting import get_cfbd_team_recruiting_group_ratings
+ 742
+ 743
+ 744    cfbd_key = "tigersAreAwesome"  # placeholder for your CFBD API Key.
  745
- 746        # Get recruiting data between 2020 and 2023,
- 747        # grouped by team and position.
- 748        print(
- 749            "Get recruiting data between 2020 and 2023, " +
- 750            "grouped by team and position."
- 751        )
- 752        json_data = get_cfbd_team_recruiting_group_ratings(
- 753            api_key=cfbd_key,
- 754            start_season=2020,
- 755            end_season=2023
- 756        )
- 757        print(json_data)
- 758        time.sleep(5)
- 759
- 760        # Get recruiting data between 2020 and 2023,
- 761        # grouped by team and position,
- 762        # for the Ohio State Buckeyes Football team.
- 763        print(
- 764            "Get recruiting data between 2020 and 2023, " +
- 765            "grouped by team and position, " +
- 766            "for the Ohio State Buckeyes Football team."
- 767        )
- 768        json_data = get_cfbd_team_recruiting_group_ratings(
- 769            api_key=cfbd_key,
- 770            start_season=2020,
- 771            end_season=2023,
- 772            team="Ohio State"
+ 746    if cfbd_key != "tigersAreAwesome":
+ 747        print(
+ 748            "Using the user's API key declared in this script " +
+ 749            "for this example."
+ 750        )
+ 751
+ 752        # Get recruiting data between 2020 and 2023,
+ 753        # grouped by team and position.
+ 754        print(
+ 755            "Get recruiting data between 2020 and 2023, " +
+ 756            "grouped by team and position."
+ 757        )
+ 758        json_data = get_cfbd_team_recruiting_group_ratings(
+ 759            api_key=cfbd_key,
+ 760            start_season=2020,
+ 761            end_season=2023
+ 762        )
+ 763        print(json_data)
+ 764        time.sleep(5)
+ 765
+ 766        # Get recruiting data between 2020 and 2023,
+ 767        # grouped by team and position,
+ 768        # for the Ohio State Buckeyes Football team.
+ 769        print(
+ 770            "Get recruiting data between 2020 and 2023, " +
+ 771            "grouped by team and position, " +
+ 772            "for the Ohio State Buckeyes Football team."
  773        )
- 774        print(json_data)
- 775        time.sleep(5)
- 776
- 777        # Get recruiting data starting in 2020,
- 778        # grouped by team and position.
- 779        print(
- 780            "Get recruiting data starting in 2020, " +
- 781            "grouped by team and position."
- 782        )
- 783        json_data = get_cfbd_team_recruiting_group_ratings(
- 784            api_key=cfbd_key,
- 785            start_season=2020
- 786        )
- 787        print(json_data)
- 788        time.sleep(5)
- 789
- 790        # Get recruiting data ending in 2018,
- 791        # grouped by team and position.
- 792        print(
- 793            "Get recruiting data ending in 2018, grouped by team and position."
- 794        )
- 795        json_data = get_cfbd_team_recruiting_group_ratings(
- 796            api_key=cfbd_key,
- 797            start_season=2020
- 798        )
- 799        print(json_data)
- 800        time.sleep(5)
- 801
- 802        # Get recruiting data starting in 2020,
- 803        # grouped by team and position,
- 804        # but only for Mountain West conference (MWC) teams.
- 805        print(
- 806            "Get recruiting data starting in 2020, " +
- 807            "grouped by team and position, " +
- 808            "but only for Mountain West conference (MWC) teams."
- 809        )
- 810        json_data = get_cfbd_team_recruiting_group_ratings(
- 811            api_key=cfbd_key,
- 812            start_season=2020,
- 813            conference="MWC"
- 814        )
- 815        print(json_data)
- 816        time.sleep(5)
- 817
- 818        # You can also tell this function to just return the API call as
- 819        # a Dictionary (read: JSON) object.
- 820        print(
- 821            "You can also tell this function to just return the API call " +
- 822            "as a Dictionary (read: JSON) object."
- 823        )
- 824        json_data = get_cfbd_team_recruiting_group_ratings(
- 825            api_key=cfbd_key,
- 826            start_season=2020,
- 827            end_season=2023,
- 828            team="Ohio",
- 829            return_as_dict=True
- 830        )
- 831        print(json_data)
- 832
- 833    else:
- 834        # Alternatively, if the CFBD API key exists in this python environment,
- 835        # or it's been set by cfbd_json_py.utls.set_cfbd_api_token(),
- 836        # you could just call these functions directly,
- 837        # without setting the API key in the script.
- 838        print(
- 839            "Using the user's API key supposedly loaded " +
- 840            "into this python environment for this example."
- 841        )
- 842
- 843
- 844        # Get recruiting data between 2020 and 2023,
- 845        # grouped by team and position.
- 846        print(
- 847            "Get recruiting data between 2020 and 2023, " +
- 848            "grouped by team and position."
- 849        )
- 850        json_data = get_cfbd_team_recruiting_group_ratings(
- 851            start_season=2020,
- 852            end_season=2023
- 853        )
- 854        print(json_data)
- 855        time.sleep(5)
- 856
- 857        # Get recruiting data between 2020 and 2023,
- 858        # grouped by team and position,
- 859        # for the Ohio State Buckeyes Football team.
- 860        print(
- 861            "Get recruiting data between 2020 and 2023, " +
- 862            "grouped by team and position, " +
- 863            "for the Ohio State Buckeyes Football team."
- 864        )
- 865        json_data = get_cfbd_team_recruiting_group_ratings(
- 866            start_season=2020,
- 867            end_season=2023,
- 868            team="Ohio State"
- 869        )
- 870        print(json_data)
- 871        time.sleep(5)
- 872
- 873        # Get recruiting data starting in 2020,
- 874        # grouped by team and position.
- 875        print(
- 876            "Get recruiting data starting in 2020, " +
- 877            "grouped by team and position."
- 878        )
- 879        json_data = get_cfbd_team_recruiting_group_ratings(
- 880            start_season=2020
- 881        )
- 882        print(json_data)
- 883        time.sleep(5)
- 884
- 885        # Get recruiting data ending in 2018,
- 886        # grouped by team and position.
- 887        print(
- 888            "Get recruiting data ending in 2018, grouped by team and position."
- 889        )
- 890        json_data = get_cfbd_team_recruiting_group_ratings(
- 891            end_season=2018
- 892        )
- 893        print(json_data)
- 894        time.sleep(5)
- 895
- 896        # Get recruiting data starting in 2020,
- 897        # grouped by team and position,
- 898        # but only for Mountain West conference (MWC) teams.
- 899        print(
- 900            "Get recruiting data starting in 2020, " +
- 901            "grouped by team and position, " +
- 902            "but only for Mountain West conference (MWC) teams."
- 903        )
- 904        json_data = get_cfbd_team_recruiting_group_ratings(
- 905            start_season=2020,
- 906            conference="MWC"
- 907        )
- 908        print(json_data)
- 909        time.sleep(5)
- 910
- 911        # You can also tell this function to just return the API call as
- 912        # a Dictionary (read: JSON) object.
- 913        print(
- 914            "You can also tell this function to just return the API call " +
- 915            "as a Dictionary (read: JSON) object."
- 916        )
- 917        json_data = get_cfbd_team_recruiting_group_ratings(
- 918            start_season=2020,
- 919            end_season=2023,
- 920            team="Ohio",
- 921            return_as_dict=True
+ 774        json_data = get_cfbd_team_recruiting_group_ratings(
+ 775            api_key=cfbd_key,
+ 776            start_season=2020,
+ 777            end_season=2023,
+ 778            team="Ohio State"
+ 779        )
+ 780        print(json_data)
+ 781        time.sleep(5)
+ 782
+ 783        # Get recruiting data starting in 2020,
+ 784        # grouped by team and position.
+ 785        print(
+ 786            "Get recruiting data starting in 2020, " +
+ 787            "grouped by team and position."
+ 788        )
+ 789        json_data = get_cfbd_team_recruiting_group_ratings(
+ 790            api_key=cfbd_key,
+ 791            start_season=2020
+ 792        )
+ 793        print(json_data)
+ 794        time.sleep(5)
+ 795
+ 796        # Get recruiting data ending in 2018,
+ 797        # grouped by team and position.
+ 798        print(
+ 799            "Get recruiting data ending in 2018, grouped by team and position."
+ 800        )
+ 801        json_data = get_cfbd_team_recruiting_group_ratings(
+ 802            api_key=cfbd_key,
+ 803            start_season=2020
+ 804        )
+ 805        print(json_data)
+ 806        time.sleep(5)
+ 807
+ 808        # Get recruiting data starting in 2020,
+ 809        # grouped by team and position,
+ 810        # but only for Mountain West conference (MWC) teams.
+ 811        print(
+ 812            "Get recruiting data starting in 2020, " +
+ 813            "grouped by team and position, " +
+ 814            "but only for Mountain West conference (MWC) teams."
+ 815        )
+ 816        json_data = get_cfbd_team_recruiting_group_ratings(
+ 817            api_key=cfbd_key,
+ 818            start_season=2020,
+ 819            conference="MWC"
+ 820        )
+ 821        print(json_data)
+ 822        time.sleep(5)
+ 823
+ 824        # You can also tell this function to just return the API call as
+ 825        # a Dictionary (read: JSON) object.
+ 826        print(
+ 827            "You can also tell this function to just return the API call " +
+ 828            "as a Dictionary (read: JSON) object."
+ 829        )
+ 830        json_data = get_cfbd_team_recruiting_group_ratings(
+ 831            api_key=cfbd_key,
+ 832            start_season=2020,
+ 833            end_season=2023,
+ 834            team="Ohio",
+ 835            return_as_dict=True
+ 836        )
+ 837        print(json_data)
+ 838
+ 839    else:
+ 840        # Alternatively, if the CFBD API key exists in this python environment,
+ 841        # or it's been set by cfbd_json_py.utls.set_cfbd_api_token(),
+ 842        # you could just call these functions directly,
+ 843        # without setting the API key in the script.
+ 844        print(
+ 845            "Using the user's API key supposedly loaded " +
+ 846            "into this python environment for this example."
+ 847        )
+ 848
+ 849
+ 850        # Get recruiting data between 2020 and 2023,
+ 851        # grouped by team and position.
+ 852        print(
+ 853            "Get recruiting data between 2020 and 2023, " +
+ 854            "grouped by team and position."
+ 855        )
+ 856        json_data = get_cfbd_team_recruiting_group_ratings(
+ 857            start_season=2020,
+ 858            end_season=2023
+ 859        )
+ 860        print(json_data)
+ 861        time.sleep(5)
+ 862
+ 863        # Get recruiting data between 2020 and 2023,
+ 864        # grouped by team and position,
+ 865        # for the Ohio State Buckeyes Football team.
+ 866        print(
+ 867            "Get recruiting data between 2020 and 2023, " +
+ 868            "grouped by team and position, " +
+ 869            "for the Ohio State Buckeyes Football team."
+ 870        )
+ 871        json_data = get_cfbd_team_recruiting_group_ratings(
+ 872            start_season=2020,
+ 873            end_season=2023,
+ 874            team="Ohio State"
+ 875        )
+ 876        print(json_data)
+ 877        time.sleep(5)
+ 878
+ 879        # Get recruiting data starting in 2020,
+ 880        # grouped by team and position.
+ 881        print(
+ 882            "Get recruiting data starting in 2020, " +
+ 883            "grouped by team and position."
+ 884        )
+ 885        json_data = get_cfbd_team_recruiting_group_ratings(
+ 886            start_season=2020
+ 887        )
+ 888        print(json_data)
+ 889        time.sleep(5)
+ 890
+ 891        # Get recruiting data ending in 2018,
+ 892        # grouped by team and position.
+ 893        print(
+ 894            "Get recruiting data ending in 2018, grouped by team and position."
+ 895        )
+ 896        json_data = get_cfbd_team_recruiting_group_ratings(
+ 897            end_season=2018
+ 898        )
+ 899        print(json_data)
+ 900        time.sleep(5)
+ 901
+ 902        # Get recruiting data starting in 2020,
+ 903        # grouped by team and position,
+ 904        # but only for Mountain West conference (MWC) teams.
+ 905        print(
+ 906            "Get recruiting data starting in 2020, " +
+ 907            "grouped by team and position, " +
+ 908            "but only for Mountain West conference (MWC) teams."
+ 909        )
+ 910        json_data = get_cfbd_team_recruiting_group_ratings(
+ 911            start_season=2020,
+ 912            conference="MWC"
+ 913        )
+ 914        print(json_data)
+ 915        time.sleep(5)
+ 916
+ 917        # You can also tell this function to just return the API call as
+ 918        # a Dictionary (read: JSON) object.
+ 919        print(
+ 920            "You can also tell this function to just return the API call " +
+ 921            "as a Dictionary (read: JSON) object."
  922        )
- 923        print(json_data)
- 924    ```
- 925    Returns
- 926    ----------
- 927    A pandas `DataFrame` object with CFB team recruiting ratings,
- 928    or (if `return_as_dict` is set to `True`)
- 929    a dictionary object with CFB team recruiting ratings.
- 930    """
- 931    now = datetime.now()
- 932    recruit_df = pd.DataFrame()
- 933    # row_df = pd.DataFrame()
- 934    url = "https://api.collegefootballdata.com/recruiting/groups"
- 935
- 936    ##########################################################################
- 937
- 938    if api_key is not None:
- 939        real_api_key = api_key
- 940        del api_key
- 941    else:
- 942        real_api_key = get_cfbd_api_token(api_key_dir=api_key_dir)
+ 923        json_data = get_cfbd_team_recruiting_group_ratings(
+ 924            start_season=2020,
+ 925            end_season=2023,
+ 926            team="Ohio",
+ 927            return_as_dict=True
+ 928        )
+ 929        print(json_data)
+ 930    ```
+ 931    Returns
+ 932    ----------
+ 933    A pandas `DataFrame` object with CFB team recruiting ratings,
+ 934    or (if `return_as_dict` is set to `True`)
+ 935    a dictionary object with CFB team recruiting ratings.
+ 936    """
+ 937    now = datetime.now()
+ 938    recruit_df = pd.DataFrame()
+ 939    # row_df = pd.DataFrame()
+ 940    url = "https://api.collegefootballdata.com/recruiting/groups"
+ 941
+ 942    ##########################################################################
  943
- 944    if real_api_key == "tigersAreAwesome":
- 945        raise ValueError(
- 946            "You actually need to change `cfbd_key` to your CFBD API key."
- 947        )
- 948    elif "Bearer " in real_api_key:
- 949        pass
- 950    elif "Bearer" in real_api_key:
- 951        real_api_key = real_api_key.replace("Bearer", "Bearer ")
- 952    else:
- 953        real_api_key = "Bearer " + real_api_key
- 954
- 955    if start_season is not None and start_season > (now.year + 1):
- 956        raise ValueError(f"`season` cannot be greater than {start_season}.")
- 957    elif start_season is not None and start_season < 1869:
- 958        raise ValueError("`season` cannot be less than 1869.")
- 959
- 960    if end_season is not None and end_season > (now.year + 1):
- 961        raise ValueError(f"`season` cannot be greater than {end_season}.")
- 962    elif end_season is not None and end_season < 1869:
- 963        raise ValueError("`season` cannot be less than 1869.")
- 964
- 965    # URL builder
- 966    ##########################################################################
- 967
- 968    url_elements = 0
- 969
- 970    if start_season is not None and url_elements == 0:
- 971        url += f"?startYear={start_season}"
- 972        url_elements += 1
- 973    elif start_season is not None:
- 974        url += f"&startYear={start_season}"
- 975        url_elements += 1
- 976
- 977    if end_season is not None and url_elements == 0:
- 978        url += f"?endYear={end_season}"
- 979        url_elements += 1
- 980    elif end_season is not None:
- 981        url += f"&endYear={end_season}"
- 982        url_elements += 1
- 983
- 984    if team is not None and url_elements == 0:
- 985        url += f"?team={team}"
- 986        url_elements += 1
- 987    elif team is not None:
- 988        url += f"&team={team}"
- 989        url_elements += 1
- 990
- 991    if conference is not None and url_elements == 0:
- 992        url += f"?conference={conference}"
- 993        url_elements += 1
- 994    elif conference is not None:
- 995        url += f"&conference={conference}"
- 996        url_elements += 1
- 997
- 998    headers = {
- 999        "Authorization": f"{real_api_key}",
-1000        "accept": "application/json"
-1001    }
-1002    response = requests.get(url, headers=headers)
+ 944    if api_key is not None:
+ 945        real_api_key = api_key
+ 946        del api_key
+ 947    else:
+ 948        real_api_key = get_cfbd_api_token(api_key_dir=api_key_dir)
+ 949
+ 950    if real_api_key == "tigersAreAwesome":
+ 951        raise ValueError(
+ 952            "You actually need to change `cfbd_key` to your CFBD API key."
+ 953        )
+ 954    elif "Bearer " in real_api_key:
+ 955        pass
+ 956    elif "Bearer" in real_api_key:
+ 957        real_api_key = real_api_key.replace("Bearer", "Bearer ")
+ 958    else:
+ 959        real_api_key = "Bearer " + real_api_key
+ 960
+ 961    if start_season is not None and start_season > (now.year + 1):
+ 962        raise ValueError(f"`season` cannot be greater than {start_season}.")
+ 963    elif start_season is not None and start_season < 1869:
+ 964        raise ValueError("`season` cannot be less than 1869.")
+ 965
+ 966    if end_season is not None and end_season > (now.year + 1):
+ 967        raise ValueError(f"`season` cannot be greater than {end_season}.")
+ 968    elif end_season is not None and end_season < 1869:
+ 969        raise ValueError("`season` cannot be less than 1869.")
+ 970
+ 971    # URL builder
+ 972    ##########################################################################
+ 973
+ 974    url_elements = 0
+ 975
+ 976    if start_season is not None and url_elements == 0:
+ 977        url += f"?startYear={start_season}"
+ 978        url_elements += 1
+ 979    elif start_season is not None:
+ 980        url += f"&startYear={start_season}"
+ 981        url_elements += 1
+ 982
+ 983    if end_season is not None and url_elements == 0:
+ 984        url += f"?endYear={end_season}"
+ 985        url_elements += 1
+ 986    elif end_season is not None:
+ 987        url += f"&endYear={end_season}"
+ 988        url_elements += 1
+ 989
+ 990    if team is not None and url_elements == 0:
+ 991        url += f"?team={team}"
+ 992        url_elements += 1
+ 993    elif team is not None:
+ 994        url += f"&team={team}"
+ 995        url_elements += 1
+ 996
+ 997    if conference is not None and url_elements == 0:
+ 998        url += f"?conference={conference}"
+ 999        url_elements += 1
+1000    elif conference is not None:
+1001        url += f"&conference={conference}"
+1002        url_elements += 1
 1003
-1004    if response.status_code == 200:
-1005        pass
-1006    elif response.status_code == 401:
-1007        raise ConnectionRefusedError(
-1008            "Could not connect. The connection was refused." +
-1009            "\nHTTP Status Code 401."
-1010        )
-1011    else:
-1012        raise ConnectionError(
-1013            f"Could not connect.\nHTTP Status code {response.status_code}"
-1014        )
-1015
-1016    json_data = response.json()
-1017
-1018    if return_as_dict is True:
-1019        return json_data
-1020
-1021    # for player in tqdm(json_data):
-1022    #     pass
-1023    recruit_df = pd.json_normalize(json_data)
-1024
-1025    return recruit_df
+1004    headers = {
+1005        "Authorization": f"{real_api_key}",
+1006        "accept": "application/json"
+1007    }
+1008    response = requests.get(url, headers=headers)
+1009
+1010    if response.status_code == 200:
+1011        pass
+1012    elif response.status_code == 401:
+1013        raise ConnectionRefusedError(
+1014            "Could not connect. The connection was refused." +
+1015            "\nHTTP Status Code 401."
+1016        )
+1017    else:
+1018        raise ConnectionError(
+1019            f"Could not connect.\nHTTP Status code {response.status_code}"
+1020        )
+1021
+1022    json_data = response.json()
+1023
+1024    if return_as_dict is True:
+1025        return json_data
+1026
+1027    # for player in tqdm(json_data):
+1028    #     pass
+1029    recruit_df = pd.json_normalize(json_data)
+1030
+1031    return recruit_df
 
@@ -4482,4 +4494,4 @@

Returns

- \ No newline at end of file + diff --git a/docs/cfbd_json_py/stats.html b/docs/cfbd_json_py/stats.html index d661e34..db80289 100644 --- a/docs/cfbd_json_py/stats.html +++ b/docs/cfbd_json_py/stats.html @@ -2097,1285 +2097,1281 @@

611 for key, value in tqdm(rebuilt_json.items()): 612 row_df = pd.DataFrame(value, index=[0]) 613 final_df = pd.concat([final_df, row_df], ignore_index=True) - 614 # print() - 615 - 616 final_df = final_df[stat_columns] - 617 return final_df + 614 + 615 final_df = final_df[stat_columns] + 616 return final_df + 617 618 - 619 - 620def get_cfbd_advanced_team_season_stats( - 621 api_key: str = None, - 622 api_key_dir: str = None, - 623 season: int = None, - 624 team: str = None, - 625 # `year` and/or `team` need to be not null for this function to work. - 626 exclude_garbage_time: bool = False, - 627 start_week: int = None, - 628 end_week: int = None, - 629 return_as_dict: bool = False, - 630): - 631 """ - 632 Allows you to get advanced CFB team season stats data from the CFBD API. - 633 - 634 Parameters - 635 ---------- - 636 - 637 `api_key` (str, optional): - 638 Semi-optional argument. - 639 If `api_key` is null, this function will attempt to load a CFBD API key - 640 from the python environment, or from a file on this computer. - 641 If `api_key` is not null, - 642 this function will automatically assume that the - 643 inputted `api_key` is a valid CFBD API key. - 644 - 645 `api_key_dir` (str, optional): - 646 Optional argument. - 647 If `api_key` is set to am empty string, this variable is ignored. - 648 If `api_key_dir` is null, and `api_key` is null, - 649 this function will try to find - 650 a CFBD API key file in this user's home directory. - 651 If `api_key_dir` is set to a string, and `api_key` is null, - 652 this function will assume that `api_key_dir` is a directory, - 653 and will try to find a CFBD API key file in that directory. - 654 - 655 `season` (int, semi-mandatory): - 656 Semi-required argument. - 657 Specifies the season you want CFB team season stats data from. - 658 This must be specified, otherwise this package, and by extension - 659 the CFBD API, will not accept the request - 660 to get CFB team season stats data. - 661 This or `team` must be set - 662 to a valid non-null variable for this to function. - 663 - 664 `team` (str, semi-mandatory): - 665 Semi-required argument. - 666 Specifies the season you want advanced CFB team season stats data from. - 667 This must be specified, otherwise this package, and by extension - 668 the CFBD API, will not accept - 669 the request to get CFB team season stats data. - 670 This or `season` must be set - 671 to a valid non-null variable for this to function. - 672 - 673 `exclude_garbage_time` (bool, optional): - 674 Optional argument. - 675 If you want to filter out plays where - 676 the result of the game is largely decided, - 677 set `exclude_garbage_time = True`. - 678 Default behavior is that this variable is set to - 679 `False` when this function is called. - 680 - 681 `start_week` (int, semi-optional): - 682 Optional argument. - 683 If you only want team stats for a range of weeks, - 684 set `start_week` and `end_week` to - 685 the range of weeks you want season-level data for. - 686 - 687 `end_week` (int, semi-optional): - 688 Optional argument. - 689 If you only want team stats for a range of weeks, - 690 set `start_week` and `end_week` to - 691 the range of weeks you want season-level data for. - 692 - 693 **NOTE**: If the following conditions are `True`, a `ValueError()` - 694 will be raised when calling this function: - 695 - `start_week < 0` - 696 - `end_week < 0` - 697 - `start_week is not None and end_week is None` - 698 (will be changed in a future version) - 699 - `start_week is None and end_week is not None` - 700 (will be changed in a future version) - 701 - `end_week < start_week` - 702 - `end_week = start_week` - 703 - 704 `return_as_dict` (bool, semi-optional): - 705 Semi-optional argument. - 706 If you want this function to return - 707 the data as a dictionary (read: JSON object), - 708 instead of a pandas `DataFrame` object, - 709 set `return_as_dict` to `True`. + 619def get_cfbd_advanced_team_season_stats( + 620 api_key: str = None, + 621 api_key_dir: str = None, + 622 season: int = None, + 623 team: str = None, + 624 # `year` and/or `team` need to be not null for this function to work. + 625 exclude_garbage_time: bool = False, + 626 start_week: int = None, + 627 end_week: int = None, + 628 return_as_dict: bool = False, + 629): + 630 """ + 631 Allows you to get advanced CFB team season stats data from the CFBD API. + 632 + 633 Parameters + 634 ---------- + 635 + 636 `api_key` (str, optional): + 637 Semi-optional argument. + 638 If `api_key` is null, this function will attempt to load a CFBD API key + 639 from the python environment, or from a file on this computer. + 640 If `api_key` is not null, + 641 this function will automatically assume that the + 642 inputted `api_key` is a valid CFBD API key. + 643 + 644 `api_key_dir` (str, optional): + 645 Optional argument. + 646 If `api_key` is set to am empty string, this variable is ignored. + 647 If `api_key_dir` is null, and `api_key` is null, + 648 this function will try to find + 649 a CFBD API key file in this user's home directory. + 650 If `api_key_dir` is set to a string, and `api_key` is null, + 651 this function will assume that `api_key_dir` is a directory, + 652 and will try to find a CFBD API key file in that directory. + 653 + 654 `season` (int, semi-mandatory): + 655 Semi-required argument. + 656 Specifies the season you want CFB team season stats data from. + 657 This must be specified, otherwise this package, and by extension + 658 the CFBD API, will not accept the request + 659 to get CFB team season stats data. + 660 This or `team` must be set + 661 to a valid non-null variable for this to function. + 662 + 663 `team` (str, semi-mandatory): + 664 Semi-required argument. + 665 Specifies the season you want advanced CFB team season stats data from. + 666 This must be specified, otherwise this package, and by extension + 667 the CFBD API, will not accept + 668 the request to get CFB team season stats data. + 669 This or `season` must be set + 670 to a valid non-null variable for this to function. + 671 + 672 `exclude_garbage_time` (bool, optional): + 673 Optional argument. + 674 If you want to filter out plays where + 675 the result of the game is largely decided, + 676 set `exclude_garbage_time = True`. + 677 Default behavior is that this variable is set to + 678 `False` when this function is called. + 679 + 680 `start_week` (int, semi-optional): + 681 Optional argument. + 682 If you only want team stats for a range of weeks, + 683 set `start_week` and `end_week` to + 684 the range of weeks you want season-level data for. + 685 + 686 `end_week` (int, semi-optional): + 687 Optional argument. + 688 If you only want team stats for a range of weeks, + 689 set `start_week` and `end_week` to + 690 the range of weeks you want season-level data for. + 691 + 692 **NOTE**: If the following conditions are `True`, a `ValueError()` + 693 will be raised when calling this function: + 694 - `start_week < 0` + 695 - `end_week < 0` + 696 - `start_week is not None and end_week is None` + 697 (will be changed in a future version) + 698 - `start_week is None and end_week is not None` + 699 (will be changed in a future version) + 700 - `end_week < start_week` + 701 - `end_week = start_week` + 702 + 703 `return_as_dict` (bool, semi-optional): + 704 Semi-optional argument. + 705 If you want this function to return + 706 the data as a dictionary (read: JSON object), + 707 instead of a pandas `DataFrame` object, + 708 set `return_as_dict` to `True`. + 709 710 - 711 - 712 Usage - 713 ---------- - 714 ``` - 715 - 716 import time - 717 - 718 from cfbd_json_py.stats import get_cfbd_advanced_team_season_stats + 711 Usage + 712 ---------- + 713 ``` + 714 + 715 import time + 716 + 717 from cfbd_json_py.stats import get_cfbd_advanced_team_season_stats + 718 719 - 720 - 721 cfbd_key = "tigersAreAwesome" # placeholder for your CFBD API Key. - 722 - 723 if cfbd_key != "tigersAreAwesome": - 724 print( - 725 "Using the user's API key declared in this script " + - 726 "for this example." - 727 ) - 728 - 729 # Get advanced team season stats for the 2020 CFB season. - 730 print("Get team season stats for the 2020 CFB season.") - 731 json_data = get_cfbd_advanced_team_season_stats( - 732 api_key=cfbd_key, - 733 season=2020 - 734 ) - 735 print(json_data) - 736 time.sleep(5) - 737 - 738 # Get advanced team season stats for the 2020 CFB season, - 739 # but remove plays that happen in garbage time. - 740 print( - 741 "Get advanced team season stats for the 2020 CFB season, " + - 742 "but remove plays that happen in garbage time." - 743 ) - 744 json_data = get_cfbd_advanced_team_season_stats( - 745 api_key=cfbd_key, - 746 season=2020, - 747 exclude_garbage_time=True - 748 ) - 749 print(json_data) - 750 time.sleep(5) - 751 - 752 # Get advanced team season stats for the 2020 CFB season, - 753 # but only between weeks 5 and 10. - 754 print( - 755 "Get advanced team season stats for the 2020 CFB season, " + - 756 "but only between weeks 5 and 10." - 757 ) - 758 json_data = get_cfbd_advanced_team_season_stats( - 759 api_key=cfbd_key, - 760 season=2020, - 761 start_week=5, - 762 end_week=10 - 763 ) - 764 print(json_data) - 765 time.sleep(5) - 766 - 767 # Get advanced team season stats for just - 768 # the Ohio State Buckeyes Football Team. - 769 print( - 770 "Get advanced team season stats for just" + - 771 " the Ohio State Buckeyes Football Team." - 772 ) - 773 json_data = get_cfbd_advanced_team_season_stats( - 774 api_key=cfbd_key, - 775 team="Ohio State" - 776 ) - 777 print(json_data) - 778 time.sleep(5) + 720 cfbd_key = "tigersAreAwesome" # placeholder for your CFBD API Key. + 721 + 722 if cfbd_key != "tigersAreAwesome": + 723 print( + 724 "Using the user's API key declared in this script " + + 725 "for this example." + 726 ) + 727 + 728 # Get advanced team season stats for the 2020 CFB season. + 729 print("Get team season stats for the 2020 CFB season.") + 730 json_data = get_cfbd_advanced_team_season_stats( + 731 api_key=cfbd_key, + 732 season=2020 + 733 ) + 734 print(json_data) + 735 time.sleep(5) + 736 + 737 # Get advanced team season stats for the 2020 CFB season, + 738 # but remove plays that happen in garbage time. + 739 print( + 740 "Get advanced team season stats for the 2020 CFB season, " + + 741 "but remove plays that happen in garbage time." + 742 ) + 743 json_data = get_cfbd_advanced_team_season_stats( + 744 api_key=cfbd_key, + 745 season=2020, + 746 exclude_garbage_time=True + 747 ) + 748 print(json_data) + 749 time.sleep(5) + 750 + 751 # Get advanced team season stats for the 2020 CFB season, + 752 # but only between weeks 5 and 10. + 753 print( + 754 "Get advanced team season stats for the 2020 CFB season, " + + 755 "but only between weeks 5 and 10." + 756 ) + 757 json_data = get_cfbd_advanced_team_season_stats( + 758 api_key=cfbd_key, + 759 season=2020, + 760 start_week=5, + 761 end_week=10 + 762 ) + 763 print(json_data) + 764 time.sleep(5) + 765 + 766 # Get advanced team season stats for just + 767 # the Ohio State Buckeyes Football Team. + 768 print( + 769 "Get advanced team season stats for just" + + 770 " the Ohio State Buckeyes Football Team." + 771 ) + 772 json_data = get_cfbd_advanced_team_season_stats( + 773 api_key=cfbd_key, + 774 team="Ohio State" + 775 ) + 776 print(json_data) + 777 time.sleep(5) + 778 779 - 780 - 781 # You can also tell this function to just return the API call as - 782 # a Dictionary (read: JSON) object. - 783 print( - 784 "You can also tell this function to just return the API call " + - 785 "as a Dictionary (read: JSON) object." - 786 ) - 787 json_data = get_cfbd_advanced_team_season_stats( - 788 api_key=cfbd_key, - 789 season=2020, - 790 team="Cincinnati", - 791 return_as_dict=True - 792 ) - 793 print(json_data) - 794 - 795 else: - 796 # Alternatively, if the CFBD API key exists in this python environment, - 797 # or it's been set by cfbd_json_py.utls.set_cfbd_api_token(), - 798 # you could just call these functions directly, - 799 # without setting the API key in the script. - 800 print( - 801 "Using the user's API key supposedly loaded " + - 802 "into this python environment for this example." - 803 ) - 804 - 805 # Get advanced team season stats for the 2020 CFB season. - 806 print("Get team season stats for the 2020 CFB season.") - 807 json_data = get_cfbd_advanced_team_season_stats( - 808 season=2020 - 809 ) - 810 print(json_data) - 811 time.sleep(5) - 812 - 813 # Get advanced team season stats for the 2020 CFB season, - 814 # but remove plays that happen in garbage time. - 815 print( - 816 "Get advanced team season stats for the 2020 CFB season, " + - 817 "but remove plays that happen in garbage time." - 818 ) - 819 json_data = get_cfbd_advanced_team_season_stats( - 820 season=2020, - 821 exclude_garbage_time=True - 822 ) - 823 print(json_data) - 824 time.sleep(5) - 825 - 826 # Get advanced team season stats for the 2020 CFB season, - 827 # but only between weeks 5 and 10. - 828 print( - 829 "Get advanced team season stats for the 2020 CFB season, " + - 830 "but only between weeks 5 and 10." - 831 ) - 832 json_data = get_cfbd_advanced_team_season_stats( - 833 season=2020, - 834 start_week=5, - 835 end_week=10 - 836 ) - 837 print(json_data) - 838 time.sleep(5) - 839 - 840 # Get advanced team season stats for the just - 841 # the Ohio State Buckeyes Football Team. - 842 print( - 843 "Get advanced team season stats for the just " + - 844 "the Ohio State Buckeyes Football Team." - 845 ) - 846 json_data = get_cfbd_advanced_team_season_stats( - 847 team="Ohio State" - 848 ) - 849 print(json_data) - 850 time.sleep(5) + 780 # You can also tell this function to just return the API call as + 781 # a Dictionary (read: JSON) object. + 782 print( + 783 "You can also tell this function to just return the API call " + + 784 "as a Dictionary (read: JSON) object." + 785 ) + 786 json_data = get_cfbd_advanced_team_season_stats( + 787 api_key=cfbd_key, + 788 season=2020, + 789 team="Cincinnati", + 790 return_as_dict=True + 791 ) + 792 print(json_data) + 793 + 794 else: + 795 # Alternatively, if the CFBD API key exists in this python environment, + 796 # or it's been set by cfbd_json_py.utls.set_cfbd_api_token(), + 797 # you could just call these functions directly, + 798 # without setting the API key in the script. + 799 print( + 800 "Using the user's API key supposedly loaded " + + 801 "into this python environment for this example." + 802 ) + 803 + 804 # Get advanced team season stats for the 2020 CFB season. + 805 print("Get team season stats for the 2020 CFB season.") + 806 json_data = get_cfbd_advanced_team_season_stats( + 807 season=2020 + 808 ) + 809 print(json_data) + 810 time.sleep(5) + 811 + 812 # Get advanced team season stats for the 2020 CFB season, + 813 # but remove plays that happen in garbage time. + 814 print( + 815 "Get advanced team season stats for the 2020 CFB season, " + + 816 "but remove plays that happen in garbage time." + 817 ) + 818 json_data = get_cfbd_advanced_team_season_stats( + 819 season=2020, + 820 exclude_garbage_time=True + 821 ) + 822 print(json_data) + 823 time.sleep(5) + 824 + 825 # Get advanced team season stats for the 2020 CFB season, + 826 # but only between weeks 5 and 10. + 827 print( + 828 "Get advanced team season stats for the 2020 CFB season, " + + 829 "but only between weeks 5 and 10." + 830 ) + 831 json_data = get_cfbd_advanced_team_season_stats( + 832 season=2020, + 833 start_week=5, + 834 end_week=10 + 835 ) + 836 print(json_data) + 837 time.sleep(5) + 838 + 839 # Get advanced team season stats for the just + 840 # the Ohio State Buckeyes Football Team. + 841 print( + 842 "Get advanced team season stats for the just " + + 843 "the Ohio State Buckeyes Football Team." + 844 ) + 845 json_data = get_cfbd_advanced_team_season_stats( + 846 team="Ohio State" + 847 ) + 848 print(json_data) + 849 time.sleep(5) + 850 851 - 852 - 853 # You can also tell this function to just return the API call as - 854 # a Dictionary (read: JSON) object. - 855 print( - 856 "You can also tell this function to just return the API call " + - 857 "as a Dictionary (read: JSON) object." - 858 ) - 859 json_data = get_cfbd_advanced_team_season_stats( - 860 season=2020, - 861 team="Cincinnati", - 862 return_as_dict=True - 863 ) - 864 print(json_data) - 865 ``` - 866 Returns - 867 ---------- - 868 A pandas `DataFrame` object with advanced team season stats data, - 869 or (if `return_as_dict` is set to `True`) - 870 a dictionary object with a with advanced team season stats data. - 871 - 872 """ - 873 now = datetime.now() - 874 url = "https://api.collegefootballdata.com/stats/season/advanced" - 875 row_df = pd.DataFrame() - 876 final_df = pd.DataFrame() - 877 - 878 if api_key is not None: - 879 real_api_key = api_key - 880 del api_key - 881 else: - 882 real_api_key = get_cfbd_api_token(api_key_dir=api_key_dir) - 883 - 884 if real_api_key == "tigersAreAwesome": - 885 raise ValueError( - 886 "You actually need to change `cfbd_key` to your CFBD API key." - 887 ) - 888 elif "Bearer " in real_api_key: - 889 pass - 890 elif "Bearer" in real_api_key: - 891 real_api_key = real_api_key.replace("Bearer", "Bearer ") - 892 else: - 893 real_api_key = "Bearer " + real_api_key - 894 - 895 if season is not None and (season > (now.year + 1)): - 896 raise ValueError(f"`season` cannot be greater than {season}.") - 897 elif season is not None and season < 1869: - 898 raise ValueError("`season` cannot be less than 1869.") - 899 - 900 if start_week is not None and end_week is not None: - 901 if start_week > end_week: - 902 raise ValueError("`start_week` cannot be greater than `end_week`.") - 903 elif start_week == end_week: - 904 raise ValueError( - 905 "`start_week` cannot be equal to `end_week`." - 906 + "\n Use " + - 907 "`cfbd_json_py.games.get_cfbd_player_game_stats()` instead " - 908 + "if you want player stats for a specific week in ." - 909 ) - 910 elif start_week < 0: - 911 raise ValueError("`start_week` cannot be less than 0.") - 912 elif end_week < 0: - 913 raise ValueError("`end_week` cannot be less than 0.") - 914 - 915 gt_str = "" - 916 - 917 # URL builder - 918 ########################################################################## - 919 - 920 if exclude_garbage_time is True: - 921 gt_str = "true" - 922 elif exclude_garbage_time is False: - 923 gt_str = "false" - 924 - 925 if season is not None and team is not None: - 926 url += f"?year={season}&team={team}" - 927 elif season is not None: - 928 url += f"?year={season}" - 929 elif team is not None: - 930 url += f"?team={team}" - 931 - 932 if exclude_garbage_time is not None: - 933 url += f"&excludeGarbageTime={gt_str}" - 934 - 935 if start_week is not None: - 936 url += f"&startWeek={start_week}" - 937 - 938 if end_week is not None: - 939 url += f"&endWeek={end_week}" - 940 - 941 headers = { - 942 "Authorization": f"{real_api_key}", - 943 "accept": "application/json" - 944 } - 945 - 946 response = requests.get(url, headers=headers) - 947 - 948 if response.status_code == 200: - 949 pass - 950 elif response.status_code == 401: - 951 raise ConnectionRefusedError( - 952 "Could not connect. The connection was refused." + - 953 "\nHTTP Status Code 401." - 954 ) - 955 else: - 956 raise ConnectionError( - 957 f"Could not connect.\nHTTP Status code {response.status_code}" - 958 ) - 959 - 960 json_data = response.json() - 961 - 962 if return_as_dict is True: - 963 return json_data + 852 # You can also tell this function to just return the API call as + 853 # a Dictionary (read: JSON) object. + 854 print( + 855 "You can also tell this function to just return the API call " + + 856 "as a Dictionary (read: JSON) object." + 857 ) + 858 json_data = get_cfbd_advanced_team_season_stats( + 859 season=2020, + 860 team="Cincinnati", + 861 return_as_dict=True + 862 ) + 863 print(json_data) + 864 ``` + 865 Returns + 866 ---------- + 867 A pandas `DataFrame` object with advanced team season stats data, + 868 or (if `return_as_dict` is set to `True`) + 869 a dictionary object with a with advanced team season stats data. + 870 + 871 """ + 872 now = datetime.now() + 873 url = "https://api.collegefootballdata.com/stats/season/advanced" + 874 row_df = pd.DataFrame() + 875 final_df = pd.DataFrame() + 876 + 877 if api_key is not None: + 878 real_api_key = api_key + 879 del api_key + 880 else: + 881 real_api_key = get_cfbd_api_token(api_key_dir=api_key_dir) + 882 + 883 if real_api_key == "tigersAreAwesome": + 884 raise ValueError( + 885 "You actually need to change `cfbd_key` to your CFBD API key." + 886 ) + 887 elif "Bearer " in real_api_key: + 888 pass + 889 elif "Bearer" in real_api_key: + 890 real_api_key = real_api_key.replace("Bearer", "Bearer ") + 891 else: + 892 real_api_key = "Bearer " + real_api_key + 893 + 894 if season is not None and (season > (now.year + 1)): + 895 raise ValueError(f"`season` cannot be greater than {season}.") + 896 elif season is not None and season < 1869: + 897 raise ValueError("`season` cannot be less than 1869.") + 898 + 899 if start_week is not None and end_week is not None: + 900 if start_week > end_week: + 901 raise ValueError("`start_week` cannot be greater than `end_week`.") + 902 elif start_week == end_week: + 903 raise ValueError( + 904 "`start_week` cannot be equal to `end_week`." + 905 + "\n Use " + + 906 "`cfbd_json_py.games.get_cfbd_player_game_stats()` instead " + 907 + "if you want player stats for a specific week in ." + 908 ) + 909 elif start_week < 0: + 910 raise ValueError("`start_week` cannot be less than 0.") + 911 elif end_week < 0: + 912 raise ValueError("`end_week` cannot be less than 0.") + 913 + 914 gt_str = "" + 915 + 916 # URL builder + 917 ########################################################################## + 918 + 919 if exclude_garbage_time is True: + 920 gt_str = "true" + 921 elif exclude_garbage_time is False: + 922 gt_str = "false" + 923 + 924 if season is not None and team is not None: + 925 url += f"?year={season}&team={team}" + 926 elif season is not None: + 927 url += f"?year={season}" + 928 elif team is not None: + 929 url += f"?team={team}" + 930 + 931 if exclude_garbage_time is not None: + 932 url += f"&excludeGarbageTime={gt_str}" + 933 + 934 if start_week is not None: + 935 url += f"&startWeek={start_week}" + 936 + 937 if end_week is not None: + 938 url += f"&endWeek={end_week}" + 939 + 940 headers = { + 941 "Authorization": f"{real_api_key}", + 942 "accept": "application/json" + 943 } + 944 + 945 response = requests.get(url, headers=headers) + 946 + 947 if response.status_code == 200: + 948 pass + 949 elif response.status_code == 401: + 950 raise ConnectionRefusedError( + 951 "Could not connect. The connection was refused." + + 952 "\nHTTP Status Code 401." + 953 ) + 954 else: + 955 raise ConnectionError( + 956 f"Could not connect.\nHTTP Status code {response.status_code}" + 957 ) + 958 + 959 json_data = response.json() + 960 + 961 if return_as_dict is True: + 962 return json_data + 963 964 - 965 # final_df = pd.json_normalize(json_data) - 966 - 967 # print(final_df.columns) - 968 - 969 for team in tqdm(json_data): - 970 t_season = team["season"] - 971 t_team = team["team"] - 972 t_conf = team["conference"] - 973 row_df = pd.DataFrame( - 974 { - 975 "season": t_season, - 976 "team": t_team, - 977 "conference": t_conf - 978 }, - 979 index=[0] - 980 ) - 981 - 982 # offense - 983 if "offense" not in team: - 984 logging.debug( - 985 f"Key `[offense]` not found for the {t_season} {t_team}." - 986 ) - 987 else: - 988 row_df["offense_plays"] = team["offense"]["plays"] - 989 row_df["offense_drives"] = team["offense"]["drives"] - 990 # row_df["offense_plays"] = team["offense"]["plays"] - 991 row_df["offense_ppa"] = team["offense"]["ppa"] - 992 row_df["offense_total_ppa"] = team["offense"]["totalPPA"] - 993 row_df["offense_success_rate"] = team["offense"]["successRate"] - 994 row_df["offense_explosiveness"] = team["offense"]["explosiveness"] - 995 row_df["offense_power_success"] = team["offense"]["powerSuccess"] - 996 row_df["offense_stuff_rate"] = team["offense"]["stuffRate"] - 997 row_df["offense_line_yards_avg"] = team["offense"]["lineYards"] - 998 row_df["offense_line_yards_total"] = team["offense"][ - 999 "lineYardsTotal" -1000 ] -1001 row_df["offense_second_level_yards_avg"] = team["offense"][ -1002 "secondLevelYards" -1003 ] -1004 row_df["offense_second_level_yards_total"] = team["offense"][ -1005 "secondLevelYardsTotal" -1006 ] -1007 row_df["offense_open_field_yards_avg"] = team["offense"][ -1008 "openFieldYards" -1009 ] -1010 row_df["offense_open_field_yards_total"] = team["offense"][ -1011 "secondLevelYardsTotal" -1012 ] -1013 row_df["offense_total_opportunities"] = team["offense"][ -1014 "totalOpportunies" -1015 ] -1016 row_df["offense_points_per_opportunity"] = team["offense"][ -1017 "pointsPerOpportunity" -1018 ] -1019 -1020 row_df["offense_field_position_avg_start"] = team["offense"][ -1021 "fieldPosition"]["averageStart"] -1022 row_df["offense_field_position_avg_predicted_points"] = team[ -1023 "offense"]["fieldPosition"]["averagePredictedPoints"] -1024 -1025 row_df["offense_havoc_total"] = team["offense"]["havoc"]["total"] -1026 row_df["offense_havoc_front_7"] = team["offense"]["havoc"][ -1027 "frontSeven" -1028 ] -1029 row_df["offense_havoc_db"] = team["offense"]["havoc"]["db"] -1030 -1031 row_df["offense_standard_downs_rate"] = team[ -1032 "offense"]["standardDowns"]["rate"] -1033 row_df["offense_standard_downs_ppa"] = team[ -1034 "offense"]["standardDowns"]["ppa"] -1035 row_df["offense_standard_downs_success_rate"] = team["offense"][ -1036 "standardDowns" -1037 ]["successRate"] -1038 row_df["offense_standard_downs_explosiveness"] = team["offense"][ -1039 "standardDowns" -1040 ]["explosiveness"] -1041 -1042 row_df["offense_passing_downs_rate"] = team[ -1043 "offense"]["passingDowns"]["rate"] -1044 row_df["offense_passing_downs_ppa"] = team[ -1045 "offense"]["passingDowns"]["ppa"] -1046 row_df["offense_passing_downs_success_rate"] = team["offense"][ -1047 "passingDowns" -1048 ]["successRate"] -1049 row_df["offense_passing_downs_explosiveness"] = team["offense"][ -1050 "passingDowns" -1051 ]["explosiveness"] -1052 -1053 row_df["offense_rushing_plays_rate"] = team[ -1054 "offense"]["rushingPlays"]["rate"] -1055 row_df["offense_rushing_plays_ppa"] = team[ -1056 "offense"]["rushingPlays"]["ppa"] -1057 row_df["offense_rushing_plays_total_ppa"] = team[ -1058 "offense"]["rushingPlays"]["totalPPA"] -1059 row_df["offense_rushing_plays_success_rate"] = team[ -1060 "offense"]["rushingPlays"]["successRate"] -1061 row_df["offense_rushing_plays_explosiveness"] = team[ -1062 "offense"]["rushingPlays"]["explosiveness"] -1063 -1064 row_df["offense_passing_plays_rate"] = team[ -1065 "offense"]["passingPlays"]["rate"] -1066 row_df["offense_passing_plays_ppa"] = team[ -1067 "offense"]["passingPlays"]["ppa"] -1068 row_df["offense_passing_plays_total_ppa"] = team[ -1069 "offense"]["passingPlays"]["totalPPA"] -1070 row_df["offense_passing_plays_success_rate"] = team[ -1071 "offense"]["passingPlays"]["successRate"] -1072 row_df["offense_passing_plays_explosiveness"] = team[ -1073 "offense"]["rushingPlays"]["explosiveness"] -1074 -1075 # defense -1076 if "defense" not in team: -1077 logging.debug( -1078 f"Key `[defense]` not found for the {t_season} {t_team}." -1079 ) -1080 else: -1081 -1082 row_df["defense_plays"] = team["defense"]["plays"] -1083 row_df["defense_drives"] = team["defense"]["drives"] -1084 # row_df["defense_plays"] = team["defense"]["plays"] -1085 row_df["defense_ppa"] = team["defense"]["ppa"] -1086 row_df["defense_total_ppa"] = team["defense"]["totalPPA"] -1087 row_df["defense_success_rate"] = team["defense"]["successRate"] -1088 row_df["defense_explosiveness"] = team["defense"]["explosiveness"] -1089 row_df["defense_power_success"] = team["defense"]["powerSuccess"] -1090 row_df["defense_stuff_rate"] = team["defense"]["stuffRate"] -1091 row_df["defense_line_yards_avg"] = team["defense"]["lineYards"] -1092 row_df["defense_line_yards_total"] = team["defense"][ -1093 "lineYardsTotal" -1094 ] -1095 row_df["defense_second_level_yards_avg"] = team["defense"][ -1096 "secondLevelYards" -1097 ] -1098 row_df["defense_second_level_yards_total"] = team["defense"][ -1099 "secondLevelYardsTotal" -1100 ] -1101 row_df["defense_open_field_yards_avg"] = team["defense"][ -1102 "openFieldYards" -1103 ] -1104 row_df["defense_open_field_yards_total"] = team["defense"][ -1105 "secondLevelYardsTotal" -1106 ] -1107 row_df["defense_total_opportunities"] = team["defense"][ -1108 "totalOpportunies" -1109 ] -1110 row_df["defense_points_per_opportunity"] = team["defense"][ -1111 "pointsPerOpportunity" -1112 ] -1113 -1114 row_df["defense_field_position_avg_start"] = team["defense"][ -1115 "fieldPosition" -1116 ]["averageStart"] -1117 row_df["defense_field_position_avg_predicted_points"] = team[ -1118 "defense"]["fieldPosition"]["averagePredictedPoints"] -1119 -1120 row_df["defense_havoc_total"] = team["defense"]["havoc"]["total"] -1121 row_df["defense_havoc_front_7"] = team["defense"]["havoc"][ -1122 "frontSeven" -1123 ] -1124 row_df["defense_havoc_db"] = team["defense"]["havoc"]["db"] -1125 -1126 row_df["defense_standard_downs_rate"] = team[ -1127 "defense"]["standardDowns"]["rate"] -1128 row_df["defense_standard_downs_ppa"] = team[ -1129 "defense"]["standardDowns"]["ppa"] -1130 row_df["defense_standard_downs_success_rate"] = team["defense"][ -1131 "standardDowns" -1132 ]["successRate"] -1133 row_df["defense_standard_downs_explosiveness"] = team["defense"][ -1134 "standardDowns" -1135 ]["explosiveness"] -1136 -1137 row_df["defense_passing_downs_rate"] = team[ -1138 "defense"]["passingDowns"]["rate"] -1139 row_df["defense_passing_downs_ppa"] = team[ -1140 "defense"]["passingDowns"]["ppa"] -1141 row_df["defense_passing_downs_success_rate"] = team["defense"][ -1142 "passingDowns" -1143 ]["successRate"] -1144 row_df["defense_passing_downs_explosiveness"] = team["defense"][ -1145 "passingDowns" -1146 ]["explosiveness"] -1147 -1148 row_df["defense_rushing_plays_rate"] = team[ -1149 "defense"]["rushingPlays"]["rate"] -1150 row_df["defense_rushing_plays_ppa"] = team[ -1151 "defense"]["rushingPlays"]["ppa"] -1152 row_df["defense_rushing_plays_total_ppa"] = team[ -1153 "defense"]["rushingPlays"]["totalPPA"] -1154 row_df["defense_rushing_plays_success_rate"] = team["defense"][ -1155 "rushingPlays" -1156 ]["successRate"] -1157 row_df["defense_rushing_plays_explosiveness"] = team["defense"][ -1158 "rushingPlays" -1159 ]["explosiveness"] -1160 -1161 row_df["defense_passing_plays_rate"] = team[ -1162 "defense"]["passingPlays"]["rate"] -1163 row_df["defense_passing_plays_ppa"] = team[ -1164 "defense"]["passingPlays"]["ppa"] -1165 row_df["defense_passing_plays_total_ppa"] = team[ -1166 "defense"]["passingPlays"]["totalPPA"] -1167 row_df["defense_passing_plays_success_rate"] = team["defense"][ -1168 "passingPlays" -1169 ]["successRate"] -1170 row_df["defense_passing_plays_explosiveness"] = team["defense"][ -1171 "rushingPlays" -1172 ]["explosiveness"] + 965 for team in tqdm(json_data): + 966 t_season = team["season"] + 967 t_team = team["team"] + 968 t_conf = team["conference"] + 969 row_df = pd.DataFrame( + 970 { + 971 "season": t_season, + 972 "team": t_team, + 973 "conference": t_conf + 974 }, + 975 index=[0] + 976 ) + 977 + 978 # offense + 979 if "offense" not in team: + 980 logging.debug( + 981 f"Key `[offense]` not found for the {t_season} {t_team}." + 982 ) + 983 else: + 984 row_df["offense_plays"] = team["offense"]["plays"] + 985 row_df["offense_drives"] = team["offense"]["drives"] + 986 # row_df["offense_plays"] = team["offense"]["plays"] + 987 row_df["offense_ppa"] = team["offense"]["ppa"] + 988 row_df["offense_total_ppa"] = team["offense"]["totalPPA"] + 989 row_df["offense_success_rate"] = team["offense"]["successRate"] + 990 row_df["offense_explosiveness"] = team["offense"]["explosiveness"] + 991 row_df["offense_power_success"] = team["offense"]["powerSuccess"] + 992 row_df["offense_stuff_rate"] = team["offense"]["stuffRate"] + 993 row_df["offense_line_yards_avg"] = team["offense"]["lineYards"] + 994 row_df["offense_line_yards_total"] = team["offense"][ + 995 "lineYardsTotal" + 996 ] + 997 row_df["offense_second_level_yards_avg"] = team["offense"][ + 998 "secondLevelYards" + 999 ] +1000 row_df["offense_second_level_yards_total"] = team["offense"][ +1001 "secondLevelYardsTotal" +1002 ] +1003 row_df["offense_open_field_yards_avg"] = team["offense"][ +1004 "openFieldYards" +1005 ] +1006 row_df["offense_open_field_yards_total"] = team["offense"][ +1007 "secondLevelYardsTotal" +1008 ] +1009 row_df["offense_total_opportunities"] = team["offense"][ +1010 "totalOpportunies" +1011 ] +1012 row_df["offense_points_per_opportunity"] = team["offense"][ +1013 "pointsPerOpportunity" +1014 ] +1015 +1016 row_df["offense_field_position_avg_start"] = team["offense"][ +1017 "fieldPosition"]["averageStart"] +1018 row_df["offense_field_position_avg_predicted_points"] = team[ +1019 "offense"]["fieldPosition"]["averagePredictedPoints"] +1020 +1021 row_df["offense_havoc_total"] = team["offense"]["havoc"]["total"] +1022 row_df["offense_havoc_front_7"] = team["offense"]["havoc"][ +1023 "frontSeven" +1024 ] +1025 row_df["offense_havoc_db"] = team["offense"]["havoc"]["db"] +1026 +1027 row_df["offense_standard_downs_rate"] = team[ +1028 "offense"]["standardDowns"]["rate"] +1029 row_df["offense_standard_downs_ppa"] = team[ +1030 "offense"]["standardDowns"]["ppa"] +1031 row_df["offense_standard_downs_success_rate"] = team["offense"][ +1032 "standardDowns" +1033 ]["successRate"] +1034 row_df["offense_standard_downs_explosiveness"] = team["offense"][ +1035 "standardDowns" +1036 ]["explosiveness"] +1037 +1038 row_df["offense_passing_downs_rate"] = team[ +1039 "offense"]["passingDowns"]["rate"] +1040 row_df["offense_passing_downs_ppa"] = team[ +1041 "offense"]["passingDowns"]["ppa"] +1042 row_df["offense_passing_downs_success_rate"] = team["offense"][ +1043 "passingDowns" +1044 ]["successRate"] +1045 row_df["offense_passing_downs_explosiveness"] = team["offense"][ +1046 "passingDowns" +1047 ]["explosiveness"] +1048 +1049 row_df["offense_rushing_plays_rate"] = team[ +1050 "offense"]["rushingPlays"]["rate"] +1051 row_df["offense_rushing_plays_ppa"] = team[ +1052 "offense"]["rushingPlays"]["ppa"] +1053 row_df["offense_rushing_plays_total_ppa"] = team[ +1054 "offense"]["rushingPlays"]["totalPPA"] +1055 row_df["offense_rushing_plays_success_rate"] = team[ +1056 "offense"]["rushingPlays"]["successRate"] +1057 row_df["offense_rushing_plays_explosiveness"] = team[ +1058 "offense"]["rushingPlays"]["explosiveness"] +1059 +1060 row_df["offense_passing_plays_rate"] = team[ +1061 "offense"]["passingPlays"]["rate"] +1062 row_df["offense_passing_plays_ppa"] = team[ +1063 "offense"]["passingPlays"]["ppa"] +1064 row_df["offense_passing_plays_total_ppa"] = team[ +1065 "offense"]["passingPlays"]["totalPPA"] +1066 row_df["offense_passing_plays_success_rate"] = team[ +1067 "offense"]["passingPlays"]["successRate"] +1068 row_df["offense_passing_plays_explosiveness"] = team[ +1069 "offense"]["rushingPlays"]["explosiveness"] +1070 +1071 # defense +1072 if "defense" not in team: +1073 logging.debug( +1074 f"Key `[defense]` not found for the {t_season} {t_team}." +1075 ) +1076 else: +1077 +1078 row_df["defense_plays"] = team["defense"]["plays"] +1079 row_df["defense_drives"] = team["defense"]["drives"] +1080 # row_df["defense_plays"] = team["defense"]["plays"] +1081 row_df["defense_ppa"] = team["defense"]["ppa"] +1082 row_df["defense_total_ppa"] = team["defense"]["totalPPA"] +1083 row_df["defense_success_rate"] = team["defense"]["successRate"] +1084 row_df["defense_explosiveness"] = team["defense"]["explosiveness"] +1085 row_df["defense_power_success"] = team["defense"]["powerSuccess"] +1086 row_df["defense_stuff_rate"] = team["defense"]["stuffRate"] +1087 row_df["defense_line_yards_avg"] = team["defense"]["lineYards"] +1088 row_df["defense_line_yards_total"] = team["defense"][ +1089 "lineYardsTotal" +1090 ] +1091 row_df["defense_second_level_yards_avg"] = team["defense"][ +1092 "secondLevelYards" +1093 ] +1094 row_df["defense_second_level_yards_total"] = team["defense"][ +1095 "secondLevelYardsTotal" +1096 ] +1097 row_df["defense_open_field_yards_avg"] = team["defense"][ +1098 "openFieldYards" +1099 ] +1100 row_df["defense_open_field_yards_total"] = team["defense"][ +1101 "secondLevelYardsTotal" +1102 ] +1103 row_df["defense_total_opportunities"] = team["defense"][ +1104 "totalOpportunies" +1105 ] +1106 row_df["defense_points_per_opportunity"] = team["defense"][ +1107 "pointsPerOpportunity" +1108 ] +1109 +1110 row_df["defense_field_position_avg_start"] = team["defense"][ +1111 "fieldPosition" +1112 ]["averageStart"] +1113 row_df["defense_field_position_avg_predicted_points"] = team[ +1114 "defense"]["fieldPosition"]["averagePredictedPoints"] +1115 +1116 row_df["defense_havoc_total"] = team["defense"]["havoc"]["total"] +1117 row_df["defense_havoc_front_7"] = team["defense"]["havoc"][ +1118 "frontSeven" +1119 ] +1120 row_df["defense_havoc_db"] = team["defense"]["havoc"]["db"] +1121 +1122 row_df["defense_standard_downs_rate"] = team[ +1123 "defense"]["standardDowns"]["rate"] +1124 row_df["defense_standard_downs_ppa"] = team[ +1125 "defense"]["standardDowns"]["ppa"] +1126 row_df["defense_standard_downs_success_rate"] = team["defense"][ +1127 "standardDowns" +1128 ]["successRate"] +1129 row_df["defense_standard_downs_explosiveness"] = team["defense"][ +1130 "standardDowns" +1131 ]["explosiveness"] +1132 +1133 row_df["defense_passing_downs_rate"] = team[ +1134 "defense"]["passingDowns"]["rate"] +1135 row_df["defense_passing_downs_ppa"] = team[ +1136 "defense"]["passingDowns"]["ppa"] +1137 row_df["defense_passing_downs_success_rate"] = team["defense"][ +1138 "passingDowns" +1139 ]["successRate"] +1140 row_df["defense_passing_downs_explosiveness"] = team["defense"][ +1141 "passingDowns" +1142 ]["explosiveness"] +1143 +1144 row_df["defense_rushing_plays_rate"] = team[ +1145 "defense"]["rushingPlays"]["rate"] +1146 row_df["defense_rushing_plays_ppa"] = team[ +1147 "defense"]["rushingPlays"]["ppa"] +1148 row_df["defense_rushing_plays_total_ppa"] = team[ +1149 "defense"]["rushingPlays"]["totalPPA"] +1150 row_df["defense_rushing_plays_success_rate"] = team["defense"][ +1151 "rushingPlays" +1152 ]["successRate"] +1153 row_df["defense_rushing_plays_explosiveness"] = team["defense"][ +1154 "rushingPlays" +1155 ]["explosiveness"] +1156 +1157 row_df["defense_passing_plays_rate"] = team[ +1158 "defense"]["passingPlays"]["rate"] +1159 row_df["defense_passing_plays_ppa"] = team[ +1160 "defense"]["passingPlays"]["ppa"] +1161 row_df["defense_passing_plays_total_ppa"] = team[ +1162 "defense"]["passingPlays"]["totalPPA"] +1163 row_df["defense_passing_plays_success_rate"] = team["defense"][ +1164 "passingPlays" +1165 ]["successRate"] +1166 row_df["defense_passing_plays_explosiveness"] = team["defense"][ +1167 "rushingPlays" +1168 ]["explosiveness"] +1169 +1170 final_df = pd.concat([final_df, row_df], ignore_index=True) +1171 del row_df +1172 del t_season, t_conf, t_team 1173 -1174 final_df = pd.concat([final_df, row_df], ignore_index=True) -1175 del row_df -1176 del t_season, t_conf, t_team -1177 -1178 return final_df -1179 -1180 -1181def get_cfbd_advanced_team_game_stats( -1182 api_key: str = None, -1183 api_key_dir: str = None, -1184 season: int = None, -1185 team: str = None, -1186 # `year` and/or `team` need to be not null for this function to work. -1187 week: int = None, -1188 opponent: str = None, -1189 exclude_garbage_time: bool = False, -1190 season_type: str = "both", # "regular", "postseason", or "both" -1191 return_as_dict: bool = False, -1192): -1193 """ -1194 Allows you to get advanced CFB team game stats data from the CFBD API. -1195 -1196 Parameters -1197 ---------- -1198 -1199 `api_key` (str, optional): -1200 Semi-optional argument. -1201 If `api_key` is null, this function will attempt to load a CFBD API key -1202 from the python environment, or from a file on this computer. -1203 If `api_key` is not null, -1204 this function will automatically assume that the -1205 inputted `api_key` is a valid CFBD API key. -1206 -1207 `api_key_dir` (str, optional): -1208 Optional argument. -1209 If `api_key` is set to am empty string, this variable is ignored. -1210 If `api_key_dir` is null, and `api_key` is null, -1211 this function will try to find -1212 a CFBD API key file in this user's home directory. -1213 If `api_key_dir` is set to a string, and `api_key` is null, -1214 this function will assume that `api_key_dir` is a directory, -1215 and will try to find a CFBD API key file in that directory. -1216 -1217 `season` (int, semi-mandatory): -1218 Semi-required argument. -1219 Specifies the season you want CFB team game stats data from. -1220 This must be specified, otherwise this package, and by extension -1221 the CFBD API, will not accept the request -1222 to get CFB team season stats data. -1223 This or `team` must be set -1224 to a valid non-null variable for this to function. -1225 -1226 `team` (str, semi-mandatory): -1227 Semi-required argument. -1228 Specifies the season you want advanced CFB team game stats data from. -1229 This must be specified, otherwise this package, and by extension -1230 the CFBD API, will not accept -1231 the request to get CFB team season stats data. -1232 This or `season` must be set -1233 to a valid non-null variable for this to function. -1234 -1235 `week` (int, optional): -1236 Optional argument. -1237 If `week` is set to an integer, this function will attempt -1238 to load CFB team game from games in that season, and that week. -1239 -1240 `opponent` (str, optional): -1241 Optional argument. -1242 If you only want games from a specific opponent, -1243 set `opponent` to the name of that team. -1244 -1245 -1246 `exclude_garbage_time` (bool, optional): -1247 Optional argument. -1248 If you want to filter out plays where -1249 the result of the game is largely decided, -1250 set `exclude_garbage_time = True`. -1251 Default behavior is that this variable is set to -1252 `False` when this function is called. -1253 -1254 `season_type` (str, semi-optional): -1255 Semi-optional argument. -1256 By default, this will be set to "regular", for the CFB regular season. -1257 If you want CFB team game stats, set `season_type` to "postseason". -1258 If `season_type` is set to anything but "regular" or "postseason", -1259 a `ValueError()` will be raised. -1260 -1261 `return_as_dict` (bool, semi-optional): -1262 Semi-optional argument. -1263 If you want this function to return -1264 the data as a dictionary (read: JSON object), -1265 instead of a pandas `DataFrame` object, -1266 set `return_as_dict` to `True`. -1267 -1268 -1269 Usage -1270 ---------- -1271 ``` -1272 import time -1273 -1274 from cfbd_json_py.stats import get_cfbd_advanced_team_game_stats -1275 -1276 -1277 cfbd_key = "tigersAreAwesome" # placeholder for your CFBD API Key. -1278 -1279 if cfbd_key != "tigersAreAwesome": -1280 print( -1281 "Using the user's API key declared in this script " + -1282 "for this example." -1283 ) -1284 -1285 # Get advanced CFBD team game stats for week 10 of the 2020 CFB season. -1286 print("Get advanced CFBD team game stats for the 2020 CFB season.") -1287 json_data = get_cfbd_advanced_team_game_stats( -1288 api_key=cfbd_key, -1289 season=2020, -1290 week=10 -1291 ) -1292 print(json_data) -1293 time.sleep(5) -1294 -1295 # Get advanced CFBD team game stats for week 10 of the 2020 CFB season, -1296 # but exclude plays that happen in garbage time. -1297 print("Get advanced CFBD team game stats for the 2020 CFB season.") -1298 json_data = get_cfbd_advanced_team_game_stats( -1299 api_key=cfbd_key, -1300 season=2020, -1301 week=10, -1302 exclude_garbage_time=True -1303 ) -1304 print(json_data) -1305 time.sleep(5) -1306 -1307 # Get advanced CFBD team game stats for the 2020 CFB season. -1308 print("Get advanced CFBD team game stats for the 2020 CFB season.") -1309 json_data = get_cfbd_advanced_team_game_stats( -1310 api_key=cfbd_key, -1311 season=2020 -1312 ) -1313 print(json_data) -1314 time.sleep(5) -1315 -1316 # Get advanced CFBD team game stats for -1317 # the University of Cincinnati Football Team in the 2020 CFB season. -1318 print( -1319 "Get advanced CFBD team game stats for " + -1320 "the University of Cincinnati Football Team " + -1321 "in the 2020 CFB season." -1322 ) -1323 json_data = get_cfbd_advanced_team_game_stats( -1324 api_key=cfbd_key, -1325 season=2020, -1326 opponent="Ohio" -1327 ) -1328 print(json_data) -1329 time.sleep(5) -1330 -1331 # Get advanced CFBD team game stats for teams that faced off -1332 # against the Ohio Bobcats Football Team in the 2020 CFB season. -1333 print( -1334 "Get advanced CFBD team game stats for teams that " + -1335 "faced off against the Ohio Bobcats Football Team " + -1336 "in the 2020 CFB season." -1337 ) -1338 json_data = get_cfbd_advanced_team_game_stats( -1339 api_key=cfbd_key, -1340 season=2020, -1341 opponent="Ohio" -1342 ) -1343 print(json_data) -1344 time.sleep(5) -1345 -1346 # Get advanced CFBD team game stats for just -1347 # postseason games in the 2020 CFB season. -1348 print( -1349 "Get advanced CFBD team game stats for just postseason games " + -1350 "in the 2020 CFB season." -1351 ) -1352 json_data = get_cfbd_advanced_team_game_stats( -1353 api_key=cfbd_key, -1354 season=2020, -1355 week=10 -1356 ) -1357 print(json_data) -1358 time.sleep(5) -1359 -1360 -1361 # You can also tell this function to just return the API call as -1362 # a Dictionary (read: JSON) object. -1363 print( -1364 "You can also tell this function to just return the API call " + -1365 "as a Dictionary (read: JSON) object." -1366 ) -1367 json_data = get_cfbd_advanced_team_game_stats( -1368 api_key=cfbd_key, -1369 season=2020, -1370 week=10, -1371 return_as_dict=True -1372 ) -1373 print(json_data) -1374 -1375 else: -1376 # Alternatively, if the CFBD API key exists in this python environment, -1377 # or it's been set by cfbd_json_py.utls.set_cfbd_api_token(), -1378 # you could just call these functions directly, -1379 # without setting the API key in the script. -1380 print( -1381 "Using the user's API key supposedly loaded " + -1382 "into this python environment for this example." -1383 ) -1384 -1385 # Get advanced CFBD team game stats for week 10 of the 2020 CFB season. -1386 print("Get advanced CFBD team game stats for the 2020 CFB season.") -1387 json_data = get_cfbd_advanced_team_game_stats( -1388 season=2020, -1389 week=10 -1390 ) -1391 print(json_data) -1392 time.sleep(5) -1393 -1394 # Get advanced CFBD team game stats for week 10 of the 2020 CFB season, -1395 # but exclude plays that happen in garbage time. -1396 print("Get advanced CFBD team game stats for the 2020 CFB season.") -1397 json_data = get_cfbd_advanced_team_game_stats( -1398 season=2020, -1399 week=10, -1400 exclude_garbage_time=True -1401 ) -1402 print(json_data) -1403 time.sleep(5) -1404 -1405 # Get advanced CFBD team game stats for the 2020 CFB season. -1406 print("Get advanced CFBD team game stats for the 2020 CFB season.") -1407 json_data = get_cfbd_advanced_team_game_stats( -1408 season=2020 -1409 ) -1410 print(json_data) -1411 time.sleep(5) -1412 -1413 # Get advanced CFBD team game stats for -1414 # the University of Cincinnati Football Team in the 2020 CFB season. -1415 print( -1416 "Get advanced CFBD team game stats for " + -1417 "the University of Cincinnati Football Team " + -1418 "in the 2020 CFB season." +1174 return final_df +1175 +1176 +1177def get_cfbd_advanced_team_game_stats( +1178 api_key: str = None, +1179 api_key_dir: str = None, +1180 season: int = None, +1181 team: str = None, +1182 # `year` and/or `team` need to be not null for this function to work. +1183 week: int = None, +1184 opponent: str = None, +1185 exclude_garbage_time: bool = False, +1186 season_type: str = "both", # "regular", "postseason", or "both" +1187 return_as_dict: bool = False, +1188): +1189 """ +1190 Allows you to get advanced CFB team game stats data from the CFBD API. +1191 +1192 Parameters +1193 ---------- +1194 +1195 `api_key` (str, optional): +1196 Semi-optional argument. +1197 If `api_key` is null, this function will attempt to load a CFBD API key +1198 from the python environment, or from a file on this computer. +1199 If `api_key` is not null, +1200 this function will automatically assume that the +1201 inputted `api_key` is a valid CFBD API key. +1202 +1203 `api_key_dir` (str, optional): +1204 Optional argument. +1205 If `api_key` is set to am empty string, this variable is ignored. +1206 If `api_key_dir` is null, and `api_key` is null, +1207 this function will try to find +1208 a CFBD API key file in this user's home directory. +1209 If `api_key_dir` is set to a string, and `api_key` is null, +1210 this function will assume that `api_key_dir` is a directory, +1211 and will try to find a CFBD API key file in that directory. +1212 +1213 `season` (int, semi-mandatory): +1214 Semi-required argument. +1215 Specifies the season you want CFB team game stats data from. +1216 This must be specified, otherwise this package, and by extension +1217 the CFBD API, will not accept the request +1218 to get CFB team season stats data. +1219 This or `team` must be set +1220 to a valid non-null variable for this to function. +1221 +1222 `team` (str, semi-mandatory): +1223 Semi-required argument. +1224 Specifies the season you want advanced CFB team game stats data from. +1225 This must be specified, otherwise this package, and by extension +1226 the CFBD API, will not accept +1227 the request to get CFB team season stats data. +1228 This or `season` must be set +1229 to a valid non-null variable for this to function. +1230 +1231 `week` (int, optional): +1232 Optional argument. +1233 If `week` is set to an integer, this function will attempt +1234 to load CFB team game from games in that season, and that week. +1235 +1236 `opponent` (str, optional): +1237 Optional argument. +1238 If you only want games from a specific opponent, +1239 set `opponent` to the name of that team. +1240 +1241 +1242 `exclude_garbage_time` (bool, optional): +1243 Optional argument. +1244 If you want to filter out plays where +1245 the result of the game is largely decided, +1246 set `exclude_garbage_time = True`. +1247 Default behavior is that this variable is set to +1248 `False` when this function is called. +1249 +1250 `season_type` (str, semi-optional): +1251 Semi-optional argument. +1252 By default, this will be set to "regular", for the CFB regular season. +1253 If you want CFB team game stats, set `season_type` to "postseason". +1254 If `season_type` is set to anything but "regular" or "postseason", +1255 a `ValueError()` will be raised. +1256 +1257 `return_as_dict` (bool, semi-optional): +1258 Semi-optional argument. +1259 If you want this function to return +1260 the data as a dictionary (read: JSON object), +1261 instead of a pandas `DataFrame` object, +1262 set `return_as_dict` to `True`. +1263 +1264 +1265 Usage +1266 ---------- +1267 ``` +1268 import time +1269 +1270 from cfbd_json_py.stats import get_cfbd_advanced_team_game_stats +1271 +1272 +1273 cfbd_key = "tigersAreAwesome" # placeholder for your CFBD API Key. +1274 +1275 if cfbd_key != "tigersAreAwesome": +1276 print( +1277 "Using the user's API key declared in this script " + +1278 "for this example." +1279 ) +1280 +1281 # Get advanced CFBD team game stats for week 10 of the 2020 CFB season. +1282 print("Get advanced CFBD team game stats for the 2020 CFB season.") +1283 json_data = get_cfbd_advanced_team_game_stats( +1284 api_key=cfbd_key, +1285 season=2020, +1286 week=10 +1287 ) +1288 print(json_data) +1289 time.sleep(5) +1290 +1291 # Get advanced CFBD team game stats for week 10 of the 2020 CFB season, +1292 # but exclude plays that happen in garbage time. +1293 print("Get advanced CFBD team game stats for the 2020 CFB season.") +1294 json_data = get_cfbd_advanced_team_game_stats( +1295 api_key=cfbd_key, +1296 season=2020, +1297 week=10, +1298 exclude_garbage_time=True +1299 ) +1300 print(json_data) +1301 time.sleep(5) +1302 +1303 # Get advanced CFBD team game stats for the 2020 CFB season. +1304 print("Get advanced CFBD team game stats for the 2020 CFB season.") +1305 json_data = get_cfbd_advanced_team_game_stats( +1306 api_key=cfbd_key, +1307 season=2020 +1308 ) +1309 print(json_data) +1310 time.sleep(5) +1311 +1312 # Get advanced CFBD team game stats for +1313 # the University of Cincinnati Football Team in the 2020 CFB season. +1314 print( +1315 "Get advanced CFBD team game stats for " + +1316 "the University of Cincinnati Football Team " + +1317 "in the 2020 CFB season." +1318 ) +1319 json_data = get_cfbd_advanced_team_game_stats( +1320 api_key=cfbd_key, +1321 season=2020, +1322 opponent="Ohio" +1323 ) +1324 print(json_data) +1325 time.sleep(5) +1326 +1327 # Get advanced CFBD team game stats for teams that faced off +1328 # against the Ohio Bobcats Football Team in the 2020 CFB season. +1329 print( +1330 "Get advanced CFBD team game stats for teams that " + +1331 "faced off against the Ohio Bobcats Football Team " + +1332 "in the 2020 CFB season." +1333 ) +1334 json_data = get_cfbd_advanced_team_game_stats( +1335 api_key=cfbd_key, +1336 season=2020, +1337 opponent="Ohio" +1338 ) +1339 print(json_data) +1340 time.sleep(5) +1341 +1342 # Get advanced CFBD team game stats for just +1343 # postseason games in the 2020 CFB season. +1344 print( +1345 "Get advanced CFBD team game stats for just postseason games " + +1346 "in the 2020 CFB season." +1347 ) +1348 json_data = get_cfbd_advanced_team_game_stats( +1349 api_key=cfbd_key, +1350 season=2020, +1351 week=10 +1352 ) +1353 print(json_data) +1354 time.sleep(5) +1355 +1356 +1357 # You can also tell this function to just return the API call as +1358 # a Dictionary (read: JSON) object. +1359 print( +1360 "You can also tell this function to just return the API call " + +1361 "as a Dictionary (read: JSON) object." +1362 ) +1363 json_data = get_cfbd_advanced_team_game_stats( +1364 api_key=cfbd_key, +1365 season=2020, +1366 week=10, +1367 return_as_dict=True +1368 ) +1369 print(json_data) +1370 +1371 else: +1372 # Alternatively, if the CFBD API key exists in this python environment, +1373 # or it's been set by cfbd_json_py.utls.set_cfbd_api_token(), +1374 # you could just call these functions directly, +1375 # without setting the API key in the script. +1376 print( +1377 "Using the user's API key supposedly loaded " + +1378 "into this python environment for this example." +1379 ) +1380 +1381 # Get advanced CFBD team game stats for week 10 of the 2020 CFB season. +1382 print("Get advanced CFBD team game stats for the 2020 CFB season.") +1383 json_data = get_cfbd_advanced_team_game_stats( +1384 season=2020, +1385 week=10 +1386 ) +1387 print(json_data) +1388 time.sleep(5) +1389 +1390 # Get advanced CFBD team game stats for week 10 of the 2020 CFB season, +1391 # but exclude plays that happen in garbage time. +1392 print("Get advanced CFBD team game stats for the 2020 CFB season.") +1393 json_data = get_cfbd_advanced_team_game_stats( +1394 season=2020, +1395 week=10, +1396 exclude_garbage_time=True +1397 ) +1398 print(json_data) +1399 time.sleep(5) +1400 +1401 # Get advanced CFBD team game stats for the 2020 CFB season. +1402 print("Get advanced CFBD team game stats for the 2020 CFB season.") +1403 json_data = get_cfbd_advanced_team_game_stats( +1404 season=2020 +1405 ) +1406 print(json_data) +1407 time.sleep(5) +1408 +1409 # Get advanced CFBD team game stats for +1410 # the University of Cincinnati Football Team in the 2020 CFB season. +1411 print( +1412 "Get advanced CFBD team game stats for " + +1413 "the University of Cincinnati Football Team " + +1414 "in the 2020 CFB season." +1415 ) +1416 json_data = get_cfbd_advanced_team_game_stats( +1417 season=2020, +1418 opponent="Ohio" 1419 ) -1420 json_data = get_cfbd_advanced_team_game_stats( -1421 season=2020, -1422 opponent="Ohio" -1423 ) -1424 print(json_data) -1425 time.sleep(5) -1426 -1427 # Get advanced CFBD team game stats for teams that faced off -1428 # against the Ohio Bobcats Football Team in the 2020 CFB season. -1429 print( -1430 "Get advanced CFBD team game stats for teams that " + -1431 "faced off against the Ohio Bobcats Football Team " + -1432 "in the 2020 CFB season." +1420 print(json_data) +1421 time.sleep(5) +1422 +1423 # Get advanced CFBD team game stats for teams that faced off +1424 # against the Ohio Bobcats Football Team in the 2020 CFB season. +1425 print( +1426 "Get advanced CFBD team game stats for teams that " + +1427 "faced off against the Ohio Bobcats Football Team " + +1428 "in the 2020 CFB season." +1429 ) +1430 json_data = get_cfbd_advanced_team_game_stats( +1431 season=2020, +1432 opponent="Ohio" 1433 ) -1434 json_data = get_cfbd_advanced_team_game_stats( -1435 season=2020, -1436 opponent="Ohio" -1437 ) -1438 print(json_data) -1439 time.sleep(5) -1440 -1441 # Get advanced CFBD team game stats for just -1442 # postseason games in the 2020 CFB season. -1443 print( -1444 "Get advanced CFBD team game stats for just postseason games " + -1445 "in the 2020 CFB season." +1434 print(json_data) +1435 time.sleep(5) +1436 +1437 # Get advanced CFBD team game stats for just +1438 # postseason games in the 2020 CFB season. +1439 print( +1440 "Get advanced CFBD team game stats for just postseason games " + +1441 "in the 2020 CFB season." +1442 ) +1443 json_data = get_cfbd_advanced_team_game_stats( +1444 season=2020, +1445 week=10 1446 ) -1447 json_data = get_cfbd_advanced_team_game_stats( -1448 season=2020, -1449 week=10 -1450 ) -1451 print(json_data) -1452 time.sleep(5) -1453 -1454 -1455 # You can also tell this function to just return the API call as -1456 # a Dictionary (read: JSON) object. -1457 print( -1458 "You can also tell this function to just return the API call " + -1459 "as a Dictionary (read: JSON) object." -1460 ) -1461 json_data = get_cfbd_advanced_team_game_stats( -1462 season=2020, -1463 week=10, -1464 return_as_dict=True -1465 ) -1466 print(json_data) -1467 -1468 ``` -1469 Returns -1470 ---------- -1471 A pandas `DataFrame` object with advanced team season stats data, -1472 or (if `return_as_dict` is set to `True`) -1473 a dictionary object with a with advanced team season stats data. -1474 """ -1475 now = datetime.now() -1476 url = "https://api.collegefootballdata.com/stats/game/advanced" -1477 row_df = pd.DataFrame() -1478 final_df = pd.DataFrame() -1479 -1480 if api_key is not None: -1481 real_api_key = api_key -1482 del api_key -1483 else: -1484 real_api_key = get_cfbd_api_token(api_key_dir=api_key_dir) -1485 -1486 if real_api_key == "tigersAreAwesome": -1487 raise ValueError( -1488 "You actually need to change `cfbd_key` to your CFBD API key." -1489 ) -1490 elif "Bearer " in real_api_key: -1491 pass -1492 elif "Bearer" in real_api_key: -1493 real_api_key = real_api_key.replace("Bearer", "Bearer ") -1494 else: -1495 real_api_key = "Bearer " + real_api_key -1496 -1497 if season is not None and (season > (now.year + 1)): -1498 raise ValueError(f"`season` cannot be greater than {season}.") -1499 elif season is not None and season < 1869: -1500 raise ValueError("`season` cannot be less than 1869.") -1501 -1502 if season_type == "regular" or season_type == "postseason" \ -1503 or season_type == "both": -1504 pass -1505 else: -1506 raise ValueError( -1507 '`season_type` must be set to either ' + -1508 '"regular","postseason", or "both".' -1509 ) -1510 -1511 gt_str = "" -1512 -1513 # URL builder -1514 ########################################################################## -1515 -1516 if exclude_garbage_time is True: -1517 gt_str = "true" -1518 elif exclude_garbage_time is False: -1519 gt_str = "false" -1520 -1521 if season is not None and team is not None: -1522 url += f"?year={season}&team={team}" -1523 elif season is not None: -1524 url += f"?year={season}" -1525 elif team is not None: -1526 url += f"?team={team}" -1527 -1528 if exclude_garbage_time is not None: -1529 url += f"&excludeGarbageTime={gt_str}" -1530 -1531 if week is not None: -1532 url += f"&week={week}" -1533 -1534 if opponent is not None: -1535 url += f"&opponent={opponent}" -1536 -1537 headers = { -1538 "Authorization": f"{real_api_key}", -1539 "accept": "application/json" -1540 } -1541 -1542 response = requests.get(url, headers=headers) -1543 -1544 if response.status_code == 200: -1545 pass -1546 elif response.status_code == 401: -1547 raise ConnectionRefusedError( -1548 "Could not connect. The connection was refused." + -1549 "\nHTTP Status Code 401." +1447 print(json_data) +1448 time.sleep(5) +1449 +1450 +1451 # You can also tell this function to just return the API call as +1452 # a Dictionary (read: JSON) object. +1453 print( +1454 "You can also tell this function to just return the API call " + +1455 "as a Dictionary (read: JSON) object." +1456 ) +1457 json_data = get_cfbd_advanced_team_game_stats( +1458 season=2020, +1459 week=10, +1460 return_as_dict=True +1461 ) +1462 print(json_data) +1463 +1464 ``` +1465 Returns +1466 ---------- +1467 A pandas `DataFrame` object with advanced team season stats data, +1468 or (if `return_as_dict` is set to `True`) +1469 a dictionary object with a with advanced team season stats data. +1470 """ +1471 now = datetime.now() +1472 url = "https://api.collegefootballdata.com/stats/game/advanced" +1473 row_df = pd.DataFrame() +1474 final_df = pd.DataFrame() +1475 +1476 if api_key is not None: +1477 real_api_key = api_key +1478 del api_key +1479 else: +1480 real_api_key = get_cfbd_api_token(api_key_dir=api_key_dir) +1481 +1482 if real_api_key == "tigersAreAwesome": +1483 raise ValueError( +1484 "You actually need to change `cfbd_key` to your CFBD API key." +1485 ) +1486 elif "Bearer " in real_api_key: +1487 pass +1488 elif "Bearer" in real_api_key: +1489 real_api_key = real_api_key.replace("Bearer", "Bearer ") +1490 else: +1491 real_api_key = "Bearer " + real_api_key +1492 +1493 if season is not None and (season > (now.year + 1)): +1494 raise ValueError(f"`season` cannot be greater than {season}.") +1495 elif season is not None and season < 1869: +1496 raise ValueError("`season` cannot be less than 1869.") +1497 +1498 if season_type == "regular" or season_type == "postseason" \ +1499 or season_type == "both": +1500 pass +1501 else: +1502 raise ValueError( +1503 '`season_type` must be set to either ' + +1504 '"regular","postseason", or "both".' +1505 ) +1506 +1507 gt_str = "" +1508 +1509 # URL builder +1510 ########################################################################## +1511 +1512 if exclude_garbage_time is True: +1513 gt_str = "true" +1514 elif exclude_garbage_time is False: +1515 gt_str = "false" +1516 +1517 if season is not None and team is not None: +1518 url += f"?year={season}&team={team}" +1519 elif season is not None: +1520 url += f"?year={season}" +1521 elif team is not None: +1522 url += f"?team={team}" +1523 +1524 if exclude_garbage_time is not None: +1525 url += f"&excludeGarbageTime={gt_str}" +1526 +1527 if week is not None: +1528 url += f"&week={week}" +1529 +1530 if opponent is not None: +1531 url += f"&opponent={opponent}" +1532 +1533 headers = { +1534 "Authorization": f"{real_api_key}", +1535 "accept": "application/json" +1536 } +1537 +1538 response = requests.get(url, headers=headers) +1539 +1540 if response.status_code == 200: +1541 pass +1542 elif response.status_code == 401: +1543 raise ConnectionRefusedError( +1544 "Could not connect. The connection was refused." + +1545 "\nHTTP Status Code 401." +1546 ) +1547 else: +1548 raise ConnectionError( +1549 f"Could not connect.\nHTTP Status code {response.status_code}" 1550 ) -1551 else: -1552 raise ConnectionError( -1553 f"Could not connect.\nHTTP Status code {response.status_code}" -1554 ) -1555 -1556 json_data = response.json() -1557 -1558 if return_as_dict is True: -1559 return json_data -1560 -1561 for team in tqdm(json_data): -1562 t_game_id = team["gameId"] -1563 t_week = team["week"] -1564 t_team = team["team"] -1565 t_opponent = team["opponent"] -1566 -1567 if season is not None: -1568 row_df = pd.DataFrame( -1569 { -1570 "season": season, -1571 "game_id": t_game_id, -1572 "week": t_week, -1573 "team_name": t_team, -1574 "opponent_name": t_opponent, -1575 }, -1576 index=[0], -1577 ) -1578 else: -1579 -1580 row_df = pd.DataFrame( -1581 { -1582 "game_id": t_game_id, -1583 "week": t_week, -1584 "team_name": t_team, -1585 "opponent_name": t_opponent, -1586 }, -1587 index=[0], -1588 ) -1589 -1590 # offense -1591 if "offense" not in team: -1592 logging.debug( -1593 "Key `[offense]` not found for " + -1594 f"Game ID #{t_game_id} and {t_team}, " -1595 + f"which happened in week {t_week}." -1596 ) -1597 else: -1598 row_df["offense_plays"] = team["offense"]["plays"] -1599 row_df["offense_drives"] = team["offense"]["drives"] -1600 row_df["offense_ppa"] = team["offense"]["ppa"] -1601 row_df["offense_total_ppa"] = team["offense"]["totalPPA"] -1602 row_df["offense_success_rate"] = team["offense"]["successRate"] -1603 row_df["offense_explosiveness"] = team["offense"]["explosiveness"] -1604 row_df["offense_power_success"] = team["offense"]["powerSuccess"] -1605 row_df["offense_stuff_rate"] = team["offense"]["stuffRate"] -1606 row_df["offense_line_yards_avg"] = team["offense"]["lineYards"] -1607 row_df["offense_line_yards_total"] = team["offense"][ -1608 "lineYardsTotal" -1609 ] -1610 row_df["offense_second_level_yards_avg"] = team["offense"][ -1611 "secondLevelYards" -1612 ] -1613 row_df["offense_second_level_yards_total"] = team["offense"][ -1614 "secondLevelYardsTotal" -1615 ] -1616 row_df["offense_open_field_yards_avg"] = team["offense"][ -1617 "openFieldYards" -1618 ] -1619 row_df["offense_open_field_yards_total"] = team["offense"][ -1620 "secondLevelYardsTotal" -1621 ] -1622 -1623 row_df["offense_standard_downs_ppa"] = team[ -1624 "offense"]["standardDowns"]["ppa"] -1625 row_df["offense_standard_downs_success_rate"] = team[ -1626 "offense"]["standardDowns"]["successRate"] -1627 row_df["offense_standard_downs_explosiveness"] = team["offense"][ -1628 "standardDowns" -1629 ]["explosiveness"] -1630 -1631 row_df["offense_passing_downs_ppa"] = team[ -1632 "offense"]["passingDowns"]["ppa"] -1633 row_df["offense_passing_downs_success_rate"] = team[ -1634 "offense"]["passingDowns"]["successRate"] -1635 row_df["offense_passing_downs_explosiveness"] = team["offense"][ -1636 "passingDowns" -1637 ]["explosiveness"] -1638 -1639 row_df["offense_rushing_plays_ppa"] = team[ -1640 "offense"]["rushingPlays"]["ppa"] -1641 row_df["offense_rushing_plays_total_ppa"] = team[ -1642 "offense"]["rushingPlays"]["totalPPA"] -1643 row_df["offense_rushing_plays_success_rate"] = team[ -1644 "offense"]["rushingPlays"]["successRate"] -1645 row_df["offense_rushing_plays_explosiveness"] = team[ -1646 "offense"]["rushingPlays"]["explosiveness"] -1647 -1648 row_df["offense_passing_plays_ppa"] = team[ -1649 "offense"]["passingPlays"]["ppa"] -1650 row_df["offense_passing_plays_total_ppa"] = team[ -1651 "offense"]["passingPlays"]["totalPPA"] -1652 row_df["offense_passing_plays_success_rate"] = team[ -1653 "offense"]["passingPlays"]["successRate"] -1654 row_df["offense_passing_plays_explosiveness"] = team[ -1655 "offense"]["rushingPlays"]["explosiveness"] -1656 -1657 # defense -1658 if "defense" not in team: -1659 logging.debug( -1660 "Key `[defense]` not found for " + -1661 f"Game ID #{t_game_id} and {t_team}, " -1662 + f"which happened in week {t_week}." -1663 ) -1664 else: -1665 row_df["defense_plays"] = team["defense"]["plays"] -1666 row_df["defense_drives"] = team["defense"]["drives"] -1667 row_df["defense_ppa"] = team["defense"]["ppa"] -1668 row_df["defense_total_ppa"] = team["defense"]["totalPPA"] -1669 row_df["defense_success_rate"] = team["defense"]["successRate"] -1670 row_df["defense_explosiveness"] = team["defense"]["explosiveness"] -1671 row_df["defense_power_success"] = team["defense"]["powerSuccess"] -1672 row_df["defense_stuff_rate"] = team["defense"]["stuffRate"] -1673 row_df["defense_line_yards_avg"] = team["defense"]["lineYards"] -1674 row_df["defense_line_yards_total"] = team["defense"][ -1675 "lineYardsTotal" -1676 ] -1677 row_df["defense_second_level_yards_avg"] = team["defense"][ -1678 "secondLevelYards" -1679 ] -1680 row_df["defense_second_level_yards_total"] = team["defense"][ -1681 "secondLevelYardsTotal" -1682 ] -1683 row_df["defense_open_field_yards_avg"] = team["defense"][ -1684 "openFieldYards" -1685 ] -1686 row_df["defense_open_field_yards_total"] = team["defense"][ -1687 "secondLevelYardsTotal" -1688 ] -1689 row_df["defense_total_opportunities"] = team["defense"][ -1690 "totalOpportunies" -1691 ] -1692 row_df["defense_points_per_opportunity"] = team["defense"][ -1693 "pointsPerOpportunity" -1694 ] -1695 -1696 row_df["defense_standard_downs_ppa"] = team[ -1697 "defense"]["standardDowns"]["ppa"] -1698 row_df["defense_standard_downs_success_rate"] = team["defense"][ -1699 "standardDowns" -1700 ]["successRate"] -1701 row_df["defense_standard_downs_explosiveness"] = team["defense"][ -1702 "standardDowns" -1703 ]["explosiveness"] -1704 -1705 row_df["defense_passing_downs_ppa"] = team[ -1706 "defense"]["passingDowns"]["ppa"] -1707 row_df["defense_passing_downs_success_rate"] = team["defense"][ -1708 "passingDowns" -1709 ]["successRate"] -1710 row_df["defense_passing_downs_explosiveness"] = team["defense"][ -1711 "passingDowns" -1712 ]["explosiveness"] -1713 -1714 row_df["defense_rushing_plays_ppa"] = team[ -1715 "defense"]["rushingPlays"]["ppa"] -1716 row_df["defense_rushing_plays_total_ppa"] = team[ -1717 "defense"]["rushingPlays"]["totalPPA"] -1718 row_df["defense_rushing_plays_success_rate"] = team["defense"][ -1719 "rushingPlays" -1720 ]["successRate"] -1721 row_df["defense_rushing_plays_explosiveness"] = team["defense"][ -1722 "rushingPlays" -1723 ]["explosiveness"] -1724 -1725 row_df["defense_passing_plays_ppa"] = team[ -1726 "defense"]["passingPlays"]["ppa"] -1727 row_df["defense_passing_plays_total_ppa"] = team[ -1728 "defense"]["passingPlays"]["totalPPA"] -1729 row_df["defense_passing_plays_success_rate"] = team["defense"][ -1730 "passingPlays" -1731 ]["successRate"] -1732 row_df["defense_passing_plays_explosiveness"] = team["defense"][ -1733 "rushingPlays" -1734 ]["explosiveness"] +1551 +1552 json_data = response.json() +1553 +1554 if return_as_dict is True: +1555 return json_data +1556 +1557 for team in tqdm(json_data): +1558 t_game_id = team["gameId"] +1559 t_week = team["week"] +1560 t_team = team["team"] +1561 t_opponent = team["opponent"] +1562 +1563 if season is not None: +1564 row_df = pd.DataFrame( +1565 { +1566 "season": season, +1567 "game_id": t_game_id, +1568 "week": t_week, +1569 "team_name": t_team, +1570 "opponent_name": t_opponent, +1571 }, +1572 index=[0], +1573 ) +1574 else: +1575 +1576 row_df = pd.DataFrame( +1577 { +1578 "game_id": t_game_id, +1579 "week": t_week, +1580 "team_name": t_team, +1581 "opponent_name": t_opponent, +1582 }, +1583 index=[0], +1584 ) +1585 +1586 # offense +1587 if "offense" not in team: +1588 logging.debug( +1589 "Key `[offense]` not found for " + +1590 f"Game ID #{t_game_id} and {t_team}, " +1591 + f"which happened in week {t_week}." +1592 ) +1593 else: +1594 row_df["offense_plays"] = team["offense"]["plays"] +1595 row_df["offense_drives"] = team["offense"]["drives"] +1596 row_df["offense_ppa"] = team["offense"]["ppa"] +1597 row_df["offense_total_ppa"] = team["offense"]["totalPPA"] +1598 row_df["offense_success_rate"] = team["offense"]["successRate"] +1599 row_df["offense_explosiveness"] = team["offense"]["explosiveness"] +1600 row_df["offense_power_success"] = team["offense"]["powerSuccess"] +1601 row_df["offense_stuff_rate"] = team["offense"]["stuffRate"] +1602 row_df["offense_line_yards_avg"] = team["offense"]["lineYards"] +1603 row_df["offense_line_yards_total"] = team["offense"][ +1604 "lineYardsTotal" +1605 ] +1606 row_df["offense_second_level_yards_avg"] = team["offense"][ +1607 "secondLevelYards" +1608 ] +1609 row_df["offense_second_level_yards_total"] = team["offense"][ +1610 "secondLevelYardsTotal" +1611 ] +1612 row_df["offense_open_field_yards_avg"] = team["offense"][ +1613 "openFieldYards" +1614 ] +1615 row_df["offense_open_field_yards_total"] = team["offense"][ +1616 "secondLevelYardsTotal" +1617 ] +1618 +1619 row_df["offense_standard_downs_ppa"] = team[ +1620 "offense"]["standardDowns"]["ppa"] +1621 row_df["offense_standard_downs_success_rate"] = team[ +1622 "offense"]["standardDowns"]["successRate"] +1623 row_df["offense_standard_downs_explosiveness"] = team["offense"][ +1624 "standardDowns" +1625 ]["explosiveness"] +1626 +1627 row_df["offense_passing_downs_ppa"] = team[ +1628 "offense"]["passingDowns"]["ppa"] +1629 row_df["offense_passing_downs_success_rate"] = team[ +1630 "offense"]["passingDowns"]["successRate"] +1631 row_df["offense_passing_downs_explosiveness"] = team["offense"][ +1632 "passingDowns" +1633 ]["explosiveness"] +1634 +1635 row_df["offense_rushing_plays_ppa"] = team[ +1636 "offense"]["rushingPlays"]["ppa"] +1637 row_df["offense_rushing_plays_total_ppa"] = team[ +1638 "offense"]["rushingPlays"]["totalPPA"] +1639 row_df["offense_rushing_plays_success_rate"] = team[ +1640 "offense"]["rushingPlays"]["successRate"] +1641 row_df["offense_rushing_plays_explosiveness"] = team[ +1642 "offense"]["rushingPlays"]["explosiveness"] +1643 +1644 row_df["offense_passing_plays_ppa"] = team[ +1645 "offense"]["passingPlays"]["ppa"] +1646 row_df["offense_passing_plays_total_ppa"] = team[ +1647 "offense"]["passingPlays"]["totalPPA"] +1648 row_df["offense_passing_plays_success_rate"] = team[ +1649 "offense"]["passingPlays"]["successRate"] +1650 row_df["offense_passing_plays_explosiveness"] = team[ +1651 "offense"]["rushingPlays"]["explosiveness"] +1652 +1653 # defense +1654 if "defense" not in team: +1655 logging.debug( +1656 "Key `[defense]` not found for " + +1657 f"Game ID #{t_game_id} and {t_team}, " +1658 + f"which happened in week {t_week}." +1659 ) +1660 else: +1661 row_df["defense_plays"] = team["defense"]["plays"] +1662 row_df["defense_drives"] = team["defense"]["drives"] +1663 row_df["defense_ppa"] = team["defense"]["ppa"] +1664 row_df["defense_total_ppa"] = team["defense"]["totalPPA"] +1665 row_df["defense_success_rate"] = team["defense"]["successRate"] +1666 row_df["defense_explosiveness"] = team["defense"]["explosiveness"] +1667 row_df["defense_power_success"] = team["defense"]["powerSuccess"] +1668 row_df["defense_stuff_rate"] = team["defense"]["stuffRate"] +1669 row_df["defense_line_yards_avg"] = team["defense"]["lineYards"] +1670 row_df["defense_line_yards_total"] = team["defense"][ +1671 "lineYardsTotal" +1672 ] +1673 row_df["defense_second_level_yards_avg"] = team["defense"][ +1674 "secondLevelYards" +1675 ] +1676 row_df["defense_second_level_yards_total"] = team["defense"][ +1677 "secondLevelYardsTotal" +1678 ] +1679 row_df["defense_open_field_yards_avg"] = team["defense"][ +1680 "openFieldYards" +1681 ] +1682 row_df["defense_open_field_yards_total"] = team["defense"][ +1683 "secondLevelYardsTotal" +1684 ] +1685 row_df["defense_total_opportunities"] = team["defense"][ +1686 "totalOpportunies" +1687 ] +1688 row_df["defense_points_per_opportunity"] = team["defense"][ +1689 "pointsPerOpportunity" +1690 ] +1691 +1692 row_df["defense_standard_downs_ppa"] = team[ +1693 "defense"]["standardDowns"]["ppa"] +1694 row_df["defense_standard_downs_success_rate"] = team["defense"][ +1695 "standardDowns" +1696 ]["successRate"] +1697 row_df["defense_standard_downs_explosiveness"] = team["defense"][ +1698 "standardDowns" +1699 ]["explosiveness"] +1700 +1701 row_df["defense_passing_downs_ppa"] = team[ +1702 "defense"]["passingDowns"]["ppa"] +1703 row_df["defense_passing_downs_success_rate"] = team["defense"][ +1704 "passingDowns" +1705 ]["successRate"] +1706 row_df["defense_passing_downs_explosiveness"] = team["defense"][ +1707 "passingDowns" +1708 ]["explosiveness"] +1709 +1710 row_df["defense_rushing_plays_ppa"] = team[ +1711 "defense"]["rushingPlays"]["ppa"] +1712 row_df["defense_rushing_plays_total_ppa"] = team[ +1713 "defense"]["rushingPlays"]["totalPPA"] +1714 row_df["defense_rushing_plays_success_rate"] = team["defense"][ +1715 "rushingPlays" +1716 ]["successRate"] +1717 row_df["defense_rushing_plays_explosiveness"] = team["defense"][ +1718 "rushingPlays" +1719 ]["explosiveness"] +1720 +1721 row_df["defense_passing_plays_ppa"] = team[ +1722 "defense"]["passingPlays"]["ppa"] +1723 row_df["defense_passing_plays_total_ppa"] = team[ +1724 "defense"]["passingPlays"]["totalPPA"] +1725 row_df["defense_passing_plays_success_rate"] = team["defense"][ +1726 "passingPlays" +1727 ]["successRate"] +1728 row_df["defense_passing_plays_explosiveness"] = team["defense"][ +1729 "rushingPlays" +1730 ]["explosiveness"] +1731 +1732 final_df = pd.concat([final_df, row_df], ignore_index=True) +1733 del row_df +1734 del t_game_id, t_week, t_team, t_opponent 1735 -1736 final_df = pd.concat([final_df, row_df], ignore_index=True) -1737 del row_df -1738 del t_game_id, t_week, t_team, t_opponent -1739 -1740 return final_df -1741 -1742 -1743def get_cfbd_team_stat_categories( -1744 api_key: str = None, api_key_dir: str = None, return_as_dict: bool = False -1745): -1746 """ -1747 Returns a list of stat categories -1748 for team stats directly from the CFBD API. -1749 -1750 Parameters -1751 ---------- -1752 -1753 `api_key` (str, optional): -1754 Semi-optional argument. -1755 If `api_key` is null, this function will attempt to load a CFBD API key -1756 from the python environment, or from a file on this computer. -1757 If `api_key` is not null, -1758 this function will automatically assume that the -1759 inputted `api_key` is a valid CFBD API key. -1760 -1761 `api_key_dir` (str, optional): -1762 Optional argument. -1763 If `api_key` is set to am empty string, this variable is ignored. -1764 If `api_key_dir` is null, and `api_key` is null, -1765 this function will try to find -1766 a CFBD API key file in this user's home directory. -1767 If `api_key_dir` is set to a string, and `api_key` is null, -1768 this function will assume that `api_key_dir` is a directory, -1769 and will try to find a CFBD API key file in that directory. -1770 -1771 `return_as_dict` (bool, semi-optional): -1772 Semi-optional argument. -1773 If you want this function to return the data -1774 as a dictionary (read: JSON object), -1775 instead of a pandas `DataFrame` object, -1776 set `return_as_dict` to `True`. -1777 -1778 Usage -1779 ---------- -1780 ``` -1781 import time -1782 -1783 from cfbd_json_py.stats import get_cfbd_team_stat_categories -1784 -1785 -1786 cfbd_key = "tigersAreAwesome" # placeholder for your CFBD API Key. -1787 -1788 if cfbd_key != "tigersAreAwesome": -1789 print( -1790 "Using the user's API key declared in this script " + -1791 "for this example." -1792 ) -1793 -1794 # Get a list of CFBD stat categories for team stats. -1795 print("Get a list of CFBD stat categories for team stats.") -1796 json_data = get_cfbd_team_stat_categories( -1797 api_key=cfbd_key -1798 ) -1799 print(json_data) -1800 time.sleep(5) -1801 -1802 # You can also tell this function to just return the API call as -1803 # a Dictionary (read: JSON) object. -1804 print( -1805 "You can also tell this function to just return the API call " + -1806 "as a Dictionary (read: JSON) object." +1736 return final_df +1737 +1738 +1739def get_cfbd_team_stat_categories( +1740 api_key: str = None, api_key_dir: str = None, return_as_dict: bool = False +1741): +1742 """ +1743 Returns a list of stat categories +1744 for team stats directly from the CFBD API. +1745 +1746 Parameters +1747 ---------- +1748 +1749 `api_key` (str, optional): +1750 Semi-optional argument. +1751 If `api_key` is null, this function will attempt to load a CFBD API key +1752 from the python environment, or from a file on this computer. +1753 If `api_key` is not null, +1754 this function will automatically assume that the +1755 inputted `api_key` is a valid CFBD API key. +1756 +1757 `api_key_dir` (str, optional): +1758 Optional argument. +1759 If `api_key` is set to am empty string, this variable is ignored. +1760 If `api_key_dir` is null, and `api_key` is null, +1761 this function will try to find +1762 a CFBD API key file in this user's home directory. +1763 If `api_key_dir` is set to a string, and `api_key` is null, +1764 this function will assume that `api_key_dir` is a directory, +1765 and will try to find a CFBD API key file in that directory. +1766 +1767 `return_as_dict` (bool, semi-optional): +1768 Semi-optional argument. +1769 If you want this function to return the data +1770 as a dictionary (read: JSON object), +1771 instead of a pandas `DataFrame` object, +1772 set `return_as_dict` to `True`. +1773 +1774 Usage +1775 ---------- +1776 ``` +1777 import time +1778 +1779 from cfbd_json_py.stats import get_cfbd_team_stat_categories +1780 +1781 +1782 cfbd_key = "tigersAreAwesome" # placeholder for your CFBD API Key. +1783 +1784 if cfbd_key != "tigersAreAwesome": +1785 print( +1786 "Using the user's API key declared in this script " + +1787 "for this example." +1788 ) +1789 +1790 # Get a list of CFBD stat categories for team stats. +1791 print("Get a list of CFBD stat categories for team stats.") +1792 json_data = get_cfbd_team_stat_categories( +1793 api_key=cfbd_key +1794 ) +1795 print(json_data) +1796 time.sleep(5) +1797 +1798 # You can also tell this function to just return the API call as +1799 # a Dictionary (read: JSON) object. +1800 print( +1801 "You can also tell this function to just return the API call " + +1802 "as a Dictionary (read: JSON) object." +1803 ) +1804 json_data = get_cfbd_team_stat_categories( +1805 api_key=cfbd_key, +1806 return_as_dict=True 1807 ) -1808 json_data = get_cfbd_team_stat_categories( -1809 api_key=cfbd_key, -1810 return_as_dict=True -1811 ) -1812 print(json_data) -1813 -1814 else: -1815 # Alternatively, if the CFBD API key exists in this python environment, -1816 # or it's been set by cfbd_json_py.utls.set_cfbd_api_token(), -1817 # you could just call these functions directly, -1818 # without setting the API key in the script. -1819 print( -1820 "Using the user's API key supposedly loaded " + -1821 "into this python environment for this example." -1822 ) -1823 -1824 # Get a list of CFBD stat categories for team stats. -1825 print("Get a list of CFBD stat categories for team stats.") -1826 json_data = get_cfbd_team_stat_categories() -1827 print(json_data) -1828 time.sleep(5) -1829 -1830 # You can also tell this function to just return the API call as -1831 # a Dictionary (read: JSON) object. -1832 print( -1833 "You can also tell this function to just return the API call " + -1834 "as a Dictionary (read: JSON) object." -1835 ) -1836 json_data = get_cfbd_team_stat_categories( -1837 return_as_dict=True -1838 ) -1839 print(json_data) -1840 -1841 ``` -1842 Returns -1843 ---------- -1844 A pandas `DataFrame` object with CFBD stat categories, -1845 or (if `return_as_dict` is set to `True`) -1846 a dictionary object with CFBD stat categories. -1847 -1848 """ -1849 url = "https://api.collegefootballdata.com/stats/categories" -1850 -1851 if api_key is not None: -1852 real_api_key = api_key -1853 del api_key -1854 else: -1855 real_api_key = get_cfbd_api_token(api_key_dir=api_key_dir) -1856 -1857 if real_api_key == "tigersAreAwesome": -1858 raise ValueError( -1859 "You actually need to change `cfbd_key` to your CFBD API key." -1860 ) -1861 elif "Bearer " in real_api_key: -1862 pass -1863 elif "Bearer" in real_api_key: -1864 real_api_key = real_api_key.replace("Bearer", "Bearer ") -1865 else: -1866 real_api_key = "Bearer " + real_api_key -1867 -1868 headers = { -1869 "Authorization": f"{real_api_key}", -1870 "accept": "application/json" -1871 } -1872 -1873 response = requests.get(url, headers=headers) -1874 -1875 if response.status_code == 200: -1876 pass -1877 elif response.status_code == 401: -1878 raise ConnectionRefusedError( -1879 "Could not connect. The connection was refused." + -1880 "\nHTTP Status Code 401." +1808 print(json_data) +1809 +1810 else: +1811 # Alternatively, if the CFBD API key exists in this python environment, +1812 # or it's been set by cfbd_json_py.utls.set_cfbd_api_token(), +1813 # you could just call these functions directly, +1814 # without setting the API key in the script. +1815 print( +1816 "Using the user's API key supposedly loaded " + +1817 "into this python environment for this example." +1818 ) +1819 +1820 # Get a list of CFBD stat categories for team stats. +1821 print("Get a list of CFBD stat categories for team stats.") +1822 json_data = get_cfbd_team_stat_categories() +1823 print(json_data) +1824 time.sleep(5) +1825 +1826 # You can also tell this function to just return the API call as +1827 # a Dictionary (read: JSON) object. +1828 print( +1829 "You can also tell this function to just return the API call " + +1830 "as a Dictionary (read: JSON) object." +1831 ) +1832 json_data = get_cfbd_team_stat_categories( +1833 return_as_dict=True +1834 ) +1835 print(json_data) +1836 +1837 ``` +1838 Returns +1839 ---------- +1840 A pandas `DataFrame` object with CFBD stat categories, +1841 or (if `return_as_dict` is set to `True`) +1842 a dictionary object with CFBD stat categories. +1843 +1844 """ +1845 url = "https://api.collegefootballdata.com/stats/categories" +1846 +1847 if api_key is not None: +1848 real_api_key = api_key +1849 del api_key +1850 else: +1851 real_api_key = get_cfbd_api_token(api_key_dir=api_key_dir) +1852 +1853 if real_api_key == "tigersAreAwesome": +1854 raise ValueError( +1855 "You actually need to change `cfbd_key` to your CFBD API key." +1856 ) +1857 elif "Bearer " in real_api_key: +1858 pass +1859 elif "Bearer" in real_api_key: +1860 real_api_key = real_api_key.replace("Bearer", "Bearer ") +1861 else: +1862 real_api_key = "Bearer " + real_api_key +1863 +1864 headers = { +1865 "Authorization": f"{real_api_key}", +1866 "accept": "application/json" +1867 } +1868 +1869 response = requests.get(url, headers=headers) +1870 +1871 if response.status_code == 200: +1872 pass +1873 elif response.status_code == 401: +1874 raise ConnectionRefusedError( +1875 "Could not connect. The connection was refused." + +1876 "\nHTTP Status Code 401." +1877 ) +1878 else: +1879 raise ConnectionError( +1880 f"Could not connect.\nHTTP Status code {response.status_code}" 1881 ) -1882 else: -1883 raise ConnectionError( -1884 f"Could not connect.\nHTTP Status code {response.status_code}" -1885 ) -1886 -1887 json_data = response.json() -1888 -1889 if return_as_dict is True: -1890 return json_data -1891 -1892 return pd.DataFrame(json_data, columns=["stat_category"]) +1882 +1883 json_data = response.json() +1884 +1885 if return_as_dict is True: +1886 return json_data +1887 +1888 return pd.DataFrame(json_data, columns=["stat_category"]) @@ -4009,10 +4005,9 @@

612 for key, value in tqdm(rebuilt_json.items()): 613 row_df = pd.DataFrame(value, index=[0]) 614 final_df = pd.concat([final_df, row_df], ignore_index=True) -615 # print() -616 -617 final_df = final_df[stat_columns] -618 return final_df +615 +616 final_df = final_df[stat_columns] +617 return final_df @@ -4260,565 +4255,562 @@

Returns

-
 621def get_cfbd_advanced_team_season_stats(
- 622    api_key: str = None,
- 623    api_key_dir: str = None,
- 624    season: int = None,
- 625    team: str = None,
- 626    # `year` and/or `team` need to be not null for this function to work.
- 627    exclude_garbage_time: bool = False,
- 628    start_week: int = None,
- 629    end_week: int = None,
- 630    return_as_dict: bool = False,
- 631):
- 632    """
- 633    Allows you to get advanced CFB team season stats data from the CFBD API.
- 634
- 635    Parameters
- 636    ----------
- 637
- 638    `api_key` (str, optional):
- 639        Semi-optional argument.
- 640        If `api_key` is null, this function will attempt to load a CFBD API key
- 641        from the python environment, or from a file on this computer.
- 642        If `api_key` is not null,
- 643        this function will automatically assume that the
- 644        inputted `api_key` is a valid CFBD API key.
- 645
- 646    `api_key_dir` (str, optional):
- 647        Optional argument.
- 648        If `api_key` is set to am empty string, this variable is ignored.
- 649        If `api_key_dir` is null, and `api_key` is null,
- 650        this function will try to find
- 651        a CFBD API key file in this user's home directory.
- 652        If `api_key_dir` is set to a string, and `api_key` is null,
- 653        this function will assume that `api_key_dir` is a directory,
- 654        and will try to find a CFBD API key file in that directory.
- 655
- 656    `season` (int, semi-mandatory):
- 657        Semi-required argument.
- 658        Specifies the season you want CFB team season stats data from.
- 659        This must be specified, otherwise this package, and by extension
- 660        the CFBD API, will not accept the request
- 661        to get CFB team season stats data.
- 662        This or `team` must be set
- 663        to a valid non-null variable for this to function.
- 664
- 665    `team` (str, semi-mandatory):
- 666        Semi-required argument.
- 667        Specifies the season you want advanced CFB team season stats data from.
- 668        This must be specified, otherwise this package, and by extension
- 669        the CFBD API, will not accept
- 670        the request to get CFB team season stats data.
- 671        This or `season` must be set
- 672        to a valid non-null variable for this to function.
- 673
- 674    `exclude_garbage_time` (bool, optional):
- 675        Optional argument.
- 676        If you want to filter out plays where
- 677        the result of the game is largely decided,
- 678        set `exclude_garbage_time = True`.
- 679        Default behavior is that this variable is set to
- 680        `False` when this function is called.
- 681
- 682    `start_week` (int, semi-optional):
- 683        Optional argument.
- 684        If you only want team stats for a range of weeks,
- 685        set `start_week` and `end_week` to
- 686        the range of weeks you want season-level data for.
- 687
- 688    `end_week` (int, semi-optional):
- 689        Optional argument.
- 690        If you only want team stats for a range of weeks,
- 691        set `start_week` and `end_week` to
- 692        the range of weeks you want season-level data for.
- 693
- 694    **NOTE**: If the following conditions are `True`, a `ValueError()`
- 695    will be raised when calling this function:
- 696    - `start_week < 0`
- 697    - `end_week < 0`
- 698    - `start_week is not None and end_week is None`
- 699        (will be changed in a future version)
- 700    - `start_week is None and end_week is not None`
- 701        (will be changed in a future version)
- 702    - `end_week < start_week`
- 703    - `end_week = start_week`
- 704
- 705    `return_as_dict` (bool, semi-optional):
- 706        Semi-optional argument.
- 707        If you want this function to return
- 708        the data as a dictionary (read: JSON object),
- 709        instead of a pandas `DataFrame` object,
- 710        set `return_as_dict` to `True`.
+                
 620def get_cfbd_advanced_team_season_stats(
+ 621    api_key: str = None,
+ 622    api_key_dir: str = None,
+ 623    season: int = None,
+ 624    team: str = None,
+ 625    # `year` and/or `team` need to be not null for this function to work.
+ 626    exclude_garbage_time: bool = False,
+ 627    start_week: int = None,
+ 628    end_week: int = None,
+ 629    return_as_dict: bool = False,
+ 630):
+ 631    """
+ 632    Allows you to get advanced CFB team season stats data from the CFBD API.
+ 633
+ 634    Parameters
+ 635    ----------
+ 636
+ 637    `api_key` (str, optional):
+ 638        Semi-optional argument.
+ 639        If `api_key` is null, this function will attempt to load a CFBD API key
+ 640        from the python environment, or from a file on this computer.
+ 641        If `api_key` is not null,
+ 642        this function will automatically assume that the
+ 643        inputted `api_key` is a valid CFBD API key.
+ 644
+ 645    `api_key_dir` (str, optional):
+ 646        Optional argument.
+ 647        If `api_key` is set to am empty string, this variable is ignored.
+ 648        If `api_key_dir` is null, and `api_key` is null,
+ 649        this function will try to find
+ 650        a CFBD API key file in this user's home directory.
+ 651        If `api_key_dir` is set to a string, and `api_key` is null,
+ 652        this function will assume that `api_key_dir` is a directory,
+ 653        and will try to find a CFBD API key file in that directory.
+ 654
+ 655    `season` (int, semi-mandatory):
+ 656        Semi-required argument.
+ 657        Specifies the season you want CFB team season stats data from.
+ 658        This must be specified, otherwise this package, and by extension
+ 659        the CFBD API, will not accept the request
+ 660        to get CFB team season stats data.
+ 661        This or `team` must be set
+ 662        to a valid non-null variable for this to function.
+ 663
+ 664    `team` (str, semi-mandatory):
+ 665        Semi-required argument.
+ 666        Specifies the season you want advanced CFB team season stats data from.
+ 667        This must be specified, otherwise this package, and by extension
+ 668        the CFBD API, will not accept
+ 669        the request to get CFB team season stats data.
+ 670        This or `season` must be set
+ 671        to a valid non-null variable for this to function.
+ 672
+ 673    `exclude_garbage_time` (bool, optional):
+ 674        Optional argument.
+ 675        If you want to filter out plays where
+ 676        the result of the game is largely decided,
+ 677        set `exclude_garbage_time = True`.
+ 678        Default behavior is that this variable is set to
+ 679        `False` when this function is called.
+ 680
+ 681    `start_week` (int, semi-optional):
+ 682        Optional argument.
+ 683        If you only want team stats for a range of weeks,
+ 684        set `start_week` and `end_week` to
+ 685        the range of weeks you want season-level data for.
+ 686
+ 687    `end_week` (int, semi-optional):
+ 688        Optional argument.
+ 689        If you only want team stats for a range of weeks,
+ 690        set `start_week` and `end_week` to
+ 691        the range of weeks you want season-level data for.
+ 692
+ 693    **NOTE**: If the following conditions are `True`, a `ValueError()`
+ 694    will be raised when calling this function:
+ 695    - `start_week < 0`
+ 696    - `end_week < 0`
+ 697    - `start_week is not None and end_week is None`
+ 698        (will be changed in a future version)
+ 699    - `start_week is None and end_week is not None`
+ 700        (will be changed in a future version)
+ 701    - `end_week < start_week`
+ 702    - `end_week = start_week`
+ 703
+ 704    `return_as_dict` (bool, semi-optional):
+ 705        Semi-optional argument.
+ 706        If you want this function to return
+ 707        the data as a dictionary (read: JSON object),
+ 708        instead of a pandas `DataFrame` object,
+ 709        set `return_as_dict` to `True`.
+ 710
  711
- 712
- 713    Usage
- 714    ----------
- 715    ```
- 716
- 717    import time
- 718
- 719    from cfbd_json_py.stats import get_cfbd_advanced_team_season_stats
+ 712    Usage
+ 713    ----------
+ 714    ```
+ 715
+ 716    import time
+ 717
+ 718    from cfbd_json_py.stats import get_cfbd_advanced_team_season_stats
+ 719
  720
- 721
- 722    cfbd_key = "tigersAreAwesome"  # placeholder for your CFBD API Key.
- 723
- 724    if cfbd_key != "tigersAreAwesome":
- 725        print(
- 726            "Using the user's API key declared in this script " +
- 727            "for this example."
- 728        )
- 729
- 730        # Get advanced team season stats for the 2020 CFB season.
- 731        print("Get team season stats for the 2020 CFB season.")
- 732        json_data = get_cfbd_advanced_team_season_stats(
- 733            api_key=cfbd_key,
- 734            season=2020
- 735        )
- 736        print(json_data)
- 737        time.sleep(5)
- 738
- 739        # Get advanced team season stats for the 2020 CFB season,
- 740        # but remove plays that happen in garbage time.
- 741        print(
- 742            "Get advanced team season stats for the 2020 CFB season, " +
- 743            "but remove plays that happen in garbage time."
- 744        )
- 745        json_data = get_cfbd_advanced_team_season_stats(
- 746            api_key=cfbd_key,
- 747            season=2020,
- 748            exclude_garbage_time=True
- 749        )
- 750        print(json_data)
- 751        time.sleep(5)
- 752
- 753        # Get advanced team season stats for the 2020 CFB season,
- 754        # but only between weeks 5 and 10.
- 755        print(
- 756            "Get advanced team season stats for the 2020 CFB season, " +
- 757            "but only between weeks 5 and 10."
- 758        )
- 759        json_data = get_cfbd_advanced_team_season_stats(
- 760            api_key=cfbd_key,
- 761            season=2020,
- 762            start_week=5,
- 763            end_week=10
- 764        )
- 765        print(json_data)
- 766        time.sleep(5)
- 767
- 768        # Get advanced team season stats for just
- 769        # the Ohio State Buckeyes Football Team.
- 770        print(
- 771            "Get advanced team season stats for just" +
- 772            " the Ohio State Buckeyes Football Team."
- 773        )
- 774        json_data = get_cfbd_advanced_team_season_stats(
- 775            api_key=cfbd_key,
- 776            team="Ohio State"
- 777        )
- 778        print(json_data)
- 779        time.sleep(5)
+ 721    cfbd_key = "tigersAreAwesome"  # placeholder for your CFBD API Key.
+ 722
+ 723    if cfbd_key != "tigersAreAwesome":
+ 724        print(
+ 725            "Using the user's API key declared in this script " +
+ 726            "for this example."
+ 727        )
+ 728
+ 729        # Get advanced team season stats for the 2020 CFB season.
+ 730        print("Get team season stats for the 2020 CFB season.")
+ 731        json_data = get_cfbd_advanced_team_season_stats(
+ 732            api_key=cfbd_key,
+ 733            season=2020
+ 734        )
+ 735        print(json_data)
+ 736        time.sleep(5)
+ 737
+ 738        # Get advanced team season stats for the 2020 CFB season,
+ 739        # but remove plays that happen in garbage time.
+ 740        print(
+ 741            "Get advanced team season stats for the 2020 CFB season, " +
+ 742            "but remove plays that happen in garbage time."
+ 743        )
+ 744        json_data = get_cfbd_advanced_team_season_stats(
+ 745            api_key=cfbd_key,
+ 746            season=2020,
+ 747            exclude_garbage_time=True
+ 748        )
+ 749        print(json_data)
+ 750        time.sleep(5)
+ 751
+ 752        # Get advanced team season stats for the 2020 CFB season,
+ 753        # but only between weeks 5 and 10.
+ 754        print(
+ 755            "Get advanced team season stats for the 2020 CFB season, " +
+ 756            "but only between weeks 5 and 10."
+ 757        )
+ 758        json_data = get_cfbd_advanced_team_season_stats(
+ 759            api_key=cfbd_key,
+ 760            season=2020,
+ 761            start_week=5,
+ 762            end_week=10
+ 763        )
+ 764        print(json_data)
+ 765        time.sleep(5)
+ 766
+ 767        # Get advanced team season stats for just
+ 768        # the Ohio State Buckeyes Football Team.
+ 769        print(
+ 770            "Get advanced team season stats for just" +
+ 771            " the Ohio State Buckeyes Football Team."
+ 772        )
+ 773        json_data = get_cfbd_advanced_team_season_stats(
+ 774            api_key=cfbd_key,
+ 775            team="Ohio State"
+ 776        )
+ 777        print(json_data)
+ 778        time.sleep(5)
+ 779
  780
- 781
- 782        # You can also tell this function to just return the API call as
- 783        # a Dictionary (read: JSON) object.
- 784        print(
- 785            "You can also tell this function to just return the API call " +
- 786            "as a Dictionary (read: JSON) object."
- 787        )
- 788        json_data = get_cfbd_advanced_team_season_stats(
- 789            api_key=cfbd_key,
- 790            season=2020,
- 791            team="Cincinnati",
- 792            return_as_dict=True
- 793        )
- 794        print(json_data)
- 795
- 796    else:
- 797        # Alternatively, if the CFBD API key exists in this python environment,
- 798        # or it's been set by cfbd_json_py.utls.set_cfbd_api_token(),
- 799        # you could just call these functions directly,
- 800        # without setting the API key in the script.
- 801        print(
- 802            "Using the user's API key supposedly loaded " +
- 803            "into this python environment for this example."
- 804        )
- 805
- 806    # Get advanced team season stats for the 2020 CFB season.
- 807        print("Get team season stats for the 2020 CFB season.")
- 808        json_data = get_cfbd_advanced_team_season_stats(
- 809            season=2020
- 810        )
- 811        print(json_data)
- 812        time.sleep(5)
- 813
- 814        # Get advanced team season stats for the 2020 CFB season,
- 815        # but remove plays that happen in garbage time.
- 816        print(
- 817            "Get advanced team season stats for the 2020 CFB season, " +
- 818            "but remove plays that happen in garbage time."
- 819        )
- 820        json_data = get_cfbd_advanced_team_season_stats(
- 821            season=2020,
- 822            exclude_garbage_time=True
- 823        )
- 824        print(json_data)
- 825        time.sleep(5)
- 826
- 827        # Get advanced team season stats for the 2020 CFB season,
- 828        # but only between weeks 5 and 10.
- 829        print(
- 830            "Get advanced team season stats for the 2020 CFB season, " +
- 831            "but only between weeks 5 and 10."
- 832        )
- 833        json_data = get_cfbd_advanced_team_season_stats(
- 834            season=2020,
- 835            start_week=5,
- 836            end_week=10
- 837        )
- 838        print(json_data)
- 839        time.sleep(5)
- 840
- 841        # Get advanced team season stats for the just
- 842        # the Ohio State Buckeyes Football Team.
- 843        print(
- 844            "Get advanced team season stats for the just " +
- 845            "the Ohio State Buckeyes Football Team."
- 846        )
- 847        json_data = get_cfbd_advanced_team_season_stats(
- 848            team="Ohio State"
- 849        )
- 850        print(json_data)
- 851        time.sleep(5)
+ 781        # You can also tell this function to just return the API call as
+ 782        # a Dictionary (read: JSON) object.
+ 783        print(
+ 784            "You can also tell this function to just return the API call " +
+ 785            "as a Dictionary (read: JSON) object."
+ 786        )
+ 787        json_data = get_cfbd_advanced_team_season_stats(
+ 788            api_key=cfbd_key,
+ 789            season=2020,
+ 790            team="Cincinnati",
+ 791            return_as_dict=True
+ 792        )
+ 793        print(json_data)
+ 794
+ 795    else:
+ 796        # Alternatively, if the CFBD API key exists in this python environment,
+ 797        # or it's been set by cfbd_json_py.utls.set_cfbd_api_token(),
+ 798        # you could just call these functions directly,
+ 799        # without setting the API key in the script.
+ 800        print(
+ 801            "Using the user's API key supposedly loaded " +
+ 802            "into this python environment for this example."
+ 803        )
+ 804
+ 805    # Get advanced team season stats for the 2020 CFB season.
+ 806        print("Get team season stats for the 2020 CFB season.")
+ 807        json_data = get_cfbd_advanced_team_season_stats(
+ 808            season=2020
+ 809        )
+ 810        print(json_data)
+ 811        time.sleep(5)
+ 812
+ 813        # Get advanced team season stats for the 2020 CFB season,
+ 814        # but remove plays that happen in garbage time.
+ 815        print(
+ 816            "Get advanced team season stats for the 2020 CFB season, " +
+ 817            "but remove plays that happen in garbage time."
+ 818        )
+ 819        json_data = get_cfbd_advanced_team_season_stats(
+ 820            season=2020,
+ 821            exclude_garbage_time=True
+ 822        )
+ 823        print(json_data)
+ 824        time.sleep(5)
+ 825
+ 826        # Get advanced team season stats for the 2020 CFB season,
+ 827        # but only between weeks 5 and 10.
+ 828        print(
+ 829            "Get advanced team season stats for the 2020 CFB season, " +
+ 830            "but only between weeks 5 and 10."
+ 831        )
+ 832        json_data = get_cfbd_advanced_team_season_stats(
+ 833            season=2020,
+ 834            start_week=5,
+ 835            end_week=10
+ 836        )
+ 837        print(json_data)
+ 838        time.sleep(5)
+ 839
+ 840        # Get advanced team season stats for the just
+ 841        # the Ohio State Buckeyes Football Team.
+ 842        print(
+ 843            "Get advanced team season stats for the just " +
+ 844            "the Ohio State Buckeyes Football Team."
+ 845        )
+ 846        json_data = get_cfbd_advanced_team_season_stats(
+ 847            team="Ohio State"
+ 848        )
+ 849        print(json_data)
+ 850        time.sleep(5)
+ 851
  852
- 853
- 854        # You can also tell this function to just return the API call as
- 855        # a Dictionary (read: JSON) object.
- 856        print(
- 857            "You can also tell this function to just return the API call " +
- 858            "as a Dictionary (read: JSON) object."
- 859        )
- 860        json_data = get_cfbd_advanced_team_season_stats(
- 861            season=2020,
- 862            team="Cincinnati",
- 863            return_as_dict=True
- 864        )
- 865        print(json_data)
- 866    ```
- 867    Returns
- 868    ----------
- 869    A pandas `DataFrame` object with advanced team season stats data,
- 870    or (if `return_as_dict` is set to `True`)
- 871    a dictionary object with a with advanced team season stats data.
- 872
- 873    """
- 874    now = datetime.now()
- 875    url = "https://api.collegefootballdata.com/stats/season/advanced"
- 876    row_df = pd.DataFrame()
- 877    final_df = pd.DataFrame()
- 878
- 879    if api_key is not None:
- 880        real_api_key = api_key
- 881        del api_key
- 882    else:
- 883        real_api_key = get_cfbd_api_token(api_key_dir=api_key_dir)
- 884
- 885    if real_api_key == "tigersAreAwesome":
- 886        raise ValueError(
- 887            "You actually need to change `cfbd_key` to your CFBD API key."
- 888        )
- 889    elif "Bearer " in real_api_key:
- 890        pass
- 891    elif "Bearer" in real_api_key:
- 892        real_api_key = real_api_key.replace("Bearer", "Bearer ")
- 893    else:
- 894        real_api_key = "Bearer " + real_api_key
- 895
- 896    if season is not None and (season > (now.year + 1)):
- 897        raise ValueError(f"`season` cannot be greater than {season}.")
- 898    elif season is not None and season < 1869:
- 899        raise ValueError("`season` cannot be less than 1869.")
- 900
- 901    if start_week is not None and end_week is not None:
- 902        if start_week > end_week:
- 903            raise ValueError("`start_week` cannot be greater than `end_week`.")
- 904        elif start_week == end_week:
- 905            raise ValueError(
- 906                "`start_week` cannot be equal to `end_week`."
- 907                + "\n Use " +
- 908                "`cfbd_json_py.games.get_cfbd_player_game_stats()` instead "
- 909                + "if you want player stats for a specific week in ."
- 910            )
- 911        elif start_week < 0:
- 912            raise ValueError("`start_week` cannot be less than 0.")
- 913        elif end_week < 0:
- 914            raise ValueError("`end_week` cannot be less than 0.")
- 915
- 916    gt_str = ""
- 917
- 918    # URL builder
- 919    ##########################################################################
- 920
- 921    if exclude_garbage_time is True:
- 922        gt_str = "true"
- 923    elif exclude_garbage_time is False:
- 924        gt_str = "false"
- 925
- 926    if season is not None and team is not None:
- 927        url += f"?year={season}&team={team}"
- 928    elif season is not None:
- 929        url += f"?year={season}"
- 930    elif team is not None:
- 931        url += f"?team={team}"
- 932
- 933    if exclude_garbage_time is not None:
- 934        url += f"&excludeGarbageTime={gt_str}"
- 935
- 936    if start_week is not None:
- 937        url += f"&startWeek={start_week}"
- 938
- 939    if end_week is not None:
- 940        url += f"&endWeek={end_week}"
- 941
- 942    headers = {
- 943        "Authorization": f"{real_api_key}",
- 944        "accept": "application/json"
- 945    }
- 946
- 947    response = requests.get(url, headers=headers)
- 948
- 949    if response.status_code == 200:
- 950        pass
- 951    elif response.status_code == 401:
- 952        raise ConnectionRefusedError(
- 953            "Could not connect. The connection was refused." +
- 954            "\nHTTP Status Code 401."
- 955        )
- 956    else:
- 957        raise ConnectionError(
- 958            f"Could not connect.\nHTTP Status code {response.status_code}"
- 959        )
- 960
- 961    json_data = response.json()
- 962
- 963    if return_as_dict is True:
- 964        return json_data
+ 853        # You can also tell this function to just return the API call as
+ 854        # a Dictionary (read: JSON) object.
+ 855        print(
+ 856            "You can also tell this function to just return the API call " +
+ 857            "as a Dictionary (read: JSON) object."
+ 858        )
+ 859        json_data = get_cfbd_advanced_team_season_stats(
+ 860            season=2020,
+ 861            team="Cincinnati",
+ 862            return_as_dict=True
+ 863        )
+ 864        print(json_data)
+ 865    ```
+ 866    Returns
+ 867    ----------
+ 868    A pandas `DataFrame` object with advanced team season stats data,
+ 869    or (if `return_as_dict` is set to `True`)
+ 870    a dictionary object with a with advanced team season stats data.
+ 871
+ 872    """
+ 873    now = datetime.now()
+ 874    url = "https://api.collegefootballdata.com/stats/season/advanced"
+ 875    row_df = pd.DataFrame()
+ 876    final_df = pd.DataFrame()
+ 877
+ 878    if api_key is not None:
+ 879        real_api_key = api_key
+ 880        del api_key
+ 881    else:
+ 882        real_api_key = get_cfbd_api_token(api_key_dir=api_key_dir)
+ 883
+ 884    if real_api_key == "tigersAreAwesome":
+ 885        raise ValueError(
+ 886            "You actually need to change `cfbd_key` to your CFBD API key."
+ 887        )
+ 888    elif "Bearer " in real_api_key:
+ 889        pass
+ 890    elif "Bearer" in real_api_key:
+ 891        real_api_key = real_api_key.replace("Bearer", "Bearer ")
+ 892    else:
+ 893        real_api_key = "Bearer " + real_api_key
+ 894
+ 895    if season is not None and (season > (now.year + 1)):
+ 896        raise ValueError(f"`season` cannot be greater than {season}.")
+ 897    elif season is not None and season < 1869:
+ 898        raise ValueError("`season` cannot be less than 1869.")
+ 899
+ 900    if start_week is not None and end_week is not None:
+ 901        if start_week > end_week:
+ 902            raise ValueError("`start_week` cannot be greater than `end_week`.")
+ 903        elif start_week == end_week:
+ 904            raise ValueError(
+ 905                "`start_week` cannot be equal to `end_week`."
+ 906                + "\n Use " +
+ 907                "`cfbd_json_py.games.get_cfbd_player_game_stats()` instead "
+ 908                + "if you want player stats for a specific week in ."
+ 909            )
+ 910        elif start_week < 0:
+ 911            raise ValueError("`start_week` cannot be less than 0.")
+ 912        elif end_week < 0:
+ 913            raise ValueError("`end_week` cannot be less than 0.")
+ 914
+ 915    gt_str = ""
+ 916
+ 917    # URL builder
+ 918    ##########################################################################
+ 919
+ 920    if exclude_garbage_time is True:
+ 921        gt_str = "true"
+ 922    elif exclude_garbage_time is False:
+ 923        gt_str = "false"
+ 924
+ 925    if season is not None and team is not None:
+ 926        url += f"?year={season}&team={team}"
+ 927    elif season is not None:
+ 928        url += f"?year={season}"
+ 929    elif team is not None:
+ 930        url += f"?team={team}"
+ 931
+ 932    if exclude_garbage_time is not None:
+ 933        url += f"&excludeGarbageTime={gt_str}"
+ 934
+ 935    if start_week is not None:
+ 936        url += f"&startWeek={start_week}"
+ 937
+ 938    if end_week is not None:
+ 939        url += f"&endWeek={end_week}"
+ 940
+ 941    headers = {
+ 942        "Authorization": f"{real_api_key}",
+ 943        "accept": "application/json"
+ 944    }
+ 945
+ 946    response = requests.get(url, headers=headers)
+ 947
+ 948    if response.status_code == 200:
+ 949        pass
+ 950    elif response.status_code == 401:
+ 951        raise ConnectionRefusedError(
+ 952            "Could not connect. The connection was refused." +
+ 953            "\nHTTP Status Code 401."
+ 954        )
+ 955    else:
+ 956        raise ConnectionError(
+ 957            f"Could not connect.\nHTTP Status code {response.status_code}"
+ 958        )
+ 959
+ 960    json_data = response.json()
+ 961
+ 962    if return_as_dict is True:
+ 963        return json_data
+ 964
  965
- 966    # final_df = pd.json_normalize(json_data)
- 967
- 968    # print(final_df.columns)
- 969
- 970    for team in tqdm(json_data):
- 971        t_season = team["season"]
- 972        t_team = team["team"]
- 973        t_conf = team["conference"]
- 974        row_df = pd.DataFrame(
- 975            {
- 976                "season": t_season,
- 977                "team": t_team,
- 978                "conference": t_conf
- 979            },
- 980            index=[0]
- 981        )
- 982
- 983        # offense
- 984        if "offense" not in team:
- 985            logging.debug(
- 986                f"Key `[offense]` not found for the {t_season} {t_team}."
- 987            )
- 988        else:
- 989            row_df["offense_plays"] = team["offense"]["plays"]
- 990            row_df["offense_drives"] = team["offense"]["drives"]
- 991            # row_df["offense_plays"] = team["offense"]["plays"]
- 992            row_df["offense_ppa"] = team["offense"]["ppa"]
- 993            row_df["offense_total_ppa"] = team["offense"]["totalPPA"]
- 994            row_df["offense_success_rate"] = team["offense"]["successRate"]
- 995            row_df["offense_explosiveness"] = team["offense"]["explosiveness"]
- 996            row_df["offense_power_success"] = team["offense"]["powerSuccess"]
- 997            row_df["offense_stuff_rate"] = team["offense"]["stuffRate"]
- 998            row_df["offense_line_yards_avg"] = team["offense"]["lineYards"]
- 999            row_df["offense_line_yards_total"] = team["offense"][
-1000                "lineYardsTotal"
-1001            ]
-1002            row_df["offense_second_level_yards_avg"] = team["offense"][
-1003                "secondLevelYards"
-1004            ]
-1005            row_df["offense_second_level_yards_total"] = team["offense"][
-1006                "secondLevelYardsTotal"
-1007            ]
-1008            row_df["offense_open_field_yards_avg"] = team["offense"][
-1009                "openFieldYards"
-1010            ]
-1011            row_df["offense_open_field_yards_total"] = team["offense"][
-1012                "secondLevelYardsTotal"
-1013            ]
-1014            row_df["offense_total_opportunities"] = team["offense"][
-1015                "totalOpportunies"
-1016            ]
-1017            row_df["offense_points_per_opportunity"] = team["offense"][
-1018                "pointsPerOpportunity"
-1019            ]
-1020
-1021            row_df["offense_field_position_avg_start"] = team["offense"][
-1022                "fieldPosition"]["averageStart"]
-1023            row_df["offense_field_position_avg_predicted_points"] = team[
-1024                "offense"]["fieldPosition"]["averagePredictedPoints"]
-1025
-1026            row_df["offense_havoc_total"] = team["offense"]["havoc"]["total"]
-1027            row_df["offense_havoc_front_7"] = team["offense"]["havoc"][
-1028                "frontSeven"
-1029            ]
-1030            row_df["offense_havoc_db"] = team["offense"]["havoc"]["db"]
-1031
-1032            row_df["offense_standard_downs_rate"] = team[
-1033                "offense"]["standardDowns"]["rate"]
-1034            row_df["offense_standard_downs_ppa"] = team[
-1035                "offense"]["standardDowns"]["ppa"]
-1036            row_df["offense_standard_downs_success_rate"] = team["offense"][
-1037                "standardDowns"
-1038            ]["successRate"]
-1039            row_df["offense_standard_downs_explosiveness"] = team["offense"][
-1040                "standardDowns"
-1041            ]["explosiveness"]
-1042
-1043            row_df["offense_passing_downs_rate"] = team[
-1044                "offense"]["passingDowns"]["rate"]
-1045            row_df["offense_passing_downs_ppa"] = team[
-1046                "offense"]["passingDowns"]["ppa"]
-1047            row_df["offense_passing_downs_success_rate"] = team["offense"][
-1048                "passingDowns"
-1049            ]["successRate"]
-1050            row_df["offense_passing_downs_explosiveness"] = team["offense"][
-1051                "passingDowns"
-1052            ]["explosiveness"]
-1053
-1054            row_df["offense_rushing_plays_rate"] = team[
-1055                "offense"]["rushingPlays"]["rate"]
-1056            row_df["offense_rushing_plays_ppa"] = team[
-1057                "offense"]["rushingPlays"]["ppa"]
-1058            row_df["offense_rushing_plays_total_ppa"] = team[
-1059                "offense"]["rushingPlays"]["totalPPA"]
-1060            row_df["offense_rushing_plays_success_rate"] = team[
-1061                "offense"]["rushingPlays"]["successRate"]
-1062            row_df["offense_rushing_plays_explosiveness"] = team[
-1063                "offense"]["rushingPlays"]["explosiveness"]
-1064
-1065            row_df["offense_passing_plays_rate"] = team[
-1066                "offense"]["passingPlays"]["rate"]
-1067            row_df["offense_passing_plays_ppa"] = team[
-1068                "offense"]["passingPlays"]["ppa"]
-1069            row_df["offense_passing_plays_total_ppa"] = team[
-1070                "offense"]["passingPlays"]["totalPPA"]
-1071            row_df["offense_passing_plays_success_rate"] = team[
-1072                "offense"]["passingPlays"]["successRate"]
-1073            row_df["offense_passing_plays_explosiveness"] = team[
-1074                "offense"]["rushingPlays"]["explosiveness"]
-1075
-1076        # defense
-1077        if "defense" not in team:
-1078            logging.debug(
-1079                f"Key `[defense]` not found for the {t_season} {t_team}."
-1080            )
-1081        else:
-1082
-1083            row_df["defense_plays"] = team["defense"]["plays"]
-1084            row_df["defense_drives"] = team["defense"]["drives"]
-1085            # row_df["defense_plays"] = team["defense"]["plays"]
-1086            row_df["defense_ppa"] = team["defense"]["ppa"]
-1087            row_df["defense_total_ppa"] = team["defense"]["totalPPA"]
-1088            row_df["defense_success_rate"] = team["defense"]["successRate"]
-1089            row_df["defense_explosiveness"] = team["defense"]["explosiveness"]
-1090            row_df["defense_power_success"] = team["defense"]["powerSuccess"]
-1091            row_df["defense_stuff_rate"] = team["defense"]["stuffRate"]
-1092            row_df["defense_line_yards_avg"] = team["defense"]["lineYards"]
-1093            row_df["defense_line_yards_total"] = team["defense"][
-1094                "lineYardsTotal"
-1095            ]
-1096            row_df["defense_second_level_yards_avg"] = team["defense"][
-1097                "secondLevelYards"
-1098            ]
-1099            row_df["defense_second_level_yards_total"] = team["defense"][
-1100                "secondLevelYardsTotal"
-1101            ]
-1102            row_df["defense_open_field_yards_avg"] = team["defense"][
-1103                "openFieldYards"
-1104            ]
-1105            row_df["defense_open_field_yards_total"] = team["defense"][
-1106                "secondLevelYardsTotal"
-1107            ]
-1108            row_df["defense_total_opportunities"] = team["defense"][
-1109                "totalOpportunies"
-1110            ]
-1111            row_df["defense_points_per_opportunity"] = team["defense"][
-1112                "pointsPerOpportunity"
-1113            ]
-1114
-1115            row_df["defense_field_position_avg_start"] = team["defense"][
-1116                "fieldPosition"
-1117            ]["averageStart"]
-1118            row_df["defense_field_position_avg_predicted_points"] = team[
-1119                "defense"]["fieldPosition"]["averagePredictedPoints"]
-1120
-1121            row_df["defense_havoc_total"] = team["defense"]["havoc"]["total"]
-1122            row_df["defense_havoc_front_7"] = team["defense"]["havoc"][
-1123                "frontSeven"
-1124            ]
-1125            row_df["defense_havoc_db"] = team["defense"]["havoc"]["db"]
-1126
-1127            row_df["defense_standard_downs_rate"] = team[
-1128                "defense"]["standardDowns"]["rate"]
-1129            row_df["defense_standard_downs_ppa"] = team[
-1130                "defense"]["standardDowns"]["ppa"]
-1131            row_df["defense_standard_downs_success_rate"] = team["defense"][
-1132                "standardDowns"
-1133            ]["successRate"]
-1134            row_df["defense_standard_downs_explosiveness"] = team["defense"][
-1135                "standardDowns"
-1136            ]["explosiveness"]
-1137
-1138            row_df["defense_passing_downs_rate"] = team[
-1139                "defense"]["passingDowns"]["rate"]
-1140            row_df["defense_passing_downs_ppa"] = team[
-1141                "defense"]["passingDowns"]["ppa"]
-1142            row_df["defense_passing_downs_success_rate"] = team["defense"][
-1143                "passingDowns"
-1144            ]["successRate"]
-1145            row_df["defense_passing_downs_explosiveness"] = team["defense"][
-1146                "passingDowns"
-1147            ]["explosiveness"]
-1148
-1149            row_df["defense_rushing_plays_rate"] = team[
-1150                "defense"]["rushingPlays"]["rate"]
-1151            row_df["defense_rushing_plays_ppa"] = team[
-1152                "defense"]["rushingPlays"]["ppa"]
-1153            row_df["defense_rushing_plays_total_ppa"] = team[
-1154                "defense"]["rushingPlays"]["totalPPA"]
-1155            row_df["defense_rushing_plays_success_rate"] = team["defense"][
-1156                "rushingPlays"
-1157            ]["successRate"]
-1158            row_df["defense_rushing_plays_explosiveness"] = team["defense"][
-1159                "rushingPlays"
-1160            ]["explosiveness"]
-1161
-1162            row_df["defense_passing_plays_rate"] = team[
-1163                "defense"]["passingPlays"]["rate"]
-1164            row_df["defense_passing_plays_ppa"] = team[
-1165                "defense"]["passingPlays"]["ppa"]
-1166            row_df["defense_passing_plays_total_ppa"] = team[
-1167                "defense"]["passingPlays"]["totalPPA"]
-1168            row_df["defense_passing_plays_success_rate"] = team["defense"][
-1169                "passingPlays"
-1170            ]["successRate"]
-1171            row_df["defense_passing_plays_explosiveness"] = team["defense"][
-1172                "rushingPlays"
-1173            ]["explosiveness"]
+ 966    for team in tqdm(json_data):
+ 967        t_season = team["season"]
+ 968        t_team = team["team"]
+ 969        t_conf = team["conference"]
+ 970        row_df = pd.DataFrame(
+ 971            {
+ 972                "season": t_season,
+ 973                "team": t_team,
+ 974                "conference": t_conf
+ 975            },
+ 976            index=[0]
+ 977        )
+ 978
+ 979        # offense
+ 980        if "offense" not in team:
+ 981            logging.debug(
+ 982                f"Key `[offense]` not found for the {t_season} {t_team}."
+ 983            )
+ 984        else:
+ 985            row_df["offense_plays"] = team["offense"]["plays"]
+ 986            row_df["offense_drives"] = team["offense"]["drives"]
+ 987            # row_df["offense_plays"] = team["offense"]["plays"]
+ 988            row_df["offense_ppa"] = team["offense"]["ppa"]
+ 989            row_df["offense_total_ppa"] = team["offense"]["totalPPA"]
+ 990            row_df["offense_success_rate"] = team["offense"]["successRate"]
+ 991            row_df["offense_explosiveness"] = team["offense"]["explosiveness"]
+ 992            row_df["offense_power_success"] = team["offense"]["powerSuccess"]
+ 993            row_df["offense_stuff_rate"] = team["offense"]["stuffRate"]
+ 994            row_df["offense_line_yards_avg"] = team["offense"]["lineYards"]
+ 995            row_df["offense_line_yards_total"] = team["offense"][
+ 996                "lineYardsTotal"
+ 997            ]
+ 998            row_df["offense_second_level_yards_avg"] = team["offense"][
+ 999                "secondLevelYards"
+1000            ]
+1001            row_df["offense_second_level_yards_total"] = team["offense"][
+1002                "secondLevelYardsTotal"
+1003            ]
+1004            row_df["offense_open_field_yards_avg"] = team["offense"][
+1005                "openFieldYards"
+1006            ]
+1007            row_df["offense_open_field_yards_total"] = team["offense"][
+1008                "secondLevelYardsTotal"
+1009            ]
+1010            row_df["offense_total_opportunities"] = team["offense"][
+1011                "totalOpportunies"
+1012            ]
+1013            row_df["offense_points_per_opportunity"] = team["offense"][
+1014                "pointsPerOpportunity"
+1015            ]
+1016
+1017            row_df["offense_field_position_avg_start"] = team["offense"][
+1018                "fieldPosition"]["averageStart"]
+1019            row_df["offense_field_position_avg_predicted_points"] = team[
+1020                "offense"]["fieldPosition"]["averagePredictedPoints"]
+1021
+1022            row_df["offense_havoc_total"] = team["offense"]["havoc"]["total"]
+1023            row_df["offense_havoc_front_7"] = team["offense"]["havoc"][
+1024                "frontSeven"
+1025            ]
+1026            row_df["offense_havoc_db"] = team["offense"]["havoc"]["db"]
+1027
+1028            row_df["offense_standard_downs_rate"] = team[
+1029                "offense"]["standardDowns"]["rate"]
+1030            row_df["offense_standard_downs_ppa"] = team[
+1031                "offense"]["standardDowns"]["ppa"]
+1032            row_df["offense_standard_downs_success_rate"] = team["offense"][
+1033                "standardDowns"
+1034            ]["successRate"]
+1035            row_df["offense_standard_downs_explosiveness"] = team["offense"][
+1036                "standardDowns"
+1037            ]["explosiveness"]
+1038
+1039            row_df["offense_passing_downs_rate"] = team[
+1040                "offense"]["passingDowns"]["rate"]
+1041            row_df["offense_passing_downs_ppa"] = team[
+1042                "offense"]["passingDowns"]["ppa"]
+1043            row_df["offense_passing_downs_success_rate"] = team["offense"][
+1044                "passingDowns"
+1045            ]["successRate"]
+1046            row_df["offense_passing_downs_explosiveness"] = team["offense"][
+1047                "passingDowns"
+1048            ]["explosiveness"]
+1049
+1050            row_df["offense_rushing_plays_rate"] = team[
+1051                "offense"]["rushingPlays"]["rate"]
+1052            row_df["offense_rushing_plays_ppa"] = team[
+1053                "offense"]["rushingPlays"]["ppa"]
+1054            row_df["offense_rushing_plays_total_ppa"] = team[
+1055                "offense"]["rushingPlays"]["totalPPA"]
+1056            row_df["offense_rushing_plays_success_rate"] = team[
+1057                "offense"]["rushingPlays"]["successRate"]
+1058            row_df["offense_rushing_plays_explosiveness"] = team[
+1059                "offense"]["rushingPlays"]["explosiveness"]
+1060
+1061            row_df["offense_passing_plays_rate"] = team[
+1062                "offense"]["passingPlays"]["rate"]
+1063            row_df["offense_passing_plays_ppa"] = team[
+1064                "offense"]["passingPlays"]["ppa"]
+1065            row_df["offense_passing_plays_total_ppa"] = team[
+1066                "offense"]["passingPlays"]["totalPPA"]
+1067            row_df["offense_passing_plays_success_rate"] = team[
+1068                "offense"]["passingPlays"]["successRate"]
+1069            row_df["offense_passing_plays_explosiveness"] = team[
+1070                "offense"]["rushingPlays"]["explosiveness"]
+1071
+1072        # defense
+1073        if "defense" not in team:
+1074            logging.debug(
+1075                f"Key `[defense]` not found for the {t_season} {t_team}."
+1076            )
+1077        else:
+1078
+1079            row_df["defense_plays"] = team["defense"]["plays"]
+1080            row_df["defense_drives"] = team["defense"]["drives"]
+1081            # row_df["defense_plays"] = team["defense"]["plays"]
+1082            row_df["defense_ppa"] = team["defense"]["ppa"]
+1083            row_df["defense_total_ppa"] = team["defense"]["totalPPA"]
+1084            row_df["defense_success_rate"] = team["defense"]["successRate"]
+1085            row_df["defense_explosiveness"] = team["defense"]["explosiveness"]
+1086            row_df["defense_power_success"] = team["defense"]["powerSuccess"]
+1087            row_df["defense_stuff_rate"] = team["defense"]["stuffRate"]
+1088            row_df["defense_line_yards_avg"] = team["defense"]["lineYards"]
+1089            row_df["defense_line_yards_total"] = team["defense"][
+1090                "lineYardsTotal"
+1091            ]
+1092            row_df["defense_second_level_yards_avg"] = team["defense"][
+1093                "secondLevelYards"
+1094            ]
+1095            row_df["defense_second_level_yards_total"] = team["defense"][
+1096                "secondLevelYardsTotal"
+1097            ]
+1098            row_df["defense_open_field_yards_avg"] = team["defense"][
+1099                "openFieldYards"
+1100            ]
+1101            row_df["defense_open_field_yards_total"] = team["defense"][
+1102                "secondLevelYardsTotal"
+1103            ]
+1104            row_df["defense_total_opportunities"] = team["defense"][
+1105                "totalOpportunies"
+1106            ]
+1107            row_df["defense_points_per_opportunity"] = team["defense"][
+1108                "pointsPerOpportunity"
+1109            ]
+1110
+1111            row_df["defense_field_position_avg_start"] = team["defense"][
+1112                "fieldPosition"
+1113            ]["averageStart"]
+1114            row_df["defense_field_position_avg_predicted_points"] = team[
+1115                "defense"]["fieldPosition"]["averagePredictedPoints"]
+1116
+1117            row_df["defense_havoc_total"] = team["defense"]["havoc"]["total"]
+1118            row_df["defense_havoc_front_7"] = team["defense"]["havoc"][
+1119                "frontSeven"
+1120            ]
+1121            row_df["defense_havoc_db"] = team["defense"]["havoc"]["db"]
+1122
+1123            row_df["defense_standard_downs_rate"] = team[
+1124                "defense"]["standardDowns"]["rate"]
+1125            row_df["defense_standard_downs_ppa"] = team[
+1126                "defense"]["standardDowns"]["ppa"]
+1127            row_df["defense_standard_downs_success_rate"] = team["defense"][
+1128                "standardDowns"
+1129            ]["successRate"]
+1130            row_df["defense_standard_downs_explosiveness"] = team["defense"][
+1131                "standardDowns"
+1132            ]["explosiveness"]
+1133
+1134            row_df["defense_passing_downs_rate"] = team[
+1135                "defense"]["passingDowns"]["rate"]
+1136            row_df["defense_passing_downs_ppa"] = team[
+1137                "defense"]["passingDowns"]["ppa"]
+1138            row_df["defense_passing_downs_success_rate"] = team["defense"][
+1139                "passingDowns"
+1140            ]["successRate"]
+1141            row_df["defense_passing_downs_explosiveness"] = team["defense"][
+1142                "passingDowns"
+1143            ]["explosiveness"]
+1144
+1145            row_df["defense_rushing_plays_rate"] = team[
+1146                "defense"]["rushingPlays"]["rate"]
+1147            row_df["defense_rushing_plays_ppa"] = team[
+1148                "defense"]["rushingPlays"]["ppa"]
+1149            row_df["defense_rushing_plays_total_ppa"] = team[
+1150                "defense"]["rushingPlays"]["totalPPA"]
+1151            row_df["defense_rushing_plays_success_rate"] = team["defense"][
+1152                "rushingPlays"
+1153            ]["successRate"]
+1154            row_df["defense_rushing_plays_explosiveness"] = team["defense"][
+1155                "rushingPlays"
+1156            ]["explosiveness"]
+1157
+1158            row_df["defense_passing_plays_rate"] = team[
+1159                "defense"]["passingPlays"]["rate"]
+1160            row_df["defense_passing_plays_ppa"] = team[
+1161                "defense"]["passingPlays"]["ppa"]
+1162            row_df["defense_passing_plays_total_ppa"] = team[
+1163                "defense"]["passingPlays"]["totalPPA"]
+1164            row_df["defense_passing_plays_success_rate"] = team["defense"][
+1165                "passingPlays"
+1166            ]["successRate"]
+1167            row_df["defense_passing_plays_explosiveness"] = team["defense"][
+1168                "rushingPlays"
+1169            ]["explosiveness"]
+1170
+1171        final_df = pd.concat([final_df, row_df], ignore_index=True)
+1172        del row_df
+1173        del t_season, t_conf, t_team
 1174
-1175        final_df = pd.concat([final_df, row_df], ignore_index=True)
-1176        del row_df
-1177        del t_season, t_conf, t_team
-1178
-1179    return final_df
+1175    return final_df
 
@@ -5103,566 +5095,566 @@

Returns

-
1182def get_cfbd_advanced_team_game_stats(
-1183    api_key: str = None,
-1184    api_key_dir: str = None,
-1185    season: int = None,
-1186    team: str = None,
-1187    # `year` and/or `team` need to be not null for this function to work.
-1188    week: int = None,
-1189    opponent: str = None,
-1190    exclude_garbage_time: bool = False,
-1191    season_type: str = "both",  # "regular", "postseason", or "both"
-1192    return_as_dict: bool = False,
-1193):
-1194    """
-1195    Allows you to get advanced CFB team game stats data from the CFBD API.
-1196
-1197    Parameters
-1198    ----------
-1199
-1200    `api_key` (str, optional):
-1201        Semi-optional argument.
-1202        If `api_key` is null, this function will attempt to load a CFBD API key
-1203        from the python environment, or from a file on this computer.
-1204        If `api_key` is not null,
-1205        this function will automatically assume that the
-1206        inputted `api_key` is a valid CFBD API key.
-1207
-1208    `api_key_dir` (str, optional):
-1209        Optional argument.
-1210        If `api_key` is set to am empty string, this variable is ignored.
-1211        If `api_key_dir` is null, and `api_key` is null,
-1212        this function will try to find
-1213        a CFBD API key file in this user's home directory.
-1214        If `api_key_dir` is set to a string, and `api_key` is null,
-1215        this function will assume that `api_key_dir` is a directory,
-1216        and will try to find a CFBD API key file in that directory.
-1217
-1218    `season` (int, semi-mandatory):
-1219        Semi-required argument.
-1220        Specifies the season you want CFB team game stats data from.
-1221        This must be specified, otherwise this package, and by extension
-1222        the CFBD API, will not accept the request
-1223        to get CFB team season stats data.
-1224        This or `team` must be set
-1225        to a valid non-null variable for this to function.
-1226
-1227    `team` (str, semi-mandatory):
-1228        Semi-required argument.
-1229        Specifies the season you want advanced CFB team game stats data from.
-1230        This must be specified, otherwise this package, and by extension
-1231        the CFBD API, will not accept
-1232        the request to get CFB team season stats data.
-1233        This or `season` must be set
-1234        to a valid non-null variable for this to function.
-1235
-1236    `week` (int, optional):
-1237        Optional argument.
-1238        If `week` is set to an integer, this function will attempt
-1239        to load CFB team game from games in that season, and that week.
-1240
-1241    `opponent` (str, optional):
-1242        Optional argument.
-1243        If you only want games from a specific opponent,
-1244        set `opponent` to the name of that team.
-1245
-1246
-1247    `exclude_garbage_time` (bool, optional):
-1248        Optional argument.
-1249        If you want to filter out plays where
-1250        the result of the game is largely decided,
-1251        set `exclude_garbage_time = True`.
-1252        Default behavior is that this variable is set to
-1253        `False` when this function is called.
-1254
-1255    `season_type` (str, semi-optional):
-1256        Semi-optional argument.
-1257        By default, this will be set to "regular", for the CFB regular season.
-1258        If you want CFB team game stats, set `season_type` to "postseason".
-1259        If `season_type` is set to anything but "regular" or "postseason",
-1260        a `ValueError()` will be raised.
-1261
-1262    `return_as_dict` (bool, semi-optional):
-1263        Semi-optional argument.
-1264        If you want this function to return
-1265        the data as a dictionary (read: JSON object),
-1266        instead of a pandas `DataFrame` object,
-1267        set `return_as_dict` to `True`.
-1268
-1269
-1270    Usage
-1271    ----------
-1272    ```
-1273    import time
-1274
-1275    from cfbd_json_py.stats import get_cfbd_advanced_team_game_stats
-1276
-1277
-1278    cfbd_key = "tigersAreAwesome"  # placeholder for your CFBD API Key.
-1279
-1280    if cfbd_key != "tigersAreAwesome":
-1281        print(
-1282            "Using the user's API key declared in this script " +
-1283            "for this example."
-1284        )
-1285
-1286        # Get advanced CFBD team game stats for week 10 of the 2020 CFB season.
-1287        print("Get advanced CFBD team game stats for the 2020 CFB season.")
-1288        json_data = get_cfbd_advanced_team_game_stats(
-1289            api_key=cfbd_key,
-1290            season=2020,
-1291            week=10
-1292        )
-1293        print(json_data)
-1294        time.sleep(5)
-1295
-1296        # Get advanced CFBD team game stats for week 10 of the 2020 CFB season,
-1297        # but exclude plays that happen in garbage time.
-1298        print("Get advanced CFBD team game stats for the 2020 CFB season.")
-1299        json_data = get_cfbd_advanced_team_game_stats(
-1300            api_key=cfbd_key,
-1301            season=2020,
-1302            week=10,
-1303            exclude_garbage_time=True
-1304        )
-1305        print(json_data)
-1306        time.sleep(5)
-1307
-1308        # Get advanced CFBD team game stats for the 2020 CFB season.
-1309        print("Get advanced CFBD team game stats for the 2020 CFB season.")
-1310        json_data = get_cfbd_advanced_team_game_stats(
-1311            api_key=cfbd_key,
-1312            season=2020
-1313        )
-1314        print(json_data)
-1315        time.sleep(5)
-1316
-1317        # Get advanced CFBD team game stats for
-1318        # the University of Cincinnati Football Team in the 2020 CFB season.
-1319        print(
-1320            "Get advanced CFBD team game stats for " +
-1321            "the University of Cincinnati Football Team " +
-1322            "in the 2020 CFB season."
-1323        )
-1324        json_data = get_cfbd_advanced_team_game_stats(
-1325            api_key=cfbd_key,
-1326            season=2020,
-1327            opponent="Ohio"
-1328        )
-1329        print(json_data)
-1330        time.sleep(5)
-1331
-1332        # Get advanced CFBD team game stats for teams that faced off
-1333        # against the Ohio Bobcats Football Team in the 2020 CFB season.
-1334        print(
-1335            "Get advanced CFBD team game stats for teams that " +
-1336            "faced off against the Ohio Bobcats Football Team " +
-1337            "in the 2020 CFB season."
-1338        )
-1339        json_data = get_cfbd_advanced_team_game_stats(
-1340            api_key=cfbd_key,
-1341            season=2020,
-1342            opponent="Ohio"
-1343        )
-1344        print(json_data)
-1345        time.sleep(5)
-1346
-1347        # Get advanced CFBD team game stats for just
-1348        # postseason games in the 2020 CFB season.
-1349        print(
-1350            "Get advanced CFBD team game stats for just postseason games " +
-1351            "in the 2020 CFB season."
-1352        )
-1353        json_data = get_cfbd_advanced_team_game_stats(
-1354            api_key=cfbd_key,
-1355            season=2020,
-1356            week=10
-1357        )
-1358        print(json_data)
-1359        time.sleep(5)
-1360
-1361
-1362        # You can also tell this function to just return the API call as
-1363        # a Dictionary (read: JSON) object.
-1364        print(
-1365            "You can also tell this function to just return the API call " +
-1366            "as a Dictionary (read: JSON) object."
-1367        )
-1368        json_data = get_cfbd_advanced_team_game_stats(
-1369            api_key=cfbd_key,
-1370            season=2020,
-1371            week=10,
-1372            return_as_dict=True
-1373        )
-1374        print(json_data)
-1375
-1376    else:
-1377        # Alternatively, if the CFBD API key exists in this python environment,
-1378        # or it's been set by cfbd_json_py.utls.set_cfbd_api_token(),
-1379        # you could just call these functions directly,
-1380        # without setting the API key in the script.
-1381        print(
-1382            "Using the user's API key supposedly loaded " +
-1383            "into this python environment for this example."
-1384        )
-1385
-1386        # Get advanced CFBD team game stats for week 10 of the 2020 CFB season.
-1387        print("Get advanced CFBD team game stats for the 2020 CFB season.")
-1388        json_data = get_cfbd_advanced_team_game_stats(
-1389            season=2020,
-1390            week=10
-1391        )
-1392        print(json_data)
-1393        time.sleep(5)
-1394
-1395        # Get advanced CFBD team game stats for week 10 of the 2020 CFB season,
-1396        # but exclude plays that happen in garbage time.
-1397        print("Get advanced CFBD team game stats for the 2020 CFB season.")
-1398        json_data = get_cfbd_advanced_team_game_stats(
-1399            season=2020,
-1400            week=10,
-1401            exclude_garbage_time=True
-1402        )
-1403        print(json_data)
-1404        time.sleep(5)
-1405
-1406        # Get advanced CFBD team game stats for the 2020 CFB season.
-1407        print("Get advanced CFBD team game stats for the 2020 CFB season.")
-1408        json_data = get_cfbd_advanced_team_game_stats(
-1409            season=2020
-1410        )
-1411        print(json_data)
-1412        time.sleep(5)
-1413
-1414        # Get advanced CFBD team game stats for
-1415        # the University of Cincinnati Football Team in the 2020 CFB season.
-1416        print(
-1417            "Get advanced CFBD team game stats for " +
-1418            "the University of Cincinnati Football Team " +
-1419            "in the 2020 CFB season."
+                
1178def get_cfbd_advanced_team_game_stats(
+1179    api_key: str = None,
+1180    api_key_dir: str = None,
+1181    season: int = None,
+1182    team: str = None,
+1183    # `year` and/or `team` need to be not null for this function to work.
+1184    week: int = None,
+1185    opponent: str = None,
+1186    exclude_garbage_time: bool = False,
+1187    season_type: str = "both",  # "regular", "postseason", or "both"
+1188    return_as_dict: bool = False,
+1189):
+1190    """
+1191    Allows you to get advanced CFB team game stats data from the CFBD API.
+1192
+1193    Parameters
+1194    ----------
+1195
+1196    `api_key` (str, optional):
+1197        Semi-optional argument.
+1198        If `api_key` is null, this function will attempt to load a CFBD API key
+1199        from the python environment, or from a file on this computer.
+1200        If `api_key` is not null,
+1201        this function will automatically assume that the
+1202        inputted `api_key` is a valid CFBD API key.
+1203
+1204    `api_key_dir` (str, optional):
+1205        Optional argument.
+1206        If `api_key` is set to am empty string, this variable is ignored.
+1207        If `api_key_dir` is null, and `api_key` is null,
+1208        this function will try to find
+1209        a CFBD API key file in this user's home directory.
+1210        If `api_key_dir` is set to a string, and `api_key` is null,
+1211        this function will assume that `api_key_dir` is a directory,
+1212        and will try to find a CFBD API key file in that directory.
+1213
+1214    `season` (int, semi-mandatory):
+1215        Semi-required argument.
+1216        Specifies the season you want CFB team game stats data from.
+1217        This must be specified, otherwise this package, and by extension
+1218        the CFBD API, will not accept the request
+1219        to get CFB team season stats data.
+1220        This or `team` must be set
+1221        to a valid non-null variable for this to function.
+1222
+1223    `team` (str, semi-mandatory):
+1224        Semi-required argument.
+1225        Specifies the season you want advanced CFB team game stats data from.
+1226        This must be specified, otherwise this package, and by extension
+1227        the CFBD API, will not accept
+1228        the request to get CFB team season stats data.
+1229        This or `season` must be set
+1230        to a valid non-null variable for this to function.
+1231
+1232    `week` (int, optional):
+1233        Optional argument.
+1234        If `week` is set to an integer, this function will attempt
+1235        to load CFB team game from games in that season, and that week.
+1236
+1237    `opponent` (str, optional):
+1238        Optional argument.
+1239        If you only want games from a specific opponent,
+1240        set `opponent` to the name of that team.
+1241
+1242
+1243    `exclude_garbage_time` (bool, optional):
+1244        Optional argument.
+1245        If you want to filter out plays where
+1246        the result of the game is largely decided,
+1247        set `exclude_garbage_time = True`.
+1248        Default behavior is that this variable is set to
+1249        `False` when this function is called.
+1250
+1251    `season_type` (str, semi-optional):
+1252        Semi-optional argument.
+1253        By default, this will be set to "regular", for the CFB regular season.
+1254        If you want CFB team game stats, set `season_type` to "postseason".
+1255        If `season_type` is set to anything but "regular" or "postseason",
+1256        a `ValueError()` will be raised.
+1257
+1258    `return_as_dict` (bool, semi-optional):
+1259        Semi-optional argument.
+1260        If you want this function to return
+1261        the data as a dictionary (read: JSON object),
+1262        instead of a pandas `DataFrame` object,
+1263        set `return_as_dict` to `True`.
+1264
+1265
+1266    Usage
+1267    ----------
+1268    ```
+1269    import time
+1270
+1271    from cfbd_json_py.stats import get_cfbd_advanced_team_game_stats
+1272
+1273
+1274    cfbd_key = "tigersAreAwesome"  # placeholder for your CFBD API Key.
+1275
+1276    if cfbd_key != "tigersAreAwesome":
+1277        print(
+1278            "Using the user's API key declared in this script " +
+1279            "for this example."
+1280        )
+1281
+1282        # Get advanced CFBD team game stats for week 10 of the 2020 CFB season.
+1283        print("Get advanced CFBD team game stats for the 2020 CFB season.")
+1284        json_data = get_cfbd_advanced_team_game_stats(
+1285            api_key=cfbd_key,
+1286            season=2020,
+1287            week=10
+1288        )
+1289        print(json_data)
+1290        time.sleep(5)
+1291
+1292        # Get advanced CFBD team game stats for week 10 of the 2020 CFB season,
+1293        # but exclude plays that happen in garbage time.
+1294        print("Get advanced CFBD team game stats for the 2020 CFB season.")
+1295        json_data = get_cfbd_advanced_team_game_stats(
+1296            api_key=cfbd_key,
+1297            season=2020,
+1298            week=10,
+1299            exclude_garbage_time=True
+1300        )
+1301        print(json_data)
+1302        time.sleep(5)
+1303
+1304        # Get advanced CFBD team game stats for the 2020 CFB season.
+1305        print("Get advanced CFBD team game stats for the 2020 CFB season.")
+1306        json_data = get_cfbd_advanced_team_game_stats(
+1307            api_key=cfbd_key,
+1308            season=2020
+1309        )
+1310        print(json_data)
+1311        time.sleep(5)
+1312
+1313        # Get advanced CFBD team game stats for
+1314        # the University of Cincinnati Football Team in the 2020 CFB season.
+1315        print(
+1316            "Get advanced CFBD team game stats for " +
+1317            "the University of Cincinnati Football Team " +
+1318            "in the 2020 CFB season."
+1319        )
+1320        json_data = get_cfbd_advanced_team_game_stats(
+1321            api_key=cfbd_key,
+1322            season=2020,
+1323            opponent="Ohio"
+1324        )
+1325        print(json_data)
+1326        time.sleep(5)
+1327
+1328        # Get advanced CFBD team game stats for teams that faced off
+1329        # against the Ohio Bobcats Football Team in the 2020 CFB season.
+1330        print(
+1331            "Get advanced CFBD team game stats for teams that " +
+1332            "faced off against the Ohio Bobcats Football Team " +
+1333            "in the 2020 CFB season."
+1334        )
+1335        json_data = get_cfbd_advanced_team_game_stats(
+1336            api_key=cfbd_key,
+1337            season=2020,
+1338            opponent="Ohio"
+1339        )
+1340        print(json_data)
+1341        time.sleep(5)
+1342
+1343        # Get advanced CFBD team game stats for just
+1344        # postseason games in the 2020 CFB season.
+1345        print(
+1346            "Get advanced CFBD team game stats for just postseason games " +
+1347            "in the 2020 CFB season."
+1348        )
+1349        json_data = get_cfbd_advanced_team_game_stats(
+1350            api_key=cfbd_key,
+1351            season=2020,
+1352            week=10
+1353        )
+1354        print(json_data)
+1355        time.sleep(5)
+1356
+1357
+1358        # You can also tell this function to just return the API call as
+1359        # a Dictionary (read: JSON) object.
+1360        print(
+1361            "You can also tell this function to just return the API call " +
+1362            "as a Dictionary (read: JSON) object."
+1363        )
+1364        json_data = get_cfbd_advanced_team_game_stats(
+1365            api_key=cfbd_key,
+1366            season=2020,
+1367            week=10,
+1368            return_as_dict=True
+1369        )
+1370        print(json_data)
+1371
+1372    else:
+1373        # Alternatively, if the CFBD API key exists in this python environment,
+1374        # or it's been set by cfbd_json_py.utls.set_cfbd_api_token(),
+1375        # you could just call these functions directly,
+1376        # without setting the API key in the script.
+1377        print(
+1378            "Using the user's API key supposedly loaded " +
+1379            "into this python environment for this example."
+1380        )
+1381
+1382        # Get advanced CFBD team game stats for week 10 of the 2020 CFB season.
+1383        print("Get advanced CFBD team game stats for the 2020 CFB season.")
+1384        json_data = get_cfbd_advanced_team_game_stats(
+1385            season=2020,
+1386            week=10
+1387        )
+1388        print(json_data)
+1389        time.sleep(5)
+1390
+1391        # Get advanced CFBD team game stats for week 10 of the 2020 CFB season,
+1392        # but exclude plays that happen in garbage time.
+1393        print("Get advanced CFBD team game stats for the 2020 CFB season.")
+1394        json_data = get_cfbd_advanced_team_game_stats(
+1395            season=2020,
+1396            week=10,
+1397            exclude_garbage_time=True
+1398        )
+1399        print(json_data)
+1400        time.sleep(5)
+1401
+1402        # Get advanced CFBD team game stats for the 2020 CFB season.
+1403        print("Get advanced CFBD team game stats for the 2020 CFB season.")
+1404        json_data = get_cfbd_advanced_team_game_stats(
+1405            season=2020
+1406        )
+1407        print(json_data)
+1408        time.sleep(5)
+1409
+1410        # Get advanced CFBD team game stats for
+1411        # the University of Cincinnati Football Team in the 2020 CFB season.
+1412        print(
+1413            "Get advanced CFBD team game stats for " +
+1414            "the University of Cincinnati Football Team " +
+1415            "in the 2020 CFB season."
+1416        )
+1417        json_data = get_cfbd_advanced_team_game_stats(
+1418            season=2020,
+1419            opponent="Ohio"
 1420        )
-1421        json_data = get_cfbd_advanced_team_game_stats(
-1422            season=2020,
-1423            opponent="Ohio"
-1424        )
-1425        print(json_data)
-1426        time.sleep(5)
-1427
-1428        # Get advanced CFBD team game stats for teams that faced off
-1429        # against the Ohio Bobcats Football Team in the 2020 CFB season.
-1430        print(
-1431            "Get advanced CFBD team game stats for teams that " +
-1432            "faced off against the Ohio Bobcats Football Team " +
-1433            "in the 2020 CFB season."
+1421        print(json_data)
+1422        time.sleep(5)
+1423
+1424        # Get advanced CFBD team game stats for teams that faced off
+1425        # against the Ohio Bobcats Football Team in the 2020 CFB season.
+1426        print(
+1427            "Get advanced CFBD team game stats for teams that " +
+1428            "faced off against the Ohio Bobcats Football Team " +
+1429            "in the 2020 CFB season."
+1430        )
+1431        json_data = get_cfbd_advanced_team_game_stats(
+1432            season=2020,
+1433            opponent="Ohio"
 1434        )
-1435        json_data = get_cfbd_advanced_team_game_stats(
-1436            season=2020,
-1437            opponent="Ohio"
-1438        )
-1439        print(json_data)
-1440        time.sleep(5)
-1441
-1442        # Get advanced CFBD team game stats for just
-1443        # postseason games in the 2020 CFB season.
-1444        print(
-1445            "Get advanced CFBD team game stats for just postseason games " +
-1446            "in the 2020 CFB season."
+1435        print(json_data)
+1436        time.sleep(5)
+1437
+1438        # Get advanced CFBD team game stats for just
+1439        # postseason games in the 2020 CFB season.
+1440        print(
+1441            "Get advanced CFBD team game stats for just postseason games " +
+1442            "in the 2020 CFB season."
+1443        )
+1444        json_data = get_cfbd_advanced_team_game_stats(
+1445            season=2020,
+1446            week=10
 1447        )
-1448        json_data = get_cfbd_advanced_team_game_stats(
-1449            season=2020,
-1450            week=10
-1451        )
-1452        print(json_data)
-1453        time.sleep(5)
-1454
-1455
-1456        # You can also tell this function to just return the API call as
-1457        # a Dictionary (read: JSON) object.
-1458        print(
-1459            "You can also tell this function to just return the API call " +
-1460            "as a Dictionary (read: JSON) object."
-1461        )
-1462        json_data = get_cfbd_advanced_team_game_stats(
-1463            season=2020,
-1464            week=10,
-1465            return_as_dict=True
-1466        )
-1467        print(json_data)
-1468
-1469    ```
-1470    Returns
-1471    ----------
-1472    A pandas `DataFrame` object with advanced team season stats data,
-1473    or (if `return_as_dict` is set to `True`)
-1474    a dictionary object with a with advanced team season stats data.
-1475    """
-1476    now = datetime.now()
-1477    url = "https://api.collegefootballdata.com/stats/game/advanced"
-1478    row_df = pd.DataFrame()
-1479    final_df = pd.DataFrame()
-1480
-1481    if api_key is not None:
-1482        real_api_key = api_key
-1483        del api_key
-1484    else:
-1485        real_api_key = get_cfbd_api_token(api_key_dir=api_key_dir)
-1486
-1487    if real_api_key == "tigersAreAwesome":
-1488        raise ValueError(
-1489            "You actually need to change `cfbd_key` to your CFBD API key."
-1490        )
-1491    elif "Bearer " in real_api_key:
-1492        pass
-1493    elif "Bearer" in real_api_key:
-1494        real_api_key = real_api_key.replace("Bearer", "Bearer ")
-1495    else:
-1496        real_api_key = "Bearer " + real_api_key
-1497
-1498    if season is not None and (season > (now.year + 1)):
-1499        raise ValueError(f"`season` cannot be greater than {season}.")
-1500    elif season is not None and season < 1869:
-1501        raise ValueError("`season` cannot be less than 1869.")
-1502
-1503    if season_type == "regular" or season_type == "postseason" \
-1504            or season_type == "both":
-1505        pass
-1506    else:
-1507        raise ValueError(
-1508            '`season_type` must be set to either ' +
-1509            '"regular","postseason", or "both".'
-1510        )
-1511
-1512    gt_str = ""
-1513
-1514    # URL builder
-1515    ##########################################################################
-1516
-1517    if exclude_garbage_time is True:
-1518        gt_str = "true"
-1519    elif exclude_garbage_time is False:
-1520        gt_str = "false"
-1521
-1522    if season is not None and team is not None:
-1523        url += f"?year={season}&team={team}"
-1524    elif season is not None:
-1525        url += f"?year={season}"
-1526    elif team is not None:
-1527        url += f"?team={team}"
-1528
-1529    if exclude_garbage_time is not None:
-1530        url += f"&excludeGarbageTime={gt_str}"
-1531
-1532    if week is not None:
-1533        url += f"&week={week}"
-1534
-1535    if opponent is not None:
-1536        url += f"&opponent={opponent}"
-1537
-1538    headers = {
-1539        "Authorization": f"{real_api_key}",
-1540        "accept": "application/json"
-1541    }
-1542
-1543    response = requests.get(url, headers=headers)
-1544
-1545    if response.status_code == 200:
-1546        pass
-1547    elif response.status_code == 401:
-1548        raise ConnectionRefusedError(
-1549            "Could not connect. The connection was refused." +
-1550            "\nHTTP Status Code 401."
+1448        print(json_data)
+1449        time.sleep(5)
+1450
+1451
+1452        # You can also tell this function to just return the API call as
+1453        # a Dictionary (read: JSON) object.
+1454        print(
+1455            "You can also tell this function to just return the API call " +
+1456            "as a Dictionary (read: JSON) object."
+1457        )
+1458        json_data = get_cfbd_advanced_team_game_stats(
+1459            season=2020,
+1460            week=10,
+1461            return_as_dict=True
+1462        )
+1463        print(json_data)
+1464
+1465    ```
+1466    Returns
+1467    ----------
+1468    A pandas `DataFrame` object with advanced team season stats data,
+1469    or (if `return_as_dict` is set to `True`)
+1470    a dictionary object with a with advanced team season stats data.
+1471    """
+1472    now = datetime.now()
+1473    url = "https://api.collegefootballdata.com/stats/game/advanced"
+1474    row_df = pd.DataFrame()
+1475    final_df = pd.DataFrame()
+1476
+1477    if api_key is not None:
+1478        real_api_key = api_key
+1479        del api_key
+1480    else:
+1481        real_api_key = get_cfbd_api_token(api_key_dir=api_key_dir)
+1482
+1483    if real_api_key == "tigersAreAwesome":
+1484        raise ValueError(
+1485            "You actually need to change `cfbd_key` to your CFBD API key."
+1486        )
+1487    elif "Bearer " in real_api_key:
+1488        pass
+1489    elif "Bearer" in real_api_key:
+1490        real_api_key = real_api_key.replace("Bearer", "Bearer ")
+1491    else:
+1492        real_api_key = "Bearer " + real_api_key
+1493
+1494    if season is not None and (season > (now.year + 1)):
+1495        raise ValueError(f"`season` cannot be greater than {season}.")
+1496    elif season is not None and season < 1869:
+1497        raise ValueError("`season` cannot be less than 1869.")
+1498
+1499    if season_type == "regular" or season_type == "postseason" \
+1500            or season_type == "both":
+1501        pass
+1502    else:
+1503        raise ValueError(
+1504            '`season_type` must be set to either ' +
+1505            '"regular","postseason", or "both".'
+1506        )
+1507
+1508    gt_str = ""
+1509
+1510    # URL builder
+1511    ##########################################################################
+1512
+1513    if exclude_garbage_time is True:
+1514        gt_str = "true"
+1515    elif exclude_garbage_time is False:
+1516        gt_str = "false"
+1517
+1518    if season is not None and team is not None:
+1519        url += f"?year={season}&team={team}"
+1520    elif season is not None:
+1521        url += f"?year={season}"
+1522    elif team is not None:
+1523        url += f"?team={team}"
+1524
+1525    if exclude_garbage_time is not None:
+1526        url += f"&excludeGarbageTime={gt_str}"
+1527
+1528    if week is not None:
+1529        url += f"&week={week}"
+1530
+1531    if opponent is not None:
+1532        url += f"&opponent={opponent}"
+1533
+1534    headers = {
+1535        "Authorization": f"{real_api_key}",
+1536        "accept": "application/json"
+1537    }
+1538
+1539    response = requests.get(url, headers=headers)
+1540
+1541    if response.status_code == 200:
+1542        pass
+1543    elif response.status_code == 401:
+1544        raise ConnectionRefusedError(
+1545            "Could not connect. The connection was refused." +
+1546            "\nHTTP Status Code 401."
+1547        )
+1548    else:
+1549        raise ConnectionError(
+1550            f"Could not connect.\nHTTP Status code {response.status_code}"
 1551        )
-1552    else:
-1553        raise ConnectionError(
-1554            f"Could not connect.\nHTTP Status code {response.status_code}"
-1555        )
-1556
-1557    json_data = response.json()
-1558
-1559    if return_as_dict is True:
-1560        return json_data
-1561
-1562    for team in tqdm(json_data):
-1563        t_game_id = team["gameId"]
-1564        t_week = team["week"]
-1565        t_team = team["team"]
-1566        t_opponent = team["opponent"]
-1567
-1568        if season is not None:
-1569            row_df = pd.DataFrame(
-1570                {
-1571                    "season": season,
-1572                    "game_id": t_game_id,
-1573                    "week": t_week,
-1574                    "team_name": t_team,
-1575                    "opponent_name": t_opponent,
-1576                },
-1577                index=[0],
-1578            )
-1579        else:
-1580
-1581            row_df = pd.DataFrame(
-1582                {
-1583                    "game_id": t_game_id,
-1584                    "week": t_week,
-1585                    "team_name": t_team,
-1586                    "opponent_name": t_opponent,
-1587                },
-1588                index=[0],
-1589            )
-1590
-1591        # offense
-1592        if "offense" not in team:
-1593            logging.debug(
-1594                "Key `[offense]` not found for " +
-1595                f"Game ID #{t_game_id} and {t_team}, "
-1596                + f"which happened in week {t_week}."
-1597            )
-1598        else:
-1599            row_df["offense_plays"] = team["offense"]["plays"]
-1600            row_df["offense_drives"] = team["offense"]["drives"]
-1601            row_df["offense_ppa"] = team["offense"]["ppa"]
-1602            row_df["offense_total_ppa"] = team["offense"]["totalPPA"]
-1603            row_df["offense_success_rate"] = team["offense"]["successRate"]
-1604            row_df["offense_explosiveness"] = team["offense"]["explosiveness"]
-1605            row_df["offense_power_success"] = team["offense"]["powerSuccess"]
-1606            row_df["offense_stuff_rate"] = team["offense"]["stuffRate"]
-1607            row_df["offense_line_yards_avg"] = team["offense"]["lineYards"]
-1608            row_df["offense_line_yards_total"] = team["offense"][
-1609                "lineYardsTotal"
-1610            ]
-1611            row_df["offense_second_level_yards_avg"] = team["offense"][
-1612                "secondLevelYards"
-1613            ]
-1614            row_df["offense_second_level_yards_total"] = team["offense"][
-1615                "secondLevelYardsTotal"
-1616            ]
-1617            row_df["offense_open_field_yards_avg"] = team["offense"][
-1618                "openFieldYards"
-1619            ]
-1620            row_df["offense_open_field_yards_total"] = team["offense"][
-1621                "secondLevelYardsTotal"
-1622            ]
-1623
-1624            row_df["offense_standard_downs_ppa"] = team[
-1625                "offense"]["standardDowns"]["ppa"]
-1626            row_df["offense_standard_downs_success_rate"] = team[
-1627                "offense"]["standardDowns"]["successRate"]
-1628            row_df["offense_standard_downs_explosiveness"] = team["offense"][
-1629                "standardDowns"
-1630            ]["explosiveness"]
-1631
-1632            row_df["offense_passing_downs_ppa"] = team[
-1633                "offense"]["passingDowns"]["ppa"]
-1634            row_df["offense_passing_downs_success_rate"] = team[
-1635                "offense"]["passingDowns"]["successRate"]
-1636            row_df["offense_passing_downs_explosiveness"] = team["offense"][
-1637                "passingDowns"
-1638            ]["explosiveness"]
-1639
-1640            row_df["offense_rushing_plays_ppa"] = team[
-1641                "offense"]["rushingPlays"]["ppa"]
-1642            row_df["offense_rushing_plays_total_ppa"] = team[
-1643                "offense"]["rushingPlays"]["totalPPA"]
-1644            row_df["offense_rushing_plays_success_rate"] = team[
-1645                "offense"]["rushingPlays"]["successRate"]
-1646            row_df["offense_rushing_plays_explosiveness"] = team[
-1647                "offense"]["rushingPlays"]["explosiveness"]
-1648
-1649            row_df["offense_passing_plays_ppa"] = team[
-1650                "offense"]["passingPlays"]["ppa"]
-1651            row_df["offense_passing_plays_total_ppa"] = team[
-1652                "offense"]["passingPlays"]["totalPPA"]
-1653            row_df["offense_passing_plays_success_rate"] = team[
-1654                "offense"]["passingPlays"]["successRate"]
-1655            row_df["offense_passing_plays_explosiveness"] = team[
-1656                "offense"]["rushingPlays"]["explosiveness"]
-1657
-1658        # defense
-1659        if "defense" not in team:
-1660            logging.debug(
-1661                "Key `[defense]` not found for " +
-1662                f"Game ID #{t_game_id} and {t_team}, "
-1663                + f"which happened in week {t_week}."
-1664            )
-1665        else:
-1666            row_df["defense_plays"] = team["defense"]["plays"]
-1667            row_df["defense_drives"] = team["defense"]["drives"]
-1668            row_df["defense_ppa"] = team["defense"]["ppa"]
-1669            row_df["defense_total_ppa"] = team["defense"]["totalPPA"]
-1670            row_df["defense_success_rate"] = team["defense"]["successRate"]
-1671            row_df["defense_explosiveness"] = team["defense"]["explosiveness"]
-1672            row_df["defense_power_success"] = team["defense"]["powerSuccess"]
-1673            row_df["defense_stuff_rate"] = team["defense"]["stuffRate"]
-1674            row_df["defense_line_yards_avg"] = team["defense"]["lineYards"]
-1675            row_df["defense_line_yards_total"] = team["defense"][
-1676                "lineYardsTotal"
-1677            ]
-1678            row_df["defense_second_level_yards_avg"] = team["defense"][
-1679                "secondLevelYards"
-1680            ]
-1681            row_df["defense_second_level_yards_total"] = team["defense"][
-1682                "secondLevelYardsTotal"
-1683            ]
-1684            row_df["defense_open_field_yards_avg"] = team["defense"][
-1685                "openFieldYards"
-1686            ]
-1687            row_df["defense_open_field_yards_total"] = team["defense"][
-1688                "secondLevelYardsTotal"
-1689            ]
-1690            row_df["defense_total_opportunities"] = team["defense"][
-1691                "totalOpportunies"
-1692            ]
-1693            row_df["defense_points_per_opportunity"] = team["defense"][
-1694                "pointsPerOpportunity"
-1695            ]
-1696
-1697            row_df["defense_standard_downs_ppa"] = team[
-1698                "defense"]["standardDowns"]["ppa"]
-1699            row_df["defense_standard_downs_success_rate"] = team["defense"][
-1700                "standardDowns"
-1701            ]["successRate"]
-1702            row_df["defense_standard_downs_explosiveness"] = team["defense"][
-1703                "standardDowns"
-1704            ]["explosiveness"]
-1705
-1706            row_df["defense_passing_downs_ppa"] = team[
-1707                "defense"]["passingDowns"]["ppa"]
-1708            row_df["defense_passing_downs_success_rate"] = team["defense"][
-1709                "passingDowns"
-1710            ]["successRate"]
-1711            row_df["defense_passing_downs_explosiveness"] = team["defense"][
-1712                "passingDowns"
-1713            ]["explosiveness"]
-1714
-1715            row_df["defense_rushing_plays_ppa"] = team[
-1716                "defense"]["rushingPlays"]["ppa"]
-1717            row_df["defense_rushing_plays_total_ppa"] = team[
-1718                "defense"]["rushingPlays"]["totalPPA"]
-1719            row_df["defense_rushing_plays_success_rate"] = team["defense"][
-1720                "rushingPlays"
-1721            ]["successRate"]
-1722            row_df["defense_rushing_plays_explosiveness"] = team["defense"][
-1723                "rushingPlays"
-1724            ]["explosiveness"]
-1725
-1726            row_df["defense_passing_plays_ppa"] = team[
-1727                "defense"]["passingPlays"]["ppa"]
-1728            row_df["defense_passing_plays_total_ppa"] = team[
-1729                "defense"]["passingPlays"]["totalPPA"]
-1730            row_df["defense_passing_plays_success_rate"] = team["defense"][
-1731                "passingPlays"
-1732            ]["successRate"]
-1733            row_df["defense_passing_plays_explosiveness"] = team["defense"][
-1734                "rushingPlays"
-1735            ]["explosiveness"]
+1552
+1553    json_data = response.json()
+1554
+1555    if return_as_dict is True:
+1556        return json_data
+1557
+1558    for team in tqdm(json_data):
+1559        t_game_id = team["gameId"]
+1560        t_week = team["week"]
+1561        t_team = team["team"]
+1562        t_opponent = team["opponent"]
+1563
+1564        if season is not None:
+1565            row_df = pd.DataFrame(
+1566                {
+1567                    "season": season,
+1568                    "game_id": t_game_id,
+1569                    "week": t_week,
+1570                    "team_name": t_team,
+1571                    "opponent_name": t_opponent,
+1572                },
+1573                index=[0],
+1574            )
+1575        else:
+1576
+1577            row_df = pd.DataFrame(
+1578                {
+1579                    "game_id": t_game_id,
+1580                    "week": t_week,
+1581                    "team_name": t_team,
+1582                    "opponent_name": t_opponent,
+1583                },
+1584                index=[0],
+1585            )
+1586
+1587        # offense
+1588        if "offense" not in team:
+1589            logging.debug(
+1590                "Key `[offense]` not found for " +
+1591                f"Game ID #{t_game_id} and {t_team}, "
+1592                + f"which happened in week {t_week}."
+1593            )
+1594        else:
+1595            row_df["offense_plays"] = team["offense"]["plays"]
+1596            row_df["offense_drives"] = team["offense"]["drives"]
+1597            row_df["offense_ppa"] = team["offense"]["ppa"]
+1598            row_df["offense_total_ppa"] = team["offense"]["totalPPA"]
+1599            row_df["offense_success_rate"] = team["offense"]["successRate"]
+1600            row_df["offense_explosiveness"] = team["offense"]["explosiveness"]
+1601            row_df["offense_power_success"] = team["offense"]["powerSuccess"]
+1602            row_df["offense_stuff_rate"] = team["offense"]["stuffRate"]
+1603            row_df["offense_line_yards_avg"] = team["offense"]["lineYards"]
+1604            row_df["offense_line_yards_total"] = team["offense"][
+1605                "lineYardsTotal"
+1606            ]
+1607            row_df["offense_second_level_yards_avg"] = team["offense"][
+1608                "secondLevelYards"
+1609            ]
+1610            row_df["offense_second_level_yards_total"] = team["offense"][
+1611                "secondLevelYardsTotal"
+1612            ]
+1613            row_df["offense_open_field_yards_avg"] = team["offense"][
+1614                "openFieldYards"
+1615            ]
+1616            row_df["offense_open_field_yards_total"] = team["offense"][
+1617                "secondLevelYardsTotal"
+1618            ]
+1619
+1620            row_df["offense_standard_downs_ppa"] = team[
+1621                "offense"]["standardDowns"]["ppa"]
+1622            row_df["offense_standard_downs_success_rate"] = team[
+1623                "offense"]["standardDowns"]["successRate"]
+1624            row_df["offense_standard_downs_explosiveness"] = team["offense"][
+1625                "standardDowns"
+1626            ]["explosiveness"]
+1627
+1628            row_df["offense_passing_downs_ppa"] = team[
+1629                "offense"]["passingDowns"]["ppa"]
+1630            row_df["offense_passing_downs_success_rate"] = team[
+1631                "offense"]["passingDowns"]["successRate"]
+1632            row_df["offense_passing_downs_explosiveness"] = team["offense"][
+1633                "passingDowns"
+1634            ]["explosiveness"]
+1635
+1636            row_df["offense_rushing_plays_ppa"] = team[
+1637                "offense"]["rushingPlays"]["ppa"]
+1638            row_df["offense_rushing_plays_total_ppa"] = team[
+1639                "offense"]["rushingPlays"]["totalPPA"]
+1640            row_df["offense_rushing_plays_success_rate"] = team[
+1641                "offense"]["rushingPlays"]["successRate"]
+1642            row_df["offense_rushing_plays_explosiveness"] = team[
+1643                "offense"]["rushingPlays"]["explosiveness"]
+1644
+1645            row_df["offense_passing_plays_ppa"] = team[
+1646                "offense"]["passingPlays"]["ppa"]
+1647            row_df["offense_passing_plays_total_ppa"] = team[
+1648                "offense"]["passingPlays"]["totalPPA"]
+1649            row_df["offense_passing_plays_success_rate"] = team[
+1650                "offense"]["passingPlays"]["successRate"]
+1651            row_df["offense_passing_plays_explosiveness"] = team[
+1652                "offense"]["rushingPlays"]["explosiveness"]
+1653
+1654        # defense
+1655        if "defense" not in team:
+1656            logging.debug(
+1657                "Key `[defense]` not found for " +
+1658                f"Game ID #{t_game_id} and {t_team}, "
+1659                + f"which happened in week {t_week}."
+1660            )
+1661        else:
+1662            row_df["defense_plays"] = team["defense"]["plays"]
+1663            row_df["defense_drives"] = team["defense"]["drives"]
+1664            row_df["defense_ppa"] = team["defense"]["ppa"]
+1665            row_df["defense_total_ppa"] = team["defense"]["totalPPA"]
+1666            row_df["defense_success_rate"] = team["defense"]["successRate"]
+1667            row_df["defense_explosiveness"] = team["defense"]["explosiveness"]
+1668            row_df["defense_power_success"] = team["defense"]["powerSuccess"]
+1669            row_df["defense_stuff_rate"] = team["defense"]["stuffRate"]
+1670            row_df["defense_line_yards_avg"] = team["defense"]["lineYards"]
+1671            row_df["defense_line_yards_total"] = team["defense"][
+1672                "lineYardsTotal"
+1673            ]
+1674            row_df["defense_second_level_yards_avg"] = team["defense"][
+1675                "secondLevelYards"
+1676            ]
+1677            row_df["defense_second_level_yards_total"] = team["defense"][
+1678                "secondLevelYardsTotal"
+1679            ]
+1680            row_df["defense_open_field_yards_avg"] = team["defense"][
+1681                "openFieldYards"
+1682            ]
+1683            row_df["defense_open_field_yards_total"] = team["defense"][
+1684                "secondLevelYardsTotal"
+1685            ]
+1686            row_df["defense_total_opportunities"] = team["defense"][
+1687                "totalOpportunies"
+1688            ]
+1689            row_df["defense_points_per_opportunity"] = team["defense"][
+1690                "pointsPerOpportunity"
+1691            ]
+1692
+1693            row_df["defense_standard_downs_ppa"] = team[
+1694                "defense"]["standardDowns"]["ppa"]
+1695            row_df["defense_standard_downs_success_rate"] = team["defense"][
+1696                "standardDowns"
+1697            ]["successRate"]
+1698            row_df["defense_standard_downs_explosiveness"] = team["defense"][
+1699                "standardDowns"
+1700            ]["explosiveness"]
+1701
+1702            row_df["defense_passing_downs_ppa"] = team[
+1703                "defense"]["passingDowns"]["ppa"]
+1704            row_df["defense_passing_downs_success_rate"] = team["defense"][
+1705                "passingDowns"
+1706            ]["successRate"]
+1707            row_df["defense_passing_downs_explosiveness"] = team["defense"][
+1708                "passingDowns"
+1709            ]["explosiveness"]
+1710
+1711            row_df["defense_rushing_plays_ppa"] = team[
+1712                "defense"]["rushingPlays"]["ppa"]
+1713            row_df["defense_rushing_plays_total_ppa"] = team[
+1714                "defense"]["rushingPlays"]["totalPPA"]
+1715            row_df["defense_rushing_plays_success_rate"] = team["defense"][
+1716                "rushingPlays"
+1717            ]["successRate"]
+1718            row_df["defense_rushing_plays_explosiveness"] = team["defense"][
+1719                "rushingPlays"
+1720            ]["explosiveness"]
+1721
+1722            row_df["defense_passing_plays_ppa"] = team[
+1723                "defense"]["passingPlays"]["ppa"]
+1724            row_df["defense_passing_plays_total_ppa"] = team[
+1725                "defense"]["passingPlays"]["totalPPA"]
+1726            row_df["defense_passing_plays_success_rate"] = team["defense"][
+1727                "passingPlays"
+1728            ]["successRate"]
+1729            row_df["defense_passing_plays_explosiveness"] = team["defense"][
+1730                "rushingPlays"
+1731            ]["explosiveness"]
+1732
+1733        final_df = pd.concat([final_df, row_df], ignore_index=True)
+1734        del row_df
+1735        del t_game_id, t_week, t_team, t_opponent
 1736
-1737        final_df = pd.concat([final_df, row_df], ignore_index=True)
-1738        del row_df
-1739        del t_game_id, t_week, t_team, t_opponent
-1740
-1741    return final_df
+1737    return final_df
 
@@ -5972,156 +5964,156 @@

Returns

-
1744def get_cfbd_team_stat_categories(
-1745    api_key: str = None, api_key_dir: str = None, return_as_dict: bool = False
-1746):
-1747    """
-1748    Returns a list of stat categories
-1749    for team stats directly from the CFBD API.
-1750
-1751    Parameters
-1752    ----------
-1753
-1754    `api_key` (str, optional):
-1755        Semi-optional argument.
-1756        If `api_key` is null, this function will attempt to load a CFBD API key
-1757        from the python environment, or from a file on this computer.
-1758        If `api_key` is not null,
-1759        this function will automatically assume that the
-1760        inputted `api_key` is a valid CFBD API key.
-1761
-1762    `api_key_dir` (str, optional):
-1763        Optional argument.
-1764        If `api_key` is set to am empty string, this variable is ignored.
-1765        If `api_key_dir` is null, and `api_key` is null,
-1766        this function will try to find
-1767        a CFBD API key file in this user's home directory.
-1768        If `api_key_dir` is set to a string, and `api_key` is null,
-1769        this function will assume that `api_key_dir` is a directory,
-1770        and will try to find a CFBD API key file in that directory.
-1771
-1772    `return_as_dict` (bool, semi-optional):
-1773        Semi-optional argument.
-1774        If you want this function to return the data
-1775        as a dictionary (read: JSON object),
-1776        instead of a pandas `DataFrame` object,
-1777        set `return_as_dict` to `True`.
-1778
-1779    Usage
-1780    ----------
-1781    ```
-1782    import time
-1783
-1784    from cfbd_json_py.stats import get_cfbd_team_stat_categories
-1785
-1786
-1787    cfbd_key = "tigersAreAwesome"  # placeholder for your CFBD API Key.
-1788
-1789    if cfbd_key != "tigersAreAwesome":
-1790        print(
-1791            "Using the user's API key declared in this script " +
-1792            "for this example."
-1793        )
-1794
-1795        # Get a list of CFBD stat categories for team stats.
-1796        print("Get a list of CFBD stat categories for team stats.")
-1797        json_data = get_cfbd_team_stat_categories(
-1798            api_key=cfbd_key
-1799        )
-1800        print(json_data)
-1801        time.sleep(5)
-1802
-1803        # You can also tell this function to just return the API call as
-1804        # a Dictionary (read: JSON) object.
-1805        print(
-1806            "You can also tell this function to just return the API call " +
-1807            "as a Dictionary (read: JSON) object."
+                
1740def get_cfbd_team_stat_categories(
+1741    api_key: str = None, api_key_dir: str = None, return_as_dict: bool = False
+1742):
+1743    """
+1744    Returns a list of stat categories
+1745    for team stats directly from the CFBD API.
+1746
+1747    Parameters
+1748    ----------
+1749
+1750    `api_key` (str, optional):
+1751        Semi-optional argument.
+1752        If `api_key` is null, this function will attempt to load a CFBD API key
+1753        from the python environment, or from a file on this computer.
+1754        If `api_key` is not null,
+1755        this function will automatically assume that the
+1756        inputted `api_key` is a valid CFBD API key.
+1757
+1758    `api_key_dir` (str, optional):
+1759        Optional argument.
+1760        If `api_key` is set to am empty string, this variable is ignored.
+1761        If `api_key_dir` is null, and `api_key` is null,
+1762        this function will try to find
+1763        a CFBD API key file in this user's home directory.
+1764        If `api_key_dir` is set to a string, and `api_key` is null,
+1765        this function will assume that `api_key_dir` is a directory,
+1766        and will try to find a CFBD API key file in that directory.
+1767
+1768    `return_as_dict` (bool, semi-optional):
+1769        Semi-optional argument.
+1770        If you want this function to return the data
+1771        as a dictionary (read: JSON object),
+1772        instead of a pandas `DataFrame` object,
+1773        set `return_as_dict` to `True`.
+1774
+1775    Usage
+1776    ----------
+1777    ```
+1778    import time
+1779
+1780    from cfbd_json_py.stats import get_cfbd_team_stat_categories
+1781
+1782
+1783    cfbd_key = "tigersAreAwesome"  # placeholder for your CFBD API Key.
+1784
+1785    if cfbd_key != "tigersAreAwesome":
+1786        print(
+1787            "Using the user's API key declared in this script " +
+1788            "for this example."
+1789        )
+1790
+1791        # Get a list of CFBD stat categories for team stats.
+1792        print("Get a list of CFBD stat categories for team stats.")
+1793        json_data = get_cfbd_team_stat_categories(
+1794            api_key=cfbd_key
+1795        )
+1796        print(json_data)
+1797        time.sleep(5)
+1798
+1799        # You can also tell this function to just return the API call as
+1800        # a Dictionary (read: JSON) object.
+1801        print(
+1802            "You can also tell this function to just return the API call " +
+1803            "as a Dictionary (read: JSON) object."
+1804        )
+1805        json_data = get_cfbd_team_stat_categories(
+1806            api_key=cfbd_key,
+1807            return_as_dict=True
 1808        )
-1809        json_data = get_cfbd_team_stat_categories(
-1810            api_key=cfbd_key,
-1811            return_as_dict=True
-1812        )
-1813        print(json_data)
-1814
-1815    else:
-1816        # Alternatively, if the CFBD API key exists in this python environment,
-1817        # or it's been set by cfbd_json_py.utls.set_cfbd_api_token(),
-1818        # you could just call these functions directly,
-1819        # without setting the API key in the script.
-1820        print(
-1821            "Using the user's API key supposedly loaded " +
-1822            "into this python environment for this example."
-1823        )
-1824
-1825        # Get a list of CFBD stat categories for team stats.
-1826        print("Get a list of CFBD stat categories for team stats.")
-1827        json_data = get_cfbd_team_stat_categories()
-1828        print(json_data)
-1829        time.sleep(5)
-1830
-1831        # You can also tell this function to just return the API call as
-1832        # a Dictionary (read: JSON) object.
-1833        print(
-1834            "You can also tell this function to just return the API call " +
-1835            "as a Dictionary (read: JSON) object."
-1836        )
-1837        json_data = get_cfbd_team_stat_categories(
-1838            return_as_dict=True
-1839        )
-1840        print(json_data)
-1841
-1842    ```
-1843    Returns
-1844    ----------
-1845    A pandas `DataFrame` object with CFBD stat categories,
-1846    or (if `return_as_dict` is set to `True`)
-1847    a dictionary object with CFBD stat categories.
-1848
-1849    """
-1850    url = "https://api.collegefootballdata.com/stats/categories"
-1851
-1852    if api_key is not None:
-1853        real_api_key = api_key
-1854        del api_key
-1855    else:
-1856        real_api_key = get_cfbd_api_token(api_key_dir=api_key_dir)
-1857
-1858    if real_api_key == "tigersAreAwesome":
-1859        raise ValueError(
-1860            "You actually need to change `cfbd_key` to your CFBD API key."
-1861        )
-1862    elif "Bearer " in real_api_key:
-1863        pass
-1864    elif "Bearer" in real_api_key:
-1865        real_api_key = real_api_key.replace("Bearer", "Bearer ")
-1866    else:
-1867        real_api_key = "Bearer " + real_api_key
-1868
-1869    headers = {
-1870        "Authorization": f"{real_api_key}",
-1871        "accept": "application/json"
-1872    }
-1873
-1874    response = requests.get(url, headers=headers)
-1875
-1876    if response.status_code == 200:
-1877        pass
-1878    elif response.status_code == 401:
-1879        raise ConnectionRefusedError(
-1880            "Could not connect. The connection was refused." +
-1881            "\nHTTP Status Code 401."
+1809        print(json_data)
+1810
+1811    else:
+1812        # Alternatively, if the CFBD API key exists in this python environment,
+1813        # or it's been set by cfbd_json_py.utls.set_cfbd_api_token(),
+1814        # you could just call these functions directly,
+1815        # without setting the API key in the script.
+1816        print(
+1817            "Using the user's API key supposedly loaded " +
+1818            "into this python environment for this example."
+1819        )
+1820
+1821        # Get a list of CFBD stat categories for team stats.
+1822        print("Get a list of CFBD stat categories for team stats.")
+1823        json_data = get_cfbd_team_stat_categories()
+1824        print(json_data)
+1825        time.sleep(5)
+1826
+1827        # You can also tell this function to just return the API call as
+1828        # a Dictionary (read: JSON) object.
+1829        print(
+1830            "You can also tell this function to just return the API call " +
+1831            "as a Dictionary (read: JSON) object."
+1832        )
+1833        json_data = get_cfbd_team_stat_categories(
+1834            return_as_dict=True
+1835        )
+1836        print(json_data)
+1837
+1838    ```
+1839    Returns
+1840    ----------
+1841    A pandas `DataFrame` object with CFBD stat categories,
+1842    or (if `return_as_dict` is set to `True`)
+1843    a dictionary object with CFBD stat categories.
+1844
+1845    """
+1846    url = "https://api.collegefootballdata.com/stats/categories"
+1847
+1848    if api_key is not None:
+1849        real_api_key = api_key
+1850        del api_key
+1851    else:
+1852        real_api_key = get_cfbd_api_token(api_key_dir=api_key_dir)
+1853
+1854    if real_api_key == "tigersAreAwesome":
+1855        raise ValueError(
+1856            "You actually need to change `cfbd_key` to your CFBD API key."
+1857        )
+1858    elif "Bearer " in real_api_key:
+1859        pass
+1860    elif "Bearer" in real_api_key:
+1861        real_api_key = real_api_key.replace("Bearer", "Bearer ")
+1862    else:
+1863        real_api_key = "Bearer " + real_api_key
+1864
+1865    headers = {
+1866        "Authorization": f"{real_api_key}",
+1867        "accept": "application/json"
+1868    }
+1869
+1870    response = requests.get(url, headers=headers)
+1871
+1872    if response.status_code == 200:
+1873        pass
+1874    elif response.status_code == 401:
+1875        raise ConnectionRefusedError(
+1876            "Could not connect. The connection was refused." +
+1877            "\nHTTP Status Code 401."
+1878        )
+1879    else:
+1880        raise ConnectionError(
+1881            f"Could not connect.\nHTTP Status code {response.status_code}"
 1882        )
-1883    else:
-1884        raise ConnectionError(
-1885            f"Could not connect.\nHTTP Status code {response.status_code}"
-1886        )
-1887
-1888    json_data = response.json()
-1889
-1890    if return_as_dict is True:
-1891        return json_data
-1892
-1893    return pd.DataFrame(json_data, columns=["stat_category"])
+1883
+1884    json_data = response.json()
+1885
+1886    if return_as_dict is True:
+1887        return json_data
+1888
+1889    return pd.DataFrame(json_data, columns=["stat_category"])
 
@@ -6415,4 +6407,4 @@

Returns

- \ No newline at end of file + diff --git a/docs/cfbd_json_py/teams.html b/docs/cfbd_json_py/teams.html index 10999f5..7ab0b54 100644 --- a/docs/cfbd_json_py/teams.html +++ b/docs/cfbd_json_py/teams.html @@ -5095,4 +5095,4 @@

Returns

- \ No newline at end of file + diff --git a/docs/cfbd_json_py/utls.html b/docs/cfbd_json_py/utls.html index 5dc3a1e..0294761 100644 --- a/docs/cfbd_json_py/utls.html +++ b/docs/cfbd_json_py/utls.html @@ -1852,8 +1852,11 @@

364# key = "hello world" 365# set_cfbd_api_token("text") 366# print(key) -367# return_key = get_cfbd_api_token() -368# print(return_key) +367 +368# if __name__ == "__main__": +369 +370# return_key = get_cfbd_api_token() +371# print(return_key) @@ -2458,4 +2461,4 @@

Returns

- \ No newline at end of file + diff --git a/docs/cfbd_json_py/venues.html b/docs/cfbd_json_py/venues.html index 699b722..c9baa82 100644 --- a/docs/cfbd_json_py/venues.html +++ b/docs/cfbd_json_py/venues.html @@ -1489,178 +1489,180 @@

13 14 15def get_cfbd_venues( - 16 api_key: str = None, api_key_dir: str = None, return_as_dict: bool = False - 17): - 18 """ - 19 Allows a user to get CFB venue/stadium information from the CFBD API. - 20 - 21 Parameters - 22 ---------- - 23 - 24 `api_key` (str, optional): - 25 Semi-optional argument. - 26 If `api_key` is null, this function will attempt to load a CFBD API key - 27 from the python environment, or from a file on this computer. - 28 If `api_key` is not null, - 29 this function will automatically assume that the - 30 inputted `api_key` is a valid CFBD API key. - 31 - 32 `api_key_dir` (str, optional): - 33 Optional argument. - 34 If `api_key` is set to am empty string, this variable is ignored. - 35 If `api_key_dir` is null, and `api_key` is null, - 36 this function will try to find - 37 a CFBD API key file in this user's home directory. - 38 If `api_key_dir` is set to a string, and `api_key` is null, - 39 this function will assume that `api_key_dir` is a directory, - 40 and will try to find a CFBD API key file in that directory. - 41 - 42 `return_as_dict` (bool, semi-optional): - 43 Semi-optional argument. - 44 If you want this function to return the data - 45 as a dictionary (read: JSON object), - 46 instead of a pandas `DataFrame` object, - 47 set `return_as_dict` to `True`. - 48 - 49 Usage - 50 ---------- - 51 ``` - 52 import time - 53 - 54 from cfbd_json_py.venues import get_cfbd_venues + 16 api_key: str = None, + 17 api_key_dir: str = None, + 18 return_as_dict: bool = False + 19): + 20 """ + 21 Allows a user to get CFB venue/stadium information from the CFBD API. + 22 + 23 Parameters + 24 ---------- + 25 + 26 `api_key` (str, optional): + 27 Semi-optional argument. + 28 If `api_key` is null, this function will attempt to load a CFBD API key + 29 from the python environment, or from a file on this computer. + 30 If `api_key` is not null, + 31 this function will automatically assume that the + 32 inputted `api_key` is a valid CFBD API key. + 33 + 34 `api_key_dir` (str, optional): + 35 Optional argument. + 36 If `api_key` is set to am empty string, this variable is ignored. + 37 If `api_key_dir` is null, and `api_key` is null, + 38 this function will try to find + 39 a CFBD API key file in this user's home directory. + 40 If `api_key_dir` is set to a string, and `api_key` is null, + 41 this function will assume that `api_key_dir` is a directory, + 42 and will try to find a CFBD API key file in that directory. + 43 + 44 `return_as_dict` (bool, semi-optional): + 45 Semi-optional argument. + 46 If you want this function to return the data + 47 as a dictionary (read: JSON object), + 48 instead of a pandas `DataFrame` object, + 49 set `return_as_dict` to `True`. + 50 + 51 Usage + 52 ---------- + 53 ``` + 54 import time 55 - 56 - 57 cfbd_key = "tigersAreAwesome" # placeholder for your CFBD API Key. + 56 from cfbd_json_py.venues import get_cfbd_venues + 57 58 - 59 if cfbd_key != "tigersAreAwesome": - 60 print( - 61 "Using the user's API key declared in this script " + - 62 "for this example." - 63 ) - 64 - 65 # Get CFB venue/stadium data from the CFBD API. - 66 print("Get CFB venue/stadium data from the CFBD API.") - 67 json_data = get_cfbd_venues( - 68 api_key=cfbd_key - 69 ) - 70 print(json_data) - 71 time.sleep(5) - 72 - 73 # You can also tell this function to just return the API call as - 74 # a Dictionary (read: JSON) object. - 75 print( - 76 "You can also tell this function to just return the API call " + - 77 "as a Dictionary (read: JSON) object." - 78 ) - 79 json_data = get_cfbd_venues( - 80 api_key=cfbd_key, - 81 return_as_dict=True - 82 ) - 83 print(json_data) - 84 - 85 else: - 86 # Alternatively, if the CFBD API key exists in this python environment, - 87 # or it's been set by cfbd_json_py.utls.set_cfbd_api_token(), - 88 # you could just call these functions directly, - 89 # without setting the API key in the script. - 90 print( - 91 "Using the user's API key supposedly loaded into " + - 92 "this python environment for this example." - 93 ) - 94 - 95 # Get CFB venue/stadium data from the CFBD API. - 96 print("Get CFB venue/stadium data from the CFBD API.") - 97 json_data = get_cfbd_venues() - 98 print(json_data) - 99 time.sleep(5) -100 -101 -102 # You can also tell this function to just return the API call as -103 # a Dictionary (read: JSON) object. -104 print( -105 "You can also tell this function to just return the API call " + -106 "as a Dictionary (read: JSON) object." -107 ) -108 json_data = get_cfbd_venues( -109 return_as_dict=True -110 ) -111 print(json_data) -112 -113 ``` -114 Returns -115 ---------- -116 A pandas `DataFrame` object with CFB venue/stadium information, -117 or (if `return_as_dict` is set to `True`) -118 a dictionary object with with CFB venue/stadium information. -119 -120 """ -121 venue_df = pd.DataFrame() -122 url = "https://api.collegefootballdata.com/venues" -123 -124 ########################################################################## + 59 cfbd_key = "tigersAreAwesome" # placeholder for your CFBD API Key. + 60 + 61 if cfbd_key != "tigersAreAwesome": + 62 print( + 63 "Using the user's API key declared in this script " + + 64 "for this example." + 65 ) + 66 + 67 # Get CFB venue/stadium data from the CFBD API. + 68 print("Get CFB venue/stadium data from the CFBD API.") + 69 json_data = get_cfbd_venues( + 70 api_key=cfbd_key + 71 ) + 72 print(json_data) + 73 time.sleep(5) + 74 + 75 # You can also tell this function to just return the API call as + 76 # a Dictionary (read: JSON) object. + 77 print( + 78 "You can also tell this function to just return the API call " + + 79 "as a Dictionary (read: JSON) object." + 80 ) + 81 json_data = get_cfbd_venues( + 82 api_key=cfbd_key, + 83 return_as_dict=True + 84 ) + 85 print(json_data) + 86 + 87 else: + 88 # Alternatively, if the CFBD API key exists in this python environment, + 89 # or it's been set by cfbd_json_py.utls.set_cfbd_api_token(), + 90 # you could just call these functions directly, + 91 # without setting the API key in the script. + 92 print( + 93 "Using the user's API key supposedly loaded into " + + 94 "this python environment for this example." + 95 ) + 96 + 97 # Get CFB venue/stadium data from the CFBD API. + 98 print("Get CFB venue/stadium data from the CFBD API.") + 99 json_data = get_cfbd_venues() +100 print(json_data) +101 time.sleep(5) +102 +103 +104 # You can also tell this function to just return the API call as +105 # a Dictionary (read: JSON) object. +106 print( +107 "You can also tell this function to just return the API call " + +108 "as a Dictionary (read: JSON) object." +109 ) +110 json_data = get_cfbd_venues( +111 return_as_dict=True +112 ) +113 print(json_data) +114 +115 ``` +116 Returns +117 ---------- +118 A pandas `DataFrame` object with CFB venue/stadium information, +119 or (if `return_as_dict` is set to `True`) +120 a dictionary object with with CFB venue/stadium information. +121 +122 """ +123 venue_df = pd.DataFrame() +124 url = "https://api.collegefootballdata.com/venues" 125 -126 if api_key is not None: -127 real_api_key = api_key -128 del api_key -129 else: -130 real_api_key = get_cfbd_api_token(api_key_dir=api_key_dir) -131 -132 if real_api_key == "tigersAreAwesome": -133 raise ValueError( -134 "You actually need to change `cfbd_key` to your CFBD API key." -135 ) -136 elif "Bearer " in real_api_key: -137 pass -138 elif "Bearer" in real_api_key: -139 real_api_key = real_api_key.replace("Bearer", "Bearer ") -140 else: -141 real_api_key = "Bearer " + real_api_key -142 -143 ########################################################################## +126 ########################################################################## +127 +128 if api_key is not None: +129 real_api_key = api_key +130 del api_key +131 else: +132 real_api_key = get_cfbd_api_token(api_key_dir=api_key_dir) +133 +134 if real_api_key == "tigersAreAwesome": +135 raise ValueError( +136 "You actually need to change `cfbd_key` to your CFBD API key." +137 ) +138 elif "Bearer " in real_api_key: +139 pass +140 elif "Bearer" in real_api_key: +141 real_api_key = real_api_key.replace("Bearer", "Bearer ") +142 else: +143 real_api_key = "Bearer " + real_api_key 144 -145 headers = { -146 "Authorization": f"{real_api_key}", -147 "accept": "application/json" -148 } -149 -150 response = requests.get(url, headers=headers) +145 ########################################################################## +146 +147 headers = { +148 "Authorization": f"{real_api_key}", +149 "accept": "application/json" +150 } 151 -152 if response.status_code == 200: -153 pass -154 elif response.status_code == 401: -155 raise ConnectionRefusedError( -156 "Could not connect. The connection was refused.\n" + -157 "HTTP Status Code 401." -158 ) -159 else: -160 raise ConnectionError( -161 f"Could not connect.\nHTTP Status code {response.status_code}" -162 ) -163 -164 json_data = response.json() +152 response = requests.get(url, headers=headers) +153 +154 if response.status_code == 200: +155 pass +156 elif response.status_code == 401: +157 raise ConnectionRefusedError( +158 "Could not connect. The connection was refused.\n" + +159 "HTTP Status Code 401." +160 ) +161 else: +162 raise ConnectionError( +163 f"Could not connect.\nHTTP Status code {response.status_code}" +164 ) 165 -166 if return_as_dict is True: -167 return json_data -168 -169 venue_df = pd.json_normalize(json_data) -170 venue_df.rename( -171 columns={ -172 "id": "venue_id", -173 "name": "venue_name", -174 "capacity": "venue_capacity", -175 "grass": "is_grass", -176 "city": "venue_city", -177 "state": "venue_state", -178 "zip": "venue_zip_code", -179 "country_code": "venue_country_code", -180 "elevation": "venue_elevation", -181 "dome": "is_dome", -182 "location.x": "venue_location_x", -183 "location.y": "venue_location_y", -184 }, -185 inplace=True, -186 ) -187 return venue_df +166 json_data = response.json() +167 +168 if return_as_dict is True: +169 return json_data +170 +171 venue_df = pd.json_normalize(json_data) +172 venue_df.rename( +173 columns={ +174 "id": "venue_id", +175 "name": "venue_name", +176 "capacity": "venue_capacity", +177 "grass": "is_grass", +178 "city": "venue_city", +179 "state": "venue_state", +180 "zip": "venue_zip_code", +181 "country_code": "venue_country_code", +182 "elevation": "venue_elevation", +183 "dome": "is_dome", +184 "location.x": "venue_location_x", +185 "location.y": "venue_location_y", +186 }, +187 inplace=True, +188 ) +189 return venue_df @@ -1687,178 +1689,180 @@

 16def get_cfbd_venues(
- 17    api_key: str = None, api_key_dir: str = None, return_as_dict: bool = False
- 18):
- 19    """
- 20    Allows a user to get CFB venue/stadium information from the CFBD API.
- 21
- 22    Parameters
- 23    ----------
- 24
- 25    `api_key` (str, optional):
- 26        Semi-optional argument.
- 27        If `api_key` is null, this function will attempt to load a CFBD API key
- 28        from the python environment, or from a file on this computer.
- 29        If `api_key` is not null,
- 30        this function will automatically assume that the
- 31        inputted `api_key` is a valid CFBD API key.
- 32
- 33    `api_key_dir` (str, optional):
- 34        Optional argument.
- 35        If `api_key` is set to am empty string, this variable is ignored.
- 36        If `api_key_dir` is null, and `api_key` is null,
- 37        this function will try to find
- 38        a CFBD API key file in this user's home directory.
- 39        If `api_key_dir` is set to a string, and `api_key` is null,
- 40        this function will assume that `api_key_dir` is a directory,
- 41        and will try to find a CFBD API key file in that directory.
- 42
- 43    `return_as_dict` (bool, semi-optional):
- 44        Semi-optional argument.
- 45        If you want this function to return the data
- 46        as a dictionary (read: JSON object),
- 47        instead of a pandas `DataFrame` object,
- 48        set `return_as_dict` to `True`.
- 49
- 50    Usage
- 51    ----------
- 52    ```
- 53    import time
- 54
- 55    from cfbd_json_py.venues import get_cfbd_venues
+ 17    api_key: str = None,
+ 18    api_key_dir: str = None,
+ 19    return_as_dict: bool = False
+ 20):
+ 21    """
+ 22    Allows a user to get CFB venue/stadium information from the CFBD API.
+ 23
+ 24    Parameters
+ 25    ----------
+ 26
+ 27    `api_key` (str, optional):
+ 28        Semi-optional argument.
+ 29        If `api_key` is null, this function will attempt to load a CFBD API key
+ 30        from the python environment, or from a file on this computer.
+ 31        If `api_key` is not null,
+ 32        this function will automatically assume that the
+ 33        inputted `api_key` is a valid CFBD API key.
+ 34
+ 35    `api_key_dir` (str, optional):
+ 36        Optional argument.
+ 37        If `api_key` is set to am empty string, this variable is ignored.
+ 38        If `api_key_dir` is null, and `api_key` is null,
+ 39        this function will try to find
+ 40        a CFBD API key file in this user's home directory.
+ 41        If `api_key_dir` is set to a string, and `api_key` is null,
+ 42        this function will assume that `api_key_dir` is a directory,
+ 43        and will try to find a CFBD API key file in that directory.
+ 44
+ 45    `return_as_dict` (bool, semi-optional):
+ 46        Semi-optional argument.
+ 47        If you want this function to return the data
+ 48        as a dictionary (read: JSON object),
+ 49        instead of a pandas `DataFrame` object,
+ 50        set `return_as_dict` to `True`.
+ 51
+ 52    Usage
+ 53    ----------
+ 54    ```
+ 55    import time
  56
- 57
- 58    cfbd_key = "tigersAreAwesome"  # placeholder for your CFBD API Key.
+ 57    from cfbd_json_py.venues import get_cfbd_venues
+ 58
  59
- 60    if cfbd_key != "tigersAreAwesome":
- 61        print(
- 62            "Using the user's API key declared in this script " +
- 63            "for this example."
- 64        )
- 65
- 66        # Get CFB venue/stadium data from the CFBD API.
- 67        print("Get CFB venue/stadium data from the CFBD API.")
- 68        json_data = get_cfbd_venues(
- 69            api_key=cfbd_key
- 70        )
- 71        print(json_data)
- 72        time.sleep(5)
- 73
- 74        # You can also tell this function to just return the API call as
- 75        # a Dictionary (read: JSON) object.
- 76        print(
- 77            "You can also tell this function to just return the API call " +
- 78            "as a Dictionary (read: JSON) object."
- 79        )
- 80        json_data = get_cfbd_venues(
- 81            api_key=cfbd_key,
- 82            return_as_dict=True
- 83        )
- 84        print(json_data)
- 85
- 86    else:
- 87        # Alternatively, if the CFBD API key exists in this python environment,
- 88        # or it's been set by cfbd_json_py.utls.set_cfbd_api_token(),
- 89        # you could just call these functions directly,
- 90        # without setting the API key in the script.
- 91        print(
- 92            "Using the user's API key supposedly loaded into " +
- 93            "this python environment for this example."
- 94        )
- 95
- 96        # Get CFB venue/stadium data from the CFBD API.
- 97        print("Get CFB venue/stadium data from the CFBD API.")
- 98        json_data = get_cfbd_venues()
- 99        print(json_data)
-100        time.sleep(5)
-101
-102
-103        # You can also tell this function to just return the API call as
-104        # a Dictionary (read: JSON) object.
-105        print(
-106            "You can also tell this function to just return the API call " +
-107            "as a Dictionary (read: JSON) object."
-108        )
-109        json_data = get_cfbd_venues(
-110            return_as_dict=True
-111        )
-112        print(json_data)
-113
-114    ```
-115    Returns
-116    ----------
-117    A pandas `DataFrame` object with CFB venue/stadium information,
-118    or (if `return_as_dict` is set to `True`)
-119    a dictionary object with with CFB venue/stadium information.
-120
-121    """
-122    venue_df = pd.DataFrame()
-123    url = "https://api.collegefootballdata.com/venues"
-124
-125    ##########################################################################
+ 60    cfbd_key = "tigersAreAwesome"  # placeholder for your CFBD API Key.
+ 61
+ 62    if cfbd_key != "tigersAreAwesome":
+ 63        print(
+ 64            "Using the user's API key declared in this script " +
+ 65            "for this example."
+ 66        )
+ 67
+ 68        # Get CFB venue/stadium data from the CFBD API.
+ 69        print("Get CFB venue/stadium data from the CFBD API.")
+ 70        json_data = get_cfbd_venues(
+ 71            api_key=cfbd_key
+ 72        )
+ 73        print(json_data)
+ 74        time.sleep(5)
+ 75
+ 76        # You can also tell this function to just return the API call as
+ 77        # a Dictionary (read: JSON) object.
+ 78        print(
+ 79            "You can also tell this function to just return the API call " +
+ 80            "as a Dictionary (read: JSON) object."
+ 81        )
+ 82        json_data = get_cfbd_venues(
+ 83            api_key=cfbd_key,
+ 84            return_as_dict=True
+ 85        )
+ 86        print(json_data)
+ 87
+ 88    else:
+ 89        # Alternatively, if the CFBD API key exists in this python environment,
+ 90        # or it's been set by cfbd_json_py.utls.set_cfbd_api_token(),
+ 91        # you could just call these functions directly,
+ 92        # without setting the API key in the script.
+ 93        print(
+ 94            "Using the user's API key supposedly loaded into " +
+ 95            "this python environment for this example."
+ 96        )
+ 97
+ 98        # Get CFB venue/stadium data from the CFBD API.
+ 99        print("Get CFB venue/stadium data from the CFBD API.")
+100        json_data = get_cfbd_venues()
+101        print(json_data)
+102        time.sleep(5)
+103
+104
+105        # You can also tell this function to just return the API call as
+106        # a Dictionary (read: JSON) object.
+107        print(
+108            "You can also tell this function to just return the API call " +
+109            "as a Dictionary (read: JSON) object."
+110        )
+111        json_data = get_cfbd_venues(
+112            return_as_dict=True
+113        )
+114        print(json_data)
+115
+116    ```
+117    Returns
+118    ----------
+119    A pandas `DataFrame` object with CFB venue/stadium information,
+120    or (if `return_as_dict` is set to `True`)
+121    a dictionary object with with CFB venue/stadium information.
+122
+123    """
+124    venue_df = pd.DataFrame()
+125    url = "https://api.collegefootballdata.com/venues"
 126
-127    if api_key is not None:
-128        real_api_key = api_key
-129        del api_key
-130    else:
-131        real_api_key = get_cfbd_api_token(api_key_dir=api_key_dir)
-132
-133    if real_api_key == "tigersAreAwesome":
-134        raise ValueError(
-135            "You actually need to change `cfbd_key` to your CFBD API key."
-136        )
-137    elif "Bearer " in real_api_key:
-138        pass
-139    elif "Bearer" in real_api_key:
-140        real_api_key = real_api_key.replace("Bearer", "Bearer ")
-141    else:
-142        real_api_key = "Bearer " + real_api_key
-143
-144    ##########################################################################
+127    ##########################################################################
+128
+129    if api_key is not None:
+130        real_api_key = api_key
+131        del api_key
+132    else:
+133        real_api_key = get_cfbd_api_token(api_key_dir=api_key_dir)
+134
+135    if real_api_key == "tigersAreAwesome":
+136        raise ValueError(
+137            "You actually need to change `cfbd_key` to your CFBD API key."
+138        )
+139    elif "Bearer " in real_api_key:
+140        pass
+141    elif "Bearer" in real_api_key:
+142        real_api_key = real_api_key.replace("Bearer", "Bearer ")
+143    else:
+144        real_api_key = "Bearer " + real_api_key
 145
-146    headers = {
-147        "Authorization": f"{real_api_key}",
-148        "accept": "application/json"
-149    }
-150
-151    response = requests.get(url, headers=headers)
+146    ##########################################################################
+147
+148    headers = {
+149        "Authorization": f"{real_api_key}",
+150        "accept": "application/json"
+151    }
 152
-153    if response.status_code == 200:
-154        pass
-155    elif response.status_code == 401:
-156        raise ConnectionRefusedError(
-157            "Could not connect. The connection was refused.\n" +
-158            "HTTP Status Code 401."
-159        )
-160    else:
-161        raise ConnectionError(
-162            f"Could not connect.\nHTTP Status code {response.status_code}"
-163        )
-164
-165    json_data = response.json()
+153    response = requests.get(url, headers=headers)
+154
+155    if response.status_code == 200:
+156        pass
+157    elif response.status_code == 401:
+158        raise ConnectionRefusedError(
+159            "Could not connect. The connection was refused.\n" +
+160            "HTTP Status Code 401."
+161        )
+162    else:
+163        raise ConnectionError(
+164            f"Could not connect.\nHTTP Status code {response.status_code}"
+165        )
 166
-167    if return_as_dict is True:
-168        return json_data
-169
-170    venue_df = pd.json_normalize(json_data)
-171    venue_df.rename(
-172        columns={
-173            "id": "venue_id",
-174            "name": "venue_name",
-175            "capacity": "venue_capacity",
-176            "grass": "is_grass",
-177            "city": "venue_city",
-178            "state": "venue_state",
-179            "zip": "venue_zip_code",
-180            "country_code": "venue_country_code",
-181            "elevation": "venue_elevation",
-182            "dome": "is_dome",
-183            "location.x": "venue_location_x",
-184            "location.y": "venue_location_y",
-185        },
-186        inplace=True,
-187    )
-188    return venue_df
+167    json_data = response.json()
+168
+169    if return_as_dict is True:
+170        return json_data
+171
+172    venue_df = pd.json_normalize(json_data)
+173    venue_df.rename(
+174        columns={
+175            "id": "venue_id",
+176            "name": "venue_name",
+177            "capacity": "venue_capacity",
+178            "grass": "is_grass",
+179            "city": "venue_city",
+180            "state": "venue_state",
+181            "zip": "venue_zip_code",
+182            "country_code": "venue_country_code",
+183            "elevation": "venue_elevation",
+184            "dome": "is_dome",
+185            "location.x": "venue_location_x",
+186            "location.y": "venue_location_y",
+187        },
+188        inplace=True,
+189    )
+190    return venue_df
 
@@ -2152,4 +2156,4 @@

Returns

- \ No newline at end of file + diff --git a/docs/index.html b/docs/index.html index 90b0295..e842ce1 100644 --- a/docs/index.html +++ b/docs/index.html @@ -6,4 +6,4 @@ - \ No newline at end of file + diff --git a/docs/search.js b/docs/search.js index 4326c6b..e39f485 100644 --- a/docs/search.js +++ b/docs/search.js @@ -984,9 +984,9 @@ window.pdocSearch = (function () { modulename: "cfbd_json_py.betting", qualname: "get_cfbd_betting_lines", kind: "function", - doc: '

Retrieves betting information from the CFBD API for a given season,\nor you could only get betting information for a single game.

\n\n

Parameters

\n\n

season (int, mandatory):\n The season you want to retrieve betting information from.

\n\n

api_key (str, optional):\n Semi-optional argument.\n If api_key is null, this function will attempt to load a CFBD API key\n from the python environment, or from a file on this computer.\n If api_key is not null,\n this function will automatically assume that the\n inputted api_key is a valid CFBD API key.

\n\n

api_key_dir (str, optional):\n Optional argument.\n If api_key is set to am empty string, this variable is ignored.\n If api_key_dir is null, and api_key is null,\n this function will try to find\n a CFBD API key file in this user\'s home directory.\n If api_key_dir is set to a string, and api_key is null,\n this function will assume that api_key_dir is a directory,\n and will try to find a CFBD API key file in that directory.

\n\n

game_id (int, optional):\n Optional argument.\n If game_id is set to a game ID,\n get_cfb_betting_lines() will try to get\n all betting information for that game ID.

\n\n

week (int, optional):\n Optional argument.\n If week is set to an integer, this function will attempt\n to load betting data from games in that season, and that week.

\n\n

season_type (str, semi-optional):\n Semi-optional argument.\n By default, this will be set to "regular", for the CFB regular season.\n If you want postseason betting data, set season_type to "postseason".\n If season_type is set to anything but "regular" or "postseason",\n a ValueError() will be raised.

\n\n

team (str, optional):\n Optional argument.\n If you only want betting information for a team,\n regardless if they are the home/away team,\n set team to the name of the team\n you want game-level betting data from.

\n\n

home_team (str, optional):\n Optional argument.\n If you only want betting information for a team,\n where that team was the home team in this season,\n set home_team to the name of the team\n you want game-level betting data from.

\n\n

away_team (str, optional):\n Optional argument.\n If you only want betting information for a team,\n where that team was the away team in this season,\n set away_team to the name of the team\n you want game-level betting data from.

\n\n

conference (str, optional):\n Optional argument.\n If you only want betting information from games\n involving teams a specific conference,\n set conference to the abbreviation\n of the conference you want betting information from.

\n\n

year (int):\n Alternative keyword for season

\n\n

home (str):\n Alternative keyword for home_team

\n\n

away (str):\n Alternative keyword for away_team

\n\n

return_as_dict (bool, semi-optional):\n Semi-optional argument.\n If you want this function to return\n the data as a dictionary (read: JSON object),\n instead of a pandas DataFrame object,\n set return_as_dict to True.

\n\n

Usage

\n\n
import time\n\nfrom cfbd_json_py.betting import get_cfbd_betting_lines\n\ncfbd_key = "tigersAreAwesome"  # placeholder for your CFBD API Key.\n\nif cfbd_key is not "tigersAreAwesome":\n    print(\n        "Using the user\'s API key declared " +\n        "in this script for this example."\n    )\n\n\n    # Get all available betting info for the 2020 CFB season, in week 2.\n    print(\n        "Get all available betting info for the 2020 CFB season, "+\n        "in week 2."\n    )\n    json_data = get_cfbd_betting_lines(\n        api_key=cfbd_key,\n        season=2020,\n        week=2\n    )\n    print(json_data)\n    time.sleep(5)\n\n    # Get all betting info for the 2020 CFB season,\n    # in the postseason (bowls, playoffs, etc.).\n    print(\n        "Get all betting info for the 2020 CFB season, " +\n        "in the postseason (bowls, playoffs, etc.)."\n    )\n    json_data = get_cfbd_betting_lines(\n        api_key=cfbd_key,\n        season=2020,\n        season_type="postseason"\n    )\n    print(json_data)\n    time.sleep(5)\n\n    # Get all betting info for the University of Cincinnati Bearcats\n    # Football games the 2020 CFB season.\n    print(\n        "Get all betting info for the University of Cincinnati " +\n        "Bearcats Football games the 2020 CFB season."\n    )\n    json_data = get_cfbd_betting_lines(\n        api_key=cfbd_key,\n        season=2020,\n        team="Cincinnati"\n    )\n    print(json_data)\n    time.sleep(5)\n\n    # Get all betting info for Ohio Bobcats home games the 2020 CFB season.\n    print(\n        "Get all betting info for Ohio Bobcats " +\n        "home games the 2020 CFB season."\n    )\n    json_data = get_cfbd_betting_lines(\n        api_key=cfbd_key,\n        season=2020,\n        home_team="Ohio"\n    )\n    print(json_data)\n    time.sleep(5)\n\n    # Get all betting info for Ohio State Buckeyes\n    # away games the 2020 CFB season.\n    print(\n        "Get all betting info for Ohio State Buckeyes " +\n        "away games the 2020 CFB season."\n    )\n    json_data = get_cfbd_betting_lines(\n        api_key=cfbd_key,\n        season=2020,\n        away_team="Ohio State"\n    )\n    print(json_data)\n    time.sleep(5)\n\n    # Get all betting info for Atlantic Coast Conference (ACC)\n    # games the 2020 CFB season.\n    print(\n        "Get all betting info for Atlantic Coast Conference (ACC) " +\n        "games the 2020 CFB season."\n    )\n    json_data = get_cfbd_betting_lines(\n        api_key=cfbd_key,\n        season=2020,\n        conference="ACC"\n    )\n    print(json_data)\n    time.sleep(5)\n\n    # Get all available betting info for the 2020 CFB season.\n    print("Get all available betting info for the 2020 CFB season.")\n    json_data = get_cfbd_betting_lines(\n        api_key=cfbd_key,\n        season=2020\n    )\n    print(json_data)\n    time.sleep(5)\n\n    # You can also tell this function to just return the API call\n    # as a Dictionary (read: JSON) object.\n    print(\n        "You can also tell this function to just return the API call " +\n        "as a Dictionary (read: JSON) object."\n    )\n    json_data = get_cfbd_betting_lines(\n        api_key=cfbd_key,\n        season=2020,\n        team="Cincinnati",\n        return_as_dict=True\n    )\n    print(json_data)\n\nelse:\n    # Alternatively, if the CFBD API key exists in this python environment,\n    # or it\'s been set by cfbd_json_py.utls.set_cfbd_api_token(),\n    # you could just call these functions directly,\n    # without setting the API key in the script.\n    print(\n        "Using the user\'s API key supposedly loaded " +\n        "into this python environment for this example."\n    )\n\n    # Get all available betting info for the 2020 CFB season, in week 2.\n    print(\n        "Get all available betting info for the 2020 CFB season, " +\n        "in week 2."\n    )\n    json_data = get_cfbd_betting_lines(\n        season=2020,\n        week=2\n    )\n    print(json_data)\n    time.sleep(5)\n    # Get all betting info for the 2020 CFB season,\n    # in the postseason (bowls, playoffs, etc.).\n    print(\n        "Get all betting info for the 2020 CFB season, " +\n        "in the postseason (bowls, playoffs, etc.)."\n    )\n    json_data = get_cfbd_betting_lines(\n        season=2020,\n        season_type="postseason"\n    )\n    print(json_data)\n    time.sleep(5)\n\n    # Get all betting info for University of Cincinnati\n    # Bearcats Football games the 2020 CFB season.\n    print(\n        "Get all betting info for University of Cincinnati " +\n        "Bearcats Football games the 2020 CFB season."\n    )\n    json_data = get_cfbd_betting_lines(\n        season=2020,\n        team="Cincinnati"\n    )\n    print(json_data)\n    time.sleep(5)\n\n    # Get all betting info for Ohio Bobcats home games the 2020 CFB season.\n    print(\n        "Get all betting info for Ohio Bobcats " +\n        "home games the 2020 CFB season."\n    )\n    json_data = get_cfbd_betting_lines(\n        season=2020,\n        home_team="Ohio"\n    )\n    print(json_data)\n    time.sleep(5)\n\n    # Get all betting info for Ohio State Buckeyes\n    # away games the 2020 CFB season.\n    print(\n        "Get all betting info for Ohio State Buckeyes " +\n        "away games the 2020 CFB season."\n    )\n    json_data = get_cfbd_betting_lines(\n\n        season=2020,\n        away_team="Ohio State"\n    )\n    print(json_data)\n    time.sleep(5)\n\n    # Get all betting info for Atlantic Coast Conference (ACC)\n    # games the 2020 CFB season.\n    print(\n        "Get all betting info for Atlantic Coast Conference (ACC) " +\n        "games the 2020 CFB season."\n    )\n    json_data = get_cfbd_betting_lines(\n        season=2020,\n        conference="ACC"\n    )\n    print(json_data)\n    time.sleep(5)\n\n    # Get all available betting info for the 2020 CFB season.\n    print("Get all available betting info for the 2020 CFB season.")\n    json_data = get_cfbd_betting_lines(\n        season=2020\n    )\n    print(json_data)\n    time.sleep(5)\n\n    # You can also tell this function to just return the API call\n    # as a Dictionary (read: JSON) object.\n    print(\n        "You can also tell this function to just return the API call " +\n        "as a Dictionary (read: JSON) object."\n    )\n    json_data = get_cfbd_betting_lines(\n        season=2020,\n        team="Cincinnati",\n        return_as_dict=True\n    )\n    print(json_data)\n\n
\n\n

Returns

\n\n

A pandas DataFrame object with college football betting data,\nor (if return_as_dict is set to True)\na dictionary object with college football betting data.

\n', + doc: '

Retrieves betting information from the CFBD API for a given season,\nor you could only get betting information for a single game.

\n\n

Parameters

\n\n

season (int, mandatory):\n The season you want to retrieve betting information from.

\n\n

api_key (str, optional):\n Semi-optional argument.\n If api_key is null, this function will attempt to load a CFBD API key\n from the python environment, or from a file on this computer.\n If api_key is not null,\n this function will automatically assume that the\n inputted api_key is a valid CFBD API key.

\n\n

api_key_dir (str, optional):\n Optional argument.\n If api_key is set to am empty string, this variable is ignored.\n If api_key_dir is null, and api_key is null,\n this function will try to find\n a CFBD API key file in this user\'s home directory.\n If api_key_dir is set to a string, and api_key is null,\n this function will assume that api_key_dir is a directory,\n and will try to find a CFBD API key file in that directory.

\n\n

game_id (int, optional):\n DEPRECATED FROM V1.\n If game_id is set to a game ID,\n get_cfb_betting_lines() will try to get\n all betting information for that game ID.

\n\n

week (int, optional):\n Optional argument.\n If week is set to an integer, this function will attempt\n to load betting data from games in that season, and that week.

\n\n

season_type (str, semi-optional):\n Semi-optional argument.\n By default, this will be set to "regular", for the CFB regular season.\n If you want postseason betting data, set season_type to "postseason".\n If season_type is set to anything but "regular" or "postseason",\n a ValueError() will be raised.

\n\n

team (str, optional):\n Optional argument.\n If you only want betting information for a team,\n regardless if they are the home/away team,\n set team to the name of the team\n you want game-level betting data from.

\n\n

home_team (str, optional):\n Optional argument.\n If you only want betting information for a team,\n where that team was the home team in this season,\n set home_team to the name of the team\n you want game-level betting data from.

\n\n

away_team (str, optional):\n Optional argument.\n If you only want betting information for a team,\n where that team was the away team in this season,\n set away_team to the name of the team\n you want game-level betting data from.

\n\n

conference (str, optional):\n Optional argument.\n If you only want betting information from games\n involving teams a specific conference,\n set conference to the abbreviation\n of the conference you want betting information from.

\n\n

year (int):\n Alternative keyword for season

\n\n

home (str):\n Alternative keyword for home_team

\n\n

away (str):\n Alternative keyword for away_team

\n\n

return_as_dict (bool, semi-optional):\n Semi-optional argument.\n If you want this function to return\n the data as a dictionary (read: JSON object),\n instead of a pandas DataFrame object,\n set return_as_dict to True.

\n\n

Usage

\n\n
import time\n\nfrom cfbd_json_py.betting import get_cfbd_betting_lines\n\ncfbd_key = "tigersAreAwesome"  # placeholder for your CFBD API Key.\n\nif cfbd_key is not "tigersAreAwesome":\n    print(\n        "Using the user\'s API key declared " +\n        "in this script for this example."\n    )\n\n\n    # Get all available betting info for the 2020 CFB season, in week 2.\n    print(\n        "Get all available betting info for the 2020 CFB season, "+\n        "in week 2."\n    )\n    json_data = get_cfbd_betting_lines(\n        api_key=cfbd_key,\n        season=2020,\n        week=2\n    )\n    print(json_data)\n    time.sleep(5)\n\n    # Get all betting info for the 2020 CFB season,\n    # in the postseason (bowls, playoffs, etc.).\n    print(\n        "Get all betting info for the 2020 CFB season, " +\n        "in the postseason (bowls, playoffs, etc.)."\n    )\n    json_data = get_cfbd_betting_lines(\n        api_key=cfbd_key,\n        season=2020,\n        season_type="postseason"\n    )\n    print(json_data)\n    time.sleep(5)\n\n    # Get all betting info for the University of Cincinnati Bearcats\n    # Football games the 2020 CFB season.\n    print(\n        "Get all betting info for the University of Cincinnati " +\n        "Bearcats Football games the 2020 CFB season."\n    )\n    json_data = get_cfbd_betting_lines(\n        api_key=cfbd_key,\n        season=2020,\n        team="Cincinnati"\n    )\n    print(json_data)\n    time.sleep(5)\n\n    # Get all betting info for Ohio Bobcats home games the 2020 CFB season.\n    print(\n        "Get all betting info for Ohio Bobcats " +\n        "home games the 2020 CFB season."\n    )\n    json_data = get_cfbd_betting_lines(\n        api_key=cfbd_key,\n        season=2020,\n        home_team="Ohio"\n    )\n    print(json_data)\n    time.sleep(5)\n\n    # Get all betting info for Ohio State Buckeyes\n    # away games the 2020 CFB season.\n    print(\n        "Get all betting info for Ohio State Buckeyes " +\n        "away games the 2020 CFB season."\n    )\n    json_data = get_cfbd_betting_lines(\n        api_key=cfbd_key,\n        season=2020,\n        away_team="Ohio State"\n    )\n    print(json_data)\n    time.sleep(5)\n\n    # Get all betting info for Atlantic Coast Conference (ACC)\n    # games the 2020 CFB season.\n    print(\n        "Get all betting info for Atlantic Coast Conference (ACC) " +\n        "games the 2020 CFB season."\n    )\n    json_data = get_cfbd_betting_lines(\n        api_key=cfbd_key,\n        season=2020,\n        conference="ACC"\n    )\n    print(json_data)\n    time.sleep(5)\n\n    # Get all available betting info for the 2020 CFB season.\n    print("Get all available betting info for the 2020 CFB season.")\n    json_data = get_cfbd_betting_lines(\n        api_key=cfbd_key,\n        season=2020\n    )\n    print(json_data)\n    time.sleep(5)\n\n    # You can also tell this function to just return the API call\n    # as a Dictionary (read: JSON) object.\n    print(\n        "You can also tell this function to just return the API call " +\n        "as a Dictionary (read: JSON) object."\n    )\n    json_data = get_cfbd_betting_lines(\n        api_key=cfbd_key,\n        season=2020,\n        team="Cincinnati",\n        return_as_dict=True\n    )\n    print(json_data)\n\nelse:\n    # Alternatively, if the CFBD API key exists in this python environment,\n    # or it\'s been set by cfbd_json_py.utls.set_cfbd_api_token(),\n    # you could just call these functions directly,\n    # without setting the API key in the script.\n    print(\n        "Using the user\'s API key supposedly loaded " +\n        "into this python environment for this example."\n    )\n\n    # Get all available betting info for the 2020 CFB season, in week 2.\n    print(\n        "Get all available betting info for the 2020 CFB season, " +\n        "in week 2."\n    )\n    json_data = get_cfbd_betting_lines(\n        season=2020,\n        week=2\n    )\n    print(json_data)\n    time.sleep(5)\n    # Get all betting info for the 2020 CFB season,\n    # in the postseason (bowls, playoffs, etc.).\n    print(\n        "Get all betting info for the 2020 CFB season, " +\n        "in the postseason (bowls, playoffs, etc.)."\n    )\n    json_data = get_cfbd_betting_lines(\n        season=2020,\n        season_type="postseason"\n    )\n    print(json_data)\n    time.sleep(5)\n\n    # Get all betting info for University of Cincinnati\n    # Bearcats Football games the 2020 CFB season.\n    print(\n        "Get all betting info for University of Cincinnati " +\n        "Bearcats Football games the 2020 CFB season."\n    )\n    json_data = get_cfbd_betting_lines(\n        season=2020,\n        team="Cincinnati"\n    )\n    print(json_data)\n    time.sleep(5)\n\n    # Get all betting info for Ohio Bobcats home games the 2020 CFB season.\n    print(\n        "Get all betting info for Ohio Bobcats " +\n        "home games the 2020 CFB season."\n    )\n    json_data = get_cfbd_betting_lines(\n        season=2020,\n        home_team="Ohio"\n    )\n    print(json_data)\n    time.sleep(5)\n\n    # Get all betting info for Ohio State Buckeyes\n    # away games the 2020 CFB season.\n    print(\n        "Get all betting info for Ohio State Buckeyes " +\n        "away games the 2020 CFB season."\n    )\n    json_data = get_cfbd_betting_lines(\n\n        season=2020,\n        away_team="Ohio State"\n    )\n    print(json_data)\n    time.sleep(5)\n\n    # Get all betting info for Atlantic Coast Conference (ACC)\n    # games the 2020 CFB season.\n    print(\n        "Get all betting info for Atlantic Coast Conference (ACC) " +\n        "games the 2020 CFB season."\n    )\n    json_data = get_cfbd_betting_lines(\n        season=2020,\n        conference="ACC"\n    )\n    print(json_data)\n    time.sleep(5)\n\n    # Get all available betting info for the 2020 CFB season.\n    print("Get all available betting info for the 2020 CFB season.")\n    json_data = get_cfbd_betting_lines(\n        season=2020\n    )\n    print(json_data)\n    time.sleep(5)\n\n    # You can also tell this function to just return the API call\n    # as a Dictionary (read: JSON) object.\n    print(\n        "You can also tell this function to just return the API call " +\n        "as a Dictionary (read: JSON) object."\n    )\n    json_data = get_cfbd_betting_lines(\n        season=2020,\n        team="Cincinnati",\n        return_as_dict=True\n    )\n    print(json_data)\n\n
\n\n

Returns

\n\n

A pandas DataFrame object with college football betting data,\nor (if return_as_dict is set to True)\na dictionary object with college football betting data.

\n', signature: - '(\tseason: int = None,\tapi_key: str = None,\tapi_key_dir: str = None,\tgame_id: int = None,\tweek: int = None,\tseason_type: str = 'regular',\tteam: str = None,\thome_team: str = None,\taway_team: str = None,\tconference: str = None,\tyear: int = None,\thome: str = None,\taway: str = None,\treturn_as_dict: bool = False):', + '(\tseason: int = None,\tapi_key: str = None,\tapi_key_dir: str = None,\tweek: int = None,\tseason_type: str = 'regular',\tteam: str = None,\thome_team: str = None,\taway_team: str = None,\tconference: str = None,\tyear: int = None,\thome: str = None,\taway: str = None,\treturn_as_dict: bool = False):', funcdef: "def", }, { @@ -1126,7 +1126,7 @@ window.pdocSearch = (function () { kind: "function", doc: '

Retrieves player game stats for a given time frame.

\n\n

Parameters

\n\n

season (int, mandatory):\n Required argument.\n Specifies the season you want CFB player game stats from.\n This must be specified, otherwise this package, and by extension\n the CFBD API, will not accept the request to get CFB player game stats.

\n\n

api_key (str, optional):\n Semi-optional argument.\n If api_key is null, this function will attempt to load a CFBD API key\n from the python environment, or from a file on this computer.\n If api_key is not null,\n this function will automatically assume that the\n inputted api_key is a valid CFBD API key.

\n\n

api_key_dir (str, optional):\n Optional argument.\n If api_key is set to am empty string, this variable is ignored.\n If api_key_dir is null, and api_key is null,\n this function will try to find\n a CFBD API key file in this user\'s home directory.\n If api_key_dir is set to a string, and api_key is null,\n this function will assume that api_key_dir is a directory,\n and will try to find a CFBD API key file in that directory.

\n\n

season_type (str, semi-optional):\n Semi-optional argument.\n By default, this will be set to "regular", for the CFB regular season.\n If you want CFB player game stats for non-regular season games,\n set season_type to "postseason".\n If season_type is set to anything but "regular" or "postseason",\n a ValueError() will be raised.

\n\n

For the following three variables,\nat least one must be set to\na non-null variable when calling this function.

\n\n

week (int, optional):\n Optional argument.\n If week is set to an integer, this function will attempt\n to load CFB player game stats from games in that season,\n and in that week.

\n\n

team (str, optional):\n Optional argument.\n If you only want CFB player game stats for a team,\n regardless if they are the home/away team,\n set team to the name of the team you want CFB player game stats from.

\n\n

conference (str, optional):\n Optional argument.\n If you only want player game stats from games\n involving teams a specific conference,\n set conference to the abbreviation\n of the conference you want stats from.

\n\n

stat_category (str, optional):\n Optional argument.\n If only want stats for a specific stat category,\n set this variable to that category.

\n\n
Valid inputs are:\n- `passing`\n- `rushing`\n- `receiving`\n- `fumbles`\n- `defensive`\n- `interceptions`\n- `punting`\n- `kicking`\n- `kickReturns`\n- `puntReturns`\n
\n\n

game_id (int, optional):\n Optional argument.\n If game_id is set to a game ID, get_cfbd_player_game_stats()\n will try to get player game stats just for that game ID.

\n\n

return_as_dict (bool, semi-optional):\n Semi-optional argument.\n If you want this function to return\n the data as a dictionary (read: JSON object),\n instead of a pandas DataFrame object,\n set return_as_dict to True.

\n\n

Usage

\n\n
import time\n\nfrom cfbd_json_py.games import get_cfbd_player_game_stats\n\n\ncfbd_key = "tigersAreAwesome"  # placeholder for your CFBD API Key.\n\nif cfbd_key is not "tigersAreAwesome":\n    print(\n        "Using the user\'s API key declared in this script " +\n        "for this example."\n    )\n\n    # Get player game stats for week 10 of the 2020 CFB season.\n    print("Get player game stats for week 10 of the 2020 CFB season.")\n    json_data = get_cfbd_player_game_stats(\n        api_key=cfbd_key,\n        season=2020,\n        week=10\n    )\n    print(json_data)\n    time.sleep(5)\n\n    # Get postseason player game stats for the 2020 CFB season.\n    print("Get postseason player game stats for the 2020 CFB season.")\n    json_data = get_cfbd_player_game_stats(\n        api_key=cfbd_key,\n        season=2020,\n        season_type="postseason",\n        week=1\n    )\n    print(json_data)\n    time.sleep(5)\n\n    # Get player game stats for\n    # the Alabama Crimson Tide Football Team for the 2018 CFB season.\n    print(\n        "Get player game stats for " +\n        "the Alabama Crimson Tide Football Team for the 2018 CFB season."\n    )\n    json_data = get_cfbd_player_game_stats(\n        api_key=cfbd_key,\n        season=2018,\n        team="Alabama"\n    )\n    print(json_data)\n    time.sleep(5)\n\n    # Get player game stats for players of teams in\n    # the Atlantic Coast Conference (ACC) in the 2020 CFB season.\n    print(\n        "Get player game stats for players of teams in " +\n        "the Atlantic Coast Conference (ACC) in the 2020 CFB season."\n    )\n    json_data = get_cfbd_player_game_stats(\n        api_key=cfbd_key,\n        season=2020,\n        conference="ACC"\n    )\n    print(json_data)\n    time.sleep(5)\n\n    # Get get passing stats from players who played\n    # in week 7 of the 2017 CFB season.\n    print(\n        "Get get passing stats from players who played " +\n        "in week 7 of the 2017 CFB season."\n    )\n    json_data = get_cfbd_player_game_stats(\n        api_key=cfbd_key,\n        season=2017,\n        week=7,\n        stat_category="passing"\n    )\n    print(json_data)\n    time.sleep(5)\n\n    # Get player game stats from the 2021 Virbo Citrus Bowl,\n    # a bowl game that happened in the 2020 CFB season.\n    print(\n        "Get player game stats from the 2021 Virbo Citrus Bowl, " +\n        "a bowl game that happened in the 2020 CFB season."\n    )\n    json_data = get_cfbd_player_game_stats(\n        api_key=cfbd_key,\n        season=2020,\n        game_id=401256199\n    )\n    print(json_data)\n    time.sleep(5)\n\n    # You can also tell this function to just return the API call as\n    # a Dictionary (read: JSON) object.\n    print(\n        "You can also tell this function to just return the API call " +\n        "as a Dictionary (read: JSON) object."\n    )\n    json_data = get_cfbd_player_game_stats(\n        season=2020,\n        week=10,\n        api_key=cfbd_key,\n        return_as_dict=True\n    )\n    print(json_data)\n\nelse:\n    # Alternatively, if the CFBD API key exists in this python environment,\n    # or it\'s been set by cfbd_json_py.utls.set_cfbd_api_token(),\n    # you could just call these functions directly,\n    # without setting the API key in the script.\n    print(\n        "Using the user\'s API key supposedly loaded " +\n        "into this python environment for this example."\n    )\n\n    # Get player game stats for week 10 of the 2020 CFB season.\n    print("Get player game stats for week 10 of the 2020 CFB season.")\n    json_data = get_cfbd_player_game_stats(\n        season=2020,\n        week=10\n    )\n    print(json_data)\n    time.sleep(5)\n\n    # Get postseason player game stats for the 2020 CFB season.\n    print("Get postseason player game stats for the 2020 CFB season.")\n    json_data = get_cfbd_player_game_stats(\n        season=2020,\n        season_type="postseason",\n        week=1\n    )\n    print(json_data)\n    time.sleep(5)\n\n    # Get player game stats for\n    # the Alabama Crimson Tide Football Team for the 2018 CFB season.\n    print(\n        "Get player game stats for " +\n        "the Alabama Crimson Tide Football Team for the 2018 CFB season."\n    )\n    json_data = get_cfbd_player_game_stats(\n        season=2018,\n        team="Alabama"\n    )\n    print(json_data)\n    time.sleep(5)\n\n    # Get player game stats for players of teams in\n    # the Atlantic Coast Conference (ACC) in the 2020 CFB season.\n    print(\n        "Get player game stats for players of teams in " +\n        "the Atlantic Coast Conference (ACC) in the 2020 CFB season."\n    )\n    json_data = get_cfbd_player_game_stats(\n        season=2020,\n        conference="ACC"\n    )\n    print(json_data)\n    time.sleep(5)\n\n    # Get get passing stats from players who played\n    # in week 7 of the 2017 CFB season.\n    print(\n        "Get get passing stats from players who played " +\n        "in week 7 of the 2017 CFB season."\n    )\n    json_data = get_cfbd_player_game_stats(\n        season=2017,\n        week=7,\n        stat_category="passing"\n    )\n    print(json_data)\n    time.sleep(5)\n\n    # Get player game stats from the 2021 Virbo Citrus Bowl,\n    # a bowl game that happened in the 2020 CFB season,\n    # between the Aubrun Tigers, and the Northwestern Wildcats.\n    print("Get player game stats from the 2021 Virbo Citrus Bowl, "+\n        "a bowl game that happened in the 2020 CFB season " +\n        "between the Aubrun Tigers, and the Northwestern Wildcats."\n    )\n    json_data = get_cfbd_player_game_stats(\n        season=2020,\n        game_id=401256199\n    )\n    print(json_data)\n    time.sleep(5)\n\n\n    # You can also tell this function to just return the API call as\n    # a Dictionary (read: JSON) object.\n    print(\n        "You can also tell this function to just return the API call " +\n        "as a Dictionary (read: JSON) object."\n    )\n    json_data = get_cfbd_player_game_stats(\n        season=2020,\n        week=10,\n        return_as_dict=True\n    )\n    print(json_data)\n\n
\n\n

Returns

\n\n

A pandas DataFrame object with player game stats data,\nor (if return_as_dict is set to True)\na dictionary object with player game stats data.

\n', signature: - '(\tseason: int,\tapi_key: str = None,\tapi_key_dir: str = None,\tseason_type: str = 'regular',\tweek: int = None,\tteam: str = None,\tconference: str = None,\tstat_category: str = None,\tgame_id: int = None,\treturn_as_dict: bool = False):', + '(\tseason: int,\tapi_key: str = None,\tapi_key_dir: str = None,\tseason_type: str = 'regular',\tweek: int = None,\tteam: str = None,\tconference: str = None,\ts_category: str = None,\tgame_id: int = None,\treturn_as_dict: bool = False):', funcdef: "def", }, { @@ -1154,9 +1154,9 @@ window.pdocSearch = (function () { modulename: "cfbd_json_py.games", qualname: "get_cfbd_weather_info", kind: "function", - doc: '

YOU MUST BE SUBSCRIBED TO THE CFBD PATREON FOR THIS FUNCTION TO WORK!\nTo view the CFBD Patreon, visit https://www.patreon.com/collegefootballdata

\n\n

Parameters

\n\n

Retrieves live scoreboard data from the CFBD API,\nassuming the API key is an API key from a Patreon supporter.

\n\n

Parameters

\n\n

game_id (int, mandatory):\n Mandatory requirement.\n Specifies the game you want weather data from.\n This or season must be set to a valid non-null value.

\n\n

season (int, mandatory):\n Mandatory requirement.\n Specifies the season you want weather data from.\n This or season must be set to a valid non-null value.

\n\n

week (int, optional):\n Optional argument.\n If week is set to an integer, this function will attempt\n to load weather data from games in that season, and in that week.

\n\n

season_type (str, semi-optional):\n Semi-optional argument.\n By default, this will be set to "both", for the CFB regular season.\n If you want postseason betting data, set season_type to "postseason".\n If season_type is set to anything but "regular" or "postseason",\n a ValueError() will be raised.

\n\n

conference (str, optional):\n Optional argument.\n If you only want weather data from games\n involving teams a specific conference,\n set conference to the abbreviation\n of the conference you want weather data from.

\n\n

team_name (str, optional):\n Optional argument.\n If you only want weather data for a team,\n regardless if they are the home/away team,\n set team to the name of the team\n you want weather data from.

\n\n

ncaa_division (str, semi-optional):\n Semi-optional argument.\n By default, ncaa_division will be set to "fbs",\n short for the Football Bowl Subdivision (FBS),\n formerly known as D1-A (read as "division one single A"),\n the highest level in the NCAA football pyramid,\n where teams can scholarship up to 85 players\n on their football team solely for athletic ability,\n and often have the largest athletics budgets\n within the NCAA.

\n\n
Other valid inputs are:\n- "fcs": Football Championship Subdivision (FCS),\n    formerly known as D1-AA (read as "division one double A").\n    An FCS school is still in the 1st division of the NCAA,\n    making them eligible for the March Madness tournament,\n    but may not have the resources to compete at the FBS level\n    at this time. FCS schools are limited to 63 athletic scholarships\n    for football.\n- "ii": NCAA Division II. Schools in this and D3 are not\n    eligible for the March Madness tournament,\n    and are limited to 36 athletic scholarships\n    for their football team.\n- "iii": NCAA Division III. The largest single division within the\n    NCAA football pyramid.\n    D3 schools have the distinction of being part of\n    the only NCAA division that cannot give out scholarships solely\n    for athletic ability.\n
\n\n

api_key (str, optional):\n Semi-optional argument.\n If api_key is null, this function will attempt to load a CFBD API key\n from the python environment, or from a file on this computer.\n If api_key is not null,\n this function will automatically assume that the\n inputted api_key is a valid CFBD API key.

\n\n

api_key_dir (str, optional):\n Optional argument.\n If api_key is set to am empty string, this variable is ignored.\n If api_key_dir is null, and api_key is null,\n this function will try to find\n a CFBD API key file in this user\'s home directory.\n If api_key_dir is set to a string, and api_key is null,\n this function will assume that api_key_dir is a directory,\n and will try to find a CFBD API key file in that directory.

\n\n

return_as_dict (bool, semi-optional):\n Semi-optional argument.\n If you want this function to return\n the data as a dictionary (read: JSON object),\n instead of a pandas DataFrame object,\n set return_as_dict to True.

\n\n

Usage

\n\n
import time\n\nfrom cfbd_json_py.games import get_cfbd_weather_info\n\n\ncfbd_key = "tigersAreAwesome"  # placeholder for your CFBD API Key.\n\nif cfbd_key != "tigersAreAwesome":\n    print(\n        "Using the user\'s API key declared " +\n        "in this script for this example."\n    )\n\n    # Get weather data for the 2024 CFB season\n    print(\n        "Get weather data for the 2024 CFB season."\n    )\n    json_data = get_cfbd_weather_info(\n        season=2024,\n        api_key=cfbd_key\n    )\n    print(json_data)\n    time.sleep(5)\n\n    # Get weather data for the 2024 Rose Bowl (game ID #401551786).\n    print(\n        "Get weather data for the 2024 Rose Bowl (game ID #401551786)."\n    )\n    json_data = get_cfbd_weather_info(\n        game_id=401551786,\n        api_key=cfbd_key\n    )\n    print(json_data)\n    time.sleep(5)\n\n    # Get weather data for week 1 of the 2024 CFB season\n    print(\n        "Get weather data for week 1 of the 2024 CFB season."\n    )\n    json_data = get_cfbd_weather_info(\n        season=2024,\n        week=1,\n        api_key=cfbd_key\n    )\n    print(json_data)\n    time.sleep(5)\n\n    # Get weather data for postseason games of the 2023 CFB season.\n    print(\n        "Get weather data for postseason games of the 2023 CFB season."\n    )\n    json_data = get_cfbd_weather_info(\n        season=2023,\n        season_type="postseason",\n        api_key=cfbd_key\n    )\n    print(json_data)\n    time.sleep(5)\n\n    # Get weather data for postseason games of the 2023 CFB season.\n    print(\n        "Get weather data for postseason games of the 2023 CFB season."\n    )\n    json_data = get_cfbd_weather_info(\n        season=2023,\n        season_type="postseason",\n        api_key=cfbd_key\n    )\n    print(json_data)\n    time.sleep(5)\n\n    # Get weather data for Big 10 (B1G) games of the 2024 CFB season.\n    print(\n        "Get weather data for Big 10 (B1G) games of the 2024 CFB season."\n    )\n    json_data = get_cfbd_weather_info(\n        season=2024,\n        conference="B1G",\n        api_key=cfbd_key\n    )\n    print(json_data)\n    time.sleep(5)\n\n    # Get weather data for FCS games of the 2024 CFB season.\n    print(\n        "Get weather data for FCS games of the 2024 CFB season."\n    )\n    json_data = get_cfbd_weather_info(\n        season=2024,\n        ncaa_division="fcs",\n        api_key=cfbd_key\n    )\n    print(json_data)\n    time.sleep(5)\n\n    # Get weather data for University of Cincinnati games\n    # of the 2024 CFB season.\n    print(\n        "Get weather data for Big 10 (B1G) games of the 2024 CFB season."\n    )\n    json_data = get_cfbd_weather_info(\n        season=2024,\n        team_name="Cincinnati",\n        api_key=cfbd_key\n    )\n    print(json_data)\n    time.sleep(5)\n\n    # You can also tell this function to just return the API call\n    # as a Dictionary (read: JSON) object.\n    print(\n        "You can also tell this function to just return the API call " +\n        "as a Dictionary (read: JSON) object."\n    )\n    json_data = get_cfbd_weather_info(\n        api_key=cfbd_key,\n        season=2023,\n        return_as_dict=True\n    )\n    print(json_data)\n\nelse:\n    # Alternatively, if the CFBD API key exists in this python environment,\n    # or it\'s been set by cfbd_json_py.utls.set_cfbd_api_token(),\n    # you could just call these functions directly,\n    # without setting the API key in the script.\n    print(\n        "Using the user\'s API key supposedly loaded " +\n        "into this python environment for this example."\n    )\n\n    # Get weather data for the 2024 CFB season\n    print(\n        "Get weather data for the 2024 CFB season."\n    )\n    json_data = get_cfbd_weather_info(\n        season=2024\n    )\n    print(json_data)\n    time.sleep(5)\n\n    # Get weather data for the 2024 Rose Bowl (game ID #401551786).\n    print(\n        "Get weather data for the 2024 Rose Bowl (game ID #401551786)."\n    )\n    json_data = get_cfbd_weather_info(\n        game_id=401551786\n    )\n    print(json_data)\n    time.sleep(5)\n\n    # Get weather data for week 1 of the 2024 CFB season\n    print(\n        "Get weather data for week 1 of the 2024 CFB season."\n    )\n    json_data = get_cfbd_weather_info(\n        season=2024,\n        week=1\n    )\n    print(json_data)\n    time.sleep(5)\n\n    # Get weather data for postseason games of the 2023 CFB season.\n    print(\n        "Get weather data for postseason games of the 2023 CFB season."\n    )\n    json_data = get_cfbd_weather_info(\n        season=2023,\n        season_type="postseason"\n    )\n    print(json_data)\n    time.sleep(5)\n\n    # Get weather data for postseason games of the 2023 CFB season.\n    print(\n        "Get weather data for postseason games of the 2023 CFB season."\n    )\n    json_data = get_cfbd_weather_info(\n        season=2023,\n        season_type="postseason"\n    )\n    print(json_data)\n    time.sleep(5)\n\n    # Get weather data for Big 10 (B1G) games of the 2024 CFB season.\n    print(\n        "Get weather data for Big 10 (B1G) games of the 2024 CFB season."\n    )\n    json_data = get_cfbd_weather_info(\n        season=2024,\n        conference="B1G"\n    )\n    print(json_data)\n    time.sleep(5)\n\n    # Get weather data for FCS games of the 2024 CFB season.\n    print(\n        "Get weather data for FCS games of the 2024 CFB season."\n    )\n    json_data = get_cfbd_weather_info(\n        season=2024,\n        ncaa_division="fcs"\n    )\n    print(json_data)\n    time.sleep(5)\n\n    # Get weather data for University of Cincinnati games\n    # of the 2024 CFB season.\n    print(\n        "Get weather data for Big 10 (B1G) games of the 2024 CFB season."\n    )\n    json_data = get_cfbd_weather_info(\n        season=2024,\n        team_name="Cincinnati"\n    )\n    print(json_data)\n    time.sleep(5)\n\n    # You can also tell this function to just return the API call\n    # as a Dictionary (read: JSON) object.\n    print(\n        "You can also tell this function to just return the API call " +\n        "as a Dictionary (read: JSON) object."\n    )\n    json_data = get_cfbd_weather_info(\n        season=2023,\n        return_as_dict=True\n    )\n    print(json_data)\n\n
\n\n

Returns

\n\n

A pandas DataFrame object with live weather data,\nor (if return_as_dict is set to True)\na dictionary object with live weather data.

\n', + doc: '

YOU MUST BE SUBSCRIBED TO THE CFBD PATREON FOR THIS FUNCTION TO WORK!\nTo view the CFBD Patreon, visit https://www.patreon.com/collegefootballdata

\n\n

Parameters

\n\n

Retrieves live scoreboard data from the CFBD API,\nassuming the API key is an API key from a Patreon supporter.

\n\n

Parameters

\n\n

game_id (int, mandatory):\n DEPRECATED FROM V1.\n Specifies the game you want weather data from.\n This or season must be set to a valid non-null value.

\n\n

season (int, mandatory):\n Mandatory requirement.\n Specifies the season you want weather data from.\n This or season must be set to a valid non-null value.

\n\n

week (int, optional):\n Optional argument.\n If week is set to an integer, this function will attempt\n to load weather data from games in that season, and in that week.

\n\n

season_type (str, semi-optional):\n Semi-optional argument.\n By default, this will be set to "both", for the CFB regular season.\n If you want postseason betting data, set season_type to "postseason".\n If season_type is set to anything but "regular" or "postseason",\n a ValueError() will be raised.

\n\n

conference (str, optional):\n Optional argument.\n If you only want weather data from games\n involving teams a specific conference,\n set conference to the abbreviation\n of the conference you want weather data from.

\n\n

team_name (str, optional):\n Optional argument.\n If you only want weather data for a team,\n regardless if they are the home/away team,\n set team to the name of the team\n you want weather data from.

\n\n

ncaa_division (str, semi-optional):\n Semi-optional argument.\n By default, ncaa_division will be set to "fbs",\n short for the Football Bowl Subdivision (FBS),\n formerly known as D1-A (read as "division one single A"),\n the highest level in the NCAA football pyramid,\n where teams can scholarship up to 85 players\n on their football team solely for athletic ability,\n and often have the largest athletics budgets\n within the NCAA.

\n\n
Other valid inputs are:\n- "fcs": Football Championship Subdivision (FCS),\n    formerly known as D1-AA (read as "division one double A").\n    An FCS school is still in the 1st division of the NCAA,\n    making them eligible for the March Madness tournament,\n    but may not have the resources to compete at the FBS level\n    at this time. FCS schools are limited to 63 athletic scholarships\n    for football.\n- "ii": NCAA Division II. Schools in this and D3 are not\n    eligible for the March Madness tournament,\n    and are limited to 36 athletic scholarships\n    for their football team.\n- "iii": NCAA Division III. The largest single division within the\n    NCAA football pyramid.\n    D3 schools have the distinction of being part of\n    the only NCAA division that cannot give out scholarships solely\n    for athletic ability.\n
\n\n

api_key (str, optional):\n Semi-optional argument.\n If api_key is null, this function will attempt to load a CFBD API key\n from the python environment, or from a file on this computer.\n If api_key is not null,\n this function will automatically assume that the\n inputted api_key is a valid CFBD API key.

\n\n

api_key_dir (str, optional):\n Optional argument.\n If api_key is set to am empty string, this variable is ignored.\n If api_key_dir is null, and api_key is null,\n this function will try to find\n a CFBD API key file in this user\'s home directory.\n If api_key_dir is set to a string, and api_key is null,\n this function will assume that api_key_dir is a directory,\n and will try to find a CFBD API key file in that directory.

\n\n

return_as_dict (bool, semi-optional):\n Semi-optional argument.\n If you want this function to return\n the data as a dictionary (read: JSON object),\n instead of a pandas DataFrame object,\n set return_as_dict to True.

\n\n

Usage

\n\n
import time\n\nfrom cfbd_json_py.games import get_cfbd_weather_info\n\n\ncfbd_key = "tigersAreAwesome"  # placeholder for your CFBD API Key.\n\nif cfbd_key != "tigersAreAwesome":\n    print(\n        "Using the user\'s API key declared " +\n        "in this script for this example."\n    )\n\n    # Get weather data for the 2024 CFB season\n    print(\n        "Get weather data for the 2024 CFB season."\n    )\n    json_data = get_cfbd_weather_info(\n        season=2024,\n        api_key=cfbd_key\n    )\n    print(json_data)\n    time.sleep(5)\n\n    # Get weather data for the 2024 Rose Bowl (game ID #401551786).\n    print(\n        "Get weather data for the 2024 Rose Bowl (game ID #401551786)."\n    )\n    json_data = get_cfbd_weather_info(\n        game_id=401551786,\n        api_key=cfbd_key\n    )\n    print(json_data)\n    time.sleep(5)\n\n    # Get weather data for week 1 of the 2024 CFB season\n    print(\n        "Get weather data for week 1 of the 2024 CFB season."\n    )\n    json_data = get_cfbd_weather_info(\n        season=2024,\n        week=1,\n        api_key=cfbd_key\n    )\n    print(json_data)\n    time.sleep(5)\n\n    # Get weather data for postseason games of the 2023 CFB season.\n    print(\n        "Get weather data for postseason games of the 2023 CFB season."\n    )\n    json_data = get_cfbd_weather_info(\n        season=2023,\n        season_type="postseason",\n        api_key=cfbd_key\n    )\n    print(json_data)\n    time.sleep(5)\n\n    # Get weather data for postseason games of the 2023 CFB season.\n    print(\n        "Get weather data for postseason games of the 2023 CFB season."\n    )\n    json_data = get_cfbd_weather_info(\n        season=2023,\n        season_type="postseason",\n        api_key=cfbd_key\n    )\n    print(json_data)\n    time.sleep(5)\n\n    # Get weather data for Big 10 (B1G) games of the 2024 CFB season.\n    print(\n        "Get weather data for Big 10 (B1G) games of the 2024 CFB season."\n    )\n    json_data = get_cfbd_weather_info(\n        season=2024,\n        conference="B1G",\n        api_key=cfbd_key\n    )\n    print(json_data)\n    time.sleep(5)\n\n    # Get weather data for FCS games of the 2024 CFB season.\n    print(\n        "Get weather data for FCS games of the 2024 CFB season."\n    )\n    json_data = get_cfbd_weather_info(\n        season=2024,\n        ncaa_division="fcs",\n        api_key=cfbd_key\n    )\n    print(json_data)\n    time.sleep(5)\n\n    # Get weather data for University of Cincinnati games\n    # of the 2024 CFB season.\n    print(\n        "Get weather data for Big 10 (B1G) games of the 2024 CFB season."\n    )\n    json_data = get_cfbd_weather_info(\n        season=2024,\n        team_name="Cincinnati",\n        api_key=cfbd_key\n    )\n    print(json_data)\n    time.sleep(5)\n\n    # You can also tell this function to just return the API call\n    # as a Dictionary (read: JSON) object.\n    print(\n        "You can also tell this function to just return the API call " +\n        "as a Dictionary (read: JSON) object."\n    )\n    json_data = get_cfbd_weather_info(\n        api_key=cfbd_key,\n        season=2023,\n        return_as_dict=True\n    )\n    print(json_data)\n\nelse:\n    # Alternatively, if the CFBD API key exists in this python environment,\n    # or it\'s been set by cfbd_json_py.utls.set_cfbd_api_token(),\n    # you could just call these functions directly,\n    # without setting the API key in the script.\n    print(\n        "Using the user\'s API key supposedly loaded " +\n        "into this python environment for this example."\n    )\n\n    # Get weather data for the 2024 CFB season\n    print(\n        "Get weather data for the 2024 CFB season."\n    )\n    json_data = get_cfbd_weather_info(\n        season=2024\n    )\n    print(json_data)\n    time.sleep(5)\n\n    # Get weather data for the 2024 Rose Bowl (game ID #401551786).\n    print(\n        "Get weather data for the 2024 Rose Bowl (game ID #401551786)."\n    )\n    json_data = get_cfbd_weather_info(\n        game_id=401551786\n    )\n    print(json_data)\n    time.sleep(5)\n\n    # Get weather data for week 1 of the 2024 CFB season\n    print(\n        "Get weather data for week 1 of the 2024 CFB season."\n    )\n    json_data = get_cfbd_weather_info(\n        season=2024,\n        week=1\n    )\n    print(json_data)\n    time.sleep(5)\n\n    # Get weather data for postseason games of the 2023 CFB season.\n    print(\n        "Get weather data for postseason games of the 2023 CFB season."\n    )\n    json_data = get_cfbd_weather_info(\n        season=2023,\n        season_type="postseason"\n    )\n    print(json_data)\n    time.sleep(5)\n\n    # Get weather data for postseason games of the 2023 CFB season.\n    print(\n        "Get weather data for postseason games of the 2023 CFB season."\n    )\n    json_data = get_cfbd_weather_info(\n        season=2023,\n        season_type="postseason"\n    )\n    print(json_data)\n    time.sleep(5)\n\n    # Get weather data for Big 10 (B1G) games of the 2024 CFB season.\n    print(\n        "Get weather data for Big 10 (B1G) games of the 2024 CFB season."\n    )\n    json_data = get_cfbd_weather_info(\n        season=2024,\n        conference="B1G"\n    )\n    print(json_data)\n    time.sleep(5)\n\n    # Get weather data for FCS games of the 2024 CFB season.\n    print(\n        "Get weather data for FCS games of the 2024 CFB season."\n    )\n    json_data = get_cfbd_weather_info(\n        season=2024,\n        ncaa_division="fcs"\n    )\n    print(json_data)\n    time.sleep(5)\n\n    # Get weather data for University of Cincinnati games\n    # of the 2024 CFB season.\n    print(\n        "Get weather data for Big 10 (B1G) games of the 2024 CFB season."\n    )\n    json_data = get_cfbd_weather_info(\n        season=2024,\n        team_name="Cincinnati"\n    )\n    print(json_data)\n    time.sleep(5)\n\n    # You can also tell this function to just return the API call\n    # as a Dictionary (read: JSON) object.\n    print(\n        "You can also tell this function to just return the API call " +\n        "as a Dictionary (read: JSON) object."\n    )\n    json_data = get_cfbd_weather_info(\n        season=2023,\n        return_as_dict=True\n    )\n    print(json_data)\n\n
\n\n

Returns

\n\n

A pandas DataFrame object with live weather data,\nor (if return_as_dict is set to True)\na dictionary object with live weather data.

\n', signature: - '(\tgame_id: int = None,\tseason: int = None,\tweek: int = None,\tseason_type: str = 'both',\tconference: str = None,\tteam_name: str = None,\tncaa_division: str = 'fbs',\tapi_key: str = None,\tapi_key_dir: str = None,\treturn_as_dict: bool = False):', + '(\tseason: int = None,\tweek: int = None,\tseason_type: str = 'both',\tconference: str = None,\tteam_name: str = None,\tncaa_division: str = 'fbs',\tapi_key: str = None,\tapi_key_dir: str = None,\treturn_as_dict: bool = False):', funcdef: "def", }, { diff --git a/pyproject.toml b/pyproject.toml index b2039f5..01360e9 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta" [project] name = "cfbd_json_py" -version = "0.2.3" +version = "0.2.4" readme = "README.md" requires-python = ">=3.10" license = {text = "MIT"}