cfbd_json_py.games
1# Creation Date: 08/30/2023 01:13 EDT 2# Last Updated Date: 09/16/2024 06:10 PM EDT 3# Author: Joseph Armstrong (armstrongjoseph08@gmail.com) 4# File Name: games.py 5# Purpose: Houses functions pertaining to CFB game data within the CFBD API. 6############################################################################### 7 8import logging 9from datetime import datetime 10 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 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 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 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 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 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 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 888 Usage 889 ---------- 890 ``` 891 import time 892 893 from cfbd_json_py.games import get_cfbd_season_weeks 894 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 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 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 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 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 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 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 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 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 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 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 stat_category is None: 2043 pass 2044 elif stat_category == "passing": 2045 filter_by_stat_category = True 2046 elif stat_category == "rushing": 2047 filter_by_stat_category = True 2048 elif stat_category == "receiving": 2049 filter_by_stat_category = True 2050 elif stat_category == "fumbles": 2051 filter_by_stat_category = True 2052 elif stat_category == "passing": 2053 filter_by_stat_category = True 2054 elif stat_category == "defensive": 2055 filter_by_stat_category = True 2056 elif stat_category == "interceptions": 2057 filter_by_stat_category = True 2058 elif stat_category == "punting": 2059 filter_by_stat_category = True 2060 elif stat_category == "kicking": 2061 filter_by_stat_category = True 2062 elif stat_category == "kickReturns": 2063 filter_by_stat_category = True 2064 elif stat_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 stat_category is not None: 2094 url += f"&category={stat_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 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 stat_category in team["categories"]: 2150 stat_category = stat_category["name"] 2151 for s_type in stat_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 "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 Parameters 2449 ---------- 2450 `game_id` (int, mandatory): 2451 Mandatory requirement. 2452 Specifies the game you want advanced game stats from. 2453 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 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 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 `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 # 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 # 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 `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 # 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 # 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 # 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 # 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 # 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 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 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 [ 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
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 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
Retrieves game schedule data from the CFBD API.
Parameters
season
(int, mandatory):
Required argument.
Specifies the season you want CFB game information from.
This must be specified, otherwise this package, and by extension
the CFBD API, will not accept the request to get CFB game information.
api_key
(str, optional):
Semi-optional argument.
If api_key
is null, this function will attempt to load a CFBD API key
from the python environment, or from a file on this computer.
If api_key
is not null,
this function will automatically assume that the
inputted api_key
is a valid CFBD API key.
api_key_dir
(str, optional):
Optional argument.
If api_key
is set to am empty string, this variable is ignored.
If api_key_dir
is null, and api_key
is null,
this function will try to find
a CFBD API key file in this user's home directory.
If api_key_dir
is set to a string, and api_key
is null,
this function will assume that api_key_dir
is a directory,
and will try to find a CFBD API key file in that directory.
season_type
(str, semi-optional):
Semi-optional argument.
By default, this will be set to "regular", for the CFB regular season.
If you want CFB game information for non-regular season games,
set season_type
to "postseason".
If season_type
is set to anything but "regular" or "postseason",
a ValueError()
will be raised.
week
(int, optional):
Optional argument.
If week
is set to an integer, this function will attempt
to load CFB game data from games in that season, and in that week.
team
(str, optional):
Optional argument.
If you only want CFB game information for a team,
regardless if they are the home/away team,
set team
to the name of the team you want CFB game information from.
home_team
(str, optional):
Optional argument.
If you only want game information for a team,
where that team was the home team in this season,
set home_team
to the name of the team you want game information for.
away_team
(str, optional):
Optional argument.
If you only want game information for a team,
where that team was the away team in this season,
set away_team
to the name of the team you want game information for.
conference
(str, optional):
Optional argument.
If you only want game information from games
involving teams a specific conference,
set conference
to the abbreviation
of the conference you want game information from.
ncaa_division
(str, semi-optional):
Semi-optional argument.
By default, ncaa_division
will be set to "fbs",
short for the Football Bowl Subdivision (FBS),
formerly known as D1-A (read as "division one single A"),
the highest level in the NCAA football pyramid,
where teams can scholarship up to 85 players
on their football team solely for athletic ability,
and often have the largest athletics budgets
within the NCAA.
Other valid inputs are:
- "fcs": Football Championship Subdivision (FCS),
formerly known as D1-AA (read as "division one double A").
An FCS school is still in the 1st division of the NCAA,
making them eligible for the March Madness tournament,
but may not have the resources to compete at the FBS level
at this time. FCS schools are limited to 63 athletic scholarships
for football.
- "ii": NCAA Division II. Schools in this and D3 are not
eligible for the March Madness tournament,
and are limited to 36 athletic scholarships
for their football team.
- "iii": NCAA Division III. The largest single division within the
NCAA football pyramid.
D3 schools have the distinction of being part of
the only NCAA division that cannot give out scholarships solely
for athletic ability.
game_id
(int, optional):
Optional argument.
If game_id
is set to a game ID,
get_cfb_betting_lines()
will try to get
game information just for that game ID.
return_as_dict
(bool, semi-optional):
Semi-optional argument.
If you want this function to return
the data as a dictionary (read: JSON object),
instead of a pandas DataFrame
object,
set return_as_dict
to True
.
Usage
import time
from cfbd_json_py.games import get_cfbd_games
cfbd_key = "tigersAreAwesome" # placeholder for your CFBD API Key.
if cfbd_key is not "tigersAreAwesome":
print(
"Using the user's API key declared in this script " +
"for this example."
)
# Get CFB games from the 2020 CFB season.
print("Get CFB games from the 2020 CFB season.")
json_data = get_cfbd_games(
api_key=cfbd_key,
season=2020
)
print(json_data)
time.sleep(5)
# Get CFB games from week 10 of the 2020 CFB season.
print("Get CFB games from week 10 of the 2020 CFB season.")
json_data = get_cfbd_games(
api_key=cfbd_key,
season=2020,
week=10
)
print(json_data)
time.sleep(5)
# Get CFB games from the 2019 CFB season
# that involved the 2019 LSU Tigers.
print(
"Get CFB games from the 2019 CFB season " +
"that involved the 2019 LSU Tigers."
)
json_data = get_cfbd_games(
api_key=cfbd_key,
season=2019,
team="LSU"
)
print(json_data)
time.sleep(5)
# Get 2021 Cincinnati Bearcats Football games
# where the Bearcats were the home team.
print(
"Get 2021 Cincinnati Bearcats Football games " +
"where the Bearcats were the home team."
)
json_data = get_cfbd_games(
api_key=cfbd_key,
season=2021,
home_team="Cincinnati"
)
print(json_data)
time.sleep(5)
# Get 2018 Ohio Bobcats Football games
# where the Bobcats were the away team.
print(
"Get 2018 Ohio Bobcats Football games " +
"where the Bobcats were the away team."
)
json_data = get_cfbd_games(
api_key=cfbd_key,
season=2019,
away_team="Ohio"
)
print(json_data)
time.sleep(5)
# Get 2022 college football games where one or more teams competing
# was a Football Championship Subdivision team.
print(
"Get 2022 college football games where one or more " +
"teams competing was a Football Championship Subdivision team."
)
json_data = get_cfbd_games(
api_key=cfbd_key,
season=2018,
away_team="Ohio"
)
print(json_data)
time.sleep(5)
# Get game information for the
# 2021 American Athletic conference (AAC) Championship Game.
print(
"Get game information for " +
"the 2021 American Athletic conference (AAC) Championship Game."
)
json_data = get_cfbd_games(
api_key=cfbd_key,
season=2018,
game_id=401331162
)
print(json_data)
time.sleep(5)
# You can also tell this function to just return the API call as
# a Dictionary (read: JSON) object.
print(
"You can also tell this function to just return the API call " +
"as a Dictionary (read: JSON) object."
)
json_data = get_cfbd_games(
season=2020,
week=10,
api_key=cfbd_key,
return_as_dict=True
)
print(json_data)
else:
# Alternatively, if the CFBD API key exists in this python environment,
# or it's been set by cfbd_json_py.utls.set_cfbd_api_token(),
# you could just call these functions directly,
# without setting the API key in the script.
print(
"Using the user's API key supposedly loaded " +
"into this python environment for this example."
)
# Get CFB games from the 2020 CFB season.
print("Get CFB games from the 2020 CFB season.")
json_data = get_cfbd_games(
season=2020
)
print(json_data)
time.sleep(5)
# Get CFB games from week 10 of the 2020 CFB season.
print("Get CFB games from week 10 of the 2020 CFB season.")
json_data = get_cfbd_games(
season=2020,
week=10
)
print(json_data)
time.sleep(5)
# Get CFB games from the 2019 CFB season
# that involved the 2019 LSU Tigers.
print(
"Get CFB games from the 2019 CFB season " +
"that involved the 2019 LSU Tigers."
)
json_data = get_cfbd_games(
season=2019,
team="LSU"
)
print(json_data)
time.sleep(5)
# Get 2021 Cincinnati Bearcats Football games
# where the Bearcats were the home team.
print(
"Get 2021 Cincinnati Bearcats Football games " +
"where the Bearcats were the home team."
)
json_data = get_cfbd_games(
season=2021,
home_team="Cincinnati"
)
print(json_data)
time.sleep(5)
# Get 2018 Ohio Bobcats Football games
# where the Bobcats were the away team.
print(
"Get 2018 Ohio Bobcats Football games " +
"where the Bobcats were the away team."
)
json_data = get_cfbd_games(
season=2019,
away_team="Ohio"
)
print(json_data)
time.sleep(5)
# Get 2018 Ohio Bobcats Football games
# where the Bobcats were the away team.
print(
"Get 2018 Ohio Bobcats Football games " +
"where the Bobcats were the away team."
)
json_data = get_cfbd_games(
season=2018,
away_team="Ohio"
)
print(json_data)
time.sleep(5)
# Get 2022 college football games where one or more teams competing
# was a Football Championship Subdivision team.
print(
"Get 2022 college football games where one or more " +
"teams competing was a Football Championship Subdivision team."
)
json_data = get_cfbd_games(
season=2018,
away_team="Ohio"
)
print(json_data)
time.sleep(5)
# Get game information for the
# 2021 American Athletic conference (AAC) Championship Game.
print(
"Get game information for " +
"the 2021 American Athletic conference (AAC) Championship Game."
)
json_data = get_cfbd_games(
season=2018,
game_id=401331162
)
print(json_data)
time.sleep(5)
# You can also tell this function to just return the API call as
# a Dictionary (read: JSON) object.
print(
"You can also tell this function to just return the API call " +
"as a Dictionary (read: JSON) object."
)
json_data = get_cfbd_games(
season=2020,
week=10,
return_as_dict=True
)
print(json_data)
Returns
A pandas DataFrame
object with college football game information,
or (if return_as_dict
is set to True
)
a dictionary object with college football game information.
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 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 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
Get a team, or multiple team's record (wins, losses, ties) for home games, away games, conference games, and the team's record for that season.
Parameters
api_key
(str, optional):
Semi-optional argument.
If api_key
is null, this function will attempt to load a CFBD API key
from the python environment, or from a file on this computer.
If api_key
is not null,
this function will automatically assume that the
inputted api_key
is a valid CFBD API key.
api_key_dir
(str, optional):
Optional argument.
If api_key
is set to am empty string, this variable is ignored.
If api_key_dir
is null, and api_key
is null,
this function will try to find
a CFBD API key file in this user's home directory.
If api_key_dir
is set to a string, and api_key
is null,
this function will assume that api_key_dir
is a directory,
and will try to find a CFBD API key file in that directory.
season
(int, optional):
Semi-optional argument.
Specifies the season you want CFB team records data from.
You MUST set season
or team
to a non-null value for
this function to work. If you don't, a ValueError()
will be raised.
team
(str, optional):
Semi-optional argument.
If you only want CFB team records data for a specific team,
set team
to the name of the team you want CFB drive data from.
You MUST set season
or team
to a non-null value for
this function to work. If you don't, a ValueError()
will be raised.
conference
(str, optional):
Optional argument.
If you only want CFB team records data from games
involving teams from a specific conference,
set conference
to the abbreviation
of the conference you want CFB team records data from.
For a list of conferences,
use the cfbd_json_py.conferences.get_cfbd_conference_info()
function.
return_as_dict
(bool, semi-optional):
Semi-optional argument.
If you want this function to return
the data as a dictionary (read: JSON object),
instead of a pandas DataFrame
object,
set return_as_dict
to True
.
Usage
import time
from cfbd_json_py.games import get_cfbd_team_records
cfbd_key = "tigersAreAwesome" # placeholder for your CFBD API Key.
if cfbd_key is not "tigersAreAwesome":
print(
"Using the user's API key declared in this script " +
"for this example."
)
# Get CFB team records from the 2020 CFB season.
print("Get CFB team records from the 2020 CFB season.")
json_data = get_cfbd_team_records(
api_key=cfbd_key,
season=2020
)
print(json_data)
time.sleep(5)
# Get team records from football teams
# fielded by the University of Cincinnati.
print(
"Get team records from football teams fielded " +
"by the University of Cincinnati."
)
json_data = get_cfbd_team_records(
api_key=cfbd_key,
team="Cincinnati"
)
print(json_data)
time.sleep(5)
# Get team records from football teams that played
# in the Big 10 (B1G) conference in the 2017 CFB season
print(
"Get team records from football teams that played " +
"in the Big 10 (B1G) conference in the 2017 CFB season"
)
json_data = get_cfbd_team_records(
api_key=cfbd_key,
season=2017,
conference="B1G"
)
print(json_data)
time.sleep(5)
# You can also tell this function to just return the API call as
# a Dictionary (read: JSON) object.
print(
"You can also tell this function to just return the API call " +
"as a Dictionary (read: JSON) object."
)
json_data = get_cfbd_team_records(
season=2020,
api_key=cfbd_key,
return_as_dict=True
)
print(json_data)
else:
# Alternatively, if the CFBD API key exists in this python environment,
# or it's been set by cfbd_json_py.utls.set_cfbd_api_token(),
# you could just call these functions directly,
# without setting the API key in the script.
print(
"Using the user's API key supposedly loaded " +
"into this python environment for this example."
)
# Get CFB team records from the 2020 CFB season.
print("Get CFB team records from the 2020 CFB season.")
json_data = get_cfbd_team_records(
season=2020
)
print(json_data)
time.sleep(5)
# Get team records from football teams
# fielded by the University of Cincinnati.
print(
"Get team records from football teams " +
"fielded by the University of Cincinnati."
)
json_data = get_cfbd_team_records(
team="Cincinnati"
)
print(json_data)
time.sleep(5)
# Get team records from football teams that played
# in the Big 10 (B1G) conference in the 2017 CFB season
print(
"Get team records from football teams that played " +
"in the Big 10 (B1G) conference in the 2017 CFB season"
)
json_data = get_cfbd_team_records(
season=2017,
conference="B1G"
)
print(json_data)
time.sleep(5)
# You can also tell this function to just return the API call as
# a Dictionary (read: JSON) object.
print(
"You can also tell this function to just return the API call " +
"as a Dictionary (read: JSON) object."
)
json_data = get_cfbd_team_records(
season=2020,
return_as_dict=True
)
print(json_data)
Returns
A pandas DataFrame
object with CFB team records data,
or (if return_as_dict
is set to True
)
a dictionary object with CFB team records data.
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 889 Usage 890 ---------- 891 ``` 892 import time 893 894 from cfbd_json_py.games import get_cfbd_season_weeks 895 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 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 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
Retrieves a list of weeks that occurred in a given CFB season.
Parameters
season
(int, mandatory):
Required argument.
Specifies the season you want a list of weeks that occurred
in a given CFB season information from.
This must be specified, otherwise this package, and by extension
the CFBD API, will not accept the request
to get a list of weeks that occurred in a given CFB season information.
api_key
(str, optional):
Semi-optional argument.
If api_key
is null, this function will attempt to load a CFBD API key
from the python environment, or from a file on this computer.
If api_key
is not null,
this function will automatically assume that the
inputted api_key
is a valid CFBD API key.
api_key_dir
(str, optional):
Optional argument.
If api_key
is set to am empty string, this variable is ignored.
If api_key_dir
is null, and api_key
is null,
this function will try to find
a CFBD API key file in this user's home directory.
If api_key_dir
is set to a string, and api_key
is null,
this function will assume that api_key_dir
is a directory,
and will try to find a CFBD API key file in that directory.
return_as_dict
(bool, semi-optional):
Semi-optional argument.
If you want this function to return
the data as a dictionary (read: JSON object),
instead of a pandas DataFrame
object,
set return_as_dict
to True
.
Usage
import time
from cfbd_json_py.games import get_cfbd_season_weeks
cfbd_key = "tigersAreAwesome" # placeholder for your CFBD API Key.
if cfbd_key is not "tigersAreAwesome":
print(
"Using the user's API key declared in this script " +
"for this example."
)
# Get a list of weeks in the 2020 CFB season.
print("Get a list of weeks in the 2020 CFB season.")
json_data = get_cfbd_season_weeks(
api_key=cfbd_key,
season=2020
)
print(json_data)
time.sleep(5)
# You can also tell this function to just return the API call as
# a Dictionary (read: JSON) object.
print(
"You can also tell this function to just return the API call " +
"as a Dictionary (read: JSON) object."
)
json_data = get_cfbd_season_weeks(
season=2020,
api_key=cfbd_key,
return_as_dict=True
)
print(json_data)
else:
# Alternatively, if the CFBD API key exists in this python environment,
# or it's been set by cfbd_json_py.utls.set_cfbd_api_token(),
# you could just call these functions directly,
# without setting the API key in the script.
print(
"Using the user's API key supposedly loaded " +
"into this python environment for this example."
)
# Get a list of weeks in the 2020 CFB season.
print("Get a list of weeks in the 2020 CFB season.")
json_data = get_cfbd_season_weeks(
season=2020
)
print(json_data)
time.sleep(5)
# You can also tell this function to just return the API call as
# a Dictionary (read: JSON) object.
print(
"You can also tell this function to just return the API call " +
"as a Dictionary (read: JSON) object."
)
json_data = get_cfbd_season_weeks(
season=2020,
return_as_dict=True
)
print(json_data)
Returns
A pandas DataFrame
object
with a list of valid weeks in a given CFB season,
or (if return_as_dict
is set to True
)
a dictionary object with a list of valid weeks in a given CFB season.
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 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 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
Gets known media information for CFB games in a given CFB season.
Parameters
season
(int, mandatory):
Required argument.
Specifies the season you want CFB media information from.
This must be specified, otherwise this package, and by extension
the CFBD API, will not accept the request to get CFB media information.
api_key
(str, optional):
Semi-optional argument.
If api_key
is null, this function will attempt to load a CFBD API key
from the python environment, or from a file on this computer.
If api_key
is not null,
this function will automatically assume that the
inputted api_key
is a valid CFBD API key.
api_key_dir
(str, optional):
Optional argument.
If api_key
is set to am empty string, this variable is ignored.
If api_key_dir
is null, and api_key
is null,
this function will try to find
a CFBD API key file in this user's home directory.
If api_key_dir
is set to a string, and api_key
is null,
this function will assume that api_key_dir
is a directory,
and will try to find a CFBD API key file in that directory.
season_type
(str, semi-optional):
Semi-optional argument.
By default, this will be set to "regular", for the CFB regular season.
If you want CFB media information for non-regular season games,
set season_type
to "postseason".
If you want both "regular" and "postseason" games returned,
set season_type
to "both"
If season_type
is set to anything but "regular" or "postseason",
a ValueError()
will be raised.
week
(int, optional):
Optional argument.
If week
is set to an integer, this function will attempt
to load CFB media information from games in that season,
and in that week.
team
(str, optional):
Optional argument.
If you only want CFB media information for a team,
regardless if they are the home/away team,
set team
to the name of the team you want CFB media information from.
conference
(str, optional):
Optional argument.
If you only want media information from games
involving teams a specific conference,
set conference
to the abbreviation
of the conference you want game information from.
media_type
(str, semi-optional):
Semi-optional argument.
If you only want game broadcast information
for a specific type of broadcast,
set this to the type of broadcast.
Valid inputs are:
- `all` (default): Returns all games,
and all known broadcasters for those games.
- `tv`: Returns all known TV broadcasters for CFB games
in the requested time frame.
- `radio`: Returns all known radio broadcasters
for CFB games in the requested time frame.
- `web`: Returns all known web broadcasts (like ESPN+)
for CFB games in the requested time frame.
- `ppv`: Returns all known Pay Per View (PPV) broadcasts
for CFB games in the requested time frame.
- `mobile`: Returns all known broadcasters that only broadcasted
games on mobile devices (?)
ncaa_division
(str, semi-optional):
Semi-optional argument.
By default, ncaa_division
will be set to "fbs",
short for the Football Bowl Subdivision (FBS),
formerly known as D1-A (read as "division one single A"),
the highest level in the NCAA football pyramid,
where teams can scholarship up to 85 players
on their football team solely for athletic ability,
and often have the largest athletics budgets
within the NCAA.
Other valid inputs are:
- "fcs": Football Championship Subdivision (FCS),
formerly known as D1-AA (read as "division one double A").
An FCS school is still in the 1st division of the NCAA,
making them eligible for the March Madness tournament,
but may not have the resources to compete at the FBS level
at this time. FCS schools are limited to 63 athletic scholarships
for football.
- "ii": NCAA Division II. Schools in this and D3 are not
eligible for the March Madness tournament,
and are limited to 36 athletic scholarships
for their football team.
- "iii": NCAA Division III. The largest single division within the
NCAA football pyramid.
D3 schools have the distinction of being part of
the only NCAA division that cannot give out scholarships solely
for athletic ability.
return_as_dict
(bool, semi-optional):
Semi-optional argument.
If you want this function to return
the data as a dictionary (read: JSON object),
instead of a pandas DataFrame
object,
set return_as_dict
to True
.
Usage
import time
from cfbd_json_py.games import get_cfbd_game_media_info
cfbd_key = "tigersAreAwesome" # placeholder for your CFBD API Key.
if cfbd_key is not "tigersAreAwesome":
print(
"Using the user's API key declared in this script " +
"for this example."
)
# Get a media information for the 2020 CFB season.
print("Get a media information for the 2020 CFB season.")
json_data = get_cfbd_game_media_info(
api_key=cfbd_key,
season=2020
)
print(json_data)
time.sleep(5)
# Get a media information for postseason games in the 2020 CFB season.
print("Get a media information for the 2020 CFB season.")
json_data = get_cfbd_game_media_info(
api_key=cfbd_key,
season=2020,
season_type="postseason"
)
print(json_data)
time.sleep(5)
# Get a media information for week 10 games in the 2020 CFB season.
print(
"Get a media information for week 10 games in the 2020 CFB season."
)
json_data = get_cfbd_game_media_info(
api_key=cfbd_key,
season=2020,
week=10
)
print(json_data)
time.sleep(5)
# Get all known broadcasters for games played by
# the Ohio State Football Program in the the 2019 CFB season.
print(
"Get all known broadcasters for games played by " +
"the Ohio State Football Program in the the 2019 CFB season."
)
json_data = get_cfbd_game_media_info(
api_key=cfbd_key,
season=2020,
team="Ohio State"
)
print(json_data)
time.sleep(5)
# Get all known radio broadcasters for games played by teams
# within the American Athletic conference (AAC)
# in the the 2021 CFB season.
print(
"Get all known radio broadcasters for games played " +
"by teams within the American Athletic conference (AAC) " +
"in the the 2021 CFB season."
)
json_data = get_cfbd_game_media_info(
api_key=cfbd_key,
season=2020,
conference="AAC"
)
print(json_data)
time.sleep(5)
# Get all known radio broadcasters
# for games in the the 2020 CFB season.
print(
"Get all known radio broadcasters " +
"for games in the the 2020 CFB season."
)
json_data = get_cfbd_game_media_info(
api_key=cfbd_key,
season=2020,
media_type="radio"
)
print(json_data)
time.sleep(5)
# Get all known broadcasters for
# the Football Championship Subdivision (FCS) games
# in the 2020 CFB season.
print(
"Get all known broadcasters for " +
"the Football Championship Subdivision (FCS) games " +
"in the 2020 CFB season."
)
json_data = get_cfbd_game_media_info(
api_key=cfbd_key,
season=2020,
ncaa_division="fcs"
)
print(json_data)
time.sleep(5)
# You can also tell this function to just return the API call as
# a Dictionary (read: JSON) object.
print(
"You can also tell this function to just return the API call " +
"as a Dictionary (read: JSON) object."
)
json_data = get_cfbd_game_media_info(
season=2020,
api_key=cfbd_key,
return_as_dict=True
)
print(json_data)
else:
# Alternatively, if the CFBD API key exists in this python environment,
# or it's been set by cfbd_json_py.utls.set_cfbd_api_token(),
# you could just call these functions directly,
# without setting the API key in the script.
print(
"Using the user's API key supposedly loaded " +
"into this python environment for this example."
)
# Get a media information for the 2020 CFB season.
print("Get a media information for the 2020 CFB season.")
json_data = get_cfbd_game_media_info(
season=2020
)
print(json_data)
time.sleep(5)
# Get a media information for postseason games in the 2020 CFB season.
print("Get a media information for the 2020 CFB season.")
json_data = get_cfbd_game_media_info(
season=2020,
season_type="postseason"
)
print(json_data)
time.sleep(5)
# Get a media information for week 10 games in the 2020 CFB season.
print(
"Get a media information for week 10 games in the 2020 CFB season."
)
json_data = get_cfbd_game_media_info(
season=2020,
week=10
)
print(json_data)
time.sleep(5)
# Get all known broadcasters for games played by
# the Ohio State Football Program in the the 2019 CFB season.
print(
"Get all known broadcasters for games played by " +
"the Ohio State Football Program in the the 2019 CFB season."
)
json_data = get_cfbd_game_media_info(
season=2020,
team="Ohio State"
)
print(json_data)
time.sleep(5)
# Get all known radio broadcasters for games played by teams
# within the American Athletic conference (AAC)
# in the the 2021 CFB season.
print(
"Get all known radio broadcasters for games played " +
"by teams within the American Athletic conference (AAC) " +
"in the the 2021 CFB season."
)
json_data = get_cfbd_game_media_info(
season=2020,
conference="AAC"
)
print(json_data)
time.sleep(5)
# Get all known radio broadcasters
# for games in the the 2020 CFB season.
print(
"Get all known radio broadcasters " +
"for games in the the 2020 CFB season."
)
json_data = get_cfbd_game_media_info(
season=2020,
media_type="radio"
)
print(json_data)
time.sleep(5)
# Get all known broadcasters for
# the Football Championship Subdivision (FCS) games
# in the 2020 CFB season.
print(
"Get all known broadcasters for " +
"the Football Championship Subdivision (FCS) games " +
"in the 2020 CFB season."
)
json_data = get_cfbd_game_media_info(
season=2020,
ncaa_division="fcs"
)
print(json_data)
time.sleep(5)
# You can also tell this function to just return the API call as
# a Dictionary (read: JSON) object.
print(
"You can also tell this function to just return the API call " +
"as a Dictionary (read: JSON) object."
)
json_data = get_cfbd_game_media_info(
season=2020,
return_as_dict=True
)
print(json_data)
Returns
A pandas DataFrame
object with college football media information,
or (if return_as_dict
is set to True
)
a dictionary object with college football media information.
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 stat_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 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 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 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 stat_category is None: 2044 pass 2045 elif stat_category == "passing": 2046 filter_by_stat_category = True 2047 elif stat_category == "rushing": 2048 filter_by_stat_category = True 2049 elif stat_category == "receiving": 2050 filter_by_stat_category = True 2051 elif stat_category == "fumbles": 2052 filter_by_stat_category = True 2053 elif stat_category == "passing": 2054 filter_by_stat_category = True 2055 elif stat_category == "defensive": 2056 filter_by_stat_category = True 2057 elif stat_category == "interceptions": 2058 filter_by_stat_category = True 2059 elif stat_category == "punting": 2060 filter_by_stat_category = True 2061 elif stat_category == "kicking": 2062 filter_by_stat_category = True 2063 elif stat_category == "kickReturns": 2064 filter_by_stat_category = True 2065 elif stat_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 stat_category is not None: 2095 url += f"&category={stat_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 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 stat_category in team["categories"]: 2151 stat_category = stat_category["name"] 2152 for s_type in stat_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 "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
Retrieves player game stats for a given time frame.
Parameters
season
(int, mandatory):
Required argument.
Specifies the season you want CFB player game stats from.
This must be specified, otherwise this package, and by extension
the CFBD API, will not accept the request to get CFB player game stats.
api_key
(str, optional):
Semi-optional argument.
If api_key
is null, this function will attempt to load a CFBD API key
from the python environment, or from a file on this computer.
If api_key
is not null,
this function will automatically assume that the
inputted api_key
is a valid CFBD API key.
api_key_dir
(str, optional):
Optional argument.
If api_key
is set to am empty string, this variable is ignored.
If api_key_dir
is null, and api_key
is null,
this function will try to find
a CFBD API key file in this user's home directory.
If api_key_dir
is set to a string, and api_key
is null,
this function will assume that api_key_dir
is a directory,
and will try to find a CFBD API key file in that directory.
season_type
(str, semi-optional):
Semi-optional argument.
By default, this will be set to "regular", for the CFB regular season.
If you want CFB player game stats for non-regular season games,
set season_type
to "postseason".
If season_type
is set to anything but "regular" or "postseason",
a ValueError()
will be raised.
For the following three variables, at least one must be set to a non-null variable when calling this function.
week
(int, optional):
Optional argument.
If week
is set to an integer, this function will attempt
to load CFB player game stats from games in that season,
and in that week.
team
(str, optional):
Optional argument.
If you only want CFB player game stats for a team,
regardless if they are the home/away team,
set team
to the name of the team you want CFB player game stats from.
conference
(str, optional):
Optional argument.
If you only want player game stats from games
involving teams a specific conference,
set conference
to the abbreviation
of the conference you want stats from.
stat_category
(str, optional):
Optional argument.
If only want stats for a specific stat category,
set this variable to that category.
Valid inputs are:
- `passing`
- `rushing`
- `receiving`
- `fumbles`
- `defensive`
- `interceptions`
- `punting`
- `kicking`
- `kickReturns`
- `puntReturns`
game_id
(int, optional):
Optional argument.
If game_id
is set to a game ID, get_cfbd_player_game_stats()
will try to get player game stats just for that game ID.
return_as_dict
(bool, semi-optional):
Semi-optional argument.
If you want this function to return
the data as a dictionary (read: JSON object),
instead of a pandas DataFrame
object,
set return_as_dict
to True
.
Usage
import time
from cfbd_json_py.games import get_cfbd_player_game_stats
cfbd_key = "tigersAreAwesome" # placeholder for your CFBD API Key.
if cfbd_key is not "tigersAreAwesome":
print(
"Using the user's API key declared in this script " +
"for this example."
)
# Get player game stats for week 10 of the 2020 CFB season.
print("Get player game stats for week 10 of the 2020 CFB season.")
json_data = get_cfbd_player_game_stats(
api_key=cfbd_key,
season=2020,
week=10
)
print(json_data)
time.sleep(5)
# Get postseason player game stats for the 2020 CFB season.
print("Get postseason player game stats for the 2020 CFB season.")
json_data = get_cfbd_player_game_stats(
api_key=cfbd_key,
season=2020,
season_type="postseason",
week=1
)
print(json_data)
time.sleep(5)
# Get player game stats for
# the Alabama Crimson Tide Football Team for the 2018 CFB season.
print(
"Get player game stats for " +
"the Alabama Crimson Tide Football Team for the 2018 CFB season."
)
json_data = get_cfbd_player_game_stats(
api_key=cfbd_key,
season=2018,
team="Alabama"
)
print(json_data)
time.sleep(5)
# Get player game stats for players of teams in
# the Atlantic Coast Conference (ACC) in the 2020 CFB season.
print(
"Get player game stats for players of teams in " +
"the Atlantic Coast Conference (ACC) in the 2020 CFB season."
)
json_data = get_cfbd_player_game_stats(
api_key=cfbd_key,
season=2020,
conference="ACC"
)
print(json_data)
time.sleep(5)
# Get get passing stats from players who played
# in week 7 of the 2017 CFB season.
print(
"Get get passing stats from players who played " +
"in week 7 of the 2017 CFB season."
)
json_data = get_cfbd_player_game_stats(
api_key=cfbd_key,
season=2017,
week=7,
stat_category="passing"
)
print(json_data)
time.sleep(5)
# Get player game stats from the 2021 Virbo Citrus Bowl,
# a bowl game that happened in the 2020 CFB season.
print(
"Get player game stats from the 2021 Virbo Citrus Bowl, " +
"a bowl game that happened in the 2020 CFB season."
)
json_data = get_cfbd_player_game_stats(
api_key=cfbd_key,
season=2020,
game_id=401256199
)
print(json_data)
time.sleep(5)
# You can also tell this function to just return the API call as
# a Dictionary (read: JSON) object.
print(
"You can also tell this function to just return the API call " +
"as a Dictionary (read: JSON) object."
)
json_data = get_cfbd_player_game_stats(
season=2020,
week=10,
api_key=cfbd_key,
return_as_dict=True
)
print(json_data)
else:
# Alternatively, if the CFBD API key exists in this python environment,
# or it's been set by cfbd_json_py.utls.set_cfbd_api_token(),
# you could just call these functions directly,
# without setting the API key in the script.
print(
"Using the user's API key supposedly loaded " +
"into this python environment for this example."
)
# Get player game stats for week 10 of the 2020 CFB season.
print("Get player game stats for week 10 of the 2020 CFB season.")
json_data = get_cfbd_player_game_stats(
season=2020,
week=10
)
print(json_data)
time.sleep(5)
# Get postseason player game stats for the 2020 CFB season.
print("Get postseason player game stats for the 2020 CFB season.")
json_data = get_cfbd_player_game_stats(
season=2020,
season_type="postseason",
week=1
)
print(json_data)
time.sleep(5)
# Get player game stats for
# the Alabama Crimson Tide Football Team for the 2018 CFB season.
print(
"Get player game stats for " +
"the Alabama Crimson Tide Football Team for the 2018 CFB season."
)
json_data = get_cfbd_player_game_stats(
season=2018,
team="Alabama"
)
print(json_data)
time.sleep(5)
# Get player game stats for players of teams in
# the Atlantic Coast Conference (ACC) in the 2020 CFB season.
print(
"Get player game stats for players of teams in " +
"the Atlantic Coast Conference (ACC) in the 2020 CFB season."
)
json_data = get_cfbd_player_game_stats(
season=2020,
conference="ACC"
)
print(json_data)
time.sleep(5)
# Get get passing stats from players who played
# in week 7 of the 2017 CFB season.
print(
"Get get passing stats from players who played " +
"in week 7 of the 2017 CFB season."
)
json_data = get_cfbd_player_game_stats(
season=2017,
week=7,
stat_category="passing"
)
print(json_data)
time.sleep(5)
# Get player game stats from the 2021 Virbo Citrus Bowl,
# a bowl game that happened in the 2020 CFB season,
# between the Aubrun Tigers, and the Northwestern Wildcats.
print("Get player game stats from the 2021 Virbo Citrus Bowl, "+
"a bowl game that happened in the 2020 CFB season " +
"between the Aubrun Tigers, and the Northwestern Wildcats."
)
json_data = get_cfbd_player_game_stats(
season=2020,
game_id=401256199
)
print(json_data)
time.sleep(5)
# You can also tell this function to just return the API call as
# a Dictionary (read: JSON) object.
print(
"You can also tell this function to just return the API call " +
"as a Dictionary (read: JSON) object."
)
json_data = get_cfbd_player_game_stats(
season=2020,
week=10,
return_as_dict=True
)
print(json_data)
Returns
A pandas DataFrame
object with player game stats data,
or (if return_as_dict
is set to True
)
a dictionary object with player game stats data.
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
Retrieves advanced game stats from the CFBD API.
Parameters
game_id
(int, mandatory):
Mandatory requirement.
Specifies the game you want advanced game stats from.
api_key
(str, optional):
Semi-optional argument.
If api_key
is null, this function will attempt to load a CFBD API key
from the python environment, or from a file on this computer.
If api_key
is not null,
this function will automatically assume that the
inputted api_key
is a valid CFBD API key.
api_key_dir
(str, optional):
Optional argument.
If api_key
is set to am empty string, this variable is ignored.
If api_key_dir
is null, and api_key
is null,
this function will try to find
a CFBD API key file in this user's home directory.
If api_key_dir
is set to a string, and api_key
is null,
this function will assume that api_key_dir
is a directory,
and will try to find a CFBD API key file in that directory.
return_as_dict
(bool, semi-optional):
Semi-optional argument.
If you want this function to return
the data as a dictionary (read: JSON object),
instead of a pandas DataFrame
object,
set return_as_dict
to True
.
Usage
import time
from cfbd_json_py.games import get_cfbd_player_advanced_game_stats
cfbd_key = "tigersAreAwesome" # placeholder for your CFBD API Key.
if cfbd_key is not "tigersAreAwesome":
print(
"Using the user's API key declared in this script " +
"for this example."
)
# Get advanced player stats for a 2019 CFB game
# between the LSU Tigers Football Program,
# and the Oklahoma Sooners Football Program.
print(
"Get advanced player stats for a 2019 CFB game between " +
"the LSU Tigers Football Program, " +
"and the Oklahoma Sooners Football Program."
)
json_data = get_cfbd_player_advanced_game_stats(
api_key=cfbd_key,
game_id=401135278
)
print(json_data)
time.sleep(5)
# You can also tell this function to just return the API call as
# a Dictionary (read: JSON) object.
print(
"You can also tell this function to just return the API call " +
"as a Dictionary (read: JSON) object."
)
json_data = get_cfbd_player_advanced_game_stats(
api_key=cfbd_key,
game_id=401135278,
return_as_dict=True
)
print(json_data)
else:
# Alternatively, if the CFBD API key exists in this python environment,
# or it's been set by cfbd_json_py.utls.set_cfbd_api_token(),
# you could just call these functions directly,
# without setting the API key in the script.
print(
"Using the user's API key supposedly loaded " +
"into this python environment for this example."
)
# Get advanced player stats for a 2019 CFB game
# between the LSU Tigers Football Program,
# and the Oklahoma Sooners Football Program.
print(
"Get advanced player stats for a 2019 CFB game " +
"between the LSU Tigers Football Program, " +
"and the Oklahoma Sooners Football Program."
)
json_data = get_cfbd_player_advanced_game_stats(
game_id=401135278
)
print(json_data)
time.sleep(5)
# You can also tell this function to just return the API call as
# a Dictionary (read: JSON) object.
print(
"You can also tell this function to just return the API call " +
"as a Dictionary (read: JSON) object."
)
json_data = get_cfbd_player_advanced_game_stats(
game_id=401135278,
return_as_dict=True
)
print(json_data)
Returns
A pandas DataFrame
object with college football game information,
or (if return_as_dict
is set to True
)
a dictionary object with college football game information.
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
YOU MUST BE SUBSCRIBED TO THE CFBD PATREON FOR THIS FUNCTION TO WORK! To view the CFBD Patreon, visit https://www.patreon.com/collegefootballdata
Retrieves live scoreboard data from the CFBD API, assuming the API key is an API key from a Patreon supporter.
Parameters
ncaa_division
(str, semi-optional):
Semi-optional argument.
By default, ncaa_division
will be set to "fbs",
short for the Football Bowl Subdivision (FBS),
formerly known as D1-A (read as "division one single A"),
the highest level in the NCAA football pyramid,
where teams can scholarship up to 85 players
on their football team solely for athletic ability,
and often have the largest athletics budgets
within the NCAA.
Other valid inputs are:
- "fcs": Football Championship Subdivision (FCS),
formerly known as D1-AA (read as "division one double A").
An FCS school is still in the 1st division of the NCAA,
making them eligible for the March Madness tournament,
but may not have the resources to compete at the FBS level
at this time. FCS schools are limited to 63 athletic scholarships
for football.
- "ii": NCAA Division II. Schools in this and D3 are not
eligible for the March Madness tournament,
and are limited to 36 athletic scholarships
for their football team.
- "iii": NCAA Division III. The largest single division within the
NCAA football pyramid.
D3 schools have the distinction of being part of
the only NCAA division that cannot give out scholarships solely
for athletic ability.
conference
(str, optional):
Optional argument.
If you only want live scoreboard data from games
involving teams a specific conference,
set conference
to the abbreviation
of the conference you want live scoreboard data from.
api_key
(str, optional):
Semi-optional argument.
If api_key
is null, this function will attempt to load a CFBD API key
from the python environment, or from a file on this computer.
If api_key
is not null,
this function will automatically assume that the
inputted api_key
is a valid CFBD API key.
api_key_dir
(str, optional):
Optional argument.
If api_key
is set to am empty string, this variable is ignored.
If api_key_dir
is null, and api_key
is null,
this function will try to find
a CFBD API key file in this user's home directory.
If api_key_dir
is set to a string, and api_key
is null,
this function will assume that api_key_dir
is a directory,
and will try to find a CFBD API key file in that directory.
return_as_dict
(bool, semi-optional):
Semi-optional argument.
If you want this function to return
the data as a dictionary (read: JSON object),
instead of a pandas DataFrame
object,
set return_as_dict
to True
.
Usage
import time
from cfbd_json_py.games import get_cfbd_live_scoreboard
cfbd_key = "tigersAreAwesome" # placeholder for your CFBD API Key.
if cfbd_key != "tigersAreAwesome":
print(
"Using the user's API key declared " +
"in this script for this example."
)
# Get live scoreboard data from the CFBD API.
print(
"Get live scoreboard data from the CFBD API."
)
json_data = get_cfbd_live_scoreboard(
api_key=cfbd_key
)
print(json_data)
time.sleep(5)
# Get live scoreboard data from the CFBD API,
# but only from the FCS ranks.
print(
"Get live scoreboard data from the CFBD API, " +
"but only from the FCS ranks."
)
json_data = get_cfbd_live_scoreboard(
ncaa_division="fcs",
api_key=cfbd_key
)
print(json_data)
time.sleep(5)
# Get live scoreboard data from the CFBD API,
# but only from the Atlantic Coast Conference.
print(
"Get live scoreboard data from the CFBD API, " +
"but only from the Atlantic Coast Conference."
)
json_data = get_cfbd_live_scoreboard(
conference="ACC",
api_key=cfbd_key
)
print(json_data)
time.sleep(5)
# You can also tell this function to just return the API call as
# a Dictionary (read: JSON) object.
print(
"You can also tell this function to just return the API call " +
"as a Dictionary (read: JSON) object."
)
json_data = get_cfbd_live_scoreboard(
api_key=cfbd_key,
return_as_dict=True
)
print(json_data)
else:
# Alternatively, if the CFBD API key exists in this python environment,
# or it's been set by cfbd_json_py.utls.set_cfbd_api_token(),
# you could just call these functions directly,
# without setting the API key in the script.
print(
"Using the user's API key supposedly loaded " +
"into this python environment for this example."
)
# Get live scoreboard data from the CFBD API.
print(
"Get live scoreboard data from the CFBD API."
)
json_data = get_cfbd_live_scoreboard()
print(json_data)
time.sleep(5)
# Get live scoreboard data from the CFBD API,
# but only from the FCS ranks.
print(
"Get live scoreboard data from the CFBD API, " +
"but only from the FCS ranks."
)
json_data = get_cfbd_live_scoreboard(
ncaa_division="fcs",
)
print(json_data)
time.sleep(5)
# Get live scoreboard data from the CFBD API,
# but only from the Atlantic Coast Conference.
print(
"Get live scoreboard data from the CFBD API, " +
"but only from the Atlantic Coast Conference."
)
json_data = get_cfbd_live_scoreboard(
conference="ACC",
)
print(json_data)
time.sleep(5)
# You can also tell this function to just return the API call as
# a Dictionary (read: JSON) object.
print(
"You can also tell this function to just return the API call " +
"as a Dictionary (read: JSON) object."
)
json_data = get_cfbd_live_scoreboard(
return_as_dict=True
)
print(json_data)
Returns
A pandas DataFrame
object with live scoreboard data,
or (if return_as_dict
is set to True
)
a dictionary object with live scoreboard data.
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
YOU MUST BE SUBSCRIBED TO THE CFBD PATREON FOR THIS FUNCTION TO WORK! To view the CFBD Patreon, visit https://www.patreon.com/collegefootballdata
Parameters
Retrieves live scoreboard data from the CFBD API, assuming the API key is an API key from a Patreon supporter.
Parameters
game_id
(int, mandatory):
DEPRECATED FROM V1.
Specifies the game you want weather data from.
This or season
must be set to a valid non-null value.
season
(int, mandatory):
Mandatory requirement.
Specifies the season you want weather data from.
This or season
must be set to a valid non-null value.
week
(int, optional):
Optional argument.
If week
is set to an integer, this function will attempt
to load weather data from games in that season, and in that week.
season_type
(str, semi-optional):
Semi-optional argument.
By default, this will be set to "both", for the CFB regular season.
If you want postseason betting data, set season_type
to "postseason".
If season_type
is set to anything but "regular" or "postseason",
a ValueError()
will be raised.
conference
(str, optional):
Optional argument.
If you only want weather data from games
involving teams a specific conference,
set conference
to the abbreviation
of the conference you want weather data from.
team_name
(str, optional):
Optional argument.
If you only want weather data for a team,
regardless if they are the home/away team,
set team
to the name of the team
you want weather data from.
ncaa_division
(str, semi-optional):
Semi-optional argument.
By default, ncaa_division
will be set to "fbs",
short for the Football Bowl Subdivision (FBS),
formerly known as D1-A (read as "division one single A"),
the highest level in the NCAA football pyramid,
where teams can scholarship up to 85 players
on their football team solely for athletic ability,
and often have the largest athletics budgets
within the NCAA.
Other valid inputs are:
- "fcs": Football Championship Subdivision (FCS),
formerly known as D1-AA (read as "division one double A").
An FCS school is still in the 1st division of the NCAA,
making them eligible for the March Madness tournament,
but may not have the resources to compete at the FBS level
at this time. FCS schools are limited to 63 athletic scholarships
for football.
- "ii": NCAA Division II. Schools in this and D3 are not
eligible for the March Madness tournament,
and are limited to 36 athletic scholarships
for their football team.
- "iii": NCAA Division III. The largest single division within the
NCAA football pyramid.
D3 schools have the distinction of being part of
the only NCAA division that cannot give out scholarships solely
for athletic ability.
api_key
(str, optional):
Semi-optional argument.
If api_key
is null, this function will attempt to load a CFBD API key
from the python environment, or from a file on this computer.
If api_key
is not null,
this function will automatically assume that the
inputted api_key
is a valid CFBD API key.
api_key_dir
(str, optional):
Optional argument.
If api_key
is set to am empty string, this variable is ignored.
If api_key_dir
is null, and api_key
is null,
this function will try to find
a CFBD API key file in this user's home directory.
If api_key_dir
is set to a string, and api_key
is null,
this function will assume that api_key_dir
is a directory,
and will try to find a CFBD API key file in that directory.
return_as_dict
(bool, semi-optional):
Semi-optional argument.
If you want this function to return
the data as a dictionary (read: JSON object),
instead of a pandas DataFrame
object,
set return_as_dict
to True
.
Usage
import time
from cfbd_json_py.games import get_cfbd_weather_info
cfbd_key = "tigersAreAwesome" # placeholder for your CFBD API Key.
if cfbd_key != "tigersAreAwesome":
print(
"Using the user's API key declared " +
"in this script for this example."
)
# Get weather data for the 2024 CFB season
print(
"Get weather data for the 2024 CFB season."
)
json_data = get_cfbd_weather_info(
season=2024,
api_key=cfbd_key
)
print(json_data)
time.sleep(5)
# Get weather data for the 2024 Rose Bowl (game ID #401551786).
print(
"Get weather data for the 2024 Rose Bowl (game ID #401551786)."
)
json_data = get_cfbd_weather_info(
game_id=401551786,
api_key=cfbd_key
)
print(json_data)
time.sleep(5)
# Get weather data for week 1 of the 2024 CFB season
print(
"Get weather data for week 1 of the 2024 CFB season."
)
json_data = get_cfbd_weather_info(
season=2024,
week=1,
api_key=cfbd_key
)
print(json_data)
time.sleep(5)
# Get weather data for postseason games of the 2023 CFB season.
print(
"Get weather data for postseason games of the 2023 CFB season."
)
json_data = get_cfbd_weather_info(
season=2023,
season_type="postseason",
api_key=cfbd_key
)
print(json_data)
time.sleep(5)
# Get weather data for postseason games of the 2023 CFB season.
print(
"Get weather data for postseason games of the 2023 CFB season."
)
json_data = get_cfbd_weather_info(
season=2023,
season_type="postseason",
api_key=cfbd_key
)
print(json_data)
time.sleep(5)
# Get weather data for Big 10 (B1G) games of the 2024 CFB season.
print(
"Get weather data for Big 10 (B1G) games of the 2024 CFB season."
)
json_data = get_cfbd_weather_info(
season=2024,
conference="B1G",
api_key=cfbd_key
)
print(json_data)
time.sleep(5)
# Get weather data for FCS games of the 2024 CFB season.
print(
"Get weather data for FCS games of the 2024 CFB season."
)
json_data = get_cfbd_weather_info(
season=2024,
ncaa_division="fcs",
api_key=cfbd_key
)
print(json_data)
time.sleep(5)
# Get weather data for University of Cincinnati games
# of the 2024 CFB season.
print(
"Get weather data for Big 10 (B1G) games of the 2024 CFB season."
)
json_data = get_cfbd_weather_info(
season=2024,
team_name="Cincinnati",
api_key=cfbd_key
)
print(json_data)
time.sleep(5)
# You can also tell this function to just return the API call
# as a Dictionary (read: JSON) object.
print(
"You can also tell this function to just return the API call " +
"as a Dictionary (read: JSON) object."
)
json_data = get_cfbd_weather_info(
api_key=cfbd_key,
season=2023,
return_as_dict=True
)
print(json_data)
else:
# Alternatively, if the CFBD API key exists in this python environment,
# or it's been set by cfbd_json_py.utls.set_cfbd_api_token(),
# you could just call these functions directly,
# without setting the API key in the script.
print(
"Using the user's API key supposedly loaded " +
"into this python environment for this example."
)
# Get weather data for the 2024 CFB season
print(
"Get weather data for the 2024 CFB season."
)
json_data = get_cfbd_weather_info(
season=2024
)
print(json_data)
time.sleep(5)
# Get weather data for the 2024 Rose Bowl (game ID #401551786).
print(
"Get weather data for the 2024 Rose Bowl (game ID #401551786)."
)
json_data = get_cfbd_weather_info(
game_id=401551786
)
print(json_data)
time.sleep(5)
# Get weather data for week 1 of the 2024 CFB season
print(
"Get weather data for week 1 of the 2024 CFB season."
)
json_data = get_cfbd_weather_info(
season=2024,
week=1
)
print(json_data)
time.sleep(5)
# Get weather data for postseason games of the 2023 CFB season.
print(
"Get weather data for postseason games of the 2023 CFB season."
)
json_data = get_cfbd_weather_info(
season=2023,
season_type="postseason"
)
print(json_data)
time.sleep(5)
# Get weather data for postseason games of the 2023 CFB season.
print(
"Get weather data for postseason games of the 2023 CFB season."
)
json_data = get_cfbd_weather_info(
season=2023,
season_type="postseason"
)
print(json_data)
time.sleep(5)
# Get weather data for Big 10 (B1G) games of the 2024 CFB season.
print(
"Get weather data for Big 10 (B1G) games of the 2024 CFB season."
)
json_data = get_cfbd_weather_info(
season=2024,
conference="B1G"
)
print(json_data)
time.sleep(5)
# Get weather data for FCS games of the 2024 CFB season.
print(
"Get weather data for FCS games of the 2024 CFB season."
)
json_data = get_cfbd_weather_info(
season=2024,
ncaa_division="fcs"
)
print(json_data)
time.sleep(5)
# Get weather data for University of Cincinnati games
# of the 2024 CFB season.
print(
"Get weather data for Big 10 (B1G) games of the 2024 CFB season."
)
json_data = get_cfbd_weather_info(
season=2024,
team_name="Cincinnati"
)
print(json_data)
time.sleep(5)
# You can also tell this function to just return the API call
# as a Dictionary (read: JSON) object.
print(
"You can also tell this function to just return the API call " +
"as a Dictionary (read: JSON) object."
)
json_data = get_cfbd_weather_info(
season=2023,
return_as_dict=True
)
print(json_data)
Returns
A pandas DataFrame
object with live weather data,
or (if return_as_dict
is set to True
)
a dictionary object with live weather data.