cfbd_json_py.ratings
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: ratings.py 5# Purpose: Houses functions pertaining to CFB team rating data 6# within the CFBD API. 7############################################################################### 8 9import warnings 10from datetime import datetime 11 12import pandas as pd 13import requests 14 15from cfbd_json_py.utls import get_cfbd_api_token 16 17 18def get_cfbd_sp_plus_ratings( 19 api_key: str = None, 20 api_key_dir: str = None, 21 season: int = None, 22 team: int = None, 23 # Either `year` or `team` have to be not null for this function to work. 24 return_as_dict: bool = False, 25): 26 """ 27 Allows you to get Success rate and equivalent Points per play (S&P+) 28 ratings data from the CFBD API. 29 30 For more information about S&P+, consult the following webpages: 31 - https://www.sbnation.com/college-football/ 32 2017/10/13/16457830/college-football-advanced-stats-analytics-rankings 33 - https://collegefootballdata.com/sp/trends 34 35 Parameters 36 ---------- 37 `api_key` (str, optional): 38 Semi-optional argument. 39 If `api_key` is null, this function will attempt to load a CFBD API key 40 from the python environment, or from a file on this computer. 41 If `api_key` is not null, 42 this function will automatically assume that the 43 inputted `api_key` is a valid CFBD API key. 44 45 `api_key_dir` (str, optional): 46 Optional argument. 47 If `api_key` is set to am empty string, this variable is ignored. 48 If `api_key_dir` is null, and `api_key` is null, 49 this function will try to find 50 a CFBD API key file in this user's home directory. 51 If `api_key_dir` is set to a string, and `api_key` is null, 52 this function will assume that `api_key_dir` is a directory, 53 and will try to find a CFBD API key file in that directory. 54 55 `season` (int, semi-mandatory): 56 Semi-required argument. 57 Specifies the season you want S&P+ ratings data from. 58 This must be specified, otherwise this package, and by extension 59 the CFBD API, will not accept the request to get S&P+ ratings data. 60 This or `team` must be set to a valid 61 non-null variable for this to function. 62 63 `team` (str, semi-mandatory): 64 Semi-required argument. 65 Specifies the season you want S&P+ ratings data from. 66 This must be specified, otherwise this package, and by extension 67 the CFBD API, will not accept the request to get S&P+ ratings data. 68 This or `season` must be set to a valid non-null variable 69 for this to function. 70 71 `return_as_dict` (bool, semi-optional): 72 Semi-optional argument. 73 If you want this function to return 74 the data as a dictionary (read: JSON object), 75 instead of a pandas `DataFrame` object, 76 set `return_as_dict` to `True`. 77 78 Usage 79 ---------- 80 ``` 81 import time 82 83 from cfbd_json_py.ratings import get_cfbd_sp_plus_ratings 84 85 86 cfbd_key = "tigersAreAwesome" # placeholder for your CFBD API Key. 87 88 if cfbd_key != "tigersAreAwesome": 89 print( 90 "Using the user's API key declared in this script " + 91 "for this example." 92 ) 93 94 # Get S&P+ ratings data for the 2020 CFB season. 95 print("Get S&P+ ratings data for the 2020 CFB season.") 96 json_data = get_cfbd_sp_plus_ratings( 97 api_key=cfbd_key, 98 season=2020 99 ) 100 print(json_data) 101 time.sleep(5) 102 103 # Get historical S&P+ ratings data for the 104 # University of Cincinnati Bearcats Football Team. 105 print( 106 "Get historical S&P+ ratings data for " + 107 "the University of Cincinnati Bearcats Football Team." 108 ) 109 json_data = get_cfbd_sp_plus_ratings( 110 api_key=cfbd_key, 111 team="Cincinnati" 112 ) 113 print(json_data) 114 time.sleep(5) 115 116 # Get S&P+ ratings data for the 2019 Ohio State Buckeyes Football Team. 117 print( 118 "Get S&P+ ratings data for " + 119 "the 2019 Ohio State Buckeyes Football Team." 120 ) 121 json_data = get_cfbd_sp_plus_ratings( 122 api_key=cfbd_key, 123 season=2020, 124 team="Ohio State" 125 ) 126 print(json_data) 127 time.sleep(5) 128 129 # You can also tell this function to just return the API call as 130 # a Dictionary (read: JSON) object. 131 print( 132 "You can also tell this function to just return the API call " + 133 "as a Dictionary (read: JSON) object." 134 ) 135 json_data = get_cfbd_sp_plus_ratings( 136 api_key=cfbd_key, 137 season=2020, 138 team="Ohio State", 139 return_as_dict=True 140 ) 141 print(json_data) 142 143 else: 144 # Alternatively, if the CFBD API key exists in this python environment, 145 # or it's been set by cfbd_json_py.utls.set_cfbd_api_token(), 146 # you could just call these functions directly, 147 # without setting the API key in the script. 148 print( 149 "Using the user's API key supposedly loaded " + 150 "into this python environment for this example." 151 ) 152 153 # Get S&P+ ratings data for the 2020 CFB season. 154 print("Get S&P+ ratings data for the 2020 CFB season.") 155 json_data = get_cfbd_sp_plus_ratings( 156 season=2020 157 ) 158 print(json_data) 159 time.sleep(5) 160 161 # Get historical S&P+ ratings data for the 162 # University of Cincinnati Bearcats Football Team. 163 print( 164 "Get historical S&P+ ratings data for " + 165 "the University of Cincinnati Bearcats Football Team." 166 ) 167 json_data = get_cfbd_sp_plus_ratings( 168 team="Cincinnati" 169 ) 170 print(json_data) 171 time.sleep(5) 172 173 # Get S&P+ ratings data for the 2019 Ohio State Buckeyes Football Team. 174 print( 175 "Get S&P+ ratings data for " + 176 "the 2019 Ohio State Buckeyes Football Team." 177 ) 178 json_data = get_cfbd_sp_plus_ratings( 179 season=2020, 180 team="Ohio State" 181 ) 182 print(json_data) 183 time.sleep(5) 184 185 # You can also tell this function to just return the API call as 186 # a Dictionary (read: JSON) object. 187 print( 188 "You can also tell this function to just return the API call " + 189 "as a Dictionary (read: JSON) object." 190 ) 191 json_data = get_cfbd_sp_plus_ratings( 192 season=2020, 193 team="Ohio State", 194 return_as_dict=True 195 ) 196 print(json_data) 197 ``` 198 Returns 199 ---------- 200 A pandas `DataFrame` object with S&P+ ratings data, 201 or (if `return_as_dict` is set to `True`) 202 a dictionary object with a with S&P+ ratings data. 203 204 """ 205 warnings.simplefilter(action="ignore", category=FutureWarning) 206 207 now = datetime.now() 208 url = "https://api.collegefootballdata.com/ratings/sp" 209 final_df = pd.DataFrame() 210 211 if api_key is not None: 212 real_api_key = api_key 213 del api_key 214 else: 215 real_api_key = get_cfbd_api_token(api_key_dir=api_key_dir) 216 217 if real_api_key == "tigersAreAwesome": 218 raise ValueError( 219 "You actually need to change `cfbd_key` to your CFBD API key." 220 ) 221 elif "Bearer " in real_api_key: 222 pass 223 elif "Bearer" in real_api_key: 224 real_api_key = real_api_key.replace("Bearer", "Bearer ") 225 else: 226 real_api_key = "Bearer " + real_api_key 227 228 if season is None and team is None: 229 raise ValueError( 230 "`season` and/or `team` must be set to a valid, " 231 + "non-null value for this function to work." 232 ) 233 234 if season is not None and (season > (now.year + 1)): 235 raise ValueError(f"`season` cannot be greater than {season}.") 236 elif season is not None and season < 1869: 237 raise ValueError("`season` cannot be less than 1869.") 238 239 # URL builder 240 ########################################################################## 241 242 # Required by the API 243 244 if season is not None and team is not None: 245 url += f"?year={season}&team={team}" 246 elif season is not None: 247 url += f"?year={season}" 248 elif team is not None: 249 url += f"?team={team}" 250 251 headers = { 252 "Authorization": f"{real_api_key}", 253 "accept": "application/json" 254 } 255 response = requests.get(url, headers=headers) 256 257 if response.status_code == 200: 258 pass 259 elif response.status_code == 401: 260 raise ConnectionRefusedError( 261 "Could not connect. The connection was refused." + 262 "\nHTTP Status Code 401." 263 ) 264 else: 265 raise ConnectionError( 266 f"Could not connect.\nHTTP Status code {response.status_code}" 267 ) 268 269 json_data = response.json() 270 271 if return_as_dict is True: 272 return json_data 273 274 final_df = pd.json_normalize(json_data) 275 final_df.rename( 276 columns={ 277 "team": "team_name", 278 "conference": "conference_name", 279 "rating": "S&P+_rating", 280 "secondOrderWins": "second_order_wins", 281 "offense.rating": "offense_S&P+_rating", 282 "offense.success": "offense_S&P+_success", 283 "offense.explosiveness": "offense_S&P+_explosiveness", 284 "offense.rushing": "offense_S&P+_rushing", 285 "offense.passing": "offense_S&P+_passing", 286 "offense.standardDowns": "offense_S&P+_standard_downs", 287 "offense.passingDowns": "offense_S&P+_passing_downs", 288 "offense.runRate": "offense_S&P+_run_rate", 289 "offense.pace": "offense_S&P+_pace", 290 "defense.rating": "defense_S&P+_rating", 291 "defense.success": "defense_S&P+_success", 292 "defense.explosiveness": "defense_S&P+_explosiveness", 293 "defense.rushing": "defense_S&P+_rushing", 294 "defense.passing": "defense_S&P+_passing", 295 "defense.standardDowns": "defense_S&P+_standard_downs", 296 "defense.passingDowns": "defense_S&P+_passing_downs", 297 "defense.havoc.total": "defense_S&P+_havoc_total", 298 "defense.havoc.frontSeven": "defense_S&P+_havoc_front_seven", 299 "defense.havoc.db": "defense_S&P+_havoc_db", 300 "specialTeams.rating": "defense_S&P+_special_teams_rating", 301 }, 302 inplace=True, 303 ) 304 # print(final_df.columns) 305 306 return final_df 307 308 309def get_cfbd_srs_ratings( 310 api_key: str = None, 311 api_key_dir: str = None, 312 season: int = None, 313 team: int = None, 314 # Either `year` or `team` have to be not null for this function to work. 315 conference: str = None, 316 return_as_dict: bool = False, 317): 318 """ 319 Allows you to get Simple Rating System (SRS) data from the CFBD API. 320 321 For more information about S&P+, consult the following webpages: 322 - https://www.sports-reference.com/blog/2015/03/srs-calculation-details/ 323 - https://blog.collegefootballdata.com/talking-tech-bu/ 324 325 Parameters 326 ---------- 327 `api_key` (str, optional): 328 Semi-optional argument. 329 If `api_key` is null, this function will attempt to load a CFBD API key 330 from the python environment, or from a file on this computer. 331 If `api_key` is not null, 332 this function will automatically assume that the 333 inputted `api_key` is a valid CFBD API key. 334 335 `api_key_dir` (str, optional): 336 Optional argument. 337 If `api_key` is set to am empty string, this variable is ignored. 338 If `api_key_dir` is null, and `api_key` is null, 339 this function will try to find 340 a CFBD API key file in this user's home directory. 341 If `api_key_dir` is set to a string, and `api_key` is null, 342 this function will assume that `api_key_dir` is a directory, 343 and will try to find a CFBD API key file in that directory. 344 345 `season` (int, semi-mandatory): 346 Semi-required argument. 347 Specifies the season you want SRS ratings data from. 348 This must be specified, otherwise this package, and by extension 349 the CFBD API, will not accept the request to get SRS ratings data. 350 This or `team` must be set to a valid non-null variable 351 for this to function. 352 353 `team` (str, semi-mandatory): 354 Semi-required argument. 355 Specifies the season you want SRS ratings data from. 356 This must be specified, otherwise this package, and by extension 357 the CFBD API, will not accept the request to get SRS ratings data. 358 This or `season` must be set to a valid non-null variable 359 for this to function. 360 361 `conference` (str, optional): 362 Optional argument. 363 If you only want game information from games 364 involving teams a specific conference, 365 set `conference` to the abbreviation 366 of the conference you want game information from. 367 368 `return_as_dict` (bool, semi-optional): 369 Semi-optional argument. 370 If you want this function to return 371 the data as a dictionary (read: JSON object), 372 instead of a pandas `DataFrame` object, 373 set `return_as_dict` to `True`. 374 375 Usage 376 ---------- 377 ``` 378 import time 379 380 from cfbd_json_py.ratings import get_cfbd_srs_ratings 381 382 383 cfbd_key = "tigersAreAwesome" # placeholder for your CFBD API Key. 384 385 if cfbd_key != "tigersAreAwesome": 386 print( 387 "Using the user's API key declared in this script " + 388 "for this example." 389 ) 390 391 # Get SRS ratings data for the 2020 CFB season. 392 print("Get SRS ratings data for the 2020 CFB season.") 393 json_data = get_cfbd_srs_ratings( 394 api_key=cfbd_key, 395 season=2020 396 ) 397 print(json_data) 398 time.sleep(5) 399 400 # Get historical SRS ratings data for the 401 # University of Cincinnati Bearcats Football Team. 402 print( 403 "Get historical SRS ratings data for " + 404 "the University of Cincinnati Bearcats Football Team." 405 ) 406 json_data = get_cfbd_srs_ratings( 407 api_key=cfbd_key, 408 team="Cincinnati" 409 ) 410 print(json_data) 411 time.sleep(5) 412 413 # Get SRS ratings data for the 2019 Ohio State Buckeyes Football Team. 414 print( 415 "Get SRS ratings data for " + 416 "the 2019 Ohio State Buckeyes Football Team." 417 ) 418 json_data = get_cfbd_srs_ratings( 419 api_key=cfbd_key, 420 season=2020, 421 team="Ohio State" 422 ) 423 print(json_data) 424 time.sleep(5) 425 426 # You can also tell this function to just return the API call as 427 # a Dictionary (read: JSON) object. 428 print( 429 "You can also tell this function to just return the API call " + 430 "as a Dictionary (read: JSON) object." 431 ) 432 json_data = get_cfbd_srs_ratings( 433 api_key=cfbd_key, 434 season=2020, 435 team="Ohio State", 436 return_as_dict=True 437 ) 438 print(json_data) 439 440 else: 441 # Alternatively, if the CFBD API key exists in this python environment, 442 # or it's been set by cfbd_json_py.utls.set_cfbd_api_token(), 443 # you could just call these functions directly, 444 # without setting the API key in the script. 445 print( 446 "Using the user's API key supposedly loaded " + 447 "into this python environment for this example." 448 ) 449 450 # Get SRS ratings data for the 2020 CFB season. 451 print("Get SRS ratings data for the 2020 CFB season.") 452 json_data = get_cfbd_srs_ratings( 453 season=2020 454 ) 455 print(json_data) 456 time.sleep(5) 457 458 # Get historical SRS ratings data for the 459 # University of Cincinnati Bearcats Football Team. 460 print( 461 "Get historical SRS ratings data for " + 462 "the University of Cincinnati Bearcats Football Team." 463 ) 464 json_data = get_cfbd_srs_ratings( 465 team="Cincinnati" 466 ) 467 print(json_data) 468 time.sleep(5) 469 470 # Get SRS ratings data for the 2019 Ohio State Buckeyes Football Team. 471 print( 472 "Get SRS ratings data for " + 473 "the 2019 Ohio State Buckeyes Football Team." 474 ) 475 json_data = get_cfbd_srs_ratings( 476 season=2020, 477 team="Ohio State" 478 ) 479 print(json_data) 480 time.sleep(5) 481 482 # You can also tell this function to just return the API call as 483 # a Dictionary (read: JSON) object. 484 print( 485 "You can also tell this function to just return the API call " + 486 "as a Dictionary (read: JSON) object." 487 ) 488 json_data = get_cfbd_srs_ratings( 489 season=2020, 490 team="Ohio State", 491 return_as_dict=True 492 ) 493 print(json_data) 494 ``` 495 Returns 496 ---------- 497 A pandas `DataFrame` object with team season stats data, 498 or (if `return_as_dict` is set to `True`) 499 a dictionary object with a with team season stats data. 500 501 """ 502 now = datetime.now() 503 url = "https://api.collegefootballdata.com/ratings/srs" 504 # row_df = pd.DataFrame() 505 final_df = pd.DataFrame() 506 507 if api_key is not None: 508 real_api_key = api_key 509 del api_key 510 else: 511 real_api_key = get_cfbd_api_token(api_key_dir=api_key_dir) 512 513 if real_api_key == "tigersAreAwesome": 514 raise ValueError( 515 "You actually need to change `cfbd_key` to your CFBD API key." 516 ) 517 elif "Bearer " in real_api_key: 518 pass 519 elif "Bearer" in real_api_key: 520 real_api_key = real_api_key.replace("Bearer", "Bearer ") 521 else: 522 real_api_key = "Bearer " + real_api_key 523 524 if season is None and team is None: 525 raise ValueError( 526 "`season` and/or `team` must be set to a valid, " 527 + "non-null value for this function to work." 528 ) 529 530 if season is not None and (season > (now.year + 1)): 531 raise ValueError(f"`season` cannot be greater than {season}.") 532 elif season is not None and season < 1869: 533 raise ValueError("`season` cannot be less than 1869.") 534 535 # URL builder 536 ########################################################################## 537 538 # Required by the API 539 540 if season is not None and team is not None: 541 url += f"?year={season}&team={team}" 542 elif season is not None: 543 url += f"?year={season}" 544 elif team is not None: 545 url += f"?team={team}" 546 547 if conference is not None: 548 url += f"&conference={conference}" 549 550 headers = { 551 "Authorization": f"{real_api_key}", 552 "accept": "application/json" 553 } 554 response = requests.get(url, headers=headers) 555 556 if response.status_code == 200: 557 pass 558 elif response.status_code == 401: 559 raise ConnectionRefusedError( 560 "Could not connect. The connection was refused." + 561 "\nHTTP Status Code 401." 562 ) 563 else: 564 raise ConnectionError( 565 f"Could not connect.\nHTTP Status code {response.status_code}" 566 ) 567 568 json_data = response.json() 569 570 if return_as_dict is True: 571 return json_data 572 573 final_df = pd.json_normalize(json_data) 574 575 final_df.rename(columns={"rating": "srs_rating"}, inplace=True) 576 return final_df 577 578 579def get_cfbd_sp_plus_conference_ratings( 580 api_key: str = None, 581 api_key_dir: str = None, 582 season: int = None, 583 conference: str = None, 584 return_as_dict: bool = False, 585): 586 """ 587 Allows you to get Success rate and equivalent Points per play (S&P+) 588 ratings data from the CFBD API. 589 590 For more information about S&P+, consult the following webpage: 591 https://collegefootballdata.com/sp/trends 592 593 Parameters 594 ---------- 595 `api_key` (str, optional): 596 Semi-optional argument. 597 If `api_key` is null, this function will attempt to load a CFBD API key 598 from the python environment, or from a file on this computer. 599 If `api_key` is not null, 600 this function will automatically assume that the 601 inputted `api_key` is a valid CFBD API key. 602 603 `api_key_dir` (str, optional): 604 Optional argument. 605 If `api_key` is set to am empty string, this variable is ignored. 606 If `api_key_dir` is null, and `api_key` is null, 607 this function will try to find 608 a CFBD API key file in this user's home directory. 609 If `api_key_dir` is set to a string, and `api_key` is null, 610 this function will assume that `api_key_dir` is a directory, 611 and will try to find a CFBD API key file in that directory. 612 613 `season` (int, optional): 614 Optional argument. 615 Specifies the season you want S&P+ ratings data from. 616 This must be specified, otherwise this package, and by extension 617 the CFBD API, will not accept the request to get S&P+ ratings data. 618 This or `team` must be set to a valid non-null variable 619 for this to function. 620 621 `team` (str, optional): 622 Optional argument. 623 Specifies the season you want S&P+ ratings data from. 624 This must be specified, otherwise this package, and by extension 625 the CFBD API, will not accept the request to get S&P+ ratings data. 626 This or `season` must be set to a valid non-null variable 627 for this to function. 628 629 `conference` (str, optional): 630 Optional argument. 631 If you only want S&P+ ratings data from games 632 involving teams a specific conference, 633 set `conference` to the abbreviation 634 of the conference you want S&P+ ratings data from. 635 636 `return_as_dict` (bool, semi-optional): 637 Semi-optional argument. 638 If you want this function to return 639 the data as a dictionary (read: JSON object), 640 instead of a pandas `DataFrame` object, 641 set `return_as_dict` to `True`. 642 643 Usage 644 ---------- 645 ``` 646 import time 647 648 from cfbd_json_py.ratings import get_cfbd_sp_plus_conference_ratings 649 650 651 cfbd_key = "tigersAreAwesome" # placeholder for your CFBD API Key. 652 653 if cfbd_key != "tigersAreAwesome": 654 print( 655 "Using the user's API key declared in this script " + 656 "for this example." 657 ) 658 659 # Get S&P+ ratings data for the 2020 CFB season. 660 print("Get S&P+ ratings data for the 2020 CFB season.") 661 json_data = get_cfbd_sp_plus_conference_ratings( 662 api_key=cfbd_key, 663 season=2020 664 ) 665 print(json_data) 666 time.sleep(5) 667 668 # You can also tell this function to just return the API call as 669 # a Dictionary (read: JSON) object. 670 print( 671 "You can also tell this function to just return the API call " + 672 "as a Dictionary (read: JSON) object." 673 ) 674 json_data = get_cfbd_sp_plus_conference_ratings( 675 api_key=cfbd_key, 676 season=2020, 677 return_as_dict=True 678 ) 679 print(json_data) 680 681 else: 682 # Alternatively, if the CFBD API key exists in this python environment, 683 # or it's been set by cfbd_json_py.utls.set_cfbd_api_token(), 684 # you could just call these functions directly, 685 # without setting the API key in the script. 686 print( 687 "Using the user's API key supposedly loaded " + 688 "into this python environment for this example." 689 ) 690 691 # Get S&P+ ratings data for the 2020 CFB season. 692 print("Get S&P+ ratings data for the 2020 CFB season.") 693 json_data = get_cfbd_sp_plus_conference_ratings( 694 season=2020 695 ) 696 print(json_data) 697 time.sleep(5) 698 699 # You can also tell this function to just return the API call as 700 # a Dictionary (read: JSON) object. 701 print( 702 "You can also tell this function to just return the API call " + 703 "as a Dictionary (read: JSON) object." 704 ) 705 json_data = get_cfbd_sp_plus_conference_ratings( 706 season=2020, 707 return_as_dict=True 708 ) 709 print(json_data) 710 ``` 711 Returns 712 ---------- 713 A pandas `DataFrame` object with S&P+ ratings data, 714 or (if `return_as_dict` is set to `True`) 715 a dictionary object with a with S&P+ ratings data. 716 """ 717 # warnings.simplefilter(action="ignore", category=FutureWarning) 718 719 now = datetime.now() 720 url = "https://api.collegefootballdata.com/ratings/sp/conferences" 721 # row_df = pd.DataFrame() 722 final_df = pd.DataFrame() 723 724 if api_key is not None: 725 real_api_key = api_key 726 del api_key 727 else: 728 real_api_key = get_cfbd_api_token(api_key_dir=api_key_dir) 729 730 if real_api_key == "tigersAreAwesome": 731 raise ValueError( 732 "You actually need to change `cfbd_key` to your CFBD API key." 733 ) 734 elif "Bearer " in real_api_key: 735 pass 736 elif "Bearer" in real_api_key: 737 real_api_key = real_api_key.replace("Bearer", "Bearer ") 738 else: 739 real_api_key = "Bearer " + real_api_key 740 741 # if season is None and team is None: 742 # raise ValueError( 743 # "`season` and/or `team` must be set to a valid, " 744 # + "non-null value for this function to work." 745 # ) 746 747 if season is not None and (season > (now.year + 1)): 748 raise ValueError(f"`season` cannot be greater than {season}.") 749 elif season is not None and season < 1869: 750 raise ValueError("`season` cannot be less than 1869.") 751 752 # URL builder 753 ########################################################################## 754 755 # Required by the API 756 url_elements = 0 757 758 if season is not None and url_elements == 0: 759 url += f"?year={season}" 760 url_elements += 1 761 elif season is not None: 762 url += f"&year={season}" 763 url_elements += 1 764 765 if conference is not None and url_elements == 0: 766 url += f"?conference={conference}" 767 url_elements += 1 768 elif conference is not None: 769 url += f"&conference={conference}" 770 url_elements += 1 771 772 headers = { 773 "Authorization": f"{real_api_key}", 774 "accept": "application/json" 775 } 776 response = requests.get(url, headers=headers) 777 778 if response.status_code == 200: 779 pass 780 elif response.status_code == 401: 781 raise ConnectionRefusedError( 782 "Could not connect. The connection was refused." + 783 "\nHTTP Status Code 401." 784 ) 785 else: 786 raise ConnectionError( 787 f"Could not connect.\nHTTP Status code {response.status_code}" 788 ) 789 790 json_data = response.json() 791 792 if return_as_dict is True: 793 return json_data 794 795 final_df = pd.json_normalize(json_data) 796 final_df.rename( 797 columns={ 798 "conference": "conference_name", 799 "rating": "S&P+_rating", 800 "secondOrderWins": "second_order_wins", 801 "offense.rating": "offense_S&P+_rating", 802 "offense.success": "offense_S&P+_success", 803 "offense.explosiveness": "offense_S&P+_explosiveness", 804 "offense.rushing": "offense_S&P+_rushing", 805 "offense.passing": "offense_S&P+_passing", 806 "offense.standardDowns": "offense_S&P+_standard_downs", 807 "offense.passingDowns": "offense_S&P+_passing_downs", 808 "offense.runRate": "offense_S&P+_run_rate", 809 "offense.pace": "offense_S&P+_pace", 810 "defense.rating": "defense_S&P+_rating", 811 "defense.success": "defense_S&P+_success", 812 "defense.explosiveness": "defense_S&P+_explosiveness", 813 "defense.rushing": "defense_S&P+_rushing", 814 "defense.passing": "defense_S&P+_passing", 815 "defense.standardDowns": "defense_S&P+_standard_downs", 816 "defense.passingDowns": "defense_S&P+_passing_downs", 817 "defense.havoc.total": "defense_S&P+_havoc_total", 818 "defense.havoc.frontSeven": "defense_S&P+_havoc_front_seven", 819 "defense.havoc.db": "defense_S&P+_havoc_db", 820 "specialTeams.rating": "defense_S&P+_special_teams_rating", 821 }, 822 inplace=True, 823 ) 824 return final_df 825 826 827def get_cfbd_elo_ratings( 828 api_key: str = None, 829 api_key_dir: str = None, 830 season: int = None, 831 week: int = None, 832 season_type: str = "postseason", # "regular" or "postseason" 833 team: str = None, 834 conference: str = None, 835 return_as_dict: bool = False, 836): 837 """ 838 Allows you to get Elo ratings data for CFB teams from the CFBD API. 839 840 For more information about S&P+, consult the following webpages: 841 - https://blog.collegefootballdata.com/talking-tech-elo-ratings/ 842 - https://fivethirtyeight.com/features/introducing-nfl-elo-ratings/ 843 844 Parameters 845 ---------- 846 `api_key` (str, optional): 847 Semi-optional argument. 848 If `api_key` is null, this function will attempt to load a CFBD API key 849 from the python environment, or from a file on this computer. 850 If `api_key` is not null, 851 this function will automatically assume that the 852 inputted `api_key` is a valid CFBD API key. 853 854 `api_key_dir` (str, optional): 855 Optional argument. 856 If `api_key` is set to am empty string, this variable is ignored. 857 If `api_key_dir` is null, and `api_key` is null, 858 this function will try to find 859 a CFBD API key file in this user's home directory. 860 If `api_key_dir` is set to a string, and `api_key` is null, 861 this function will assume that `api_key_dir` is a directory, 862 and will try to find a CFBD API key file in that directory. 863 864 `season` (int, optional): 865 Optional argument. 866 Specifies the season you want S&P+ ratings data from. 867 This must be specified, otherwise this package, and by extension 868 the CFBD API, will not accept the request to get S&P+ ratings data. 869 This or `team` must be set to a valid non-null variable 870 for this to function. 871 872 `week` (int, optional): 873 Optional argument. 874 If `week` is set to a valid, non-null integer, 875 the CFBD API will return back Elo data for a team up to that week 876 in a season. 877 878 `season_type` (str, semi-optional): 879 Semi-optional argument. 880 By default, this will be set to "postseason". 881 If `season_type` is set to "regular", 882 the API will ignore postseason games 883 (like bowls and CFP games) when calculating elo. 884 If `season_type` is set to anything but "regular" or "postseason", 885 a `ValueError()` will be raised. 886 887 `team` (str, optional): 888 Optional argument. 889 Specifies the season you want S&P+ ratings data from. 890 This must be specified, otherwise this package, and by extension 891 the CFBD API, will not accept the request to get S&P+ ratings data. 892 This or `season` must be set to a valid non-null variable 893 for this to function. 894 895 `conference` (str, optional): 896 Optional argument. 897 If you only want S&P+ ratings data from games 898 involving teams a specific conference, 899 set `conference` to the abbreviation 900 of the conference you want S&P+ ratings data from. 901 902 `return_as_dict` (bool, semi-optional): 903 Semi-optional argument. 904 If you want this function to return 905 the data as a dictionary (read: JSON object), 906 instead of a pandas `DataFrame` object, 907 set `return_as_dict` to `True`. 908 909 Usage 910 ---------- 911 ``` 912 import time 913 914 from cfbd_json_py.ratings import get_cfbd_elo_ratings 915 916 917 cfbd_key = "tigersAreAwesome" # placeholder for your CFBD API Key. 918 919 if cfbd_key != "tigersAreAwesome": 920 print( 921 "Using the user's API key declared in this script " + 922 "for this example." 923 ) 924 925 # Get Elo ratings data for the 2020 CFB season. 926 print("Get Elo ratings data for the 2020 CFB season.") 927 json_data = get_cfbd_elo_ratings( 928 api_key=cfbd_key, 929 season=2020 930 ) 931 print(json_data) 932 time.sleep(5) 933 934 # Get Elo ratings data up to week 12 of the 2021 CFB season. 935 print("Get Elo ratings data up to week 12 of the 2021 CFB season.") 936 json_data = get_cfbd_elo_ratings( 937 api_key=cfbd_key, 938 season=2020, 939 week=12 940 ) 941 print(json_data) 942 time.sleep(5) 943 944 # Get Elo ratings data for the 2020 CFB season, 945 # but only for games in the regular season. 946 print( 947 "Get Elo ratings data for the 2020 CFB season, " + 948 "but only for games in the regular season." 949 ) 950 json_data = get_cfbd_elo_ratings( 951 api_key=cfbd_key, 952 season=2020, 953 season_type="regular" 954 ) 955 print(json_data) 956 time.sleep(5) 957 958 # Get historical Elo ratings data for the 959 # University of Cincinnati Football Team. 960 print( 961 "Get historical Elo ratings data for " + 962 "the University of Cincinnati Football Team." 963 ) 964 json_data = get_cfbd_elo_ratings( 965 api_key=cfbd_key, 966 team="Cincinnati" 967 ) 968 print(json_data) 969 time.sleep(5) 970 971 972 # Get Elo ratings data for teams competing in the 973 # Atlantic Coast conference (ACC) in the 2021 CFB season. 974 print( 975 "Get Elo ratings data for teams competing in " + 976 "the Atlantic Coast conference (ACC) in the 2021 CFB season." 977 ) 978 json_data = get_cfbd_elo_ratings( 979 api_key=cfbd_key, 980 season=2021, 981 conference="ACC" 982 ) 983 print(json_data) 984 time.sleep(5) 985 986 # You can also tell this function to just return the API call as 987 # a Dictionary (read: JSON) object. 988 print( 989 "You can also tell this function to just return the API call " + 990 "as a Dictionary (read: JSON) object." 991 ) 992 json_data = get_cfbd_elo_ratings( 993 api_key=cfbd_key, 994 season=2020, 995 team="Cincinnati", 996 return_as_dict=True 997 ) 998 print(json_data) 999 1000 else: 1001 # Alternatively, if the CFBD API key exists in this python environment, 1002 # or it's been set by cfbd_json_py.utls.set_cfbd_api_token(), 1003 # you could just call these functions directly, 1004 # without setting the API key in the script. 1005 print( 1006 "Using the user's API key supposedly loaded " + 1007 "into this python environment for this example." 1008 ) 1009 1010 # Get Elo ratings data for the 2020 CFB season. 1011 print("Get Elo ratings data for the 2020 CFB season.") 1012 json_data = get_cfbd_elo_ratings( 1013 season=2020 1014 ) 1015 print(json_data) 1016 time.sleep(5) 1017 1018 # Get Elo ratings data up to week 12 of the 2021 CFB season. 1019 print("Get Elo ratings data up to week 12 of the 2021 CFB season.") 1020 json_data = get_cfbd_elo_ratings( 1021 season=2020, 1022 week=12 1023 ) 1024 print(json_data) 1025 time.sleep(5) 1026 1027 # Get Elo ratings data for the 2020 CFB season, 1028 # but only for games in the regular season. 1029 print( 1030 "Get Elo ratings data for the 2020 CFB season, " + 1031 "but only for games in the regular season." 1032 ) 1033 json_data = get_cfbd_elo_ratings( 1034 season=2020, 1035 season_type="regular" 1036 ) 1037 print(json_data) 1038 time.sleep(5) 1039 1040 # Get historical Elo ratings data for the 1041 # University of Cincinnati Football Team. 1042 print( 1043 "Get historical Elo ratings data for " + 1044 "the University of Cincinnati Football Team." 1045 ) 1046 json_data = get_cfbd_elo_ratings( 1047 team="Cincinnati" 1048 ) 1049 print(json_data) 1050 time.sleep(5) 1051 1052 1053 # Get Elo ratings data for teams competing in the 1054 # Atlantic Coast conference (ACC) in the 2021 CFB season. 1055 print( 1056 "Get Elo ratings data for teams competing in " + 1057 "the Atlantic Coast conference (ACC) in the 2021 CFB season." 1058 ) 1059 json_data = get_cfbd_elo_ratings( 1060 season=2021, 1061 conference="ACC" 1062 ) 1063 print(json_data) 1064 time.sleep(5) 1065 1066 # You can also tell this function to just return the API call as 1067 # a Dictionary (read: JSON) object. 1068 print( 1069 "You can also tell this function to just return the API call " + 1070 "as a Dictionary (read: JSON) object." 1071 ) 1072 json_data = get_cfbd_elo_ratings( 1073 season=2020, 1074 team="Cincinnati", 1075 return_as_dict=True 1076 ) 1077 print(json_data) 1078 ``` 1079 Returns 1080 ---------- 1081 A pandas `DataFrame` object with Elo ratings data, 1082 or (if `return_as_dict` is set to `True`) 1083 a dictionary object with a with Elo ratings data. 1084 1085 """ 1086 now = datetime.now() 1087 url = "https://api.collegefootballdata.com/ratings/elo" 1088 # row_df = pd.DataFrame() 1089 final_df = pd.DataFrame() 1090 1091 if api_key is not None: 1092 real_api_key = api_key 1093 del api_key 1094 else: 1095 real_api_key = get_cfbd_api_token(api_key_dir=api_key_dir) 1096 1097 if real_api_key == "tigersAreAwesome": 1098 raise ValueError( 1099 "You actually need to change `cfbd_key` to your CFBD API key." 1100 ) 1101 elif "Bearer " in real_api_key: 1102 pass 1103 elif "Bearer" in real_api_key: 1104 real_api_key = real_api_key.replace("Bearer", "Bearer ") 1105 else: 1106 real_api_key = "Bearer " + real_api_key 1107 1108 # if season is None and team is None: 1109 # raise ValueError( 1110 # "`season` and/or `team` must be set to a valid, " 1111 # + "non-null value for this function to work." 1112 # ) 1113 1114 if season is not None and (season > (now.year + 1)): 1115 raise ValueError(f"`season` cannot be greater than {season}.") 1116 elif season is not None and season < 1869: 1117 raise ValueError("`season` cannot be less than 1869.") 1118 1119 # URL builder 1120 ########################################################################## 1121 1122 # Required by the API 1123 1124 if season is not None and team is not None: 1125 url += f"?year={season}&team={team}" 1126 elif season is not None: 1127 url += f"?year={season}" 1128 elif team is not None: 1129 url += f"?team={team}" 1130 1131 if week is not None: 1132 url += f"&week={week}" 1133 1134 if conference is not None: 1135 url += f"&conference={conference}" 1136 1137 if season_type is not None: 1138 url += f"&seasonType={season_type}" 1139 1140 headers = { 1141 "Authorization": f"{real_api_key}", 1142 "accept": "application/json" 1143 } 1144 response = requests.get(url, headers=headers) 1145 1146 if response.status_code == 200: 1147 pass 1148 elif response.status_code == 401: 1149 raise ConnectionRefusedError( 1150 "Could not connect. The connection was refused." + 1151 "\nHTTP Status Code 401." 1152 ) 1153 else: 1154 raise ConnectionError( 1155 f"Could not connect.\nHTTP Status code {response.status_code}" 1156 ) 1157 1158 json_data = response.json() 1159 1160 if return_as_dict is True: 1161 return json_data 1162 1163 final_df = pd.json_normalize(json_data) 1164 1165 final_df.rename(columns={"rating": "elo_rating"}, inplace=True) 1166 1167 if week is not None and len(final_df) > 0: 1168 final_df["week"] = week 1169 return final_df 1170 1171 1172def get_cfbd_fpi_ratings( 1173 api_key: str = None, 1174 api_key_dir: str = None, 1175 season: int = None, 1176 week: int = None, 1177 team: str = None, 1178 conference: str = None, 1179 return_as_dict: bool = False, 1180): 1181 """ 1182 Allows you to get Football Power Index (FPI) ratings data 1183 for CFB teams from the CFBD API. 1184 1185 For more information about FPI, consult the following webpage: 1186 https://thepowerrank.com/guide-cfb-rankings/ 1187 1188 Parameters 1189 ---------- 1190 `api_key` (str, optional): 1191 Semi-optional argument. 1192 If `api_key` is null, this function will attempt to load a CFBD API key 1193 from the python environment, or from a file on this computer. 1194 If `api_key` is not null, 1195 this function will automatically assume that the 1196 inputted `api_key` is a valid CFBD API key. 1197 1198 `api_key_dir` (str, optional): 1199 Optional argument. 1200 If `api_key` is set to am empty string, this variable is ignored. 1201 If `api_key_dir` is null, and `api_key` is null, 1202 this function will try to find 1203 a CFBD API key file in this user's home directory. 1204 If `api_key_dir` is set to a string, and `api_key` is null, 1205 this function will assume that `api_key_dir` is a directory, 1206 and will try to find a CFBD API key file in that directory. 1207 1208 `season` (int, optional): 1209 Optional argument. 1210 Specifies the season you want FPI ratings data from. 1211 This must be specified, otherwise this package, and by extension 1212 the CFBD API, will not accept the request to get FPI ratings data. 1213 This or `team` must be set to a valid non-null variable 1214 for this to function. 1215 1216 `week` (int, optional): 1217 Optional argument. 1218 If `week` is set to a valid, non-null integer, 1219 the CFBD API will return back Elo data for a team up to that week 1220 in a season. 1221 1222 `team` (str, optional): 1223 Optional argument. 1224 Specifies the season you want FPI ratings data from. 1225 This must be specified, otherwise this package, and by extension 1226 the CFBD API, will not accept the request to get FPI ratings data. 1227 This or `season` must be set to a valid non-null variable 1228 for this to function. 1229 1230 `conference` (str, optional): 1231 Optional argument. 1232 If you only want FPI ratings data from games 1233 involving teams a specific conference, 1234 set `conference` to the abbreviation 1235 of the conference you want FPI ratings data from. 1236 1237 `return_as_dict` (bool, semi-optional): 1238 Semi-optional argument. 1239 If you want this function to return 1240 the data as a dictionary (read: JSON object), 1241 instead of a pandas `DataFrame` object, 1242 set `return_as_dict` to `True`. 1243 1244 Usage 1245 ---------- 1246 ``` 1247 import time 1248 1249 from cfbd_json_py.ratings import get_cfbd_fpi_ratings 1250 1251 1252 cfbd_key = "tigersAreAwesome" # placeholder for your CFBD API Key. 1253 1254 if cfbd_key != "tigersAreAwesome": 1255 print( 1256 "Using the user's API key declared in this script " + 1257 "for this example." 1258 ) 1259 1260 # Get FPI ratings data for the 2020 CFB season. 1261 print("Get FPI ratings data for the 2020 CFB season.") 1262 json_data = get_cfbd_fpi_ratings( 1263 api_key=cfbd_key, 1264 season=2020 1265 ) 1266 print(json_data) 1267 time.sleep(5) 1268 1269 # Get FPI ratings data up to week 12 of the 2021 CFB season. 1270 print("Get FPI ratings data up to week 12 of the 2021 CFB season.") 1271 json_data = get_cfbd_fpi_ratings( 1272 api_key=cfbd_key, 1273 season=2020, 1274 week=12 1275 ) 1276 print(json_data) 1277 time.sleep(5) 1278 1279 # Get historical FPI ratings data for the 1280 # University of Cincinnati Football Team. 1281 print( 1282 "Get historical FPI ratings data for " + 1283 "the University of Cincinnati Football Team." 1284 ) 1285 json_data = get_cfbd_fpi_ratings( 1286 api_key=cfbd_key, 1287 team="Cincinnati" 1288 ) 1289 print(json_data) 1290 time.sleep(5) 1291 1292 1293 # Get FPI ratings data for teams competing in the 1294 # Atlantic Coast conference (ACC) in the 2021 CFB season. 1295 print( 1296 "Get FPI ratings data for teams competing in the " + 1297 "Atlantic Coast conference (ACC) in the 2021 CFB season." 1298 ) 1299 json_data = get_cfbd_fpi_ratings( 1300 api_key=cfbd_key, 1301 season=2021, 1302 conference="ACC" 1303 ) 1304 print(json_data) 1305 time.sleep(5) 1306 1307 # You can also tell this function to just return the API call as 1308 # a Dictionary (read: JSON) object. 1309 print( 1310 "You can also tell this function to just return the API call " + 1311 "as a Dictionary (read: JSON) object." 1312 ) 1313 json_data = get_cfbd_fpi_ratings( 1314 api_key=cfbd_key, 1315 season=2020, 1316 team="Cincinnati", 1317 return_as_dict=True 1318 ) 1319 print(json_data) 1320 1321 else: 1322 # Alternatively, if the CFBD API key exists in this python environment, 1323 # or it's been set by cfbd_json_py.utls.set_cfbd_api_token(), 1324 # you could just call these functions directly, 1325 # without setting the API key in the script. 1326 print( 1327 "Using the user's API key supposedly loaded " + 1328 "into this python environment for this example." 1329 ) 1330 1331 # Get FPI ratings data for the 2020 CFB season. 1332 print("Get FPI ratings data for the 2020 CFB season.") 1333 json_data = get_cfbd_fpi_ratings( 1334 season=2020 1335 ) 1336 print(json_data) 1337 time.sleep(5) 1338 1339 # Get FPI ratings data up to week 12 of the 2021 CFB season. 1340 print("Get FPI ratings data up to week 12 of the 2021 CFB season.") 1341 json_data = get_cfbd_fpi_ratings( 1342 season=2020, 1343 week=12 1344 ) 1345 print(json_data) 1346 time.sleep(5) 1347 1348 1349 1350 # Get historical FPI ratings data for the 1351 # University of Cincinnati Football Team. 1352 print( 1353 "Get historical FPI ratings data for " + 1354 "the University of Cincinnati Football Team." 1355 ) 1356 json_data = get_cfbd_fpi_ratings( 1357 team="Cincinnati" 1358 ) 1359 print(json_data) 1360 time.sleep(5) 1361 1362 1363 # Get FPI ratings data for teams competing in the 1364 # Atlantic Coast conference (ACC) in the 2021 CFB season. 1365 print( 1366 "Get FPI ratings data for teams competing in the " + 1367 "Atlantic Coast conference (ACC) in the 2021 CFB season." 1368 ) 1369 json_data = get_cfbd_fpi_ratings( 1370 season=2021, 1371 conference="ACC" 1372 ) 1373 print(json_data) 1374 time.sleep(5) 1375 1376 # You can also tell this function to just return the API call as 1377 # a Dictionary (read: JSON) object. 1378 print( 1379 "You can also tell this function to just return the API call " + 1380 "as a Dictionary (read: JSON) object." 1381 ) 1382 json_data = get_cfbd_fpi_ratings( 1383 season=2020, 1384 team="Cincinnati", 1385 return_as_dict=True 1386 ) 1387 print(json_data) 1388 1389 1390 ``` 1391 Returns 1392 ---------- 1393 A pandas `DataFrame` object with FPI ratings data, 1394 or (if `return_as_dict` is set to `True`) 1395 a dictionary object with a with FPI ratings data. 1396 1397 """ 1398 now = datetime.now() 1399 url = "https://api.collegefootballdata.com/ratings/fpi" 1400 # row_df = pd.DataFrame() 1401 final_df = pd.DataFrame() 1402 1403 if api_key is not None: 1404 real_api_key = api_key 1405 del api_key 1406 else: 1407 real_api_key = get_cfbd_api_token(api_key_dir=api_key_dir) 1408 1409 if real_api_key == "tigersAreAwesome": 1410 raise ValueError( 1411 "You actually need to change `cfbd_key` to your CFBD API key." 1412 ) 1413 elif "Bearer " in real_api_key: 1414 pass 1415 elif "Bearer" in real_api_key: 1416 real_api_key = real_api_key.replace("Bearer", "Bearer ") 1417 else: 1418 real_api_key = "Bearer " + real_api_key 1419 1420 if season is None and team is None: 1421 raise ValueError( 1422 "`season` and/or `team` must be set to a valid, " 1423 + "non-null value for this function to work." 1424 ) 1425 1426 if season is not None and (season > (now.year + 1)): 1427 raise ValueError(f"`season` cannot be greater than {season}.") 1428 elif season is not None and season < 1869: 1429 raise ValueError("`season` cannot be less than 1869.") 1430 1431 # URL builder 1432 ########################################################################## 1433 1434 # Required by the API 1435 1436 if season is not None and team is not None: 1437 url += f"?year={season}&team={team}" 1438 elif season is not None: 1439 url += f"?year={season}" 1440 elif team is not None: 1441 url += f"?team={team}" 1442 1443 if week is not None: 1444 url += f"&week={week}" 1445 1446 if conference is not None: 1447 url += f"&conference={conference}" 1448 1449 headers = { 1450 "Authorization": f"{real_api_key}", 1451 "accept": "application/json" 1452 } 1453 response = requests.get(url, headers=headers) 1454 1455 if response.status_code == 200: 1456 pass 1457 elif response.status_code == 401: 1458 raise ConnectionRefusedError( 1459 "Could not connect. The connection was refused." + 1460 "\nHTTP Status Code 401." 1461 ) 1462 else: 1463 raise ConnectionError( 1464 f"Could not connect.\nHTTP Status code {response.status_code}" 1465 ) 1466 1467 json_data = response.json() 1468 1469 if return_as_dict is True: 1470 return json_data 1471 1472 final_df = pd.json_normalize(json_data) 1473 1474 final_df.rename( 1475 columns={ 1476 "year": "season", 1477 "team": "team_name", 1478 "conference": "conference_name", 1479 "resumeRanks.strengthOfRecord": "resume_strength_of_record", 1480 "resumeRanks.fpi": "fpi_rank", 1481 "resumeRanks.averageWinProbability": "resume_avg_win_probability", 1482 "resumeRanks.strengthOfSchedule": "resume_strength_of_schedule", 1483 "resumeRanks.remainingStrengthOfSchedule": 1484 "resume_remaining_strength_of_schedule", 1485 "resumeRanks.gameControl": "resume_game_control", 1486 "efficiencies.overall": "efficiency_overall", 1487 "efficiencies.offense": "efficiency_offense", 1488 "efficiencies.defense": "efficiency_defense", 1489 "efficiencies.specialTeams": "efficiency_special_teams", 1490 }, 1491 inplace=True, 1492 ) 1493 return final_df
19def get_cfbd_sp_plus_ratings( 20 api_key: str = None, 21 api_key_dir: str = None, 22 season: int = None, 23 team: int = None, 24 # Either `year` or `team` have to be not null for this function to work. 25 return_as_dict: bool = False, 26): 27 """ 28 Allows you to get Success rate and equivalent Points per play (S&P+) 29 ratings data from the CFBD API. 30 31 For more information about S&P+, consult the following webpages: 32 - https://www.sbnation.com/college-football/ 33 2017/10/13/16457830/college-football-advanced-stats-analytics-rankings 34 - https://collegefootballdata.com/sp/trends 35 36 Parameters 37 ---------- 38 `api_key` (str, optional): 39 Semi-optional argument. 40 If `api_key` is null, this function will attempt to load a CFBD API key 41 from the python environment, or from a file on this computer. 42 If `api_key` is not null, 43 this function will automatically assume that the 44 inputted `api_key` is a valid CFBD API key. 45 46 `api_key_dir` (str, optional): 47 Optional argument. 48 If `api_key` is set to am empty string, this variable is ignored. 49 If `api_key_dir` is null, and `api_key` is null, 50 this function will try to find 51 a CFBD API key file in this user's home directory. 52 If `api_key_dir` is set to a string, and `api_key` is null, 53 this function will assume that `api_key_dir` is a directory, 54 and will try to find a CFBD API key file in that directory. 55 56 `season` (int, semi-mandatory): 57 Semi-required argument. 58 Specifies the season you want S&P+ ratings data from. 59 This must be specified, otherwise this package, and by extension 60 the CFBD API, will not accept the request to get S&P+ ratings data. 61 This or `team` must be set to a valid 62 non-null variable for this to function. 63 64 `team` (str, semi-mandatory): 65 Semi-required argument. 66 Specifies the season you want S&P+ ratings data from. 67 This must be specified, otherwise this package, and by extension 68 the CFBD API, will not accept the request to get S&P+ ratings data. 69 This or `season` must be set to a valid non-null variable 70 for this to function. 71 72 `return_as_dict` (bool, semi-optional): 73 Semi-optional argument. 74 If you want this function to return 75 the data as a dictionary (read: JSON object), 76 instead of a pandas `DataFrame` object, 77 set `return_as_dict` to `True`. 78 79 Usage 80 ---------- 81 ``` 82 import time 83 84 from cfbd_json_py.ratings import get_cfbd_sp_plus_ratings 85 86 87 cfbd_key = "tigersAreAwesome" # placeholder for your CFBD API Key. 88 89 if cfbd_key != "tigersAreAwesome": 90 print( 91 "Using the user's API key declared in this script " + 92 "for this example." 93 ) 94 95 # Get S&P+ ratings data for the 2020 CFB season. 96 print("Get S&P+ ratings data for the 2020 CFB season.") 97 json_data = get_cfbd_sp_plus_ratings( 98 api_key=cfbd_key, 99 season=2020 100 ) 101 print(json_data) 102 time.sleep(5) 103 104 # Get historical S&P+ ratings data for the 105 # University of Cincinnati Bearcats Football Team. 106 print( 107 "Get historical S&P+ ratings data for " + 108 "the University of Cincinnati Bearcats Football Team." 109 ) 110 json_data = get_cfbd_sp_plus_ratings( 111 api_key=cfbd_key, 112 team="Cincinnati" 113 ) 114 print(json_data) 115 time.sleep(5) 116 117 # Get S&P+ ratings data for the 2019 Ohio State Buckeyes Football Team. 118 print( 119 "Get S&P+ ratings data for " + 120 "the 2019 Ohio State Buckeyes Football Team." 121 ) 122 json_data = get_cfbd_sp_plus_ratings( 123 api_key=cfbd_key, 124 season=2020, 125 team="Ohio State" 126 ) 127 print(json_data) 128 time.sleep(5) 129 130 # You can also tell this function to just return the API call as 131 # a Dictionary (read: JSON) object. 132 print( 133 "You can also tell this function to just return the API call " + 134 "as a Dictionary (read: JSON) object." 135 ) 136 json_data = get_cfbd_sp_plus_ratings( 137 api_key=cfbd_key, 138 season=2020, 139 team="Ohio State", 140 return_as_dict=True 141 ) 142 print(json_data) 143 144 else: 145 # Alternatively, if the CFBD API key exists in this python environment, 146 # or it's been set by cfbd_json_py.utls.set_cfbd_api_token(), 147 # you could just call these functions directly, 148 # without setting the API key in the script. 149 print( 150 "Using the user's API key supposedly loaded " + 151 "into this python environment for this example." 152 ) 153 154 # Get S&P+ ratings data for the 2020 CFB season. 155 print("Get S&P+ ratings data for the 2020 CFB season.") 156 json_data = get_cfbd_sp_plus_ratings( 157 season=2020 158 ) 159 print(json_data) 160 time.sleep(5) 161 162 # Get historical S&P+ ratings data for the 163 # University of Cincinnati Bearcats Football Team. 164 print( 165 "Get historical S&P+ ratings data for " + 166 "the University of Cincinnati Bearcats Football Team." 167 ) 168 json_data = get_cfbd_sp_plus_ratings( 169 team="Cincinnati" 170 ) 171 print(json_data) 172 time.sleep(5) 173 174 # Get S&P+ ratings data for the 2019 Ohio State Buckeyes Football Team. 175 print( 176 "Get S&P+ ratings data for " + 177 "the 2019 Ohio State Buckeyes Football Team." 178 ) 179 json_data = get_cfbd_sp_plus_ratings( 180 season=2020, 181 team="Ohio State" 182 ) 183 print(json_data) 184 time.sleep(5) 185 186 # You can also tell this function to just return the API call as 187 # a Dictionary (read: JSON) object. 188 print( 189 "You can also tell this function to just return the API call " + 190 "as a Dictionary (read: JSON) object." 191 ) 192 json_data = get_cfbd_sp_plus_ratings( 193 season=2020, 194 team="Ohio State", 195 return_as_dict=True 196 ) 197 print(json_data) 198 ``` 199 Returns 200 ---------- 201 A pandas `DataFrame` object with S&P+ ratings data, 202 or (if `return_as_dict` is set to `True`) 203 a dictionary object with a with S&P+ ratings data. 204 205 """ 206 warnings.simplefilter(action="ignore", category=FutureWarning) 207 208 now = datetime.now() 209 url = "https://api.collegefootballdata.com/ratings/sp" 210 final_df = pd.DataFrame() 211 212 if api_key is not None: 213 real_api_key = api_key 214 del api_key 215 else: 216 real_api_key = get_cfbd_api_token(api_key_dir=api_key_dir) 217 218 if real_api_key == "tigersAreAwesome": 219 raise ValueError( 220 "You actually need to change `cfbd_key` to your CFBD API key." 221 ) 222 elif "Bearer " in real_api_key: 223 pass 224 elif "Bearer" in real_api_key: 225 real_api_key = real_api_key.replace("Bearer", "Bearer ") 226 else: 227 real_api_key = "Bearer " + real_api_key 228 229 if season is None and team is None: 230 raise ValueError( 231 "`season` and/or `team` must be set to a valid, " 232 + "non-null value for this function to work." 233 ) 234 235 if season is not None and (season > (now.year + 1)): 236 raise ValueError(f"`season` cannot be greater than {season}.") 237 elif season is not None and season < 1869: 238 raise ValueError("`season` cannot be less than 1869.") 239 240 # URL builder 241 ########################################################################## 242 243 # Required by the API 244 245 if season is not None and team is not None: 246 url += f"?year={season}&team={team}" 247 elif season is not None: 248 url += f"?year={season}" 249 elif team is not None: 250 url += f"?team={team}" 251 252 headers = { 253 "Authorization": f"{real_api_key}", 254 "accept": "application/json" 255 } 256 response = requests.get(url, headers=headers) 257 258 if response.status_code == 200: 259 pass 260 elif response.status_code == 401: 261 raise ConnectionRefusedError( 262 "Could not connect. The connection was refused." + 263 "\nHTTP Status Code 401." 264 ) 265 else: 266 raise ConnectionError( 267 f"Could not connect.\nHTTP Status code {response.status_code}" 268 ) 269 270 json_data = response.json() 271 272 if return_as_dict is True: 273 return json_data 274 275 final_df = pd.json_normalize(json_data) 276 final_df.rename( 277 columns={ 278 "team": "team_name", 279 "conference": "conference_name", 280 "rating": "S&P+_rating", 281 "secondOrderWins": "second_order_wins", 282 "offense.rating": "offense_S&P+_rating", 283 "offense.success": "offense_S&P+_success", 284 "offense.explosiveness": "offense_S&P+_explosiveness", 285 "offense.rushing": "offense_S&P+_rushing", 286 "offense.passing": "offense_S&P+_passing", 287 "offense.standardDowns": "offense_S&P+_standard_downs", 288 "offense.passingDowns": "offense_S&P+_passing_downs", 289 "offense.runRate": "offense_S&P+_run_rate", 290 "offense.pace": "offense_S&P+_pace", 291 "defense.rating": "defense_S&P+_rating", 292 "defense.success": "defense_S&P+_success", 293 "defense.explosiveness": "defense_S&P+_explosiveness", 294 "defense.rushing": "defense_S&P+_rushing", 295 "defense.passing": "defense_S&P+_passing", 296 "defense.standardDowns": "defense_S&P+_standard_downs", 297 "defense.passingDowns": "defense_S&P+_passing_downs", 298 "defense.havoc.total": "defense_S&P+_havoc_total", 299 "defense.havoc.frontSeven": "defense_S&P+_havoc_front_seven", 300 "defense.havoc.db": "defense_S&P+_havoc_db", 301 "specialTeams.rating": "defense_S&P+_special_teams_rating", 302 }, 303 inplace=True, 304 ) 305 # print(final_df.columns) 306 307 return final_df
Allows you to get Success rate and equivalent Points per play (S&P+) ratings data from the CFBD API.
For more information about S&P+, consult the following webpages:
- https://www.sbnation.com/college-football/ 2017/10/13/16457830/college-football-advanced-stats-analytics-rankings
- https://collegefootballdata.com/sp/trends
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, semi-mandatory):
Semi-required argument.
Specifies the season you want S&P+ ratings data from.
This must be specified, otherwise this package, and by extension
the CFBD API, will not accept the request to get S&P+ ratings data.
This or team
must be set to a valid
non-null variable for this to function.
team
(str, semi-mandatory):
Semi-required argument.
Specifies the season you want S&P+ ratings data from.
This must be specified, otherwise this package, and by extension
the CFBD API, will not accept the request to get S&P+ ratings data.
This or season
must be set to a valid non-null variable
for this to 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.ratings import get_cfbd_sp_plus_ratings
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 S&P+ ratings data for the 2020 CFB season.
print("Get S&P+ ratings data for the 2020 CFB season.")
json_data = get_cfbd_sp_plus_ratings(
api_key=cfbd_key,
season=2020
)
print(json_data)
time.sleep(5)
# Get historical S&P+ ratings data for the
# University of Cincinnati Bearcats Football Team.
print(
"Get historical S&P+ ratings data for " +
"the University of Cincinnati Bearcats Football Team."
)
json_data = get_cfbd_sp_plus_ratings(
api_key=cfbd_key,
team="Cincinnati"
)
print(json_data)
time.sleep(5)
# Get S&P+ ratings data for the 2019 Ohio State Buckeyes Football Team.
print(
"Get S&P+ ratings data for " +
"the 2019 Ohio State Buckeyes Football Team."
)
json_data = get_cfbd_sp_plus_ratings(
api_key=cfbd_key,
season=2020,
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_sp_plus_ratings(
api_key=cfbd_key,
season=2020,
team="Ohio State",
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 S&P+ ratings data for the 2020 CFB season.
print("Get S&P+ ratings data for the 2020 CFB season.")
json_data = get_cfbd_sp_plus_ratings(
season=2020
)
print(json_data)
time.sleep(5)
# Get historical S&P+ ratings data for the
# University of Cincinnati Bearcats Football Team.
print(
"Get historical S&P+ ratings data for " +
"the University of Cincinnati Bearcats Football Team."
)
json_data = get_cfbd_sp_plus_ratings(
team="Cincinnati"
)
print(json_data)
time.sleep(5)
# Get S&P+ ratings data for the 2019 Ohio State Buckeyes Football Team.
print(
"Get S&P+ ratings data for " +
"the 2019 Ohio State Buckeyes Football Team."
)
json_data = get_cfbd_sp_plus_ratings(
season=2020,
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_sp_plus_ratings(
season=2020,
team="Ohio State",
return_as_dict=True
)
print(json_data)
Returns
A pandas DataFrame
object with S&P+ ratings data,
or (if return_as_dict
is set to True
)
a dictionary object with a with S&P+ ratings data.
310def get_cfbd_srs_ratings( 311 api_key: str = None, 312 api_key_dir: str = None, 313 season: int = None, 314 team: int = None, 315 # Either `year` or `team` have to be not null for this function to work. 316 conference: str = None, 317 return_as_dict: bool = False, 318): 319 """ 320 Allows you to get Simple Rating System (SRS) data from the CFBD API. 321 322 For more information about S&P+, consult the following webpages: 323 - https://www.sports-reference.com/blog/2015/03/srs-calculation-details/ 324 - https://blog.collegefootballdata.com/talking-tech-bu/ 325 326 Parameters 327 ---------- 328 `api_key` (str, optional): 329 Semi-optional argument. 330 If `api_key` is null, this function will attempt to load a CFBD API key 331 from the python environment, or from a file on this computer. 332 If `api_key` is not null, 333 this function will automatically assume that the 334 inputted `api_key` is a valid CFBD API key. 335 336 `api_key_dir` (str, optional): 337 Optional argument. 338 If `api_key` is set to am empty string, this variable is ignored. 339 If `api_key_dir` is null, and `api_key` is null, 340 this function will try to find 341 a CFBD API key file in this user's home directory. 342 If `api_key_dir` is set to a string, and `api_key` is null, 343 this function will assume that `api_key_dir` is a directory, 344 and will try to find a CFBD API key file in that directory. 345 346 `season` (int, semi-mandatory): 347 Semi-required argument. 348 Specifies the season you want SRS ratings data from. 349 This must be specified, otherwise this package, and by extension 350 the CFBD API, will not accept the request to get SRS ratings data. 351 This or `team` must be set to a valid non-null variable 352 for this to function. 353 354 `team` (str, semi-mandatory): 355 Semi-required argument. 356 Specifies the season you want SRS ratings data from. 357 This must be specified, otherwise this package, and by extension 358 the CFBD API, will not accept the request to get SRS ratings data. 359 This or `season` must be set to a valid non-null variable 360 for this to function. 361 362 `conference` (str, optional): 363 Optional argument. 364 If you only want game information from games 365 involving teams a specific conference, 366 set `conference` to the abbreviation 367 of the conference you want game information from. 368 369 `return_as_dict` (bool, semi-optional): 370 Semi-optional argument. 371 If you want this function to return 372 the data as a dictionary (read: JSON object), 373 instead of a pandas `DataFrame` object, 374 set `return_as_dict` to `True`. 375 376 Usage 377 ---------- 378 ``` 379 import time 380 381 from cfbd_json_py.ratings import get_cfbd_srs_ratings 382 383 384 cfbd_key = "tigersAreAwesome" # placeholder for your CFBD API Key. 385 386 if cfbd_key != "tigersAreAwesome": 387 print( 388 "Using the user's API key declared in this script " + 389 "for this example." 390 ) 391 392 # Get SRS ratings data for the 2020 CFB season. 393 print("Get SRS ratings data for the 2020 CFB season.") 394 json_data = get_cfbd_srs_ratings( 395 api_key=cfbd_key, 396 season=2020 397 ) 398 print(json_data) 399 time.sleep(5) 400 401 # Get historical SRS ratings data for the 402 # University of Cincinnati Bearcats Football Team. 403 print( 404 "Get historical SRS ratings data for " + 405 "the University of Cincinnati Bearcats Football Team." 406 ) 407 json_data = get_cfbd_srs_ratings( 408 api_key=cfbd_key, 409 team="Cincinnati" 410 ) 411 print(json_data) 412 time.sleep(5) 413 414 # Get SRS ratings data for the 2019 Ohio State Buckeyes Football Team. 415 print( 416 "Get SRS ratings data for " + 417 "the 2019 Ohio State Buckeyes Football Team." 418 ) 419 json_data = get_cfbd_srs_ratings( 420 api_key=cfbd_key, 421 season=2020, 422 team="Ohio State" 423 ) 424 print(json_data) 425 time.sleep(5) 426 427 # You can also tell this function to just return the API call as 428 # a Dictionary (read: JSON) object. 429 print( 430 "You can also tell this function to just return the API call " + 431 "as a Dictionary (read: JSON) object." 432 ) 433 json_data = get_cfbd_srs_ratings( 434 api_key=cfbd_key, 435 season=2020, 436 team="Ohio State", 437 return_as_dict=True 438 ) 439 print(json_data) 440 441 else: 442 # Alternatively, if the CFBD API key exists in this python environment, 443 # or it's been set by cfbd_json_py.utls.set_cfbd_api_token(), 444 # you could just call these functions directly, 445 # without setting the API key in the script. 446 print( 447 "Using the user's API key supposedly loaded " + 448 "into this python environment for this example." 449 ) 450 451 # Get SRS ratings data for the 2020 CFB season. 452 print("Get SRS ratings data for the 2020 CFB season.") 453 json_data = get_cfbd_srs_ratings( 454 season=2020 455 ) 456 print(json_data) 457 time.sleep(5) 458 459 # Get historical SRS ratings data for the 460 # University of Cincinnati Bearcats Football Team. 461 print( 462 "Get historical SRS ratings data for " + 463 "the University of Cincinnati Bearcats Football Team." 464 ) 465 json_data = get_cfbd_srs_ratings( 466 team="Cincinnati" 467 ) 468 print(json_data) 469 time.sleep(5) 470 471 # Get SRS ratings data for the 2019 Ohio State Buckeyes Football Team. 472 print( 473 "Get SRS ratings data for " + 474 "the 2019 Ohio State Buckeyes Football Team." 475 ) 476 json_data = get_cfbd_srs_ratings( 477 season=2020, 478 team="Ohio State" 479 ) 480 print(json_data) 481 time.sleep(5) 482 483 # You can also tell this function to just return the API call as 484 # a Dictionary (read: JSON) object. 485 print( 486 "You can also tell this function to just return the API call " + 487 "as a Dictionary (read: JSON) object." 488 ) 489 json_data = get_cfbd_srs_ratings( 490 season=2020, 491 team="Ohio State", 492 return_as_dict=True 493 ) 494 print(json_data) 495 ``` 496 Returns 497 ---------- 498 A pandas `DataFrame` object with team season stats data, 499 or (if `return_as_dict` is set to `True`) 500 a dictionary object with a with team season stats data. 501 502 """ 503 now = datetime.now() 504 url = "https://api.collegefootballdata.com/ratings/srs" 505 # row_df = pd.DataFrame() 506 final_df = pd.DataFrame() 507 508 if api_key is not None: 509 real_api_key = api_key 510 del api_key 511 else: 512 real_api_key = get_cfbd_api_token(api_key_dir=api_key_dir) 513 514 if real_api_key == "tigersAreAwesome": 515 raise ValueError( 516 "You actually need to change `cfbd_key` to your CFBD API key." 517 ) 518 elif "Bearer " in real_api_key: 519 pass 520 elif "Bearer" in real_api_key: 521 real_api_key = real_api_key.replace("Bearer", "Bearer ") 522 else: 523 real_api_key = "Bearer " + real_api_key 524 525 if season is None and team is None: 526 raise ValueError( 527 "`season` and/or `team` must be set to a valid, " 528 + "non-null value for this function to work." 529 ) 530 531 if season is not None and (season > (now.year + 1)): 532 raise ValueError(f"`season` cannot be greater than {season}.") 533 elif season is not None and season < 1869: 534 raise ValueError("`season` cannot be less than 1869.") 535 536 # URL builder 537 ########################################################################## 538 539 # Required by the API 540 541 if season is not None and team is not None: 542 url += f"?year={season}&team={team}" 543 elif season is not None: 544 url += f"?year={season}" 545 elif team is not None: 546 url += f"?team={team}" 547 548 if conference is not None: 549 url += f"&conference={conference}" 550 551 headers = { 552 "Authorization": f"{real_api_key}", 553 "accept": "application/json" 554 } 555 response = requests.get(url, headers=headers) 556 557 if response.status_code == 200: 558 pass 559 elif response.status_code == 401: 560 raise ConnectionRefusedError( 561 "Could not connect. The connection was refused." + 562 "\nHTTP Status Code 401." 563 ) 564 else: 565 raise ConnectionError( 566 f"Could not connect.\nHTTP Status code {response.status_code}" 567 ) 568 569 json_data = response.json() 570 571 if return_as_dict is True: 572 return json_data 573 574 final_df = pd.json_normalize(json_data) 575 576 final_df.rename(columns={"rating": "srs_rating"}, inplace=True) 577 return final_df
Allows you to get Simple Rating System (SRS) data from the CFBD API.
For more information about S&P+, consult the following webpages:
- https://www.sports-reference.com/blog/2015/03/srs-calculation-details/
- https://blog.collegefootballdata.com/talking-tech-bu/
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, semi-mandatory):
Semi-required argument.
Specifies the season you want SRS ratings data from.
This must be specified, otherwise this package, and by extension
the CFBD API, will not accept the request to get SRS ratings data.
This or team
must be set to a valid non-null variable
for this to function.
team
(str, semi-mandatory):
Semi-required argument.
Specifies the season you want SRS ratings data from.
This must be specified, otherwise this package, and by extension
the CFBD API, will not accept the request to get SRS ratings data.
This or season
must be set to a valid non-null variable
for this to function.
conference
(str, optional):
Optional argument.
If you only want game information from games
involving teams a specific conference,
set conference
to the abbreviation
of the conference you want game information from.
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.ratings import get_cfbd_srs_ratings
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 SRS ratings data for the 2020 CFB season.
print("Get SRS ratings data for the 2020 CFB season.")
json_data = get_cfbd_srs_ratings(
api_key=cfbd_key,
season=2020
)
print(json_data)
time.sleep(5)
# Get historical SRS ratings data for the
# University of Cincinnati Bearcats Football Team.
print(
"Get historical SRS ratings data for " +
"the University of Cincinnati Bearcats Football Team."
)
json_data = get_cfbd_srs_ratings(
api_key=cfbd_key,
team="Cincinnati"
)
print(json_data)
time.sleep(5)
# Get SRS ratings data for the 2019 Ohio State Buckeyes Football Team.
print(
"Get SRS ratings data for " +
"the 2019 Ohio State Buckeyes Football Team."
)
json_data = get_cfbd_srs_ratings(
api_key=cfbd_key,
season=2020,
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_srs_ratings(
api_key=cfbd_key,
season=2020,
team="Ohio State",
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 SRS ratings data for the 2020 CFB season.
print("Get SRS ratings data for the 2020 CFB season.")
json_data = get_cfbd_srs_ratings(
season=2020
)
print(json_data)
time.sleep(5)
# Get historical SRS ratings data for the
# University of Cincinnati Bearcats Football Team.
print(
"Get historical SRS ratings data for " +
"the University of Cincinnati Bearcats Football Team."
)
json_data = get_cfbd_srs_ratings(
team="Cincinnati"
)
print(json_data)
time.sleep(5)
# Get SRS ratings data for the 2019 Ohio State Buckeyes Football Team.
print(
"Get SRS ratings data for " +
"the 2019 Ohio State Buckeyes Football Team."
)
json_data = get_cfbd_srs_ratings(
season=2020,
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_srs_ratings(
season=2020,
team="Ohio State",
return_as_dict=True
)
print(json_data)
Returns
A pandas DataFrame
object with team season stats data,
or (if return_as_dict
is set to True
)
a dictionary object with a with team season stats data.
580def get_cfbd_sp_plus_conference_ratings( 581 api_key: str = None, 582 api_key_dir: str = None, 583 season: int = None, 584 conference: str = None, 585 return_as_dict: bool = False, 586): 587 """ 588 Allows you to get Success rate and equivalent Points per play (S&P+) 589 ratings data from the CFBD API. 590 591 For more information about S&P+, consult the following webpage: 592 https://collegefootballdata.com/sp/trends 593 594 Parameters 595 ---------- 596 `api_key` (str, optional): 597 Semi-optional argument. 598 If `api_key` is null, this function will attempt to load a CFBD API key 599 from the python environment, or from a file on this computer. 600 If `api_key` is not null, 601 this function will automatically assume that the 602 inputted `api_key` is a valid CFBD API key. 603 604 `api_key_dir` (str, optional): 605 Optional argument. 606 If `api_key` is set to am empty string, this variable is ignored. 607 If `api_key_dir` is null, and `api_key` is null, 608 this function will try to find 609 a CFBD API key file in this user's home directory. 610 If `api_key_dir` is set to a string, and `api_key` is null, 611 this function will assume that `api_key_dir` is a directory, 612 and will try to find a CFBD API key file in that directory. 613 614 `season` (int, optional): 615 Optional argument. 616 Specifies the season you want S&P+ ratings data from. 617 This must be specified, otherwise this package, and by extension 618 the CFBD API, will not accept the request to get S&P+ ratings data. 619 This or `team` must be set to a valid non-null variable 620 for this to function. 621 622 `team` (str, optional): 623 Optional argument. 624 Specifies the season you want S&P+ ratings data from. 625 This must be specified, otherwise this package, and by extension 626 the CFBD API, will not accept the request to get S&P+ ratings data. 627 This or `season` must be set to a valid non-null variable 628 for this to function. 629 630 `conference` (str, optional): 631 Optional argument. 632 If you only want S&P+ ratings data from games 633 involving teams a specific conference, 634 set `conference` to the abbreviation 635 of the conference you want S&P+ ratings data from. 636 637 `return_as_dict` (bool, semi-optional): 638 Semi-optional argument. 639 If you want this function to return 640 the data as a dictionary (read: JSON object), 641 instead of a pandas `DataFrame` object, 642 set `return_as_dict` to `True`. 643 644 Usage 645 ---------- 646 ``` 647 import time 648 649 from cfbd_json_py.ratings import get_cfbd_sp_plus_conference_ratings 650 651 652 cfbd_key = "tigersAreAwesome" # placeholder for your CFBD API Key. 653 654 if cfbd_key != "tigersAreAwesome": 655 print( 656 "Using the user's API key declared in this script " + 657 "for this example." 658 ) 659 660 # Get S&P+ ratings data for the 2020 CFB season. 661 print("Get S&P+ ratings data for the 2020 CFB season.") 662 json_data = get_cfbd_sp_plus_conference_ratings( 663 api_key=cfbd_key, 664 season=2020 665 ) 666 print(json_data) 667 time.sleep(5) 668 669 # You can also tell this function to just return the API call as 670 # a Dictionary (read: JSON) object. 671 print( 672 "You can also tell this function to just return the API call " + 673 "as a Dictionary (read: JSON) object." 674 ) 675 json_data = get_cfbd_sp_plus_conference_ratings( 676 api_key=cfbd_key, 677 season=2020, 678 return_as_dict=True 679 ) 680 print(json_data) 681 682 else: 683 # Alternatively, if the CFBD API key exists in this python environment, 684 # or it's been set by cfbd_json_py.utls.set_cfbd_api_token(), 685 # you could just call these functions directly, 686 # without setting the API key in the script. 687 print( 688 "Using the user's API key supposedly loaded " + 689 "into this python environment for this example." 690 ) 691 692 # Get S&P+ ratings data for the 2020 CFB season. 693 print("Get S&P+ ratings data for the 2020 CFB season.") 694 json_data = get_cfbd_sp_plus_conference_ratings( 695 season=2020 696 ) 697 print(json_data) 698 time.sleep(5) 699 700 # You can also tell this function to just return the API call as 701 # a Dictionary (read: JSON) object. 702 print( 703 "You can also tell this function to just return the API call " + 704 "as a Dictionary (read: JSON) object." 705 ) 706 json_data = get_cfbd_sp_plus_conference_ratings( 707 season=2020, 708 return_as_dict=True 709 ) 710 print(json_data) 711 ``` 712 Returns 713 ---------- 714 A pandas `DataFrame` object with S&P+ ratings data, 715 or (if `return_as_dict` is set to `True`) 716 a dictionary object with a with S&P+ ratings data. 717 """ 718 # warnings.simplefilter(action="ignore", category=FutureWarning) 719 720 now = datetime.now() 721 url = "https://api.collegefootballdata.com/ratings/sp/conferences" 722 # row_df = pd.DataFrame() 723 final_df = pd.DataFrame() 724 725 if api_key is not None: 726 real_api_key = api_key 727 del api_key 728 else: 729 real_api_key = get_cfbd_api_token(api_key_dir=api_key_dir) 730 731 if real_api_key == "tigersAreAwesome": 732 raise ValueError( 733 "You actually need to change `cfbd_key` to your CFBD API key." 734 ) 735 elif "Bearer " in real_api_key: 736 pass 737 elif "Bearer" in real_api_key: 738 real_api_key = real_api_key.replace("Bearer", "Bearer ") 739 else: 740 real_api_key = "Bearer " + real_api_key 741 742 # if season is None and team is None: 743 # raise ValueError( 744 # "`season` and/or `team` must be set to a valid, " 745 # + "non-null value for this function to work." 746 # ) 747 748 if season is not None and (season > (now.year + 1)): 749 raise ValueError(f"`season` cannot be greater than {season}.") 750 elif season is not None and season < 1869: 751 raise ValueError("`season` cannot be less than 1869.") 752 753 # URL builder 754 ########################################################################## 755 756 # Required by the API 757 url_elements = 0 758 759 if season is not None and url_elements == 0: 760 url += f"?year={season}" 761 url_elements += 1 762 elif season is not None: 763 url += f"&year={season}" 764 url_elements += 1 765 766 if conference is not None and url_elements == 0: 767 url += f"?conference={conference}" 768 url_elements += 1 769 elif conference is not None: 770 url += f"&conference={conference}" 771 url_elements += 1 772 773 headers = { 774 "Authorization": f"{real_api_key}", 775 "accept": "application/json" 776 } 777 response = requests.get(url, headers=headers) 778 779 if response.status_code == 200: 780 pass 781 elif response.status_code == 401: 782 raise ConnectionRefusedError( 783 "Could not connect. The connection was refused." + 784 "\nHTTP Status Code 401." 785 ) 786 else: 787 raise ConnectionError( 788 f"Could not connect.\nHTTP Status code {response.status_code}" 789 ) 790 791 json_data = response.json() 792 793 if return_as_dict is True: 794 return json_data 795 796 final_df = pd.json_normalize(json_data) 797 final_df.rename( 798 columns={ 799 "conference": "conference_name", 800 "rating": "S&P+_rating", 801 "secondOrderWins": "second_order_wins", 802 "offense.rating": "offense_S&P+_rating", 803 "offense.success": "offense_S&P+_success", 804 "offense.explosiveness": "offense_S&P+_explosiveness", 805 "offense.rushing": "offense_S&P+_rushing", 806 "offense.passing": "offense_S&P+_passing", 807 "offense.standardDowns": "offense_S&P+_standard_downs", 808 "offense.passingDowns": "offense_S&P+_passing_downs", 809 "offense.runRate": "offense_S&P+_run_rate", 810 "offense.pace": "offense_S&P+_pace", 811 "defense.rating": "defense_S&P+_rating", 812 "defense.success": "defense_S&P+_success", 813 "defense.explosiveness": "defense_S&P+_explosiveness", 814 "defense.rushing": "defense_S&P+_rushing", 815 "defense.passing": "defense_S&P+_passing", 816 "defense.standardDowns": "defense_S&P+_standard_downs", 817 "defense.passingDowns": "defense_S&P+_passing_downs", 818 "defense.havoc.total": "defense_S&P+_havoc_total", 819 "defense.havoc.frontSeven": "defense_S&P+_havoc_front_seven", 820 "defense.havoc.db": "defense_S&P+_havoc_db", 821 "specialTeams.rating": "defense_S&P+_special_teams_rating", 822 }, 823 inplace=True, 824 ) 825 return final_df
Allows you to get Success rate and equivalent Points per play (S&P+) ratings data from the CFBD API.
For more information about S&P+, consult the following webpage: https://collegefootballdata.com/sp/trends
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.
Specifies the season you want S&P+ ratings data from.
This must be specified, otherwise this package, and by extension
the CFBD API, will not accept the request to get S&P+ ratings data.
This or team
must be set to a valid non-null variable
for this to function.
team
(str, optional):
Optional argument.
Specifies the season you want S&P+ ratings data from.
This must be specified, otherwise this package, and by extension
the CFBD API, will not accept the request to get S&P+ ratings data.
This or season
must be set to a valid non-null variable
for this to function.
conference
(str, optional):
Optional argument.
If you only want S&P+ ratings data from games
involving teams a specific conference,
set conference
to the abbreviation
of the conference you want S&P+ ratings data from.
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.ratings import get_cfbd_sp_plus_conference_ratings
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 S&P+ ratings data for the 2020 CFB season.
print("Get S&P+ ratings data for the 2020 CFB season.")
json_data = get_cfbd_sp_plus_conference_ratings(
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_sp_plus_conference_ratings(
api_key=cfbd_key,
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 S&P+ ratings data for the 2020 CFB season.
print("Get S&P+ ratings data for the 2020 CFB season.")
json_data = get_cfbd_sp_plus_conference_ratings(
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_sp_plus_conference_ratings(
season=2020,
return_as_dict=True
)
print(json_data)
Returns
A pandas DataFrame
object with S&P+ ratings data,
or (if return_as_dict
is set to True
)
a dictionary object with a with S&P+ ratings data.
828def get_cfbd_elo_ratings( 829 api_key: str = None, 830 api_key_dir: str = None, 831 season: int = None, 832 week: int = None, 833 season_type: str = "postseason", # "regular" or "postseason" 834 team: str = None, 835 conference: str = None, 836 return_as_dict: bool = False, 837): 838 """ 839 Allows you to get Elo ratings data for CFB teams from the CFBD API. 840 841 For more information about S&P+, consult the following webpages: 842 - https://blog.collegefootballdata.com/talking-tech-elo-ratings/ 843 - https://fivethirtyeight.com/features/introducing-nfl-elo-ratings/ 844 845 Parameters 846 ---------- 847 `api_key` (str, optional): 848 Semi-optional argument. 849 If `api_key` is null, this function will attempt to load a CFBD API key 850 from the python environment, or from a file on this computer. 851 If `api_key` is not null, 852 this function will automatically assume that the 853 inputted `api_key` is a valid CFBD API key. 854 855 `api_key_dir` (str, optional): 856 Optional argument. 857 If `api_key` is set to am empty string, this variable is ignored. 858 If `api_key_dir` is null, and `api_key` is null, 859 this function will try to find 860 a CFBD API key file in this user's home directory. 861 If `api_key_dir` is set to a string, and `api_key` is null, 862 this function will assume that `api_key_dir` is a directory, 863 and will try to find a CFBD API key file in that directory. 864 865 `season` (int, optional): 866 Optional argument. 867 Specifies the season you want S&P+ ratings data from. 868 This must be specified, otherwise this package, and by extension 869 the CFBD API, will not accept the request to get S&P+ ratings data. 870 This or `team` must be set to a valid non-null variable 871 for this to function. 872 873 `week` (int, optional): 874 Optional argument. 875 If `week` is set to a valid, non-null integer, 876 the CFBD API will return back Elo data for a team up to that week 877 in a season. 878 879 `season_type` (str, semi-optional): 880 Semi-optional argument. 881 By default, this will be set to "postseason". 882 If `season_type` is set to "regular", 883 the API will ignore postseason games 884 (like bowls and CFP games) when calculating elo. 885 If `season_type` is set to anything but "regular" or "postseason", 886 a `ValueError()` will be raised. 887 888 `team` (str, optional): 889 Optional argument. 890 Specifies the season you want S&P+ ratings data from. 891 This must be specified, otherwise this package, and by extension 892 the CFBD API, will not accept the request to get S&P+ ratings data. 893 This or `season` must be set to a valid non-null variable 894 for this to function. 895 896 `conference` (str, optional): 897 Optional argument. 898 If you only want S&P+ ratings data from games 899 involving teams a specific conference, 900 set `conference` to the abbreviation 901 of the conference you want S&P+ ratings data from. 902 903 `return_as_dict` (bool, semi-optional): 904 Semi-optional argument. 905 If you want this function to return 906 the data as a dictionary (read: JSON object), 907 instead of a pandas `DataFrame` object, 908 set `return_as_dict` to `True`. 909 910 Usage 911 ---------- 912 ``` 913 import time 914 915 from cfbd_json_py.ratings import get_cfbd_elo_ratings 916 917 918 cfbd_key = "tigersAreAwesome" # placeholder for your CFBD API Key. 919 920 if cfbd_key != "tigersAreAwesome": 921 print( 922 "Using the user's API key declared in this script " + 923 "for this example." 924 ) 925 926 # Get Elo ratings data for the 2020 CFB season. 927 print("Get Elo ratings data for the 2020 CFB season.") 928 json_data = get_cfbd_elo_ratings( 929 api_key=cfbd_key, 930 season=2020 931 ) 932 print(json_data) 933 time.sleep(5) 934 935 # Get Elo ratings data up to week 12 of the 2021 CFB season. 936 print("Get Elo ratings data up to week 12 of the 2021 CFB season.") 937 json_data = get_cfbd_elo_ratings( 938 api_key=cfbd_key, 939 season=2020, 940 week=12 941 ) 942 print(json_data) 943 time.sleep(5) 944 945 # Get Elo ratings data for the 2020 CFB season, 946 # but only for games in the regular season. 947 print( 948 "Get Elo ratings data for the 2020 CFB season, " + 949 "but only for games in the regular season." 950 ) 951 json_data = get_cfbd_elo_ratings( 952 api_key=cfbd_key, 953 season=2020, 954 season_type="regular" 955 ) 956 print(json_data) 957 time.sleep(5) 958 959 # Get historical Elo ratings data for the 960 # University of Cincinnati Football Team. 961 print( 962 "Get historical Elo ratings data for " + 963 "the University of Cincinnati Football Team." 964 ) 965 json_data = get_cfbd_elo_ratings( 966 api_key=cfbd_key, 967 team="Cincinnati" 968 ) 969 print(json_data) 970 time.sleep(5) 971 972 973 # Get Elo ratings data for teams competing in the 974 # Atlantic Coast conference (ACC) in the 2021 CFB season. 975 print( 976 "Get Elo ratings data for teams competing in " + 977 "the Atlantic Coast conference (ACC) in the 2021 CFB season." 978 ) 979 json_data = get_cfbd_elo_ratings( 980 api_key=cfbd_key, 981 season=2021, 982 conference="ACC" 983 ) 984 print(json_data) 985 time.sleep(5) 986 987 # You can also tell this function to just return the API call as 988 # a Dictionary (read: JSON) object. 989 print( 990 "You can also tell this function to just return the API call " + 991 "as a Dictionary (read: JSON) object." 992 ) 993 json_data = get_cfbd_elo_ratings( 994 api_key=cfbd_key, 995 season=2020, 996 team="Cincinnati", 997 return_as_dict=True 998 ) 999 print(json_data) 1000 1001 else: 1002 # Alternatively, if the CFBD API key exists in this python environment, 1003 # or it's been set by cfbd_json_py.utls.set_cfbd_api_token(), 1004 # you could just call these functions directly, 1005 # without setting the API key in the script. 1006 print( 1007 "Using the user's API key supposedly loaded " + 1008 "into this python environment for this example." 1009 ) 1010 1011 # Get Elo ratings data for the 2020 CFB season. 1012 print("Get Elo ratings data for the 2020 CFB season.") 1013 json_data = get_cfbd_elo_ratings( 1014 season=2020 1015 ) 1016 print(json_data) 1017 time.sleep(5) 1018 1019 # Get Elo ratings data up to week 12 of the 2021 CFB season. 1020 print("Get Elo ratings data up to week 12 of the 2021 CFB season.") 1021 json_data = get_cfbd_elo_ratings( 1022 season=2020, 1023 week=12 1024 ) 1025 print(json_data) 1026 time.sleep(5) 1027 1028 # Get Elo ratings data for the 2020 CFB season, 1029 # but only for games in the regular season. 1030 print( 1031 "Get Elo ratings data for the 2020 CFB season, " + 1032 "but only for games in the regular season." 1033 ) 1034 json_data = get_cfbd_elo_ratings( 1035 season=2020, 1036 season_type="regular" 1037 ) 1038 print(json_data) 1039 time.sleep(5) 1040 1041 # Get historical Elo ratings data for the 1042 # University of Cincinnati Football Team. 1043 print( 1044 "Get historical Elo ratings data for " + 1045 "the University of Cincinnati Football Team." 1046 ) 1047 json_data = get_cfbd_elo_ratings( 1048 team="Cincinnati" 1049 ) 1050 print(json_data) 1051 time.sleep(5) 1052 1053 1054 # Get Elo ratings data for teams competing in the 1055 # Atlantic Coast conference (ACC) in the 2021 CFB season. 1056 print( 1057 "Get Elo ratings data for teams competing in " + 1058 "the Atlantic Coast conference (ACC) in the 2021 CFB season." 1059 ) 1060 json_data = get_cfbd_elo_ratings( 1061 season=2021, 1062 conference="ACC" 1063 ) 1064 print(json_data) 1065 time.sleep(5) 1066 1067 # You can also tell this function to just return the API call as 1068 # a Dictionary (read: JSON) object. 1069 print( 1070 "You can also tell this function to just return the API call " + 1071 "as a Dictionary (read: JSON) object." 1072 ) 1073 json_data = get_cfbd_elo_ratings( 1074 season=2020, 1075 team="Cincinnati", 1076 return_as_dict=True 1077 ) 1078 print(json_data) 1079 ``` 1080 Returns 1081 ---------- 1082 A pandas `DataFrame` object with Elo ratings data, 1083 or (if `return_as_dict` is set to `True`) 1084 a dictionary object with a with Elo ratings data. 1085 1086 """ 1087 now = datetime.now() 1088 url = "https://api.collegefootballdata.com/ratings/elo" 1089 # row_df = pd.DataFrame() 1090 final_df = pd.DataFrame() 1091 1092 if api_key is not None: 1093 real_api_key = api_key 1094 del api_key 1095 else: 1096 real_api_key = get_cfbd_api_token(api_key_dir=api_key_dir) 1097 1098 if real_api_key == "tigersAreAwesome": 1099 raise ValueError( 1100 "You actually need to change `cfbd_key` to your CFBD API key." 1101 ) 1102 elif "Bearer " in real_api_key: 1103 pass 1104 elif "Bearer" in real_api_key: 1105 real_api_key = real_api_key.replace("Bearer", "Bearer ") 1106 else: 1107 real_api_key = "Bearer " + real_api_key 1108 1109 # if season is None and team is None: 1110 # raise ValueError( 1111 # "`season` and/or `team` must be set to a valid, " 1112 # + "non-null value for this function to work." 1113 # ) 1114 1115 if season is not None and (season > (now.year + 1)): 1116 raise ValueError(f"`season` cannot be greater than {season}.") 1117 elif season is not None and season < 1869: 1118 raise ValueError("`season` cannot be less than 1869.") 1119 1120 # URL builder 1121 ########################################################################## 1122 1123 # Required by the API 1124 1125 if season is not None and team is not None: 1126 url += f"?year={season}&team={team}" 1127 elif season is not None: 1128 url += f"?year={season}" 1129 elif team is not None: 1130 url += f"?team={team}" 1131 1132 if week is not None: 1133 url += f"&week={week}" 1134 1135 if conference is not None: 1136 url += f"&conference={conference}" 1137 1138 if season_type is not None: 1139 url += f"&seasonType={season_type}" 1140 1141 headers = { 1142 "Authorization": f"{real_api_key}", 1143 "accept": "application/json" 1144 } 1145 response = requests.get(url, headers=headers) 1146 1147 if response.status_code == 200: 1148 pass 1149 elif response.status_code == 401: 1150 raise ConnectionRefusedError( 1151 "Could not connect. The connection was refused." + 1152 "\nHTTP Status Code 401." 1153 ) 1154 else: 1155 raise ConnectionError( 1156 f"Could not connect.\nHTTP Status code {response.status_code}" 1157 ) 1158 1159 json_data = response.json() 1160 1161 if return_as_dict is True: 1162 return json_data 1163 1164 final_df = pd.json_normalize(json_data) 1165 1166 final_df.rename(columns={"rating": "elo_rating"}, inplace=True) 1167 1168 if week is not None and len(final_df) > 0: 1169 final_df["week"] = week 1170 return final_df
Allows you to get Elo ratings data for CFB teams from the CFBD API.
For more information about S&P+, consult the following webpages:
- https://blog.collegefootballdata.com/talking-tech-elo-ratings/
- https://fivethirtyeight.com/features/introducing-nfl-elo-ratings/
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.
Specifies the season you want S&P+ ratings data from.
This must be specified, otherwise this package, and by extension
the CFBD API, will not accept the request to get S&P+ ratings data.
This or team
must be set to a valid non-null variable
for this to function.
week
(int, optional):
Optional argument.
If week
is set to a valid, non-null integer,
the CFBD API will return back Elo data for a team up to that week
in a season.
season_type
(str, semi-optional):
Semi-optional argument.
By default, this will be set to "postseason".
If season_type
is set to "regular",
the API will ignore postseason games
(like bowls and CFP games) when calculating elo.
If season_type
is set to anything but "regular" or "postseason",
a ValueError()
will be raised.
team
(str, optional):
Optional argument.
Specifies the season you want S&P+ ratings data from.
This must be specified, otherwise this package, and by extension
the CFBD API, will not accept the request to get S&P+ ratings data.
This or season
must be set to a valid non-null variable
for this to function.
conference
(str, optional):
Optional argument.
If you only want S&P+ ratings data from games
involving teams a specific conference,
set conference
to the abbreviation
of the conference you want S&P+ ratings data from.
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.ratings import get_cfbd_elo_ratings
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 Elo ratings data for the 2020 CFB season.
print("Get Elo ratings data for the 2020 CFB season.")
json_data = get_cfbd_elo_ratings(
api_key=cfbd_key,
season=2020
)
print(json_data)
time.sleep(5)
# Get Elo ratings data up to week 12 of the 2021 CFB season.
print("Get Elo ratings data up to week 12 of the 2021 CFB season.")
json_data = get_cfbd_elo_ratings(
api_key=cfbd_key,
season=2020,
week=12
)
print(json_data)
time.sleep(5)
# Get Elo ratings data for the 2020 CFB season,
# but only for games in the regular season.
print(
"Get Elo ratings data for the 2020 CFB season, " +
"but only for games in the regular season."
)
json_data = get_cfbd_elo_ratings(
api_key=cfbd_key,
season=2020,
season_type="regular"
)
print(json_data)
time.sleep(5)
# Get historical Elo ratings data for the
# University of Cincinnati Football Team.
print(
"Get historical Elo ratings data for " +
"the University of Cincinnati Football Team."
)
json_data = get_cfbd_elo_ratings(
api_key=cfbd_key,
team="Cincinnati"
)
print(json_data)
time.sleep(5)
# Get Elo ratings data for teams competing in the
# Atlantic Coast conference (ACC) in the 2021 CFB season.
print(
"Get Elo ratings data for teams competing in " +
"the Atlantic Coast conference (ACC) in the 2021 CFB season."
)
json_data = get_cfbd_elo_ratings(
api_key=cfbd_key,
season=2021,
conference="ACC"
)
print(json_data)
time.sleep(5)
# You can also tell this function to just return the API call as
# a Dictionary (read: JSON) object.
print(
"You can also tell this function to just return the API call " +
"as a Dictionary (read: JSON) object."
)
json_data = get_cfbd_elo_ratings(
api_key=cfbd_key,
season=2020,
team="Cincinnati",
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 Elo ratings data for the 2020 CFB season.
print("Get Elo ratings data for the 2020 CFB season.")
json_data = get_cfbd_elo_ratings(
season=2020
)
print(json_data)
time.sleep(5)
# Get Elo ratings data up to week 12 of the 2021 CFB season.
print("Get Elo ratings data up to week 12 of the 2021 CFB season.")
json_data = get_cfbd_elo_ratings(
season=2020,
week=12
)
print(json_data)
time.sleep(5)
# Get Elo ratings data for the 2020 CFB season,
# but only for games in the regular season.
print(
"Get Elo ratings data for the 2020 CFB season, " +
"but only for games in the regular season."
)
json_data = get_cfbd_elo_ratings(
season=2020,
season_type="regular"
)
print(json_data)
time.sleep(5)
# Get historical Elo ratings data for the
# University of Cincinnati Football Team.
print(
"Get historical Elo ratings data for " +
"the University of Cincinnati Football Team."
)
json_data = get_cfbd_elo_ratings(
team="Cincinnati"
)
print(json_data)
time.sleep(5)
# Get Elo ratings data for teams competing in the
# Atlantic Coast conference (ACC) in the 2021 CFB season.
print(
"Get Elo ratings data for teams competing in " +
"the Atlantic Coast conference (ACC) in the 2021 CFB season."
)
json_data = get_cfbd_elo_ratings(
season=2021,
conference="ACC"
)
print(json_data)
time.sleep(5)
# You can also tell this function to just return the API call as
# a Dictionary (read: JSON) object.
print(
"You can also tell this function to just return the API call " +
"as a Dictionary (read: JSON) object."
)
json_data = get_cfbd_elo_ratings(
season=2020,
team="Cincinnati",
return_as_dict=True
)
print(json_data)
Returns
A pandas DataFrame
object with Elo ratings data,
or (if return_as_dict
is set to True
)
a dictionary object with a with Elo ratings data.
1173def get_cfbd_fpi_ratings( 1174 api_key: str = None, 1175 api_key_dir: str = None, 1176 season: int = None, 1177 week: int = None, 1178 team: str = None, 1179 conference: str = None, 1180 return_as_dict: bool = False, 1181): 1182 """ 1183 Allows you to get Football Power Index (FPI) ratings data 1184 for CFB teams from the CFBD API. 1185 1186 For more information about FPI, consult the following webpage: 1187 https://thepowerrank.com/guide-cfb-rankings/ 1188 1189 Parameters 1190 ---------- 1191 `api_key` (str, optional): 1192 Semi-optional argument. 1193 If `api_key` is null, this function will attempt to load a CFBD API key 1194 from the python environment, or from a file on this computer. 1195 If `api_key` is not null, 1196 this function will automatically assume that the 1197 inputted `api_key` is a valid CFBD API key. 1198 1199 `api_key_dir` (str, optional): 1200 Optional argument. 1201 If `api_key` is set to am empty string, this variable is ignored. 1202 If `api_key_dir` is null, and `api_key` is null, 1203 this function will try to find 1204 a CFBD API key file in this user's home directory. 1205 If `api_key_dir` is set to a string, and `api_key` is null, 1206 this function will assume that `api_key_dir` is a directory, 1207 and will try to find a CFBD API key file in that directory. 1208 1209 `season` (int, optional): 1210 Optional argument. 1211 Specifies the season you want FPI ratings data from. 1212 This must be specified, otherwise this package, and by extension 1213 the CFBD API, will not accept the request to get FPI ratings data. 1214 This or `team` must be set to a valid non-null variable 1215 for this to function. 1216 1217 `week` (int, optional): 1218 Optional argument. 1219 If `week` is set to a valid, non-null integer, 1220 the CFBD API will return back Elo data for a team up to that week 1221 in a season. 1222 1223 `team` (str, optional): 1224 Optional argument. 1225 Specifies the season you want FPI ratings data from. 1226 This must be specified, otherwise this package, and by extension 1227 the CFBD API, will not accept the request to get FPI ratings data. 1228 This or `season` must be set to a valid non-null variable 1229 for this to function. 1230 1231 `conference` (str, optional): 1232 Optional argument. 1233 If you only want FPI ratings data from games 1234 involving teams a specific conference, 1235 set `conference` to the abbreviation 1236 of the conference you want FPI ratings data from. 1237 1238 `return_as_dict` (bool, semi-optional): 1239 Semi-optional argument. 1240 If you want this function to return 1241 the data as a dictionary (read: JSON object), 1242 instead of a pandas `DataFrame` object, 1243 set `return_as_dict` to `True`. 1244 1245 Usage 1246 ---------- 1247 ``` 1248 import time 1249 1250 from cfbd_json_py.ratings import get_cfbd_fpi_ratings 1251 1252 1253 cfbd_key = "tigersAreAwesome" # placeholder for your CFBD API Key. 1254 1255 if cfbd_key != "tigersAreAwesome": 1256 print( 1257 "Using the user's API key declared in this script " + 1258 "for this example." 1259 ) 1260 1261 # Get FPI ratings data for the 2020 CFB season. 1262 print("Get FPI ratings data for the 2020 CFB season.") 1263 json_data = get_cfbd_fpi_ratings( 1264 api_key=cfbd_key, 1265 season=2020 1266 ) 1267 print(json_data) 1268 time.sleep(5) 1269 1270 # Get FPI ratings data up to week 12 of the 2021 CFB season. 1271 print("Get FPI ratings data up to week 12 of the 2021 CFB season.") 1272 json_data = get_cfbd_fpi_ratings( 1273 api_key=cfbd_key, 1274 season=2020, 1275 week=12 1276 ) 1277 print(json_data) 1278 time.sleep(5) 1279 1280 # Get historical FPI ratings data for the 1281 # University of Cincinnati Football Team. 1282 print( 1283 "Get historical FPI ratings data for " + 1284 "the University of Cincinnati Football Team." 1285 ) 1286 json_data = get_cfbd_fpi_ratings( 1287 api_key=cfbd_key, 1288 team="Cincinnati" 1289 ) 1290 print(json_data) 1291 time.sleep(5) 1292 1293 1294 # Get FPI ratings data for teams competing in the 1295 # Atlantic Coast conference (ACC) in the 2021 CFB season. 1296 print( 1297 "Get FPI ratings data for teams competing in the " + 1298 "Atlantic Coast conference (ACC) in the 2021 CFB season." 1299 ) 1300 json_data = get_cfbd_fpi_ratings( 1301 api_key=cfbd_key, 1302 season=2021, 1303 conference="ACC" 1304 ) 1305 print(json_data) 1306 time.sleep(5) 1307 1308 # You can also tell this function to just return the API call as 1309 # a Dictionary (read: JSON) object. 1310 print( 1311 "You can also tell this function to just return the API call " + 1312 "as a Dictionary (read: JSON) object." 1313 ) 1314 json_data = get_cfbd_fpi_ratings( 1315 api_key=cfbd_key, 1316 season=2020, 1317 team="Cincinnati", 1318 return_as_dict=True 1319 ) 1320 print(json_data) 1321 1322 else: 1323 # Alternatively, if the CFBD API key exists in this python environment, 1324 # or it's been set by cfbd_json_py.utls.set_cfbd_api_token(), 1325 # you could just call these functions directly, 1326 # without setting the API key in the script. 1327 print( 1328 "Using the user's API key supposedly loaded " + 1329 "into this python environment for this example." 1330 ) 1331 1332 # Get FPI ratings data for the 2020 CFB season. 1333 print("Get FPI ratings data for the 2020 CFB season.") 1334 json_data = get_cfbd_fpi_ratings( 1335 season=2020 1336 ) 1337 print(json_data) 1338 time.sleep(5) 1339 1340 # Get FPI ratings data up to week 12 of the 2021 CFB season. 1341 print("Get FPI ratings data up to week 12 of the 2021 CFB season.") 1342 json_data = get_cfbd_fpi_ratings( 1343 season=2020, 1344 week=12 1345 ) 1346 print(json_data) 1347 time.sleep(5) 1348 1349 1350 1351 # Get historical FPI ratings data for the 1352 # University of Cincinnati Football Team. 1353 print( 1354 "Get historical FPI ratings data for " + 1355 "the University of Cincinnati Football Team." 1356 ) 1357 json_data = get_cfbd_fpi_ratings( 1358 team="Cincinnati" 1359 ) 1360 print(json_data) 1361 time.sleep(5) 1362 1363 1364 # Get FPI ratings data for teams competing in the 1365 # Atlantic Coast conference (ACC) in the 2021 CFB season. 1366 print( 1367 "Get FPI ratings data for teams competing in the " + 1368 "Atlantic Coast conference (ACC) in the 2021 CFB season." 1369 ) 1370 json_data = get_cfbd_fpi_ratings( 1371 season=2021, 1372 conference="ACC" 1373 ) 1374 print(json_data) 1375 time.sleep(5) 1376 1377 # You can also tell this function to just return the API call as 1378 # a Dictionary (read: JSON) object. 1379 print( 1380 "You can also tell this function to just return the API call " + 1381 "as a Dictionary (read: JSON) object." 1382 ) 1383 json_data = get_cfbd_fpi_ratings( 1384 season=2020, 1385 team="Cincinnati", 1386 return_as_dict=True 1387 ) 1388 print(json_data) 1389 1390 1391 ``` 1392 Returns 1393 ---------- 1394 A pandas `DataFrame` object with FPI ratings data, 1395 or (if `return_as_dict` is set to `True`) 1396 a dictionary object with a with FPI ratings data. 1397 1398 """ 1399 now = datetime.now() 1400 url = "https://api.collegefootballdata.com/ratings/fpi" 1401 # row_df = pd.DataFrame() 1402 final_df = pd.DataFrame() 1403 1404 if api_key is not None: 1405 real_api_key = api_key 1406 del api_key 1407 else: 1408 real_api_key = get_cfbd_api_token(api_key_dir=api_key_dir) 1409 1410 if real_api_key == "tigersAreAwesome": 1411 raise ValueError( 1412 "You actually need to change `cfbd_key` to your CFBD API key." 1413 ) 1414 elif "Bearer " in real_api_key: 1415 pass 1416 elif "Bearer" in real_api_key: 1417 real_api_key = real_api_key.replace("Bearer", "Bearer ") 1418 else: 1419 real_api_key = "Bearer " + real_api_key 1420 1421 if season is None and team is None: 1422 raise ValueError( 1423 "`season` and/or `team` must be set to a valid, " 1424 + "non-null value for this function to work." 1425 ) 1426 1427 if season is not None and (season > (now.year + 1)): 1428 raise ValueError(f"`season` cannot be greater than {season}.") 1429 elif season is not None and season < 1869: 1430 raise ValueError("`season` cannot be less than 1869.") 1431 1432 # URL builder 1433 ########################################################################## 1434 1435 # Required by the API 1436 1437 if season is not None and team is not None: 1438 url += f"?year={season}&team={team}" 1439 elif season is not None: 1440 url += f"?year={season}" 1441 elif team is not None: 1442 url += f"?team={team}" 1443 1444 if week is not None: 1445 url += f"&week={week}" 1446 1447 if conference is not None: 1448 url += f"&conference={conference}" 1449 1450 headers = { 1451 "Authorization": f"{real_api_key}", 1452 "accept": "application/json" 1453 } 1454 response = requests.get(url, headers=headers) 1455 1456 if response.status_code == 200: 1457 pass 1458 elif response.status_code == 401: 1459 raise ConnectionRefusedError( 1460 "Could not connect. The connection was refused." + 1461 "\nHTTP Status Code 401." 1462 ) 1463 else: 1464 raise ConnectionError( 1465 f"Could not connect.\nHTTP Status code {response.status_code}" 1466 ) 1467 1468 json_data = response.json() 1469 1470 if return_as_dict is True: 1471 return json_data 1472 1473 final_df = pd.json_normalize(json_data) 1474 1475 final_df.rename( 1476 columns={ 1477 "year": "season", 1478 "team": "team_name", 1479 "conference": "conference_name", 1480 "resumeRanks.strengthOfRecord": "resume_strength_of_record", 1481 "resumeRanks.fpi": "fpi_rank", 1482 "resumeRanks.averageWinProbability": "resume_avg_win_probability", 1483 "resumeRanks.strengthOfSchedule": "resume_strength_of_schedule", 1484 "resumeRanks.remainingStrengthOfSchedule": 1485 "resume_remaining_strength_of_schedule", 1486 "resumeRanks.gameControl": "resume_game_control", 1487 "efficiencies.overall": "efficiency_overall", 1488 "efficiencies.offense": "efficiency_offense", 1489 "efficiencies.defense": "efficiency_defense", 1490 "efficiencies.specialTeams": "efficiency_special_teams", 1491 }, 1492 inplace=True, 1493 ) 1494 return final_df
Allows you to get Football Power Index (FPI) ratings data for CFB teams from the CFBD API.
For more information about FPI, consult the following webpage: https://thepowerrank.com/guide-cfb-rankings/
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.
Specifies the season you want FPI ratings data from.
This must be specified, otherwise this package, and by extension
the CFBD API, will not accept the request to get FPI ratings data.
This or team
must be set to a valid non-null variable
for this to function.
week
(int, optional):
Optional argument.
If week
is set to a valid, non-null integer,
the CFBD API will return back Elo data for a team up to that week
in a season.
team
(str, optional):
Optional argument.
Specifies the season you want FPI ratings data from.
This must be specified, otherwise this package, and by extension
the CFBD API, will not accept the request to get FPI ratings data.
This or season
must be set to a valid non-null variable
for this to function.
conference
(str, optional):
Optional argument.
If you only want FPI ratings data from games
involving teams a specific conference,
set conference
to the abbreviation
of the conference you want FPI ratings data from.
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.ratings import get_cfbd_fpi_ratings
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 FPI ratings data for the 2020 CFB season.
print("Get FPI ratings data for the 2020 CFB season.")
json_data = get_cfbd_fpi_ratings(
api_key=cfbd_key,
season=2020
)
print(json_data)
time.sleep(5)
# Get FPI ratings data up to week 12 of the 2021 CFB season.
print("Get FPI ratings data up to week 12 of the 2021 CFB season.")
json_data = get_cfbd_fpi_ratings(
api_key=cfbd_key,
season=2020,
week=12
)
print(json_data)
time.sleep(5)
# Get historical FPI ratings data for the
# University of Cincinnati Football Team.
print(
"Get historical FPI ratings data for " +
"the University of Cincinnati Football Team."
)
json_data = get_cfbd_fpi_ratings(
api_key=cfbd_key,
team="Cincinnati"
)
print(json_data)
time.sleep(5)
# Get FPI ratings data for teams competing in the
# Atlantic Coast conference (ACC) in the 2021 CFB season.
print(
"Get FPI ratings data for teams competing in the " +
"Atlantic Coast conference (ACC) in the 2021 CFB season."
)
json_data = get_cfbd_fpi_ratings(
api_key=cfbd_key,
season=2021,
conference="ACC"
)
print(json_data)
time.sleep(5)
# You can also tell this function to just return the API call as
# a Dictionary (read: JSON) object.
print(
"You can also tell this function to just return the API call " +
"as a Dictionary (read: JSON) object."
)
json_data = get_cfbd_fpi_ratings(
api_key=cfbd_key,
season=2020,
team="Cincinnati",
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 FPI ratings data for the 2020 CFB season.
print("Get FPI ratings data for the 2020 CFB season.")
json_data = get_cfbd_fpi_ratings(
season=2020
)
print(json_data)
time.sleep(5)
# Get FPI ratings data up to week 12 of the 2021 CFB season.
print("Get FPI ratings data up to week 12 of the 2021 CFB season.")
json_data = get_cfbd_fpi_ratings(
season=2020,
week=12
)
print(json_data)
time.sleep(5)
# Get historical FPI ratings data for the
# University of Cincinnati Football Team.
print(
"Get historical FPI ratings data for " +
"the University of Cincinnati Football Team."
)
json_data = get_cfbd_fpi_ratings(
team="Cincinnati"
)
print(json_data)
time.sleep(5)
# Get FPI ratings data for teams competing in the
# Atlantic Coast conference (ACC) in the 2021 CFB season.
print(
"Get FPI ratings data for teams competing in the " +
"Atlantic Coast conference (ACC) in the 2021 CFB season."
)
json_data = get_cfbd_fpi_ratings(
season=2021,
conference="ACC"
)
print(json_data)
time.sleep(5)
# You can also tell this function to just return the API call as
# a Dictionary (read: JSON) object.
print(
"You can also tell this function to just return the API call " +
"as a Dictionary (read: JSON) object."
)
json_data = get_cfbd_fpi_ratings(
season=2020,
team="Cincinnati",
return_as_dict=True
)
print(json_data)
Returns
A pandas DataFrame
object with FPI ratings data,
or (if return_as_dict
is set to True
)
a dictionary object with a with FPI ratings data.