cfbd_json_py.teams
1# Creation Date: 08/30/2023 01:13 EDT 2# Last Updated Date: 08/13/2024 02:10 PM EDT 3# Author: Joseph Armstrong (armstrongjoseph08@gmail.com) 4# File Name: teams.py 5# Purpose: Houses functions pertaining to CFB team data within the CFBD API. 6############################################################################### 7 8import warnings 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_team_information( 20 api_key: str = None, 21 api_key_dir: str = None, 22 conference: str = None, 23 return_as_dict: bool = False, 24): 25 """ 26 Allows you to get CFB team information from the CFBD API. 27 28 Parameters 29 ---------- 30 `api_key` (str, optional): 31 Semi-optional argument. 32 If `api_key` is null, this function will attempt to load a CFBD API key 33 from the python environment, or from a file on this computer. 34 If `api_key` is not null, this function will automatically 35 assume that the inputted `api_key` is a valid CFBD API key. 36 37 `api_key_dir` (str, optional): 38 Optional argument. 39 If `api_key` is set to am empty string, this variable is ignored. 40 If `api_key_dir` is null, and `api_key` is null, 41 this function will try to find 42 a CFBD API key file in this user's home directory. 43 If `api_key_dir` is set to a string, and `api_key` is null, 44 this function will assume that `api_key_dir` is a directory, 45 and will try to find a CFBD API key file in that directory. 46 47 `conference` (str, optional): 48 Optional argument. 49 If you only want CFB team information from a specific conference, 50 set `conference` to the abbreviation 51 of the conference you want CFB team information from. 52 For a list of conferences, 53 use the `cfbd_json_py.conferences.get_cfbd_conference_info()` 54 function. 55 56 `return_as_dict` (bool, semi-optional): 57 Semi-optional argument. 58 If you want this function to return 59 the data as a dictionary (read: JSON object), 60 instead of a pandas `DataFrame` object, 61 set `return_as_dict` to `True`. 62 63 Usage 64 ---------- 65 ``` 66 import time 67 68 from cfbd_json_py.teams import get_cfbd_team_information 69 70 71 cfbd_key = "tigersAreAwesome" # placeholder for your CFBD API Key. 72 73 if cfbd_key != "tigersAreAwesome": 74 print( 75 "Using the user's API key declared "+ 76 "in this script for this example." 77 ) 78 79 # Get CFB team information for all known CFB teams. 80 print("Get CFB team information for all known CFB teams.") 81 json_data = get_cfbd_team_information( 82 api_key=cfbd_key 83 ) 84 print(json_data) 85 time.sleep(5) 86 87 88 # Get CFB team information for all known 89 # Southeastern conference (SEC) CFB teams. 90 print( 91 "Get CFB team information for all known " + 92 "Southeastern conference (SEC) CFB teams." 93 ) 94 json_data = get_cfbd_team_information( 95 api_key=cfbd_key, 96 conference="SEC" 97 ) 98 print(json_data) 99 time.sleep(5) 100 101 102 # You can also tell this function to just return the API call as 103 # a Dictionary (read: JSON) object. 104 print( 105 "You can also tell this function to " + 106 "just return the API call as a Dictionary (read: JSON) object." 107 ) 108 json_data = get_cfbd_team_information( 109 api_key=cfbd_key, 110 conference="B1G", 111 return_as_dict=True 112 ) 113 print(json_data) 114 115 else: 116 # Alternatively, if the CFBD API key exists in this python environment, 117 # or it's been set by cfbd_json_py.utls.set_cfbd_api_token(), 118 # you could just call these functions directly, 119 # without setting the API key in the script. 120 print( 121 "Using the user's API key supposedly loaded into " + 122 "this python environment for this example." 123 ) 124 125 # Get CFB team information for all known CFB teams. 126 print("Get CFB team information for all known CFB teams.") 127 json_data = get_cfbd_team_information() 128 print(json_data) 129 time.sleep(5) 130 131 132 # Get CFB team information for all known 133 # Southeastern conference (SEC) CFB teams. 134 print( 135 "Get CFB team information for all known " + 136 "Southeastern conference (SEC) CFB teams." 137 ) 138 json_data = get_cfbd_team_information( 139 conference="SEC" 140 ) 141 print(json_data) 142 time.sleep(5) 143 144 145 # You can also tell this function to just return the API call as 146 # a Dictionary (read: JSON) object. 147 print( 148 "You can also tell this function to just return " + 149 "the API call as a Dictionary (read: JSON) object." 150 ) 151 json_data = get_cfbd_team_information( 152 conference="B1G", 153 return_as_dict=True 154 ) 155 print(json_data) 156 157 ``` 158 Returns 159 ---------- 160 A pandas `DataFrame` object with CFB team information, 161 or (if `return_as_dict` is set to `True`) 162 a dictionary object with CFB team information. 163 164 """ 165 warnings.simplefilter(action="ignore", category=FutureWarning) 166 167 teams_df = pd.DataFrame() 168 row_df = pd.DataFrame() 169 url = "https://api.collegefootballdata.com/teams" 170 171 ########################################################################## 172 173 if api_key is not None: 174 real_api_key = api_key 175 del api_key 176 else: 177 real_api_key = get_cfbd_api_token(api_key_dir=api_key_dir) 178 179 if real_api_key == "tigersAreAwesome": 180 raise ValueError( 181 "You actually need to change `cfbd_key` to your CFBD API key." 182 ) 183 elif "Bearer " in real_api_key: 184 pass 185 elif "Bearer" in real_api_key: 186 real_api_key = real_api_key.replace("Bearer", "Bearer ") 187 else: 188 real_api_key = "Bearer " + real_api_key 189 # URL builder 190 ########################################################################## 191 192 if conference is not None: 193 url += f"?conference={conference}" 194 195 headers = { 196 "Authorization": f"{real_api_key}", "accept": "application/json" 197 } 198 199 response = requests.get(url, headers=headers) 200 201 if response.status_code == 200: 202 pass 203 elif response.status_code == 401: 204 raise ConnectionRefusedError( 205 "Could not connect. The connection was refused.\n" + 206 "HTTP Status Code 401." 207 ) 208 else: 209 raise ConnectionError( 210 f"Could not connect.\nHTTP Status code {response.status_code}" 211 ) 212 213 json_data = response.json() 214 215 if return_as_dict is True: 216 return json_data 217 218 for team in tqdm(json_data): 219 t_team_id = team["id"] 220 row_df = pd.DataFrame({"team_id": t_team_id}, index=[0]) 221 row_df["school"] = team["school"] 222 row_df["school_mascot"] = team["mascot"] 223 row_df["school_abbreviation"] = team["abbreviation"] 224 row_df["school_alt_name_1"] = team["alt_name1"] 225 row_df["school_alt_name_2"] = team["alt_name2"] 226 row_df["school_alt_name_3"] = team["alt_name3"] 227 row_df["conference"] = team["conference"] 228 row_df["ncaa_classification"] = team["classification"] 229 row_df["school_primary_color"] = team["color"] 230 row_df["school_alt_color"] = team["alt_color"] 231 try: 232 row_df["school_primary_logo"] = team["logos"][0] 233 except: # noqa: E722 234 row_df["school_primary_logo"] = np.NaN 235 236 try: 237 row_df["school_primary_logo"] = team["logos"][1] 238 except: # noqa: E722 239 row_df["school_primary_logo"] = np.NaN 240 241 row_df["school_twitter"] = team["twitter"] 242 row_df["home_venue_id"] = team["location"]["venue_id"] 243 row_df["home_venue_name"] = team["location"]["name"] 244 row_df["home_venue_capacity"] = team["location"]["capacity"] 245 row_df["home_venue_year_constructed"] = team["location"]["capacity"] 246 row_df["is_home_venue_grass"] = team["location"]["grass"] 247 row_df["is_home_venue_dome"] = team["location"]["dome"] 248 row_df["city"] = team["location"]["city"] 249 row_df["state"] = team["location"]["state"] 250 row_df["zip"] = team["location"]["zip"] 251 row_df["country_code"] = team["location"]["country_code"] 252 row_df["timezone"] = team["location"]["timezone"] 253 row_df["latitude"] = team["location"]["latitude"] 254 row_df["longitude"] = team["location"]["longitude"] 255 row_df["elevation"] = team["location"]["elevation"] 256 257 teams_df = pd.concat([teams_df, row_df], ignore_index=True) 258 259 del row_df 260 del t_team_id 261 262 return teams_df 263 264 265def get_cfbd_fbs_team_list( 266 api_key: str = None, 267 api_key_dir: str = None, 268 season: int = None, 269 return_as_dict: bool = False, 270): 271 """ 272 Allows you to get CFB team information for FBS teams from the CFBD API. 273 274 Parameters 275 ---------- 276 `api_key` (str, optional): 277 Semi-optional argument. 278 If `api_key` is null, this function will attempt to load a CFBD API key 279 from the python environment, or from a file on this computer. 280 If `api_key` is not null, 281 this function will automatically assume that the 282 inputted `api_key` is a valid CFBD API key. 283 284 `api_key_dir` (str, optional): 285 Optional argument. 286 If `api_key` is set to am empty string, this variable is ignored. 287 If `api_key_dir` is null, and `api_key` is null, 288 this function will try to find 289 a CFBD API key file in this user's home directory. 290 If `api_key_dir` is set to a string, and `api_key` is null, 291 this function will assume that `api_key_dir` is a directory, 292 and will try to find a CFBD API key file in that directory. 293 294 `season` (int, optional): 295 Optional argument. 296 If you only want CFB team information 297 for FBS teams in a specific season, 298 set `season` to that season. 299 300 `return_as_dict` (bool, semi-optional): 301 Semi-optional argument. 302 If you want this function to return the data 303 as a dictionary (read: JSON object), 304 instead of a pandas `DataFrame` object, 305 set `return_as_dict` to `True`. 306 307 Usage 308 ---------- 309 ``` 310 import time 311 312 from cfbd_json_py.teams import get_cfbd_fbs_team_list 313 314 315 cfbd_key = "tigersAreAwesome" # placeholder for your CFBD API Key. 316 317 if cfbd_key != "tigersAreAwesome": 318 print( 319 "Using the user's API key declared " + 320 "in this script for this example." 321 ) 322 323 # Get the current list of FBS teams. 324 print("Get the current list of FBS teams.") 325 json_data = get_cfbd_fbs_team_list( 326 api_key=cfbd_key 327 ) 328 print(json_data) 329 time.sleep(5) 330 331 332 # Get a list of FBS teams for the 2020 CFB season. 333 print("Get a list of FBS teams for the 2020 CFB season.") 334 json_data = get_cfbd_fbs_team_list( 335 api_key=cfbd_key, 336 season=2020 337 ) 338 print(json_data) 339 time.sleep(5) 340 341 342 # You can also tell this function to just return the API call as 343 # a Dictionary (read: JSON) object. 344 print( 345 "You can also tell this function to just return the API call as " + 346 "a Dictionary (read: JSON) object." 347 ) 348 json_data = get_cfbd_fbs_team_list( 349 api_key=cfbd_key, 350 season=1990, 351 return_as_dict=True 352 ) 353 print(json_data) 354 355 else: 356 # Alternatively, if the CFBD API key exists in this python environment, 357 # or it's been set by cfbd_json_py.utls.set_cfbd_api_token(), 358 # you could just call these functions directly, 359 # without setting the API key 360 # in the script. 361 print( 362 "Using the user's API key supposedly loaded into " + 363 "this python environment for this example." 364 ) 365 366 # Get the current list of FBS teams. 367 print("Get the current list of FBS teams.") 368 json_data = get_cfbd_fbs_team_list() 369 print(json_data) 370 time.sleep(5) 371 372 373 # Get a list of FBS teams for the 2020 CFB season. 374 print("Get a list of FBS teams for the 2020 CFB season.") 375 json_data = get_cfbd_fbs_team_list( 376 season=2020 377 ) 378 print(json_data) 379 time.sleep(5) 380 381 382 # You can also tell this function to just return the API call as 383 # a Dictionary (read: JSON) object. 384 print( 385 "You can also tell this function to just return the API call " + 386 "as a Dictionary (read: JSON) object." 387 ) 388 json_data = get_cfbd_fbs_team_list( 389 season=1990, 390 return_as_dict=True 391 ) 392 print(json_data) 393 ``` 394 Returns 395 ---------- 396 A pandas `DataFrame` object with CFB team information, 397 or (if `return_as_dict` is set to `True`) 398 a dictionary object with CFB team information. 399 400 """ 401 warnings.simplefilter(action="ignore", category=FutureWarning) 402 403 teams_df = pd.DataFrame() 404 row_df = pd.DataFrame() 405 url = "https://api.collegefootballdata.com/teams/fbs" 406 407 ########################################################################## 408 409 if api_key is not None: 410 real_api_key = api_key 411 del api_key 412 else: 413 real_api_key = get_cfbd_api_token(api_key_dir=api_key_dir) 414 415 if real_api_key == "tigersAreAwesome": 416 raise ValueError( 417 "You actually need to change `cfbd_key` to your CFBD API key." 418 ) 419 elif "Bearer " in real_api_key: 420 pass 421 elif "Bearer" in real_api_key: 422 real_api_key = real_api_key.replace("Bearer", "Bearer ") 423 else: 424 real_api_key = "Bearer " + real_api_key 425 426 # URL builder 427 ########################################################################## 428 429 if season is not None: 430 url += f"?year={season}" 431 432 headers = { 433 "Authorization": f"{real_api_key}", "accept": "application/json" 434 } 435 436 response = requests.get(url, headers=headers) 437 438 if response.status_code == 200: 439 pass 440 elif response.status_code == 401: 441 raise ConnectionRefusedError( 442 "Could not connect. The connection was refused.\n" + 443 "HTTP Status Code 401." 444 ) 445 else: 446 raise ConnectionError( 447 f"Could not connect.\nHTTP Status code {response.status_code}" 448 ) 449 450 json_data = response.json() 451 452 if return_as_dict is True: 453 return json_data 454 455 for team in tqdm(json_data): 456 t_team_id = team["id"] 457 row_df = pd.DataFrame({"team_id": t_team_id}, index=[0]) 458 row_df["school"] = team["school"] 459 row_df["school_mascot"] = team["mascot"] 460 row_df["school_abbreviation"] = team["abbreviation"] 461 row_df["school_alt_name_1"] = team["alt_name1"] 462 row_df["school_alt_name_2"] = team["alt_name2"] 463 row_df["school_alt_name_3"] = team["alt_name3"] 464 row_df["conference"] = team["conference"] 465 # row_df['ncaa_classification'] = team['classification'] 466 row_df["ncaa_classification"] = "fbs" 467 row_df["school_primary_color"] = team["color"] 468 row_df["school_alt_color"] = team["alt_color"] 469 try: 470 row_df["school_primary_logo"] = team["logos"][0] 471 except: # noqa: E722 472 row_df["school_primary_logo"] = np.NaN 473 474 try: 475 row_df["school_primary_logo"] = team["logos"][1] 476 except: # noqa: E722 477 row_df["school_primary_logo"] = np.NaN 478 479 row_df["school_twitter"] = team["twitter"] 480 row_df["home_venue_id"] = team["location"]["venue_id"] 481 row_df["home_venue_name"] = team["location"]["name"] 482 row_df["home_venue_capacity"] = team["location"]["capacity"] 483 row_df["home_venue_year_constructed"] = team["location"]["capacity"] 484 row_df["is_home_venue_grass"] = team["location"]["grass"] 485 row_df["is_home_venue_dome"] = team["location"]["dome"] 486 row_df["city"] = team["location"]["city"] 487 row_df["state"] = team["location"]["state"] 488 row_df["zip"] = team["location"]["zip"] 489 row_df["country_code"] = team["location"]["country_code"] 490 row_df["timezone"] = team["location"]["timezone"] 491 row_df["latitude"] = team["location"]["latitude"] 492 row_df["longitude"] = team["location"]["longitude"] 493 row_df["elevation"] = team["location"]["elevation"] 494 495 teams_df = pd.concat([teams_df, row_df], ignore_index=True) 496 497 del row_df 498 del t_team_id 499 500 return teams_df 501 502 503def get_cfbd_team_rosters( 504 api_key: str = None, 505 api_key_dir: str = None, 506 team: str = None, 507 season: int = None, 508 return_as_dict: bool = False, 509): 510 """ 511 Allows you to get CFB team roster data for FBS teams from the CFBD API. 512 513 Parameters 514 ---------- 515 `api_key` (str, optional): 516 Semi-optional argument. 517 If `api_key` is null, this function will attempt to load a CFBD API key 518 from the python environment, or from a file on this computer. 519 If `api_key` is not null, 520 this function will automatically assume that the 521 inputted `api_key` is a valid CFBD API key. 522 523 `api_key_dir` (str, optional): 524 Optional argument. 525 If `api_key` is set to am empty string, this variable is ignored. 526 If `api_key_dir` is null, and `api_key` is null, 527 this function will try to find 528 a CFBD API key file in this user's home directory. 529 If `api_key_dir` is set to a string, and `api_key` is null, 530 this function will assume that `api_key_dir` is a directory, 531 and will try to find a CFBD API key file in that directory. 532 533 `season` (int, optional): 534 Optional argument. 535 If you only want CFB team roster data 536 for FBS teams in a specific season, 537 set `season` to that season. 538 539 `team` (str, optional): 540 Optional argument. 541 If you only want CFB team roster data for a specific CFB team, 542 set `team` to that CFB team's name. 543 544 `return_as_dict` (bool, semi-optional): 545 Semi-optional argument. 546 If you want this function to return 547 the data as a dictionary (read: JSON object), 548 instead of a pandas `DataFrame` object, 549 set `return_as_dict` to `True`. 550 551 Usage 552 ---------- 553 ``` 554 import time 555 556 from cfbd_json_py.teams import get_cfbd_team_rosters 557 558 559 cfbd_key = "tigersAreAwesome" # placeholder for your CFBD API Key. 560 561 if cfbd_key != "tigersAreAwesome": 562 print( 563 "Using the user's API key declared in this script " + 564 "for this example." 565 ) 566 567 # Get the team roster for the 2019 LSU Tigers Football Team. 568 print("Get the team rosters for the 2020 CFB season.") 569 json_data = get_cfbd_team_rosters( 570 api_key=cfbd_key, 571 season=2020, 572 team="LSU" 573 ) 574 print(json_data) 575 time.sleep(5) 576 577 # Get the team rosters for the 2020 CFB season. 578 print("Get the team rosters for the 2020 CFB season.") 579 json_data = get_cfbd_team_rosters( 580 api_key=cfbd_key, 581 season=2020 582 ) 583 print(json_data) 584 time.sleep(5) 585 586 # Get a list of known players with 587 # the Ohio State Buckeyes Football Team. 588 print( 589 "Get a list of known players with " + 590 "the Ohio State Buckeyes Football Team." 591 ) 592 json_data = get_cfbd_team_rosters( 593 api_key=cfbd_key, 594 team="Ohio State" 595 ) 596 print(json_data) 597 time.sleep(5) 598 599 600 # You can also tell this function to just return the API call as 601 # a Dictionary (read: JSON) object. 602 print( 603 "You can also tell this function to just return the API call " + 604 "as a Dictionary (read: JSON) object." 605 ) 606 json_data = get_cfbd_team_rosters( 607 api_key=cfbd_key, 608 season=2015, 609 team="LSU", 610 return_as_dict=True 611 ) 612 print(json_data) 613 614 else: 615 # Alternatively, if the CFBD API key exists in this python environment, 616 # or it's been set by cfbd_json_py.utls.set_cfbd_api_token(), 617 # you could just call these functions directly, 618 # without setting the API key in the script. 619 print( 620 "Using the user's API key supposedly loaded " + 621 "into this python environment for this example." 622 ) 623 624 625 # Get the team roster for the 2019 LSU Tigers Football Team. 626 print("Get the team roster for the 2019 LSU Tigers Football Team.") 627 json_data = get_cfbd_team_rosters( 628 season=2020, 629 team="LSU" 630 ) 631 print(json_data) 632 time.sleep(5) 633 634 # Get the team rosters for the 2020 CFB season. 635 print("Get the team rosters for the 2020 CFB season.") 636 json_data = get_cfbd_team_rosters( 637 season=2020 638 ) 639 print(json_data) 640 time.sleep(5) 641 642 # Get a list of known players with 643 # the Ohio State Buckeyes Football Team. 644 print( 645 "Get a list of known players with " + 646 "the Ohio State Buckeyes Football Team." 647 ) 648 json_data = get_cfbd_team_rosters( 649 team="Ohio State" 650 ) 651 print(json_data) 652 time.sleep(5) 653 654 655 # You can also tell this function to just return the API call as 656 # a Dictionary (read: JSON) object. 657 print( 658 "You can also tell this function to just return the API call " + 659 "as a Dictionary (read: JSON) object." 660 ) 661 json_data = get_cfbd_team_rosters( 662 season=2015, 663 team="LSU", 664 return_as_dict=True 665 ) 666 print(json_data) 667 668 ``` 669 Returns 670 ---------- 671 A pandas `DataFrame` object with CFB team roster data, 672 or (if `return_as_dict` is set to `True`) 673 a dictionary object with CFB team roster data. 674 675 """ 676 now = datetime.now() 677 roster_df = pd.DataFrame() 678 # row_df = pd.DataFrame() 679 url = "https://api.collegefootballdata.com/roster" 680 681 ########################################################################## 682 683 if api_key is not None: 684 real_api_key = api_key 685 del api_key 686 else: 687 real_api_key = get_cfbd_api_token(api_key_dir=api_key_dir) 688 689 if real_api_key == "tigersAreAwesome": 690 raise ValueError( 691 "You actually need to change `cfbd_key` to your CFBD API key." 692 ) 693 elif "Bearer " in real_api_key: 694 pass 695 elif "Bearer" in real_api_key: 696 real_api_key = real_api_key.replace("Bearer", "Bearer ") 697 else: 698 real_api_key = "Bearer " + real_api_key 699 700 if season is not None and season > (now.year + 1): 701 raise ValueError(f"`season` cannot be greater than {season}.") 702 elif season is not None and season < 1869: 703 raise ValueError("`season` cannot be less than 1869.") 704 705 # URL builder 706 ########################################################################## 707 708 url_elements = 0 709 710 if season is not None and url_elements == 0: 711 url += f"?year={season}" 712 url_elements += 1 713 elif season is not None: 714 url += f"&year={season}" 715 url_elements += 1 716 717 if team is not None and url_elements == 0: 718 url += f"?team={team}" 719 url_elements += 1 720 elif team is not None: 721 url += f"&team={team}" 722 url_elements += 1 723 724 headers = { 725 "Authorization": f"{real_api_key}", 726 "accept": "application/json" 727 } 728 729 response = requests.get(url, headers=headers) 730 731 if response.status_code == 200: 732 pass 733 elif response.status_code == 401: 734 raise ConnectionRefusedError( 735 "Could not connect. The connection was refused." + 736 "\nHTTP Status Code 401." 737 ) 738 else: 739 raise ConnectionError( 740 f"Could not connect.\nHTTP Status code {response.status_code}" 741 ) 742 743 json_data = response.json() 744 745 if return_as_dict is True: 746 return json_data 747 748 roster_df = pd.DataFrame(json_data) 749 return roster_df 750 751 752def get_cfbd_team_talent_rankings( 753 api_key: str = None, 754 api_key_dir: str = None, 755 season: int = None, 756 return_as_dict: bool = False, 757): 758 """ 759 Get a list of teams, and their overall talent rankings, from the CFBD API. 760 761 Parameters 762 ---------- 763 `api_key` (str, optional): 764 Semi-optional argument. 765 If `api_key` is null, this function will attempt to load a CFBD API key 766 from the python environment, or from a file on this computer. 767 If `api_key` is not null, 768 this function will automatically assume that the 769 inputted `api_key` is a valid CFBD API key. 770 771 `api_key_dir` (str, optional): 772 Optional argument. 773 If `api_key` is set to am empty string, this variable is ignored. 774 If `api_key_dir` is null, and `api_key` is null, 775 this function will try to find 776 a CFBD API key file in this user's home directory. 777 If `api_key_dir` is set to a string, and `api_key` is null, 778 this function will assume that `api_key_dir` is a directory, 779 and will try to find a CFBD API key file in that directory. 780 781 `season` (int, optional): 782 Optional argument. 783 If you only want CFB team talent ranking data 784 for FBS teams in a specific season, 785 set `season` to that season. 786 787 `return_as_dict` (bool, semi-optional): 788 Semi-optional argument. 789 If you want this function to return 790 the data as a dictionary (read: JSON object), 791 instead of a pandas `DataFrame` object, 792 set `return_as_dict` to `True`. 793 794 Usage 795 ---------- 796 ``` 797 import time 798 799 from cfbd_json_py.teams import get_cfbd_team_talent_rankings 800 801 802 cfbd_key = "tigersAreAwesome" # placeholder for your CFBD API Key. 803 804 if cfbd_key != "tigersAreAwesome": 805 print( 806 "Using the user's API key declared in this script " + 807 "for this example." 808 ) 809 810 # Get team talent rankings data for the 2020 CFB season. 811 print("Get team talent rankings data for the 2020 CFB season.") 812 json_data = get_cfbd_team_talent_rankings( 813 api_key=cfbd_key, 814 season=2020 815 ) 816 print(json_data) 817 time.sleep(5) 818 819 # Get team talent rankings data for as many seasons as possible. 820 print("Get team talent rankings data for as many seasons as possible.") 821 json_data = get_cfbd_team_talent_rankings( 822 api_key=cfbd_key 823 ) 824 print(json_data) 825 time.sleep(5) 826 827 # You can also tell this function to just return the API call as 828 # a Dictionary (read: JSON) object. 829 print( 830 "You can also tell this function to just return the API call " + 831 "as a Dictionary (read: JSON) object." 832 ) 833 json_data = get_cfbd_team_talent_rankings( 834 api_key=cfbd_key, 835 season=2015, 836 return_as_dict=True 837 ) 838 print(json_data) 839 840 else: 841 # Alternatively, if the CFBD API key exists in this python environment, 842 # or it's been set by cfbd_json_py.utls.set_cfbd_api_token(), 843 # you could just call these functions directly, 844 # without setting the API key in the script. 845 print( 846 "Using the user's API key supposedly loaded " + 847 "into this python environment for this example." 848 ) 849 850 851 # Get team talent rankings data for the 2020 CFB season. 852 print("Get team talent rankings data for the 2020 CFB season.") 853 json_data = get_cfbd_team_talent_rankings( 854 season=2020 855 ) 856 print(json_data) 857 time.sleep(5) 858 859 # Get team talent rankings data for as many seasons as possible. 860 print("Get team talent rankings data for as many seasons as possible.") 861 json_data = get_cfbd_team_talent_rankings() 862 print(json_data) 863 time.sleep(5) 864 865 # You can also tell this function to just return the API call as 866 # a Dictionary (read: JSON) object. 867 print( 868 "You can also tell this function to just return the API call " + 869 "as a Dictionary (read: JSON) object." 870 ) 871 json_data = get_cfbd_team_talent_rankings( 872 season=2015, 873 return_as_dict=True 874 ) 875 print(json_data) 876 877 ``` 878 Returns 879 ---------- 880 A pandas `DataFrame` object with CFB team talent ratings data, 881 or (if `return_as_dict` is set to `True`) 882 a dictionary object with CFB team talent ratings data. 883 """ 884 now = datetime.now() 885 teams_df = pd.DataFrame() 886 # row_df = pd.DataFrame() 887 url = "https://api.collegefootballdata.com/talent" 888 889 ########################################################################## 890 891 if api_key is not None: 892 real_api_key = api_key 893 del api_key 894 else: 895 real_api_key = get_cfbd_api_token(api_key_dir=api_key_dir) 896 897 if real_api_key == "tigersAreAwesome": 898 raise ValueError( 899 "You actually need to change `cfbd_key` to your CFBD API key." 900 ) 901 elif "Bearer " in real_api_key: 902 pass 903 elif "Bearer" in real_api_key: 904 real_api_key = real_api_key.replace("Bearer", "Bearer ") 905 else: 906 real_api_key = "Bearer " + real_api_key 907 908 if season is not None and season > (now.year + 1): 909 raise ValueError(f"`season` cannot be greater than {season}.") 910 elif season is not None and season < 1869: 911 raise ValueError("`season` cannot be less than 1869.") 912 913 # URL builder 914 ########################################################################## 915 916 if season is not None: 917 url += f"?year={season}" 918 919 headers = { 920 "Authorization": f"{real_api_key}", 921 "accept": "application/json" 922 } 923 924 response = requests.get(url, headers=headers) 925 926 if response.status_code == 200: 927 pass 928 elif response.status_code == 401: 929 raise ConnectionRefusedError( 930 "Could not connect. The connection was refused." + 931 "\nHTTP Status Code 401." 932 ) 933 else: 934 raise ConnectionError( 935 f"Could not connect.\nHTTP Status code {response.status_code}" 936 ) 937 938 json_data = response.json() 939 940 if return_as_dict is True: 941 return json_data 942 943 teams_df = pd.DataFrame(json_data) 944 945 return teams_df 946 947 948def get_cfbd_team_matchup_history( 949 team_1: str, 950 team_2: str, 951 api_key: str = None, 952 api_key_dir: str = None, 953 min_season: int = None, 954 max_season: int = None, 955 return_as_dict: bool = False, 956): 957 """ 958 Get a list of matchups between two teams, from the CFBD API. 959 960 Parameters 961 ---------- 962 `team_1` (str, mandatory): 963 Mandatory argument. 964 This is the name of the **first** team in this matchup. 965 966 `team_1` (str, mandatory): 967 Mandatory argument. 968 This is the name of the **second** team in this matchup. 969 970 `api_key` (str, optional): 971 Semi-optional argument. 972 If `api_key` is null, this function will attempt to load a CFBD API key 973 from the python environment, or from a file on this computer. 974 If `api_key` is not null, 975 this function will automatically assume that the 976 inputted `api_key` is a valid CFBD API key. 977 978 `api_key_dir` (str, optional): 979 Optional argument. 980 If `api_key` is set to am empty string, this variable is ignored. 981 If `api_key_dir` is null, and `api_key` is null, 982 this function will try to find 983 a CFBD API key file in this user's home directory. 984 If `api_key_dir` is set to a string, and `api_key` is null, 985 this function will assume that `api_key_dir` is a directory, 986 and will try to find a CFBD API key file in that directory. 987 988 `min_season` (int, optional): 989 Optional argument. 990 If you only want matchups starting in a specific season, 991 set `min_season` to that season. 992 993 `max_season` (int, optional): 994 Optional argument. 995 If you only want matchups up to a specific season, 996 set `max_season` to that season. 997 998 `return_as_dict` (bool, semi-optional): 999 Semi-optional argument. 1000 If you want this function to return 1001 the data as a dictionary (read: JSON object), 1002 instead of a pandas `DataFrame` object, 1003 set `return_as_dict` to `True`. 1004 1005 Usage 1006 ---------- 1007 ``` 1008 import time 1009 1010 from cfbd_json_py.teams import get_cfbd_team_matchup_history 1011 1012 1013 cfbd_key = "tigersAreAwesome" # placeholder for your CFBD API Key. 1014 1015 if cfbd_key != "tigersAreAwesome": 1016 print( 1017 "Using the user's API key declared in this script " + 1018 "for this example." 1019 ) 1020 1021 # Get the matchup history between the University of Cincinnati 1022 # and the Miami (OH) Redhawks football teams. 1023 print( 1024 "Get the matchup history between the University of Cincinnati " + 1025 "and the Miami (OH) Redhawks football teams." 1026 ) 1027 json_data = get_cfbd_team_matchup_history( 1028 api_key=cfbd_key, 1029 team_1="Cincinnati", 1030 team_2="Miami (OH)" 1031 ) 1032 print(json_data) 1033 time.sleep(5) 1034 1035 # Get the matchup history between the Ohio State Buckeyes 1036 # and the Michigan Wolverines football teams, 1037 # starting in 2002. 1038 print( 1039 "Get the matchup history between the Ohio State Buckeyes " + 1040 "and the University of Michigan Wolverines " + 1041 "football teams, starting in 2002." 1042 ) 1043 json_data = get_cfbd_team_matchup_history( 1044 api_key=cfbd_key, 1045 team_1="Ohio State", 1046 team_2="Michigan", 1047 min_season=2002 1048 ) 1049 print(json_data) 1050 time.sleep(5) 1051 1052 # Get the matchup history between the Ohio Bobcats 1053 # and the Miami (OH) Redhawks football teams, 1054 # starting in 1990 and ending in 2005. 1055 print( 1056 "Get the matchup history between the University of Cincinnati " + 1057 "and the Miami (OH) Redhawks football teams." 1058 ) 1059 json_data = get_cfbd_team_matchup_history( 1060 api_key=cfbd_key, 1061 team_1="Ohio", 1062 team_2="Miami (OH)", 1063 min_season=1990, 1064 max_season=2005 1065 ) 1066 print(json_data) 1067 time.sleep(5) 1068 1069 # You can also tell this function to just return the API call as 1070 # a Dictionary (read: JSON) object. 1071 print( 1072 "You can also tell this function to just return the API call " + 1073 "as a Dictionary (read: JSON) object." 1074 ) 1075 json_data = get_cfbd_team_matchup_history( 1076 api_key=cfbd_key, 1077 team_1="Cincinnati", 1078 team_2="Miami (OH)", 1079 min_season=2020, 1080 return_as_dict=True 1081 ) 1082 print(json_data) 1083 1084 else: 1085 # Alternatively, if the CFBD API key exists in this python environment, 1086 # or it's been set by cfbd_json_py.utls.set_cfbd_api_token(), 1087 # you could just call these functions directly, 1088 # without setting the API key in the script. 1089 print( 1090 "Using the user's API key supposedly loaded " + 1091 "into this python environment for this example." 1092 ) 1093 1094 1095 # Get the matchup history between the University of Cincinnati 1096 # and the Miami (OH) Redhawks football teams. 1097 print( 1098 "Get the matchup history between the University of Cincinnati " + 1099 "and the Miami (OH) Redhawks football teams." 1100 ) 1101 json_data = get_cfbd_team_matchup_history( 1102 team_1="Cincinnati", 1103 team_2="Miami (OH)" 1104 ) 1105 print(json_data) 1106 time.sleep(5) 1107 1108 # Get the matchup history between the Ohio State Buckeyes 1109 # and the Michigan Wolverines football teams, 1110 # starting in 2002. 1111 print( 1112 "Get the matchup history between the Ohio State Buckeyes " + 1113 "and the University of Michigan Wolverines " + 1114 "football teams, starting in 2002." 1115 ) 1116 json_data = get_cfbd_team_matchup_history( 1117 team_1="Ohio State", 1118 team_2="Michigan", 1119 min_season=2002 1120 ) 1121 print(json_data) 1122 time.sleep(5) 1123 1124 # Get the matchup history between the Ohio Bobcats 1125 # and the Miami (OH) Redhawks football teams, 1126 # starting in 1990 and ending in 2005. 1127 print( 1128 "Get the matchup history between the University of Cincinnati " + 1129 "and the Miami (OH) Redhawks football teams." 1130 ) 1131 json_data = get_cfbd_team_matchup_history( 1132 team_1="Ohio", 1133 team_2="Miami (OH)", 1134 min_season=1990, 1135 max_season=2005 1136 ) 1137 print(json_data) 1138 time.sleep(5) 1139 1140 # You can also tell this function to just return the API call as 1141 # a Dictionary (read: JSON) object. 1142 print( 1143 "You can also tell this function to just return the API call " + 1144 "as a Dictionary (read: JSON) object." 1145 ) 1146 json_data = get_cfbd_team_matchup_history( 1147 team_1="Cincinnati", 1148 team_2="Miami (OH)", 1149 min_season=2020, 1150 return_as_dict=True 1151 ) 1152 print(json_data) 1153 ``` 1154 Returns 1155 ---------- 1156 A pandas `DataFrame` object with CFB team matchup data, 1157 or (if `return_as_dict` is set to `True`) 1158 a dictionary object with CFB team matchup data. 1159 """ 1160 now = datetime.now() 1161 matchups_df = pd.DataFrame() 1162 row_df = pd.DataFrame() 1163 url = "https://api.collegefootballdata.com/teams/matchup" 1164 1165 ########################################################################## 1166 1167 if api_key is not None: 1168 real_api_key = api_key 1169 del api_key 1170 else: 1171 real_api_key = get_cfbd_api_token(api_key_dir=api_key_dir) 1172 1173 if real_api_key == "tigersAreAwesome": 1174 raise ValueError( 1175 "You actually need to change `cfbd_key` to your CFBD API key." 1176 ) 1177 elif "Bearer " in real_api_key: 1178 pass 1179 elif "Bearer" in real_api_key: 1180 real_api_key = real_api_key.replace("Bearer", "Bearer ") 1181 else: 1182 real_api_key = "Bearer " + real_api_key 1183 1184 if min_season is not None and min_season > (now.year + 1): 1185 raise ValueError(f"`min_season` cannot be greater than {min_season}.") 1186 elif min_season is not None and min_season < 1869: 1187 raise ValueError("`min_season` cannot be less than 1869.") 1188 1189 if max_season is not None and max_season > (now.year + 1): 1190 raise ValueError(f"`max_season` cannot be greater than {max_season}.") 1191 elif max_season is not None and max_season < 1869: 1192 raise ValueError("`max_season` cannot be less than 1869.") 1193 1194 # URL builder 1195 ########################################################################## 1196 1197 # Required by the API: 1198 url += f"?team1={team_1}&team2={team_2}" 1199 1200 if min_season is not None: 1201 url += f"&minYear={min_season}" 1202 1203 if max_season is not None: 1204 url += f"&maxYear={max_season}" 1205 1206 headers = { 1207 "Authorization": f"{real_api_key}", 1208 "accept": "application/json" 1209 } 1210 1211 response = requests.get(url, headers=headers) 1212 1213 if response.status_code == 200: 1214 pass 1215 elif response.status_code == 401: 1216 raise ConnectionRefusedError( 1217 "Could not connect. The connection was refused." + 1218 "\nHTTP Status Code 401." 1219 ) 1220 else: 1221 raise ConnectionError( 1222 f"Could not connect.\nHTTP Status code {response.status_code}" 1223 ) 1224 1225 json_data = response.json() 1226 1227 if return_as_dict is True: 1228 return json_data 1229 1230 team_1_wins = json_data["team1Wins"] 1231 team_2_wins = json_data["team2Wins"] 1232 total_ties = json_data["ties"] 1233 1234 for game in tqdm(json_data["games"]): 1235 row_df = pd.DataFrame( 1236 { 1237 "team_1": team_1, 1238 "team_2": team_2, 1239 "start_year": min_season, 1240 "end_year": max_season, 1241 "team_1_wins": team_1_wins, 1242 "team_2_wins": team_2_wins, 1243 "ties": total_ties, 1244 }, 1245 index=[0], 1246 ) 1247 row_df["season"] = game["season"] 1248 row_df["week"] = game["week"] 1249 row_df["season_type"] = game["seasonType"] 1250 row_df["date"] = game["date"] 1251 row_df["is_neutral_site_game"] = game["neutralSite"] 1252 row_df["venue"] = game["venue"] 1253 row_df["home_team"] = game["homeTeam"] 1254 row_df["home_score"] = game["homeScore"] 1255 row_df["away_team"] = game["awayTeam"] 1256 row_df["away_score"] = game["awayScore"] 1257 row_df["winner"] = game["winner"] 1258 1259 matchups_df = pd.concat([matchups_df, row_df], ignore_index=True) 1260 del row_df 1261 1262 return matchups_df
20def get_cfbd_team_information( 21 api_key: str = None, 22 api_key_dir: str = None, 23 conference: str = None, 24 return_as_dict: bool = False, 25): 26 """ 27 Allows you to get CFB team information from the CFBD API. 28 29 Parameters 30 ---------- 31 `api_key` (str, optional): 32 Semi-optional argument. 33 If `api_key` is null, this function will attempt to load a CFBD API key 34 from the python environment, or from a file on this computer. 35 If `api_key` is not null, this function will automatically 36 assume that the inputted `api_key` is a valid CFBD API key. 37 38 `api_key_dir` (str, optional): 39 Optional argument. 40 If `api_key` is set to am empty string, this variable is ignored. 41 If `api_key_dir` is null, and `api_key` is null, 42 this function will try to find 43 a CFBD API key file in this user's home directory. 44 If `api_key_dir` is set to a string, and `api_key` is null, 45 this function will assume that `api_key_dir` is a directory, 46 and will try to find a CFBD API key file in that directory. 47 48 `conference` (str, optional): 49 Optional argument. 50 If you only want CFB team information from a specific conference, 51 set `conference` to the abbreviation 52 of the conference you want CFB team information from. 53 For a list of conferences, 54 use the `cfbd_json_py.conferences.get_cfbd_conference_info()` 55 function. 56 57 `return_as_dict` (bool, semi-optional): 58 Semi-optional argument. 59 If you want this function to return 60 the data as a dictionary (read: JSON object), 61 instead of a pandas `DataFrame` object, 62 set `return_as_dict` to `True`. 63 64 Usage 65 ---------- 66 ``` 67 import time 68 69 from cfbd_json_py.teams import get_cfbd_team_information 70 71 72 cfbd_key = "tigersAreAwesome" # placeholder for your CFBD API Key. 73 74 if cfbd_key != "tigersAreAwesome": 75 print( 76 "Using the user's API key declared "+ 77 "in this script for this example." 78 ) 79 80 # Get CFB team information for all known CFB teams. 81 print("Get CFB team information for all known CFB teams.") 82 json_data = get_cfbd_team_information( 83 api_key=cfbd_key 84 ) 85 print(json_data) 86 time.sleep(5) 87 88 89 # Get CFB team information for all known 90 # Southeastern conference (SEC) CFB teams. 91 print( 92 "Get CFB team information for all known " + 93 "Southeastern conference (SEC) CFB teams." 94 ) 95 json_data = get_cfbd_team_information( 96 api_key=cfbd_key, 97 conference="SEC" 98 ) 99 print(json_data) 100 time.sleep(5) 101 102 103 # You can also tell this function to just return the API call as 104 # a Dictionary (read: JSON) object. 105 print( 106 "You can also tell this function to " + 107 "just return the API call as a Dictionary (read: JSON) object." 108 ) 109 json_data = get_cfbd_team_information( 110 api_key=cfbd_key, 111 conference="B1G", 112 return_as_dict=True 113 ) 114 print(json_data) 115 116 else: 117 # Alternatively, if the CFBD API key exists in this python environment, 118 # or it's been set by cfbd_json_py.utls.set_cfbd_api_token(), 119 # you could just call these functions directly, 120 # without setting the API key in the script. 121 print( 122 "Using the user's API key supposedly loaded into " + 123 "this python environment for this example." 124 ) 125 126 # Get CFB team information for all known CFB teams. 127 print("Get CFB team information for all known CFB teams.") 128 json_data = get_cfbd_team_information() 129 print(json_data) 130 time.sleep(5) 131 132 133 # Get CFB team information for all known 134 # Southeastern conference (SEC) CFB teams. 135 print( 136 "Get CFB team information for all known " + 137 "Southeastern conference (SEC) CFB teams." 138 ) 139 json_data = get_cfbd_team_information( 140 conference="SEC" 141 ) 142 print(json_data) 143 time.sleep(5) 144 145 146 # You can also tell this function to just return the API call as 147 # a Dictionary (read: JSON) object. 148 print( 149 "You can also tell this function to just return " + 150 "the API call as a Dictionary (read: JSON) object." 151 ) 152 json_data = get_cfbd_team_information( 153 conference="B1G", 154 return_as_dict=True 155 ) 156 print(json_data) 157 158 ``` 159 Returns 160 ---------- 161 A pandas `DataFrame` object with CFB team information, 162 or (if `return_as_dict` is set to `True`) 163 a dictionary object with CFB team information. 164 165 """ 166 warnings.simplefilter(action="ignore", category=FutureWarning) 167 168 teams_df = pd.DataFrame() 169 row_df = pd.DataFrame() 170 url = "https://api.collegefootballdata.com/teams" 171 172 ########################################################################## 173 174 if api_key is not None: 175 real_api_key = api_key 176 del api_key 177 else: 178 real_api_key = get_cfbd_api_token(api_key_dir=api_key_dir) 179 180 if real_api_key == "tigersAreAwesome": 181 raise ValueError( 182 "You actually need to change `cfbd_key` to your CFBD API key." 183 ) 184 elif "Bearer " in real_api_key: 185 pass 186 elif "Bearer" in real_api_key: 187 real_api_key = real_api_key.replace("Bearer", "Bearer ") 188 else: 189 real_api_key = "Bearer " + real_api_key 190 # URL builder 191 ########################################################################## 192 193 if conference is not None: 194 url += f"?conference={conference}" 195 196 headers = { 197 "Authorization": f"{real_api_key}", "accept": "application/json" 198 } 199 200 response = requests.get(url, headers=headers) 201 202 if response.status_code == 200: 203 pass 204 elif response.status_code == 401: 205 raise ConnectionRefusedError( 206 "Could not connect. The connection was refused.\n" + 207 "HTTP Status Code 401." 208 ) 209 else: 210 raise ConnectionError( 211 f"Could not connect.\nHTTP Status code {response.status_code}" 212 ) 213 214 json_data = response.json() 215 216 if return_as_dict is True: 217 return json_data 218 219 for team in tqdm(json_data): 220 t_team_id = team["id"] 221 row_df = pd.DataFrame({"team_id": t_team_id}, index=[0]) 222 row_df["school"] = team["school"] 223 row_df["school_mascot"] = team["mascot"] 224 row_df["school_abbreviation"] = team["abbreviation"] 225 row_df["school_alt_name_1"] = team["alt_name1"] 226 row_df["school_alt_name_2"] = team["alt_name2"] 227 row_df["school_alt_name_3"] = team["alt_name3"] 228 row_df["conference"] = team["conference"] 229 row_df["ncaa_classification"] = team["classification"] 230 row_df["school_primary_color"] = team["color"] 231 row_df["school_alt_color"] = team["alt_color"] 232 try: 233 row_df["school_primary_logo"] = team["logos"][0] 234 except: # noqa: E722 235 row_df["school_primary_logo"] = np.NaN 236 237 try: 238 row_df["school_primary_logo"] = team["logos"][1] 239 except: # noqa: E722 240 row_df["school_primary_logo"] = np.NaN 241 242 row_df["school_twitter"] = team["twitter"] 243 row_df["home_venue_id"] = team["location"]["venue_id"] 244 row_df["home_venue_name"] = team["location"]["name"] 245 row_df["home_venue_capacity"] = team["location"]["capacity"] 246 row_df["home_venue_year_constructed"] = team["location"]["capacity"] 247 row_df["is_home_venue_grass"] = team["location"]["grass"] 248 row_df["is_home_venue_dome"] = team["location"]["dome"] 249 row_df["city"] = team["location"]["city"] 250 row_df["state"] = team["location"]["state"] 251 row_df["zip"] = team["location"]["zip"] 252 row_df["country_code"] = team["location"]["country_code"] 253 row_df["timezone"] = team["location"]["timezone"] 254 row_df["latitude"] = team["location"]["latitude"] 255 row_df["longitude"] = team["location"]["longitude"] 256 row_df["elevation"] = team["location"]["elevation"] 257 258 teams_df = pd.concat([teams_df, row_df], ignore_index=True) 259 260 del row_df 261 del t_team_id 262 263 return teams_df
Allows you to get CFB team information from the CFBD API.
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.
conference
(str, optional):
Optional argument.
If you only want CFB team information from a specific conference,
set conference
to the abbreviation
of the conference you want CFB team information 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.teams import get_cfbd_team_information
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 CFB team information for all known CFB teams.
print("Get CFB team information for all known CFB teams.")
json_data = get_cfbd_team_information(
api_key=cfbd_key
)
print(json_data)
time.sleep(5)
# Get CFB team information for all known
# Southeastern conference (SEC) CFB teams.
print(
"Get CFB team information for all known " +
"Southeastern conference (SEC) CFB teams."
)
json_data = get_cfbd_team_information(
api_key=cfbd_key,
conference="SEC"
)
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_information(
api_key=cfbd_key,
conference="B1G",
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 information for all known CFB teams.
print("Get CFB team information for all known CFB teams.")
json_data = get_cfbd_team_information()
print(json_data)
time.sleep(5)
# Get CFB team information for all known
# Southeastern conference (SEC) CFB teams.
print(
"Get CFB team information for all known " +
"Southeastern conference (SEC) CFB teams."
)
json_data = get_cfbd_team_information(
conference="SEC"
)
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_information(
conference="B1G",
return_as_dict=True
)
print(json_data)
Returns
A pandas DataFrame
object with CFB team information,
or (if return_as_dict
is set to True
)
a dictionary object with CFB team information.
266def get_cfbd_fbs_team_list( 267 api_key: str = None, 268 api_key_dir: str = None, 269 season: int = None, 270 return_as_dict: bool = False, 271): 272 """ 273 Allows you to get CFB team information for FBS teams from the CFBD API. 274 275 Parameters 276 ---------- 277 `api_key` (str, optional): 278 Semi-optional argument. 279 If `api_key` is null, this function will attempt to load a CFBD API key 280 from the python environment, or from a file on this computer. 281 If `api_key` is not null, 282 this function will automatically assume that the 283 inputted `api_key` is a valid CFBD API key. 284 285 `api_key_dir` (str, optional): 286 Optional argument. 287 If `api_key` is set to am empty string, this variable is ignored. 288 If `api_key_dir` is null, and `api_key` is null, 289 this function will try to find 290 a CFBD API key file in this user's home directory. 291 If `api_key_dir` is set to a string, and `api_key` is null, 292 this function will assume that `api_key_dir` is a directory, 293 and will try to find a CFBD API key file in that directory. 294 295 `season` (int, optional): 296 Optional argument. 297 If you only want CFB team information 298 for FBS teams in a specific season, 299 set `season` to that season. 300 301 `return_as_dict` (bool, semi-optional): 302 Semi-optional argument. 303 If you want this function to return the data 304 as a dictionary (read: JSON object), 305 instead of a pandas `DataFrame` object, 306 set `return_as_dict` to `True`. 307 308 Usage 309 ---------- 310 ``` 311 import time 312 313 from cfbd_json_py.teams import get_cfbd_fbs_team_list 314 315 316 cfbd_key = "tigersAreAwesome" # placeholder for your CFBD API Key. 317 318 if cfbd_key != "tigersAreAwesome": 319 print( 320 "Using the user's API key declared " + 321 "in this script for this example." 322 ) 323 324 # Get the current list of FBS teams. 325 print("Get the current list of FBS teams.") 326 json_data = get_cfbd_fbs_team_list( 327 api_key=cfbd_key 328 ) 329 print(json_data) 330 time.sleep(5) 331 332 333 # Get a list of FBS teams for the 2020 CFB season. 334 print("Get a list of FBS teams for the 2020 CFB season.") 335 json_data = get_cfbd_fbs_team_list( 336 api_key=cfbd_key, 337 season=2020 338 ) 339 print(json_data) 340 time.sleep(5) 341 342 343 # You can also tell this function to just return the API call as 344 # a Dictionary (read: JSON) object. 345 print( 346 "You can also tell this function to just return the API call as " + 347 "a Dictionary (read: JSON) object." 348 ) 349 json_data = get_cfbd_fbs_team_list( 350 api_key=cfbd_key, 351 season=1990, 352 return_as_dict=True 353 ) 354 print(json_data) 355 356 else: 357 # Alternatively, if the CFBD API key exists in this python environment, 358 # or it's been set by cfbd_json_py.utls.set_cfbd_api_token(), 359 # you could just call these functions directly, 360 # without setting the API key 361 # in the script. 362 print( 363 "Using the user's API key supposedly loaded into " + 364 "this python environment for this example." 365 ) 366 367 # Get the current list of FBS teams. 368 print("Get the current list of FBS teams.") 369 json_data = get_cfbd_fbs_team_list() 370 print(json_data) 371 time.sleep(5) 372 373 374 # Get a list of FBS teams for the 2020 CFB season. 375 print("Get a list of FBS teams for the 2020 CFB season.") 376 json_data = get_cfbd_fbs_team_list( 377 season=2020 378 ) 379 print(json_data) 380 time.sleep(5) 381 382 383 # You can also tell this function to just return the API call as 384 # a Dictionary (read: JSON) object. 385 print( 386 "You can also tell this function to just return the API call " + 387 "as a Dictionary (read: JSON) object." 388 ) 389 json_data = get_cfbd_fbs_team_list( 390 season=1990, 391 return_as_dict=True 392 ) 393 print(json_data) 394 ``` 395 Returns 396 ---------- 397 A pandas `DataFrame` object with CFB team information, 398 or (if `return_as_dict` is set to `True`) 399 a dictionary object with CFB team information. 400 401 """ 402 warnings.simplefilter(action="ignore", category=FutureWarning) 403 404 teams_df = pd.DataFrame() 405 row_df = pd.DataFrame() 406 url = "https://api.collegefootballdata.com/teams/fbs" 407 408 ########################################################################## 409 410 if api_key is not None: 411 real_api_key = api_key 412 del api_key 413 else: 414 real_api_key = get_cfbd_api_token(api_key_dir=api_key_dir) 415 416 if real_api_key == "tigersAreAwesome": 417 raise ValueError( 418 "You actually need to change `cfbd_key` to your CFBD API key." 419 ) 420 elif "Bearer " in real_api_key: 421 pass 422 elif "Bearer" in real_api_key: 423 real_api_key = real_api_key.replace("Bearer", "Bearer ") 424 else: 425 real_api_key = "Bearer " + real_api_key 426 427 # URL builder 428 ########################################################################## 429 430 if season is not None: 431 url += f"?year={season}" 432 433 headers = { 434 "Authorization": f"{real_api_key}", "accept": "application/json" 435 } 436 437 response = requests.get(url, headers=headers) 438 439 if response.status_code == 200: 440 pass 441 elif response.status_code == 401: 442 raise ConnectionRefusedError( 443 "Could not connect. The connection was refused.\n" + 444 "HTTP Status Code 401." 445 ) 446 else: 447 raise ConnectionError( 448 f"Could not connect.\nHTTP Status code {response.status_code}" 449 ) 450 451 json_data = response.json() 452 453 if return_as_dict is True: 454 return json_data 455 456 for team in tqdm(json_data): 457 t_team_id = team["id"] 458 row_df = pd.DataFrame({"team_id": t_team_id}, index=[0]) 459 row_df["school"] = team["school"] 460 row_df["school_mascot"] = team["mascot"] 461 row_df["school_abbreviation"] = team["abbreviation"] 462 row_df["school_alt_name_1"] = team["alt_name1"] 463 row_df["school_alt_name_2"] = team["alt_name2"] 464 row_df["school_alt_name_3"] = team["alt_name3"] 465 row_df["conference"] = team["conference"] 466 # row_df['ncaa_classification'] = team['classification'] 467 row_df["ncaa_classification"] = "fbs" 468 row_df["school_primary_color"] = team["color"] 469 row_df["school_alt_color"] = team["alt_color"] 470 try: 471 row_df["school_primary_logo"] = team["logos"][0] 472 except: # noqa: E722 473 row_df["school_primary_logo"] = np.NaN 474 475 try: 476 row_df["school_primary_logo"] = team["logos"][1] 477 except: # noqa: E722 478 row_df["school_primary_logo"] = np.NaN 479 480 row_df["school_twitter"] = team["twitter"] 481 row_df["home_venue_id"] = team["location"]["venue_id"] 482 row_df["home_venue_name"] = team["location"]["name"] 483 row_df["home_venue_capacity"] = team["location"]["capacity"] 484 row_df["home_venue_year_constructed"] = team["location"]["capacity"] 485 row_df["is_home_venue_grass"] = team["location"]["grass"] 486 row_df["is_home_venue_dome"] = team["location"]["dome"] 487 row_df["city"] = team["location"]["city"] 488 row_df["state"] = team["location"]["state"] 489 row_df["zip"] = team["location"]["zip"] 490 row_df["country_code"] = team["location"]["country_code"] 491 row_df["timezone"] = team["location"]["timezone"] 492 row_df["latitude"] = team["location"]["latitude"] 493 row_df["longitude"] = team["location"]["longitude"] 494 row_df["elevation"] = team["location"]["elevation"] 495 496 teams_df = pd.concat([teams_df, row_df], ignore_index=True) 497 498 del row_df 499 del t_team_id 500 501 return teams_df
Allows you to get CFB team information for FBS teams from the CFBD API.
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):
Optional argument.
If you only want CFB team information
for FBS teams in a specific season,
set season
to that season.
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.teams import get_cfbd_fbs_team_list
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 the current list of FBS teams.
print("Get the current list of FBS teams.")
json_data = get_cfbd_fbs_team_list(
api_key=cfbd_key
)
print(json_data)
time.sleep(5)
# Get a list of FBS teams for the 2020 CFB season.
print("Get a list of FBS teams for the 2020 CFB season.")
json_data = get_cfbd_fbs_team_list(
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_fbs_team_list(
api_key=cfbd_key,
season=1990,
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 the current list of FBS teams.
print("Get the current list of FBS teams.")
json_data = get_cfbd_fbs_team_list()
print(json_data)
time.sleep(5)
# Get a list of FBS teams for the 2020 CFB season.
print("Get a list of FBS teams for the 2020 CFB season.")
json_data = get_cfbd_fbs_team_list(
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_fbs_team_list(
season=1990,
return_as_dict=True
)
print(json_data)
Returns
A pandas DataFrame
object with CFB team information,
or (if return_as_dict
is set to True
)
a dictionary object with CFB team information.
504def get_cfbd_team_rosters( 505 api_key: str = None, 506 api_key_dir: str = None, 507 team: str = None, 508 season: int = None, 509 return_as_dict: bool = False, 510): 511 """ 512 Allows you to get CFB team roster data for FBS teams from the CFBD API. 513 514 Parameters 515 ---------- 516 `api_key` (str, optional): 517 Semi-optional argument. 518 If `api_key` is null, this function will attempt to load a CFBD API key 519 from the python environment, or from a file on this computer. 520 If `api_key` is not null, 521 this function will automatically assume that the 522 inputted `api_key` is a valid CFBD API key. 523 524 `api_key_dir` (str, optional): 525 Optional argument. 526 If `api_key` is set to am empty string, this variable is ignored. 527 If `api_key_dir` is null, and `api_key` is null, 528 this function will try to find 529 a CFBD API key file in this user's home directory. 530 If `api_key_dir` is set to a string, and `api_key` is null, 531 this function will assume that `api_key_dir` is a directory, 532 and will try to find a CFBD API key file in that directory. 533 534 `season` (int, optional): 535 Optional argument. 536 If you only want CFB team roster data 537 for FBS teams in a specific season, 538 set `season` to that season. 539 540 `team` (str, optional): 541 Optional argument. 542 If you only want CFB team roster data for a specific CFB team, 543 set `team` to that CFB team's name. 544 545 `return_as_dict` (bool, semi-optional): 546 Semi-optional argument. 547 If you want this function to return 548 the data as a dictionary (read: JSON object), 549 instead of a pandas `DataFrame` object, 550 set `return_as_dict` to `True`. 551 552 Usage 553 ---------- 554 ``` 555 import time 556 557 from cfbd_json_py.teams import get_cfbd_team_rosters 558 559 560 cfbd_key = "tigersAreAwesome" # placeholder for your CFBD API Key. 561 562 if cfbd_key != "tigersAreAwesome": 563 print( 564 "Using the user's API key declared in this script " + 565 "for this example." 566 ) 567 568 # Get the team roster for the 2019 LSU Tigers Football Team. 569 print("Get the team rosters for the 2020 CFB season.") 570 json_data = get_cfbd_team_rosters( 571 api_key=cfbd_key, 572 season=2020, 573 team="LSU" 574 ) 575 print(json_data) 576 time.sleep(5) 577 578 # Get the team rosters for the 2020 CFB season. 579 print("Get the team rosters for the 2020 CFB season.") 580 json_data = get_cfbd_team_rosters( 581 api_key=cfbd_key, 582 season=2020 583 ) 584 print(json_data) 585 time.sleep(5) 586 587 # Get a list of known players with 588 # the Ohio State Buckeyes Football Team. 589 print( 590 "Get a list of known players with " + 591 "the Ohio State Buckeyes Football Team." 592 ) 593 json_data = get_cfbd_team_rosters( 594 api_key=cfbd_key, 595 team="Ohio State" 596 ) 597 print(json_data) 598 time.sleep(5) 599 600 601 # You can also tell this function to just return the API call as 602 # a Dictionary (read: JSON) object. 603 print( 604 "You can also tell this function to just return the API call " + 605 "as a Dictionary (read: JSON) object." 606 ) 607 json_data = get_cfbd_team_rosters( 608 api_key=cfbd_key, 609 season=2015, 610 team="LSU", 611 return_as_dict=True 612 ) 613 print(json_data) 614 615 else: 616 # Alternatively, if the CFBD API key exists in this python environment, 617 # or it's been set by cfbd_json_py.utls.set_cfbd_api_token(), 618 # you could just call these functions directly, 619 # without setting the API key in the script. 620 print( 621 "Using the user's API key supposedly loaded " + 622 "into this python environment for this example." 623 ) 624 625 626 # Get the team roster for the 2019 LSU Tigers Football Team. 627 print("Get the team roster for the 2019 LSU Tigers Football Team.") 628 json_data = get_cfbd_team_rosters( 629 season=2020, 630 team="LSU" 631 ) 632 print(json_data) 633 time.sleep(5) 634 635 # Get the team rosters for the 2020 CFB season. 636 print("Get the team rosters for the 2020 CFB season.") 637 json_data = get_cfbd_team_rosters( 638 season=2020 639 ) 640 print(json_data) 641 time.sleep(5) 642 643 # Get a list of known players with 644 # the Ohio State Buckeyes Football Team. 645 print( 646 "Get a list of known players with " + 647 "the Ohio State Buckeyes Football Team." 648 ) 649 json_data = get_cfbd_team_rosters( 650 team="Ohio State" 651 ) 652 print(json_data) 653 time.sleep(5) 654 655 656 # You can also tell this function to just return the API call as 657 # a Dictionary (read: JSON) object. 658 print( 659 "You can also tell this function to just return the API call " + 660 "as a Dictionary (read: JSON) object." 661 ) 662 json_data = get_cfbd_team_rosters( 663 season=2015, 664 team="LSU", 665 return_as_dict=True 666 ) 667 print(json_data) 668 669 ``` 670 Returns 671 ---------- 672 A pandas `DataFrame` object with CFB team roster data, 673 or (if `return_as_dict` is set to `True`) 674 a dictionary object with CFB team roster data. 675 676 """ 677 now = datetime.now() 678 roster_df = pd.DataFrame() 679 # row_df = pd.DataFrame() 680 url = "https://api.collegefootballdata.com/roster" 681 682 ########################################################################## 683 684 if api_key is not None: 685 real_api_key = api_key 686 del api_key 687 else: 688 real_api_key = get_cfbd_api_token(api_key_dir=api_key_dir) 689 690 if real_api_key == "tigersAreAwesome": 691 raise ValueError( 692 "You actually need to change `cfbd_key` to your CFBD API key." 693 ) 694 elif "Bearer " in real_api_key: 695 pass 696 elif "Bearer" in real_api_key: 697 real_api_key = real_api_key.replace("Bearer", "Bearer ") 698 else: 699 real_api_key = "Bearer " + real_api_key 700 701 if season is not None and season > (now.year + 1): 702 raise ValueError(f"`season` cannot be greater than {season}.") 703 elif season is not None and season < 1869: 704 raise ValueError("`season` cannot be less than 1869.") 705 706 # URL builder 707 ########################################################################## 708 709 url_elements = 0 710 711 if season is not None and url_elements == 0: 712 url += f"?year={season}" 713 url_elements += 1 714 elif season is not None: 715 url += f"&year={season}" 716 url_elements += 1 717 718 if team is not None and url_elements == 0: 719 url += f"?team={team}" 720 url_elements += 1 721 elif team is not None: 722 url += f"&team={team}" 723 url_elements += 1 724 725 headers = { 726 "Authorization": f"{real_api_key}", 727 "accept": "application/json" 728 } 729 730 response = requests.get(url, headers=headers) 731 732 if response.status_code == 200: 733 pass 734 elif response.status_code == 401: 735 raise ConnectionRefusedError( 736 "Could not connect. The connection was refused." + 737 "\nHTTP Status Code 401." 738 ) 739 else: 740 raise ConnectionError( 741 f"Could not connect.\nHTTP Status code {response.status_code}" 742 ) 743 744 json_data = response.json() 745 746 if return_as_dict is True: 747 return json_data 748 749 roster_df = pd.DataFrame(json_data) 750 return roster_df
Allows you to get CFB team roster data for FBS teams from the CFBD API.
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):
Optional argument.
If you only want CFB team roster data
for FBS teams in a specific season,
set season
to that season.
team
(str, optional):
Optional argument.
If you only want CFB team roster data for a specific CFB team,
set team
to that CFB team's name.
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.teams import get_cfbd_team_rosters
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 the team roster for the 2019 LSU Tigers Football Team.
print("Get the team rosters for the 2020 CFB season.")
json_data = get_cfbd_team_rosters(
api_key=cfbd_key,
season=2020,
team="LSU"
)
print(json_data)
time.sleep(5)
# Get the team rosters for the 2020 CFB season.
print("Get the team rosters for the 2020 CFB season.")
json_data = get_cfbd_team_rosters(
api_key=cfbd_key,
season=2020
)
print(json_data)
time.sleep(5)
# Get a list of known players with
# the Ohio State Buckeyes Football Team.
print(
"Get a list of known players with " +
"the Ohio State Buckeyes Football Team."
)
json_data = get_cfbd_team_rosters(
api_key=cfbd_key,
team="Ohio State"
)
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_rosters(
api_key=cfbd_key,
season=2015,
team="LSU",
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 the team roster for the 2019 LSU Tigers Football Team.
print("Get the team roster for the 2019 LSU Tigers Football Team.")
json_data = get_cfbd_team_rosters(
season=2020,
team="LSU"
)
print(json_data)
time.sleep(5)
# Get the team rosters for the 2020 CFB season.
print("Get the team rosters for the 2020 CFB season.")
json_data = get_cfbd_team_rosters(
season=2020
)
print(json_data)
time.sleep(5)
# Get a list of known players with
# the Ohio State Buckeyes Football Team.
print(
"Get a list of known players with " +
"the Ohio State Buckeyes Football Team."
)
json_data = get_cfbd_team_rosters(
team="Ohio State"
)
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_rosters(
season=2015,
team="LSU",
return_as_dict=True
)
print(json_data)
Returns
A pandas DataFrame
object with CFB team roster data,
or (if return_as_dict
is set to True
)
a dictionary object with CFB team roster data.
753def get_cfbd_team_talent_rankings( 754 api_key: str = None, 755 api_key_dir: str = None, 756 season: int = None, 757 return_as_dict: bool = False, 758): 759 """ 760 Get a list of teams, and their overall talent rankings, from the CFBD API. 761 762 Parameters 763 ---------- 764 `api_key` (str, optional): 765 Semi-optional argument. 766 If `api_key` is null, this function will attempt to load a CFBD API key 767 from the python environment, or from a file on this computer. 768 If `api_key` is not null, 769 this function will automatically assume that the 770 inputted `api_key` is a valid CFBD API key. 771 772 `api_key_dir` (str, optional): 773 Optional argument. 774 If `api_key` is set to am empty string, this variable is ignored. 775 If `api_key_dir` is null, and `api_key` is null, 776 this function will try to find 777 a CFBD API key file in this user's home directory. 778 If `api_key_dir` is set to a string, and `api_key` is null, 779 this function will assume that `api_key_dir` is a directory, 780 and will try to find a CFBD API key file in that directory. 781 782 `season` (int, optional): 783 Optional argument. 784 If you only want CFB team talent ranking data 785 for FBS teams in a specific season, 786 set `season` to that season. 787 788 `return_as_dict` (bool, semi-optional): 789 Semi-optional argument. 790 If you want this function to return 791 the data as a dictionary (read: JSON object), 792 instead of a pandas `DataFrame` object, 793 set `return_as_dict` to `True`. 794 795 Usage 796 ---------- 797 ``` 798 import time 799 800 from cfbd_json_py.teams import get_cfbd_team_talent_rankings 801 802 803 cfbd_key = "tigersAreAwesome" # placeholder for your CFBD API Key. 804 805 if cfbd_key != "tigersAreAwesome": 806 print( 807 "Using the user's API key declared in this script " + 808 "for this example." 809 ) 810 811 # Get team talent rankings data for the 2020 CFB season. 812 print("Get team talent rankings data for the 2020 CFB season.") 813 json_data = get_cfbd_team_talent_rankings( 814 api_key=cfbd_key, 815 season=2020 816 ) 817 print(json_data) 818 time.sleep(5) 819 820 # Get team talent rankings data for as many seasons as possible. 821 print("Get team talent rankings data for as many seasons as possible.") 822 json_data = get_cfbd_team_talent_rankings( 823 api_key=cfbd_key 824 ) 825 print(json_data) 826 time.sleep(5) 827 828 # You can also tell this function to just return the API call as 829 # a Dictionary (read: JSON) object. 830 print( 831 "You can also tell this function to just return the API call " + 832 "as a Dictionary (read: JSON) object." 833 ) 834 json_data = get_cfbd_team_talent_rankings( 835 api_key=cfbd_key, 836 season=2015, 837 return_as_dict=True 838 ) 839 print(json_data) 840 841 else: 842 # Alternatively, if the CFBD API key exists in this python environment, 843 # or it's been set by cfbd_json_py.utls.set_cfbd_api_token(), 844 # you could just call these functions directly, 845 # without setting the API key in the script. 846 print( 847 "Using the user's API key supposedly loaded " + 848 "into this python environment for this example." 849 ) 850 851 852 # Get team talent rankings data for the 2020 CFB season. 853 print("Get team talent rankings data for the 2020 CFB season.") 854 json_data = get_cfbd_team_talent_rankings( 855 season=2020 856 ) 857 print(json_data) 858 time.sleep(5) 859 860 # Get team talent rankings data for as many seasons as possible. 861 print("Get team talent rankings data for as many seasons as possible.") 862 json_data = get_cfbd_team_talent_rankings() 863 print(json_data) 864 time.sleep(5) 865 866 # You can also tell this function to just return the API call as 867 # a Dictionary (read: JSON) object. 868 print( 869 "You can also tell this function to just return the API call " + 870 "as a Dictionary (read: JSON) object." 871 ) 872 json_data = get_cfbd_team_talent_rankings( 873 season=2015, 874 return_as_dict=True 875 ) 876 print(json_data) 877 878 ``` 879 Returns 880 ---------- 881 A pandas `DataFrame` object with CFB team talent ratings data, 882 or (if `return_as_dict` is set to `True`) 883 a dictionary object with CFB team talent ratings data. 884 """ 885 now = datetime.now() 886 teams_df = pd.DataFrame() 887 # row_df = pd.DataFrame() 888 url = "https://api.collegefootballdata.com/talent" 889 890 ########################################################################## 891 892 if api_key is not None: 893 real_api_key = api_key 894 del api_key 895 else: 896 real_api_key = get_cfbd_api_token(api_key_dir=api_key_dir) 897 898 if real_api_key == "tigersAreAwesome": 899 raise ValueError( 900 "You actually need to change `cfbd_key` to your CFBD API key." 901 ) 902 elif "Bearer " in real_api_key: 903 pass 904 elif "Bearer" in real_api_key: 905 real_api_key = real_api_key.replace("Bearer", "Bearer ") 906 else: 907 real_api_key = "Bearer " + real_api_key 908 909 if season is not None and season > (now.year + 1): 910 raise ValueError(f"`season` cannot be greater than {season}.") 911 elif season is not None and season < 1869: 912 raise ValueError("`season` cannot be less than 1869.") 913 914 # URL builder 915 ########################################################################## 916 917 if season is not None: 918 url += f"?year={season}" 919 920 headers = { 921 "Authorization": f"{real_api_key}", 922 "accept": "application/json" 923 } 924 925 response = requests.get(url, headers=headers) 926 927 if response.status_code == 200: 928 pass 929 elif response.status_code == 401: 930 raise ConnectionRefusedError( 931 "Could not connect. The connection was refused." + 932 "\nHTTP Status Code 401." 933 ) 934 else: 935 raise ConnectionError( 936 f"Could not connect.\nHTTP Status code {response.status_code}" 937 ) 938 939 json_data = response.json() 940 941 if return_as_dict is True: 942 return json_data 943 944 teams_df = pd.DataFrame(json_data) 945 946 return teams_df
Get a list of teams, and their overall talent rankings, from the CFBD API.
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):
Optional argument.
If you only want CFB team talent ranking data
for FBS teams in a specific season,
set season
to that season.
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.teams import get_cfbd_team_talent_rankings
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 team talent rankings data for the 2020 CFB season.
print("Get team talent rankings data for the 2020 CFB season.")
json_data = get_cfbd_team_talent_rankings(
api_key=cfbd_key,
season=2020
)
print(json_data)
time.sleep(5)
# Get team talent rankings data for as many seasons as possible.
print("Get team talent rankings data for as many seasons as possible.")
json_data = get_cfbd_team_talent_rankings(
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_team_talent_rankings(
api_key=cfbd_key,
season=2015,
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 team talent rankings data for the 2020 CFB season.
print("Get team talent rankings data for the 2020 CFB season.")
json_data = get_cfbd_team_talent_rankings(
season=2020
)
print(json_data)
time.sleep(5)
# Get team talent rankings data for as many seasons as possible.
print("Get team talent rankings data for as many seasons as possible.")
json_data = get_cfbd_team_talent_rankings()
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_talent_rankings(
season=2015,
return_as_dict=True
)
print(json_data)
Returns
A pandas DataFrame
object with CFB team talent ratings data,
or (if return_as_dict
is set to True
)
a dictionary object with CFB team talent ratings data.
949def get_cfbd_team_matchup_history( 950 team_1: str, 951 team_2: str, 952 api_key: str = None, 953 api_key_dir: str = None, 954 min_season: int = None, 955 max_season: int = None, 956 return_as_dict: bool = False, 957): 958 """ 959 Get a list of matchups between two teams, from the CFBD API. 960 961 Parameters 962 ---------- 963 `team_1` (str, mandatory): 964 Mandatory argument. 965 This is the name of the **first** team in this matchup. 966 967 `team_1` (str, mandatory): 968 Mandatory argument. 969 This is the name of the **second** team in this matchup. 970 971 `api_key` (str, optional): 972 Semi-optional argument. 973 If `api_key` is null, this function will attempt to load a CFBD API key 974 from the python environment, or from a file on this computer. 975 If `api_key` is not null, 976 this function will automatically assume that the 977 inputted `api_key` is a valid CFBD API key. 978 979 `api_key_dir` (str, optional): 980 Optional argument. 981 If `api_key` is set to am empty string, this variable is ignored. 982 If `api_key_dir` is null, and `api_key` is null, 983 this function will try to find 984 a CFBD API key file in this user's home directory. 985 If `api_key_dir` is set to a string, and `api_key` is null, 986 this function will assume that `api_key_dir` is a directory, 987 and will try to find a CFBD API key file in that directory. 988 989 `min_season` (int, optional): 990 Optional argument. 991 If you only want matchups starting in a specific season, 992 set `min_season` to that season. 993 994 `max_season` (int, optional): 995 Optional argument. 996 If you only want matchups up to a specific season, 997 set `max_season` to that season. 998 999 `return_as_dict` (bool, semi-optional): 1000 Semi-optional argument. 1001 If you want this function to return 1002 the data as a dictionary (read: JSON object), 1003 instead of a pandas `DataFrame` object, 1004 set `return_as_dict` to `True`. 1005 1006 Usage 1007 ---------- 1008 ``` 1009 import time 1010 1011 from cfbd_json_py.teams import get_cfbd_team_matchup_history 1012 1013 1014 cfbd_key = "tigersAreAwesome" # placeholder for your CFBD API Key. 1015 1016 if cfbd_key != "tigersAreAwesome": 1017 print( 1018 "Using the user's API key declared in this script " + 1019 "for this example." 1020 ) 1021 1022 # Get the matchup history between the University of Cincinnati 1023 # and the Miami (OH) Redhawks football teams. 1024 print( 1025 "Get the matchup history between the University of Cincinnati " + 1026 "and the Miami (OH) Redhawks football teams." 1027 ) 1028 json_data = get_cfbd_team_matchup_history( 1029 api_key=cfbd_key, 1030 team_1="Cincinnati", 1031 team_2="Miami (OH)" 1032 ) 1033 print(json_data) 1034 time.sleep(5) 1035 1036 # Get the matchup history between the Ohio State Buckeyes 1037 # and the Michigan Wolverines football teams, 1038 # starting in 2002. 1039 print( 1040 "Get the matchup history between the Ohio State Buckeyes " + 1041 "and the University of Michigan Wolverines " + 1042 "football teams, starting in 2002." 1043 ) 1044 json_data = get_cfbd_team_matchup_history( 1045 api_key=cfbd_key, 1046 team_1="Ohio State", 1047 team_2="Michigan", 1048 min_season=2002 1049 ) 1050 print(json_data) 1051 time.sleep(5) 1052 1053 # Get the matchup history between the Ohio Bobcats 1054 # and the Miami (OH) Redhawks football teams, 1055 # starting in 1990 and ending in 2005. 1056 print( 1057 "Get the matchup history between the University of Cincinnati " + 1058 "and the Miami (OH) Redhawks football teams." 1059 ) 1060 json_data = get_cfbd_team_matchup_history( 1061 api_key=cfbd_key, 1062 team_1="Ohio", 1063 team_2="Miami (OH)", 1064 min_season=1990, 1065 max_season=2005 1066 ) 1067 print(json_data) 1068 time.sleep(5) 1069 1070 # You can also tell this function to just return the API call as 1071 # a Dictionary (read: JSON) object. 1072 print( 1073 "You can also tell this function to just return the API call " + 1074 "as a Dictionary (read: JSON) object." 1075 ) 1076 json_data = get_cfbd_team_matchup_history( 1077 api_key=cfbd_key, 1078 team_1="Cincinnati", 1079 team_2="Miami (OH)", 1080 min_season=2020, 1081 return_as_dict=True 1082 ) 1083 print(json_data) 1084 1085 else: 1086 # Alternatively, if the CFBD API key exists in this python environment, 1087 # or it's been set by cfbd_json_py.utls.set_cfbd_api_token(), 1088 # you could just call these functions directly, 1089 # without setting the API key in the script. 1090 print( 1091 "Using the user's API key supposedly loaded " + 1092 "into this python environment for this example." 1093 ) 1094 1095 1096 # Get the matchup history between the University of Cincinnati 1097 # and the Miami (OH) Redhawks football teams. 1098 print( 1099 "Get the matchup history between the University of Cincinnati " + 1100 "and the Miami (OH) Redhawks football teams." 1101 ) 1102 json_data = get_cfbd_team_matchup_history( 1103 team_1="Cincinnati", 1104 team_2="Miami (OH)" 1105 ) 1106 print(json_data) 1107 time.sleep(5) 1108 1109 # Get the matchup history between the Ohio State Buckeyes 1110 # and the Michigan Wolverines football teams, 1111 # starting in 2002. 1112 print( 1113 "Get the matchup history between the Ohio State Buckeyes " + 1114 "and the University of Michigan Wolverines " + 1115 "football teams, starting in 2002." 1116 ) 1117 json_data = get_cfbd_team_matchup_history( 1118 team_1="Ohio State", 1119 team_2="Michigan", 1120 min_season=2002 1121 ) 1122 print(json_data) 1123 time.sleep(5) 1124 1125 # Get the matchup history between the Ohio Bobcats 1126 # and the Miami (OH) Redhawks football teams, 1127 # starting in 1990 and ending in 2005. 1128 print( 1129 "Get the matchup history between the University of Cincinnati " + 1130 "and the Miami (OH) Redhawks football teams." 1131 ) 1132 json_data = get_cfbd_team_matchup_history( 1133 team_1="Ohio", 1134 team_2="Miami (OH)", 1135 min_season=1990, 1136 max_season=2005 1137 ) 1138 print(json_data) 1139 time.sleep(5) 1140 1141 # You can also tell this function to just return the API call as 1142 # a Dictionary (read: JSON) object. 1143 print( 1144 "You can also tell this function to just return the API call " + 1145 "as a Dictionary (read: JSON) object." 1146 ) 1147 json_data = get_cfbd_team_matchup_history( 1148 team_1="Cincinnati", 1149 team_2="Miami (OH)", 1150 min_season=2020, 1151 return_as_dict=True 1152 ) 1153 print(json_data) 1154 ``` 1155 Returns 1156 ---------- 1157 A pandas `DataFrame` object with CFB team matchup data, 1158 or (if `return_as_dict` is set to `True`) 1159 a dictionary object with CFB team matchup data. 1160 """ 1161 now = datetime.now() 1162 matchups_df = pd.DataFrame() 1163 row_df = pd.DataFrame() 1164 url = "https://api.collegefootballdata.com/teams/matchup" 1165 1166 ########################################################################## 1167 1168 if api_key is not None: 1169 real_api_key = api_key 1170 del api_key 1171 else: 1172 real_api_key = get_cfbd_api_token(api_key_dir=api_key_dir) 1173 1174 if real_api_key == "tigersAreAwesome": 1175 raise ValueError( 1176 "You actually need to change `cfbd_key` to your CFBD API key." 1177 ) 1178 elif "Bearer " in real_api_key: 1179 pass 1180 elif "Bearer" in real_api_key: 1181 real_api_key = real_api_key.replace("Bearer", "Bearer ") 1182 else: 1183 real_api_key = "Bearer " + real_api_key 1184 1185 if min_season is not None and min_season > (now.year + 1): 1186 raise ValueError(f"`min_season` cannot be greater than {min_season}.") 1187 elif min_season is not None and min_season < 1869: 1188 raise ValueError("`min_season` cannot be less than 1869.") 1189 1190 if max_season is not None and max_season > (now.year + 1): 1191 raise ValueError(f"`max_season` cannot be greater than {max_season}.") 1192 elif max_season is not None and max_season < 1869: 1193 raise ValueError("`max_season` cannot be less than 1869.") 1194 1195 # URL builder 1196 ########################################################################## 1197 1198 # Required by the API: 1199 url += f"?team1={team_1}&team2={team_2}" 1200 1201 if min_season is not None: 1202 url += f"&minYear={min_season}" 1203 1204 if max_season is not None: 1205 url += f"&maxYear={max_season}" 1206 1207 headers = { 1208 "Authorization": f"{real_api_key}", 1209 "accept": "application/json" 1210 } 1211 1212 response = requests.get(url, headers=headers) 1213 1214 if response.status_code == 200: 1215 pass 1216 elif response.status_code == 401: 1217 raise ConnectionRefusedError( 1218 "Could not connect. The connection was refused." + 1219 "\nHTTP Status Code 401." 1220 ) 1221 else: 1222 raise ConnectionError( 1223 f"Could not connect.\nHTTP Status code {response.status_code}" 1224 ) 1225 1226 json_data = response.json() 1227 1228 if return_as_dict is True: 1229 return json_data 1230 1231 team_1_wins = json_data["team1Wins"] 1232 team_2_wins = json_data["team2Wins"] 1233 total_ties = json_data["ties"] 1234 1235 for game in tqdm(json_data["games"]): 1236 row_df = pd.DataFrame( 1237 { 1238 "team_1": team_1, 1239 "team_2": team_2, 1240 "start_year": min_season, 1241 "end_year": max_season, 1242 "team_1_wins": team_1_wins, 1243 "team_2_wins": team_2_wins, 1244 "ties": total_ties, 1245 }, 1246 index=[0], 1247 ) 1248 row_df["season"] = game["season"] 1249 row_df["week"] = game["week"] 1250 row_df["season_type"] = game["seasonType"] 1251 row_df["date"] = game["date"] 1252 row_df["is_neutral_site_game"] = game["neutralSite"] 1253 row_df["venue"] = game["venue"] 1254 row_df["home_team"] = game["homeTeam"] 1255 row_df["home_score"] = game["homeScore"] 1256 row_df["away_team"] = game["awayTeam"] 1257 row_df["away_score"] = game["awayScore"] 1258 row_df["winner"] = game["winner"] 1259 1260 matchups_df = pd.concat([matchups_df, row_df], ignore_index=True) 1261 del row_df 1262 1263 return matchups_df
Get a list of matchups between two teams, from the CFBD API.
Parameters
team_1
(str, mandatory):
Mandatory argument.
This is the name of the first team in this matchup.
team_1
(str, mandatory):
Mandatory argument.
This is the name of the second team in this matchup.
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.
min_season
(int, optional):
Optional argument.
If you only want matchups starting in a specific season,
set min_season
to that season.
max_season
(int, optional):
Optional argument.
If you only want matchups up to a specific season,
set max_season
to that season.
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.teams import get_cfbd_team_matchup_history
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 the matchup history between the University of Cincinnati
# and the Miami (OH) Redhawks football teams.
print(
"Get the matchup history between the University of Cincinnati " +
"and the Miami (OH) Redhawks football teams."
)
json_data = get_cfbd_team_matchup_history(
api_key=cfbd_key,
team_1="Cincinnati",
team_2="Miami (OH)"
)
print(json_data)
time.sleep(5)
# Get the matchup history between the Ohio State Buckeyes
# and the Michigan Wolverines football teams,
# starting in 2002.
print(
"Get the matchup history between the Ohio State Buckeyes " +
"and the University of Michigan Wolverines " +
"football teams, starting in 2002."
)
json_data = get_cfbd_team_matchup_history(
api_key=cfbd_key,
team_1="Ohio State",
team_2="Michigan",
min_season=2002
)
print(json_data)
time.sleep(5)
# Get the matchup history between the Ohio Bobcats
# and the Miami (OH) Redhawks football teams,
# starting in 1990 and ending in 2005.
print(
"Get the matchup history between the University of Cincinnati " +
"and the Miami (OH) Redhawks football teams."
)
json_data = get_cfbd_team_matchup_history(
api_key=cfbd_key,
team_1="Ohio",
team_2="Miami (OH)",
min_season=1990,
max_season=2005
)
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_matchup_history(
api_key=cfbd_key,
team_1="Cincinnati",
team_2="Miami (OH)",
min_season=2020,
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 the matchup history between the University of Cincinnati
# and the Miami (OH) Redhawks football teams.
print(
"Get the matchup history between the University of Cincinnati " +
"and the Miami (OH) Redhawks football teams."
)
json_data = get_cfbd_team_matchup_history(
team_1="Cincinnati",
team_2="Miami (OH)"
)
print(json_data)
time.sleep(5)
# Get the matchup history between the Ohio State Buckeyes
# and the Michigan Wolverines football teams,
# starting in 2002.
print(
"Get the matchup history between the Ohio State Buckeyes " +
"and the University of Michigan Wolverines " +
"football teams, starting in 2002."
)
json_data = get_cfbd_team_matchup_history(
team_1="Ohio State",
team_2="Michigan",
min_season=2002
)
print(json_data)
time.sleep(5)
# Get the matchup history between the Ohio Bobcats
# and the Miami (OH) Redhawks football teams,
# starting in 1990 and ending in 2005.
print(
"Get the matchup history between the University of Cincinnati " +
"and the Miami (OH) Redhawks football teams."
)
json_data = get_cfbd_team_matchup_history(
team_1="Ohio",
team_2="Miami (OH)",
min_season=1990,
max_season=2005
)
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_matchup_history(
team_1="Cincinnati",
team_2="Miami (OH)",
min_season=2020,
return_as_dict=True
)
print(json_data)
Returns
A pandas DataFrame
object with CFB team matchup data,
or (if return_as_dict
is set to True
)
a dictionary object with CFB team matchup data.